CreditGuard_Pro / app.py
FRANCKYPRO's picture
Update app.py
55b67dd
import streamlit as st
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import pickle
import numpy as np
import base64
import streamlit_authenticator as stauth
from authenticator import sign_up, fetch_users
from pycaret.classification import load_model, predict_model
import joblib
import altair as alt
# ici c'est le logo de mon application web
st.set_page_config(page_title='CreditGuard Pro', page_icon='🏛', initial_sidebar_state='collapsed')
# conditions pour l'authentification et de connection a internet
try:
users = fetch_users()
emails = []
usernames = []
passwords = []
for user in users:
emails.append(user['key'])
usernames.append(user['username'])
passwords.append(user['password'])
credentials = {'usernames': {}}
for index in range(len(emails)):
credentials['usernames'][usernames[index]] = {'name': emails[index], 'password': passwords[index]}
Authenticator = stauth.Authenticate(credentials, cookie_name='Streamlit', key='abcdef', cookie_expiry_days=4)
email, authentication_status, username = Authenticator.login(':green[Login]', 'main')
info, info1 = st.columns(2)
if not authentication_status:
sign_up()
if username:
if username in usernames:
if authentication_status:
# let User see app
# Contenu de la page
#code de la page d'accuille et les menus
st.sidebar.image("CFC.png",width=220)
st.sidebar.subheader(f'Welcome :orange[{email}]')
Authenticator.logout('Log Out', 'sidebar')
st.set_option('deprecation.showPyplotGlobalUse', False)
#fonction qui est sensé garde j'etat d'une page
@st.cache_data
def load_data(dataset):
df = pd.read_csv(dataset)
return df
#image de fond
def get_img_as_base64(file):
with open(file, "rb") as f:
data = f.read()
return base64.b64encode(data).decode()
img = get_img_as_base64("imagebare2.jpg")
# création des differents menus
menu=["ACCUEIL","ANALYSE DES DONNÉES","VISUALISATION","CLASSIFICATION","PRÉDICTION INDIVIDUELLE","À PROPOS"]
choice = st.sidebar.selectbox("selectionne un Menu",menu)
#les differents menus et les fonctionalités
#menu HOME
if choice == "ACCUEIL":
#Image de fond du menu
page_bg_img = f"""
<style>
[data-testid="stAppViewContainer"] > .main {{
background-image: url("https://www.creditfoncier.cm/images/revslider/uploads/slides-1bis_1.jpg");
background-size: 700%;
background-position: top left;
background-repeat: no-repeat;
background-attachment: local;
}}
[data-testid="stSidebar"] > div:first-child {{
background-image: url("data:image/png;base64,{img}");
background-position: top lef;
background-repeat: no-repeat;
background-attachment: fixed;
}}
[data-testid="stHeader"] {{
background: rgba(0,0,0,0);
}}
[data-testid="stToolbar"] {{
right: 2rem;
}}
</style>
"""
st.markdown(page_bg_img, unsafe_allow_html=True)# condition pour autoriser le CSS et le HTML
left,middle,right = st.columns((2,3,2))
with middle:
st.image("logo_CFC.png",width=300)
st.markdown("<h1 style='text-align:center;color: orange;'>CREDIT FONCIER DU CAMEROUN </h1>",unsafe_allow_html=True)
st.write("<h2 style='text-align:center;color: black;'>Vous loger,notre seul souci.</h2>",unsafe_allow_html=True)
st.write ("<br><br>",unsafe_allow_html=True)
#bande deroulente pour la decription du CFC
expander = st.expander("DESCRIPTION DE L'APPLICATION")
expander.write("""
L'application CreditGuard Pro est une application conçue pour résoudre les problèmes de prise de décision automatisée
pour l'octroi de prêt classique ordinaire au sein du CFC. Grâce à des techniques avancées de machine Learning,
l'application analyse les profits des demandeurs de prêt en se basant sur des differentes paramètres pertinents.
Elle génère ensuite des évaluations de risque précises et rapides, permettant au CFC de prendre des décisions
éclairées et efficentes en matière d'octroi de prêts. L'application CreditGuard Pro vise à améliorer la précision des décisions
de crédit tout en optimisant le processus global d'octroi de prêts, ce qui contribue à renforcer la qualité des services
financiers du CFC.
""")# mettre une description ici
expander.image("https://www.creditfoncier.cm/images/revslider/uploads/slides-1bis_1.jpg")#image qui parle du CFC avec la main et le maison
#bande deroulante pour les services qu'offre le cfc
expander = st.expander("SERVICES QU'OFFRE CreditGuard Pro")
expander.write("""
-I- la classification des individus à risque ou pas pour le remboursement d'un credit reçu.
""")# mettre une description ici
expander.image("https://media.istockphoto.com/id/1347375207/fr/photo/mains-tenant-le-visage-triste-cach%C3%A9-derri%C3%A8re-un-visage-heureux-bipolaire-et-d%C3%A9pression-sant%C3%A9.webp?b=1&s=612x612&w=0&k=20&c=Cv6RY2Io-HTM8sN-5I587k4BruOAadtkotU8R3r83cM=")
expander.write("""
""")
expander.write("""
-II- La proportion des individus qui ont reçus un prêt et ont rembousés et la proportion des individus qui ont reçus un prêt et n'ont pas rembousés
""")
expander.image("cercle de risque.png")
#page
#menu DATA ANALYSIS
if choice == "ANALYSE DES DONNÉES":
#image de font
page_bg_img = f"""
<style>
[data-testid="stAppViewContainer"] > .main {{
background-image: url("https://www.creditfoncier.cm/images/revslider/uploads/slides-1bis_1.jpg");
background-size: 700%;
background-position: top left;
background-repeat: no-repeat;
background-attachment: local;
}}
[data-testid="stSidebar"] > div:first-child {{
background-image: url("data:image/png;base64,{img}");
background-position: top lef;
background-repeat: no-repeat;
background-attachment: fixed;
}}
[data-testid="stHeader"] {{
background: rgba(0,0,0,0);
}}
[data-testid="stToolbar"] {{
right: 2rem;
}}
</style>
"""
st.markdown(page_bg_img, unsafe_allow_html=True)
st.markdown("<h1 style='text-align:center;color: red;'>ANALYSE DE DONNÉES </h1>",unsafe_allow_html=True)
st.write ("<br><br>",unsafe_allow_html=True)
tb, tb1, tb2 = st.tabs([":clipboard: Dataset",":bar_chart: summary",":chart_with_upwards_trend: correlation"])
data = load_data("credit_risk_dataset.csv")
with tb: #display les 5 premières lignes de notre dataset
st.subheader("Credit risk Dataset")
st.write(data.head(10))
st.write("""-------""")
st.write("Notre dataset qui port sur le Credit Risk joue un rôle fondamental pour les analyses, les visualisations, les classifications et les predictions")
st.write("- Person_age: représente l'âge des individus")
st.write("- Person_icome: représente le revenu annuel")
st.write("- Person_home_ownership: représente l'accesion à al propriété.")
st.write("- Preson_emp_length: représente la durée de l'emploi (en années)")
st.write("- loan_intent: représente l'intention de prêt")
st.write("- loan_grade: représente la catégorie de prêt")
st.write("- loan_amnt: représente le montant du prêt")
st.write("- loan_int_rate: représente le taux d'intérêt")
st.write("- loan_status: représente le statu du prêt ( accorder ou pas)")
st.write("- loan_percent_income: représente le pourcentage de revenu")
st.write("- loan_person_default_on_file: représente le défaut historique")
st.write("- loan_person_cred_hist_length: représente la durée de l'historique de crédit")
st.write("""-------""")
with tb1:
#AFFICHER LE SUMMARY
st.subheader("TABLEAU DE SUMMARY ")
st.write(data.describe().head(8))
st.write("""-------""")
st.write("COUNT : fait référence au nombre total d'observations (ou d'echantillons) présentes dans un ensemble de données pour une variable particulière. C'est une mesure statistique fondamentale qui indique combien de fois une certaine valeur ou catégorie apparaît dans la variable.")
st.write("""-------""")
st.write("MEAN: fait référence à la moyenne des valeurs d'une variable numérique. c'est une mesure statistique couramment utilisée pour représenter la valeur centrale d'une distribution de données.")
st.write("""-------""")
st.write("STD: fait référence à l'écart-type(standard deviation en anglais) d'une variable numerique. l'écart-type étant une mesure statistique qui indique à quel point les valeurs d'une distribution dde données sont dispersées par rapport à la moyenne (MEAN).")
st.write("""-------""")
st.write("25%: sont appelé le premier quartile, qui représente le point auquel 25 pour-cent des données dans une distribution sont inférieures et 75 pour-cent sont supérieures. C'est un indicateur de la dispersion des données dans la partie inférieure de la distribution")
st.write("""-------""")
st.write("50%: souvant appelé la médiane ou le deuxième quartile, représente la valeur qui divise les données en deux parties égales: 50 pour-cent des données sont en dessous de cette valeur et 50 pour-cent au dessus")
st.write("""-------""")
st.write("75%: appelé le troisième quartile il représente la valeur qui divise les données en deux parties: 25 pour-cent des données sont en dessous de cette valur et 75 pour-cent sont au-dessus")
st.write("""-------""")
st.write("MAX: représente la valeur maximale observée dans un ensemble de données. En d'autre termes, c'est la plus grande valeur parmit toutes les valeurs présentes dans le jeu de données.")
#AFFICHER LA MATRIXE DE CORELATION
with tb2:
st.subheader("MATRICE DE CORRÉLATION")
fig = plt.figure(figsize=(15,15))
st.write(sns.heatmap(data.corr(), annot=True))
st.pyplot(fig)
st.write("""-------""")
st.write("La Matrice de Corrélation joue un rôle crucial dans l'analyse et la visualisation des relations entre les différentes caractéristiques(variable) présentes dans notre ensemble de données.")
st.write("- Elle identifi des relations entre les variable")
st.write("- Sélectionne des caractéristiques")
st.write("- Visualise des relations")
st.write("- Détecte des anomalies")
st.write("- Effectue une prise de décision")
st.write("""-------""")
# afficher la figure
#fig , ax = plt.histplot()
#ax.bar(data["loan_amnt"], data["person_age"])
#plt.xlabel("person_age")
#plt.ylabel("loan_amnt")
#plt.title('Presentation.......')
#afficher le graphique
#menu DATA VISUALISATION
if choice == "VISUALISATION":
#image de font
page_bg_img = f"""
<style>
[data-testid="stAppViewContainer"] > .main {{
background-image: url("https://cdn.pixabay.com/photo/2017/10/05/10/59/background-2819026_640.jpg");
background-size: 700%;
background-position: center;
background-repeat: no-repeat;
background-attachment: local;
}}
[data-testid="stSidebar"] > div:first-child {{
background-image: url("data:image/png;base64,{img}");
background-position: top lef;
background-repeat: no-repeat;
background-attachment: fixed;
}}
[data-testid="stHeader"] {{
background: rgba(0,0,0,0);
}}
[data-testid="stToolbar"] {{
right: 2rem;
}}
</style>
"""
st.markdown(page_bg_img, unsafe_allow_html=True)
st.markdown("<h1 style='text-align:center;color: red;'>VISUALISATION GRAPHIQUE </h1>",unsafe_allow_html=True)
data = load_data("credit_risk_dataset.csv")
st.write(data.head(5))
#representation du Countplot
if st.checkbox("REPRESENTATION"):
#parametres de visualisation
x_variable = st.selectbox("variable X",data.columns)
#y_variable = st.selectbox("variable Y",data.columns)
#color_variable = st.selectbox("variable de couleur",data.columns)
#crée le graphique
fig = plt.figure(figsize = (13,13))
sns.countplot(x=x_variable,data=data)
st.pyplot(fig)
#representation de l'importance des colonnes
if st.checkbox("Importance des colonnes"):
#visualiser l'importance des colonnes
model=joblib.load('credit_risk_prop.pkl')
feature_importances = model.feature_importances_
#recupération des noms de colonnes
column_names = data.columns
#creation d'un dictionnaire pour assoicier chaque colonne à son importance
feature_importances_dict = dict(zip(column_names, feature_importances))
#tri des colonnes par importance décroissante
sorted_features = sorted(feature_importances_dict.items(),key = lambda x:[1], reverse=True)
#extration des noms de colonnes trié et de leurs importances
sorted_columns, sorted_importances = zip(*sorted_features)
fig, ax = plt.subplots (figsize=(10,6))
ax.bar(sorted_columns, sorted_importances)
ax.set_xticklabels(sorted_columns, rotation = 90)
ax.set_xlabel('colonnes')
ax.set_ylabel('Importance')
ax.set_title ('Importance des colonnes')
#affichage de la figure
st.pyplot(fig)
#menu Prediction Score_risK
if choice == "CLASSIFICATION":
page_bg_img = f"""
<style>
[data-testid="stAppViewContainer"] > .main {{
background-image: url("https://images.unsplash.com/photo-1501426026826-31c667bdf23d");
background-size: 250%;
background-position: top left;
background-repeat: no-repeat;
background-attachment: local;
}}
[data-testid="stSidebar"] > div:first-child {{
background-image: url("data:image/png;base64,{img}");
background-position: top left;
background-repeat: no-repeat;
background-attachment: fixed;
}}
[data-testid="stHeader"] {{
background: rgba(0,0,0,0);
}}
[data-testid="stToolbar"] {{
right: 2rem;
}}
</style>
"""
st.markdown(page_bg_img, unsafe_allow_html=True)
st.markdown("<h1 style='text-align:center;color: red;'>CLASSIFICATION DES INDIVIDUS </h1>",unsafe_allow_html=True)
st.write ("<br>",unsafe_allow_html=True)
st.write("<h3 style='text-align:center;color: black;'>DATASET IMPORTER </h3>",unsafe_allow_html=True)
#inporter un data set pour faire une classification
uploaded_file = st.sidebar.file_uploader("Importer un le DATASET", type=["csv"])
if uploaded_file is not None:
data = load_data(uploaded_file)
st.subheader("dataset")
st.write(data)
if st.button("EFFECTUER UNE CLASSIFICATION"):
from pycaret.classification import *
# Charger les données
#data = pd.read_csv('credit_risk_predict.csv')
# Initialiser l'environnement de classification
clf = setup(data=data, target='loan_status', session_id=123)
# Comparer les modèles
#compare_models()
# Créer le modèle
#model = create_model('lightgbm')
model = joblib.load("credit.pkl")
# Afficher les performances du modèle
#plot_model(model, plot='auc')
# Prédire les valeurs sur de nouvelles données
predictions = predict_model(model)
# Afficher les prédictions
predictions.prediction_label.replace(0, "Crédit non à risque", inplace = True)
predictions.prediction_label.replace(1, "Credit à risque",inplace = True)
st.write(predictions)
#pour télécharger le dataset deja classé
def filedownload(data):
csv = data.to_csv(index=False)
b64 = base64.b64encode(csv.encode()).decode() # strings <-> bytes conversions
href = f'<a href="data:file/csv;base64,{b64}" download="credit_risk_dataset_1.csv">Download CSV File</a>'
return href
button = st.button("Download (télécharger)")
if button:
st.markdown(filedownload(predictions), unsafe_allow_html=True)
#menu Prédiction
if choice == "PRÉDICTION INDIVIDUELLE":
#image de font
page_bg_img = f"""
<style>
[data-testid="stAppViewContainer"] > .main {{
background-image: url("https://images.unsplash.com/photo-1501426026826-31c667bdf23d");
background-size: 250%;
background-position: top left;
background-repeat: no-repeat;
background-attachment: local;
}}
[data-testid="stSidebar"] > div:first-child {{
background-image: url("data:image/png;base64,{img}");
background-position: top left;
background-repeat: no-repeat;
background-attachment: fixed;
}}
[data-testid="stHeader"] {{
background: rgba(0,0,0,0);
}}
[data-testid="stToolbar"] {{
right: 2rem;
}}
</style>
"""
st.markdown(page_bg_img, unsafe_allow_html=True)
model = joblib.load("credit.pkl")
df = pd.read_csv("credit_risk_dataset.csv")
#selected_features=["person_age","person_income","person_home_ownership_MORTGAGE","person_home_ownership_OTHER","person_home_ownership_OWN","person_home_ownership_RENT","person_emp_length","loan_intent_DEBTCONSOLIDATION","loan_intent_EDUCATION","loan_intent_HOMEIMPROVEMENT","loan_intent_MEDICAL","loan_intent_PERSONAL","loan_intent_VENTURE","loan_grade_A","loan_grade_B","loan_grade_C","loan_grade_D","loan_grade_E","loan_grade_F","loan_grade_G","loan_amnt","loan_int_rate","loan_percent_income","cb_person_default_on_file","cb_person_cred_hist_length"]
selected_features= ["person_age","person_income","person_home_ownership","person_emp_length","loan_intent","loan_grade","loan_amnt","loan_int_rate","loan_percent_income","cb_person_default_on_file","cb_person_cred_hist_length"]
st.markdown("<h1 style='text-align:center;color: red;'>PRÉDICTION DU RISQUE DE CRÉDIT </h1>",unsafe_allow_html=True)
st.write ("<br><br>",unsafe_allow_html=True)
st.subheader("Remplissez les champs")
user_input = []
for feature in selected_features:
if feature == "person_home_ownership" or feature == "loan_intent" or feature == "loan_grade" or feature =="cb_person_default_on_file":
value = st.text_input(f"Entrez la valeur pour {feature}")
else:
value = st.number_input (f"Entrez la valeur pour {feature}")
user_input.append(value)
user_data = pd.DataFrame([user_input], columns=selected_features)
st.subheader("Paramètres d'entrée de l'utilisateur (User Input parameters)")
st.write(user_data)
if st.button("Prédire"):
prediction = model.predict(user_data)
prediction_proba = model.predict_proba(user_data)
st.write("la prédiction est : ", prediction )
if prediction == 1:
st.write("<h1 style='text-align:center;color: red;'>Individu à risque pour un crédit</h1>",unsafe_allow_html=True)
else:
st.write("<h1 style='text-align:center;color: green;'>Individu non à risque pour un crédit</h1>",unsafe_allow_html=True)
st.subheader('Prediction Probability')
st.write(prediction_proba)
# value = st.number_input(f"Entrez la valeur pour {feature}")
# user_input.append(value)
#tab1, tab2 = st.tabs([":clipboard: Data",":bar_chart: Visualisation", ":angry: :smile: Prediction"])
#uploaded_file = st.sidebar.file_uploader("Importer un le DATASET", type=["csv"])
#if uploaded_file is not None:
# df = load_data(uploaded_file)
#
# with tab1:
# st.subheader("Loaded dataset")
# st.write(df)
# with tab2:
# st.subheader("REPRESENTATION")
#with tab3:
# data =load_model("credit_risk_prop")
# prediction = data.predict(df)
# st.subheader('Prediction')
# pp = pd.DataFrame(prediction,columns=["Prediction"])
# ndf = pd.concat([df,pp],axis=1)
# ndf.Prediction.replace(0, "NO Credit_Risk", inplace = True)
# ndf.Prediction.replace(1, "Credit_Risk", inplace = True)
# st.write(ndf)
# def filedownload(df):
# 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="credit_risk_dataset_prop.csv">Download CSV File</a>'
# return href
# button = st.button("Download (telecharger)")
# if button:
# st.markdown(filedownload(ndf), unsafe_allow_html=True)
if choice == "À PROPOS":
#Image de fond du menu
page_bg_img = f"""
<style>
[data-testid="stAppViewContainer"] > .main {{
background-image: url("https://www.creditfoncier.cm/images/revslider/uploads/slides-1bis_1.jpg");
background-size: 700%;
background-position: top left;
background-repeat: no-repeat;
background-attachment: local;
}}
[data-testid="stSidebar"] > div:first-child {{
background-image: url("data:image/png;base64,{img}");
background-position: top lef;
background-repeat: no-repeat;
background-attachment: fixed;
}}
[data-testid="stHeader"] {{
background: rgba(0,0,0,0);
}}
[data-testid="stToolbar"] {{
right: 2rem;
}}
</style>
"""
st.markdown(page_bg_img, unsafe_allow_html=True)# condition pour autoriser le CSS et le HTML
st.write ("<br><br>",unsafe_allow_html=True)
# etapes pouyr utilisation de l'apk
expander = st.expander("GUIDE D'UTILISATION")
expander.write("""
""")# mettre une description ici
expander.write("Étape 1 (authentification)")
expander.write("""-------""")
expander.image("aide1.JPG")
expander.write("""-------""")
expander.write("Étape 2 (authentification)")
expander.write("""-------""")
expander.image("aide2.JPG")
expander.write("""-------""")
expander.write("Étape 3 (Accuiel après)")
expander.write("""-------""")
expander.image("aide3.JPG")
expander.write("""-------""")
expander.write("Étape 4 (pour la barre de sélection des menus )")
expander.write("""-------""")
expander.image("aide4.JPG")
expander.write("""-------""")
expander.write("Étape 5")
expander.write("""-------""")
expander.image("aide5.JPG")
expander.write("""-------""")
expander.write("Étape 6 (selection d'un menu")
expander.write("""-------""")
expander.image("aide6.JPG")
expander.write("""-------""")
expander.write("Étape 7 (Exemple de menu : menu CLASSIFICATION)")
expander.write("""-------""")
expander.image("aide7.JPG")
elif not authentication_status:
with info:
st.error('Incorrect Password or username')
else:
with info:
st.warning('Please feed in your credentials')
else:
with info:
st.warning('Username does not exist, Please Sign up')
except:
st.success('Refresh Page')