NchourupouoM commited on
Commit
0a888f1
·
verified ·
1 Parent(s): 78c2348

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +104 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,106 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
1
+ # streamlit_app/app.py
 
 
2
  import streamlit as st
3
+ import pandas as pd
4
+ import joblib
5
+ from huggingface_hub import hf_hub_download
6
+
7
+ # --- CONFIGURATION DE LA PAGE ---
8
+ st.set_page_config(
9
+ page_title="Prédiction Maladie Cardiaque",
10
+ page_icon="❤️",
11
+ layout="wide"
12
+ )
13
+
14
+ # --- CHARGEMENT DU MODÈLE ---
15
+ # On utilise le cache de Streamlit pour ne télécharger et charger le modèle qu'une seule fois.
16
+ @st.cache_resource
17
+ def load_model():
18
+ """
19
+ Télécharge et charge le pipeline de modèle depuis le Hub Hugging Face.
20
+ """
21
+ try:
22
+ # Remplacez par votre REPO_ID sur Hugging Face
23
+ repo_id = "NchourupouoM/heart-disease-classifier"
24
+ filename = "heart_disease_pipeline.joblib"
25
+
26
+ model_path = hf_hub_download(repo_id=repo_id, filename=filename)
27
+ pipeline = joblib.load(model_path)
28
+ return pipeline
29
+ except Exception as e:
30
+ st.error(f"Erreur lors du chargement du modèle : {e}")
31
+ return None
32
+
33
+ pipeline = load_model()
34
+
35
+ # --- INTERFACE UTILISATEUR ---
36
+ st.title("🤖 Prédiction du Risque de Maladie Cardiaque")
37
+ st.markdown("Cette application utilise un modèle de Machine Learning pour prédire le risque de maladie cardiaque basé sur les données d'un patient. Entrez les informations dans la barre latérale et cliquez sur 'Prédire'.")
38
+
39
+ # Barre latérale pour les entrées utilisateur
40
+ with st.sidebar:
41
+ st.header("👤 Données du Patient")
42
+
43
+ # Dictionnaires pour les options catégorielles (plus clair pour l'utilisateur)
44
+ sex_options = {0: "Femme", 1: "Homme"}
45
+ cp_options = {0: "Angine typique", 1: "Angine atypique", 2: "Douleur non angineuse", 3: "Asymptomatique"}
46
+ fbs_options = {0: "Non (> 120 mg/dl)", 1: "Oui (<= 120 mg/dl)"}
47
+ restecg_options = {0: "Normal", 1: "Anomalie ST-T", 2: "Hypertrophie ventriculaire gauche"}
48
+ exang_options = {0: "Non", 1: "Oui"}
49
+ slope_options = {0: "Ascendant", 1: "Plat", 2: "Descendant"}
50
+ thal_options = {0: "Normal", 1: "Défaut corrigé", 2: "Défaut réversible"}
51
+
52
+ # Création des widgets de saisie
53
+ age = st.number_input("Âge", min_value=1, max_value=120, value=50)
54
+ sex = st.selectbox("Sexe", options=list(sex_options.keys()), format_func=lambda x: sex_options[x])
55
+ cp = st.selectbox("Type de douleur thoracique (CP)", options=list(cp_options.keys()), format_func=lambda x: cp_options[x])
56
+ trestbps = st.number_input("Pression artérielle au repos (trestbps)", min_value=50, max_value=250, value=120)
57
+ chol = st.number_input("Cholestérol sérique (chol)", min_value=100, max_value=600, value=200)
58
+ fbs = st.selectbox("Glycémie à jeun > 120 mg/dl (fbs)", options=list(fbs_options.keys()), format_func=lambda x: fbs_options[x])
59
+ restecg = st.selectbox("Résultats électrocardiographiques au repos (restecg)", options=list(restecg_options.keys()), format_func=lambda x: restecg_options[x])
60
+ thalach = st.number_input("Fréquence cardiaque maximale atteinte (thalach)", min_value=50, max_value=250, value=150)
61
+ exang = st.selectbox("Angine de poitrine induite par l'exercice (exang)", options=list(exang_options.keys()), format_func=lambda x: exang_options[x])
62
+ oldpeak = st.number_input("Dépression ST induite par l'exercice (oldpeak)", min_value=0.0, max_value=10.0, value=1.0, step=0.1)
63
+ slope = st.selectbox("Pente du segment ST à l'exercice de pointe (slope)", options=list(slope_options.keys()), format_func=lambda x: slope_options[x])
64
+ ca = st.number_input("Nombre de vaisseaux principaux colorés par fluoroscopie (ca)", min_value=0, max_value=4, value=0)
65
+ thal = st.selectbox("Thalassémie (thal)", options=list(thal_options.keys()), format_func=lambda x: thal_options[x])
66
+
67
+ predict_button = st.button("Lancer la Prédiction", type="primary")
68
+
69
+ # --- PRÉDICTION ET AFFICHAGE ---
70
+ if pipeline is not None and predict_button:
71
+ # 1. Créer un DataFrame avec les entrées utilisateur
72
+ # Les noms de colonnes DOIVENT correspondre à ceux utilisés lors de l'entraînement
73
+ input_data = {
74
+ 'age': [age], 'sex': [sex], 'cp': [cp], 'trestbps': [trestbps],
75
+ 'chol': [chol], 'fbs': [fbs], 'restecg': [restecg],
76
+ 'thalach': [thalach], 'exang': [exang], 'oldpeak': [oldpeak],
77
+ 'slope': [slope], 'ca': [ca], 'thal': [thal]
78
+ }
79
+ input_df = pd.DataFrame(input_data)
80
+
81
+ st.subheader("📋 Données fournies pour la prédiction :")
82
+ st.dataframe(input_df)
83
+
84
+ # 2. Faire la prédiction
85
+ prediction = pipeline.predict(input_df)[0]
86
+ prediction_proba = pipeline.predict_proba(input_df)[0]
87
+
88
+ # 3. Afficher le résultat
89
+ st.subheader("🎯 Résultat de la Prédiction")
90
+
91
+ if prediction == 1:
92
+ st.error("🔴 Risque de maladie cardiaque DÉTECTÉ", icon="🚨")
93
+ else:
94
+ st.success("🟢 Faible risque de maladie cardiaque", icon="✅")
95
 
96
+ # Afficher les probabilités
97
+ col1, col2 = st.columns(2)
98
+ with col1:
99
+ st.metric("Probabilité de Faible Risque", f"{prediction_proba[0]*100:.2f}%")
100
+ with col2:
101
+ st.metric("Probabilité de Risque Élevé", f"{prediction_proba[1]*100:.2f}%")
102
+
103
+ st.progress(prediction_proba[1])
104
+
105
+ elif pipeline is None:
106
+ st.warning("Le modèle n'a pas pu être chargé. Veuillez vérifier la connexion ou la configuration du repository Hugging Face.")