FRANCKYPRO commited on
Commit
4fa41df
·
1 Parent(s): 5317421

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +566 -0
app.py ADDED
@@ -0,0 +1,566 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import seaborn as sns
4
+ import matplotlib.pyplot as plt
5
+ import pickle
6
+ import numpy as np
7
+ import base64
8
+ import streamlit_authenticator as stauth
9
+ from authenticator import sign_up, fetch_users
10
+ from pycaret.classification import load_model, predict_model
11
+ import joblib
12
+ import altair as alt
13
+
14
+
15
+ # ici c'est le logo de mon application web
16
+ st.set_page_config(page_title='CreditGuard Pro', page_icon='🏛', initial_sidebar_state='collapsed')
17
+
18
+ # conditions pour l'authentification et de connection a internet
19
+ try:
20
+ users = fetch_users()
21
+ emails = []
22
+ usernames = []
23
+ passwords = []
24
+
25
+ for user in users:
26
+ emails.append(user['key'])
27
+ usernames.append(user['username'])
28
+ passwords.append(user['password'])
29
+
30
+ credentials = {'usernames': {}}
31
+ for index in range(len(emails)):
32
+ credentials['usernames'][usernames[index]] = {'name': emails[index], 'password': passwords[index]}
33
+
34
+ Authenticator = stauth.Authenticate(credentials, cookie_name='Streamlit', key='abcdef', cookie_expiry_days=4)
35
+
36
+ email, authentication_status, username = Authenticator.login(':green[Login]', 'main')
37
+
38
+ info, info1 = st.columns(2)
39
+
40
+ if not authentication_status:
41
+ sign_up()
42
+
43
+ if username:
44
+ if username in usernames:
45
+ if authentication_status:
46
+ # let User see app
47
+
48
+
49
+ # Contenu de la page
50
+
51
+
52
+ #code de la page d'accuille et les menus
53
+ st.sidebar.image("CFC.png",width=220)
54
+ st.sidebar.subheader(f'Welcome :orange[{email}]')
55
+ Authenticator.logout('Log Out', 'sidebar')
56
+
57
+ st.set_option('deprecation.showPyplotGlobalUse', False)
58
+
59
+ #fonction qui est sensé garde j'etat d'une page
60
+ @st.cache_data
61
+ def load_data(dataset):
62
+ df = pd.read_csv(dataset)
63
+ return df
64
+
65
+ #image de fond
66
+ def get_img_as_base64(file):
67
+ with open(file, "rb") as f:
68
+ data = f.read()
69
+ return base64.b64encode(data).decode()
70
+
71
+ img = get_img_as_base64("imagebare2.jpg")
72
+
73
+
74
+
75
+ # création des differents menus
76
+ menu=["ACCUEIL","ANALYSE DES DONNÉES","VISUALISATION","CLASSIFICATION","PRÉDICTION"]
77
+ choice = st.sidebar.selectbox("selectionne un Menu",menu)
78
+
79
+ #les differents menus et les fonctionalités
80
+
81
+ #menu HOME
82
+
83
+ if choice == "ACCUEIL":
84
+
85
+ #Image de fond du menu
86
+ page_bg_img = f"""
87
+ <style>
88
+ [data-testid="stAppViewContainer"] > .main {{
89
+ background-image: url("https://www.creditfoncier.cm/images/revslider/uploads/slides-1bis_1.jpg");
90
+ background-size: 5000%;
91
+ background-position: top left;
92
+ background-repeat: no-repeat;
93
+ background-attachment: local;
94
+ }}
95
+
96
+ [data-testid="stSidebar"] > div:first-child {{
97
+ background-image: url("data:image/png;base64,{img}");
98
+ background-position: top lef;
99
+ background-repeat: no-repeat;
100
+ background-attachment: fixed;
101
+ }}
102
+
103
+ [data-testid="stHeader"] {{
104
+ background: rgba(0,0,0,0);
105
+ }}
106
+
107
+ [data-testid="stToolbar"] {{
108
+ right: 2rem;
109
+ }}
110
+ </style>
111
+ """
112
+
113
+ st.markdown(page_bg_img, unsafe_allow_html=True)# condition pour autoriser le CSS et le HTML
114
+
115
+ left,middle,right = st.columns((2,3,2))
116
+ with middle:
117
+ st.image("logo_CFC.png",width=300)
118
+ st.markdown("<h1 style='text-align:center;color: orange;'>CREDIT FONCIER DU CAMEROUN </h1>",unsafe_allow_html=True)
119
+ st.write("<h2 style='text-align:center;color: black;'>Vous loger,notre seul souci.</h2>",unsafe_allow_html=True)
120
+
121
+
122
+
123
+ #bande deroulente pour la decription du CFC
124
+ expander = st.expander("DESCRIPTION DE L'APPLICATION")
125
+ expander.write("""
126
+ L'application CreditGuard Pro est une application conçue pour résoudre les problèmes de prise de décision automatisée
127
+ pour l'octroi de prêt classique ordinaire au sein du CFC. Grâce à des techniques avancées de machine Learning,
128
+ l'application analyse les profits des demandeurs de prêt en se basant sur des differentes paramètres pertinents.
129
+ Elle génère ensuite des évaluations de risque précises et rapides, permettant au CFC de prendre des décisions
130
+ é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
131
+ de crédit tout en optimisant le processus global d'octroi de prêts, ce qui contribue à renforcer la qualité des services
132
+ financiers du CFC.
133
+
134
+ """)# mettre une description ici
135
+ expander.image("https://www.creditfoncier.cm/images/revslider/uploads/slides-1bis_1.jpg")#image qui parle du CFC avec la main et le maison
136
+
137
+
138
+
139
+ #bande deroulante pour les services qu'offre le cfc
140
+ expander = st.expander("SERVICES QU'OFFRE CreditGuard Pro")
141
+ expander.write("""
142
+ -I- la classification des individus à risque ou pas pour le remboursement d'un credit reçu.
143
+ """)# mettre une description ici
144
+ 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=")
145
+ expander.write("""
146
+
147
+
148
+
149
+ """)
150
+ expander.write("""
151
+ -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
152
+ """)
153
+ expander.image("cercle de risque.png")
154
+ expander = st.expander("GUIDE D'UTILISATION")
155
+ expander.write("""
156
+
157
+ """)# mettre une description ici
158
+ expander.write("Étape 1 (authentification)")
159
+ expander.write("""-------""")
160
+ expander.image("aide1.JPG")
161
+ expander.write("""-------""")
162
+ expander.write("Étape 2 (authentification)")
163
+ expander.write("""-------""")
164
+ expander.image("aide2.JPG")
165
+ expander.write("""-------""")
166
+ expander.write("Étape 3 (Accuiel après)")
167
+ expander.write("""-------""")
168
+ expander.image("aide3.JPG")
169
+ expander.write("""-------""")
170
+ expander.write("Étape 4 (pour la barre de sélection des menus )")
171
+ expander.write("""-------""")
172
+ expander.image("aide4.JPG")
173
+ expander.write("""-------""")
174
+ expander.write("Étape 5")
175
+ expander.write("""-------""")
176
+ expander.image("aide5.JPG")
177
+ expander.write("""-------""")
178
+ expander.write("Étape 6 (selection d'un menu")
179
+ expander.write("""-------""")
180
+ expander.image("aide6.JPG")
181
+ expander.write("""-------""")
182
+ expander.write("Étape 7 (Exemple de menu : menu CLASSIFICATION)")
183
+ expander.write("""-------""")
184
+ expander.image("aide7.JPG")
185
+
186
+
187
+
188
+ #page
189
+
190
+ #menu DATA ANALYSIS
191
+
192
+ if choice == "ANALYSE DES DONNÉES":
193
+ #image de font
194
+
195
+ page_bg_img = f"""
196
+ <style>
197
+ [data-testid="stAppViewContainer"] > .main {{
198
+ background-image: url("https://cdn.pixabay.com/photo/2017/02/26/12/38/sunset-2100140_640.jpg");
199
+ background-size: 700%;
200
+ background-position: top left;
201
+ background-repeat: no-repeat;
202
+ background-attachment: local;
203
+ }}
204
+
205
+ [data-testid="stSidebar"] > div:first-child {{
206
+ background-image: url("data:image/png;base64,{img}");
207
+ background-position: top lef;
208
+ background-repeat: no-repeat;
209
+ background-attachment: fixed;
210
+ }}
211
+
212
+ [data-testid="stHeader"] {{
213
+ background: rgba(0,0,0,0);
214
+ }}
215
+
216
+ [data-testid="stToolbar"] {{
217
+ right: 2rem;
218
+ }}
219
+ </style>
220
+ """
221
+ st.markdown(page_bg_img, unsafe_allow_html=True)
222
+
223
+ st.markdown("<h1 style='text-align:center;color: red;'>ANALYSE DE DONNÉES </h1>",unsafe_allow_html=True)
224
+ st.write ("<br><br>",unsafe_allow_html=True)
225
+ tb, tb1, tb2 = st.tabs([":clipboard: Dataset",":bar_chart: summary",":chart_with_upwards_trend: correlation"])
226
+ data = load_data("credit_risk_dataset.csv")
227
+
228
+ with tb: #display les 5 premières lignes de notre dataset
229
+ st.subheader("Credit risk Dataset")
230
+ st.write(data.head(10))
231
+ st.write("""-------""")
232
+ 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")
233
+ st.write("- Person_age: représente l'âge des individus")
234
+ st.write("- Person_icome: représente le revenu annuel")
235
+ st.write("- Person_home_ownership: représente l'accesion à al propriété.")
236
+ st.write("- Preson_emp_length: représente la durée de l'emploi (en années)")
237
+ st.write("- loan_intent: représente l'intention de prêt")
238
+ st.write("- loan_grade: représente la catégorie de prêt")
239
+ st.write("- loan_amnt: représente le montant du prêt")
240
+ st.write("- loan_int_rate: représente le taux d'intérêt")
241
+ st.write("- loan_status: représente le statu du prêt ( accorder ou pas)")
242
+ st.write("- loan_percent_income: représente le pourcentage de revenu")
243
+ st.write("- loan_person_default_on_file: représente le défaut historique")
244
+ st.write("- loan_person_cred_hist_length: représente la durée de l'historique de crédit")
245
+ st.write("""-------""")
246
+
247
+
248
+ with tb1:
249
+
250
+ #AFFICHER LE SUMMARY
251
+ st.subheader("TABLEAU DE SUMMARY ")
252
+ st.write(data.describe().head(8))
253
+ st.write("""-------""")
254
+ 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.")
255
+ st.write("""-------""")
256
+ 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.")
257
+ st.write("""-------""")
258
+ 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).")
259
+ st.write("""-------""")
260
+ 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")
261
+ st.write("""-------""")
262
+ 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")
263
+ st.write("""-------""")
264
+ 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")
265
+ st.write("""-------""")
266
+ 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.")
267
+
268
+ #AFFICHER LA MATRIXE DE CORELATION
269
+ with tb2:
270
+ st.subheader("MATRICE DE CORRÉLATION")
271
+ fig = plt.figure(figsize=(15,15))
272
+ st.write(sns.heatmap(data.corr(), annot=True))
273
+ st.pyplot(fig)
274
+
275
+ st.write("""-------""")
276
+ 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.")
277
+ st.write("- Elle identifi des relations entre les variable")
278
+ st.write("- Sélectionne des caractéristiques")
279
+ st.write("- Visualise des relations")
280
+ st.write("- Détecte des anomalies")
281
+ st.write("- Effectue une prise de décision")
282
+ st.write("""-------""")
283
+
284
+
285
+ # afficher la figure
286
+
287
+ #fig , ax = plt.histplot()
288
+ #ax.bar(data["loan_amnt"], data["person_age"])
289
+ #plt.xlabel("person_age")
290
+ #plt.ylabel("loan_amnt")
291
+ #plt.title('Presentation.......')
292
+ #afficher le graphique
293
+
294
+ #menu DATA VISUALISATION
295
+
296
+ if choice == "VISUALISATION":
297
+
298
+ #image de font
299
+
300
+ page_bg_img = f"""
301
+ <style>
302
+ [data-testid="stAppViewContainer"] > .main {{
303
+ background-image: url("https://cdn.pixabay.com/photo/2017/10/05/10/59/background-2819026_640.jpg");
304
+ background-size: 700%;
305
+ background-position: center;
306
+ background-repeat: no-repeat;
307
+ background-attachment: local;
308
+ }}
309
+
310
+ [data-testid="stSidebar"] > div:first-child {{
311
+ background-image: url("data:image/png;base64,{img}");
312
+ background-position: top lef;
313
+ background-repeat: no-repeat;
314
+ background-attachment: fixed;
315
+ }}
316
+
317
+ [data-testid="stHeader"] {{
318
+ background: rgba(0,0,0,0);
319
+ }}
320
+
321
+ [data-testid="stToolbar"] {{
322
+ right: 2rem;
323
+ }}
324
+ </style>
325
+ """
326
+ st.markdown(page_bg_img, unsafe_allow_html=True)
327
+
328
+ st.markdown("<h1 style='text-align:center;color: red;'>VISUALISATION GRAPHIQUE </h1>",unsafe_allow_html=True)
329
+ data = load_data("credit_risk_dataset.csv")
330
+ st.write(data.head(5))
331
+
332
+ #representation du Countplot
333
+ if st.checkbox("Countplot"):
334
+ #parametres de visualisation
335
+ x_variable = st.selectbox("variable X",data.columns)
336
+ #y_variable = st.selectbox("variable Y",data.columns)
337
+ #color_variable = st.selectbox("variable de couleur",data.columns)
338
+ #crée le graphique
339
+ fig = plt.figure(figsize = (13,13))
340
+ sns.countplot(x=x_variable,data=data)
341
+ st.pyplot(fig)
342
+
343
+ #representation du scatterplot
344
+ if st.checkbox(" REPRESENTATION "):
345
+ fig = plt.figure(figsize = (8,8))
346
+ data = load_data('credit_risk_dataset.csv')
347
+ sns.scatterplot(x="person_age",y="loan_amnt",data=data,hue="loan_status")
348
+ st.pyplot(fig)
349
+
350
+
351
+ #representation de l'importance des colonnes
352
+ if st.checkbox("Importance des colonnes"):
353
+ #visualiser l'importance des colonnes
354
+ model=joblib.load('credit_risk_prop.pkl')
355
+ feature_importances = model.feature_importances_
356
+ #recupération des noms de colonnes
357
+ column_names = data.columns
358
+ #creation d'un dictionnaire pour assoicier chaque colonne à son importance
359
+ feature_importances_dict = dict(zip(column_names, feature_importances))
360
+ #tri des colonnes par importance décroissante
361
+ sorted_features = sorted(feature_importances_dict.items(),key = lambda x:[1], reverse=True)
362
+
363
+ #extration des noms de colonnes trié et de leurs importances
364
+ sorted_columns, sorted_importances = zip(*sorted_features)
365
+ fig, ax = plt.subplots (figsize=(10,6))
366
+ ax.bar(sorted_columns, sorted_importances)
367
+ ax.set_xticklabels(sorted_columns, rotation = 90)
368
+ ax.set_xlabel('colonnes')
369
+ ax.set_ylabel('Importance')
370
+ ax.set_title ('Importance des colonnes')
371
+ #affichage de la figure
372
+ st.pyplot(fig)
373
+
374
+ #menu Prediction Score_risK
375
+ if choice == "CLASSIFICATION":
376
+ page_bg_img = f"""
377
+ <style>
378
+ [data-testid="stAppViewContainer"] > .main {{
379
+ background-image: url("https://images.unsplash.com/photo-1501426026826-31c667bdf23d");
380
+ background-size: 250%;
381
+ background-position: top left;
382
+ background-repeat: no-repeat;
383
+ background-attachment: local;
384
+ }}
385
+
386
+ [data-testid="stSidebar"] > div:first-child {{
387
+ background-image: url("data:image/png;base64,{img}");
388
+ background-position: top left;
389
+ background-repeat: no-repeat;
390
+ background-attachment: fixed;
391
+ }}
392
+
393
+ [data-testid="stHeader"] {{
394
+ background: rgba(0,0,0,0);
395
+ }}
396
+
397
+ [data-testid="stToolbar"] {{
398
+ right: 2rem;
399
+ }}
400
+ </style>
401
+ """
402
+ st.markdown(page_bg_img, unsafe_allow_html=True)
403
+ st.markdown("<h1 style='text-align:center;color: red;'>CLASSIFICATION DES INDIVIDUS </h1>",unsafe_allow_html=True)
404
+
405
+ #inporter un data set pour faire une classification
406
+
407
+ uploaded_file = st.sidebar.file_uploader("Importer un le DATASET", type=["csv"])
408
+ if uploaded_file is not None:
409
+ data = load_data(uploaded_file)
410
+
411
+ from pycaret.classification import *
412
+
413
+ # Charger les données
414
+ #data = pd.read_csv('credit_risk_predict.csv')
415
+
416
+ # Initialiser l'environnement de classification
417
+ clf = setup(data=data, target='loan_status', session_id=123)
418
+
419
+ # Comparer les modèles
420
+ #compare_models()
421
+
422
+ # Créer le modèle
423
+ #model = create_model('lightgbm')
424
+ model = joblib.load("credit.pkl")
425
+
426
+ # Afficher les performances du modèle
427
+ #plot_model(model, plot='auc')
428
+
429
+ # Prédire les valeurs sur de nouvelles données
430
+ predictions = predict_model(model)
431
+
432
+ # Afficher les prédictions
433
+ predictions.prediction_label.replace(0, "Crédit accordable", inplace = True)
434
+ predictions.prediction_label.replace(1, "Credit à risque",inplace = True)
435
+ st.write(predictions)
436
+
437
+ #pour télécharger le dataset deja classé
438
+ def filedownload(data):
439
+ csv = data.to_csv(index=False)
440
+ b64 = base64.b64encode(csv.encode()).decode() # strings <-> bytes conversions
441
+ href = f'<a href="data:file/csv;base64,{b64}" download="credit_risk_dataset_1.csv">Download CSV File</a>'
442
+ return href
443
+ button = st.button("Download (télécharger)")
444
+ if button:
445
+ st.markdown(filedownload(predictions), unsafe_allow_html=True)
446
+
447
+
448
+
449
+
450
+ #menu Prédiction
451
+ if choice == "PRÉDICTION":
452
+
453
+ #image de font
454
+
455
+ page_bg_img = f"""
456
+ <style>
457
+ [data-testid="stAppViewContainer"] > .main {{
458
+ background-image: url("https://images.unsplash.com/photo-1501426026826-31c667bdf23d");
459
+ background-size: 250%;
460
+ background-position: top left;
461
+ background-repeat: no-repeat;
462
+ background-attachment: local;
463
+ }}
464
+
465
+ [data-testid="stSidebar"] > div:first-child {{
466
+ background-image: url("data:image/png;base64,{img}");
467
+ background-position: top left;
468
+ background-repeat: no-repeat;
469
+ background-attachment: fixed;
470
+ }}
471
+
472
+ [data-testid="stHeader"] {{
473
+ background: rgba(0,0,0,0);
474
+ }}
475
+
476
+ [data-testid="stToolbar"] {{
477
+ right: 2rem;
478
+ }}
479
+ </style>
480
+ """
481
+ st.markdown(page_bg_img, unsafe_allow_html=True)
482
+
483
+ model = joblib.load("credit.pkl")
484
+
485
+ df = pd.read_csv("credit_risk_dataset.csv")
486
+ #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"]
487
+
488
+ 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"]
489
+
490
+ st.title("Prédiction du ristque de crédit")
491
+ st.write("Remplissez les champs")
492
+
493
+ user_input = []
494
+
495
+ for feature in selected_features:
496
+ if feature == "person_home_ownership" or feature == "loan_intent" or feature == "loan_grade" or feature =="cb_person_default_on_file":
497
+ value = st.text_input(f"Entrez la valeur ppour {feature}")
498
+ else:
499
+ value = st.number_input (f"Entrez la valeur ppour {feature}")
500
+ user_input.append(value)
501
+
502
+ user_data = pd.DataFrame([user_input], columns=selected_features)
503
+
504
+ st.subheader('User Input parameters')
505
+ st.write(user_data)
506
+
507
+ if st.button("Prediction"):
508
+ prediction = model.predict(user_data)
509
+ prediction_proba = model.predict_proba(user_data)
510
+ st.write("la prédiction est : ", prediction )
511
+
512
+ if prediction == 1:
513
+ st.write("positif")
514
+ else:
515
+ st.write("negative")
516
+
517
+ st.subheader('Prediction Probability')
518
+ st.write(prediction_proba)
519
+ # value = st.number_input(f"Entrez la valeur pour {feature}")
520
+ # user_input.append(value)
521
+
522
+
523
+ #tab1, tab2 = st.tabs([":clipboard: Data",":bar_chart: Visualisation", ":angry: :smile: Prediction"])
524
+ #uploaded_file = st.sidebar.file_uploader("Importer un le DATASET", type=["csv"])
525
+ #if uploaded_file is not None:
526
+ # df = load_data(uploaded_file)
527
+ #
528
+ # with tab1:
529
+ # st.subheader("Loaded dataset")
530
+ # st.write(df)
531
+
532
+ # with tab2:
533
+ # st.subheader("REPRESENTATION")
534
+
535
+ #with tab3:
536
+ # data =load_model("credit_risk_prop")
537
+ # prediction = data.predict(df)
538
+ # st.subheader('Prediction')
539
+ # pp = pd.DataFrame(prediction,columns=["Prediction"])
540
+ # ndf = pd.concat([df,pp],axis=1)
541
+ # ndf.Prediction.replace(0, "NO Credit_Risk", inplace = True)
542
+ # ndf.Prediction.replace(1, "Credit_Risk", inplace = True)
543
+ # st.write(ndf)
544
+ # def filedownload(df):
545
+ # csv = df.to_csv(index=False)
546
+ # b64 = base64.b64encode(csv.encode()).decode() # strings <-> bytes conversions
547
+ # href = f'<a href="data:file/csv;base64,{b64}" download="credit_risk_dataset_prop.csv">Download CSV File</a>'
548
+ # return href
549
+ # button = st.button("Download (telecharger)")
550
+ # if button:
551
+ # st.markdown(filedownload(ndf), unsafe_allow_html=True)
552
+
553
+
554
+ elif not authentication_status:
555
+ with info:
556
+ st.error('Incorrect Password or username')
557
+ else:
558
+ with info:
559
+ st.warning('Please feed in your credentials')
560
+ else:
561
+ with info:
562
+ st.warning('Username does not exist, Please Sign up')
563
+
564
+
565
+ except:
566
+ st.success('Refresh Page')