Djohell commited on
Commit
a4eb225
·
verified ·
1 Parent(s): 34ed5d2

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +44 -60
src/streamlit_app.py CHANGED
@@ -14,6 +14,10 @@ AWS_SECRET_ACCESS_KEY = os.getenv("AWS_SECRET_ACCESS_KEY")
14
  AWS_DEFAULT_REGION = os.getenv("AWS_DEFAULT_REGION", "eu-west-3")
15
  S3_BUCKET_NAME = os.getenv("S3_BUCKET_NAME")
16
 
 
 
 
 
17
  s3 = None
18
  if AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY and S3_BUCKET_NAME:
19
  s3 = boto3.client(
@@ -27,15 +31,23 @@ if AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY and S3_BUCKET_NAME:
27
  @st.cache_data(ttl=600)
28
  def load_csv_from_s3(s3_client, bucket_name, key):
29
  local_path = f"/tmp/{key.split('/')[-1]}"
30
- s3_client.download_file(bucket_name, key, local_path)
31
- return pd.read_csv(local_path)
 
 
 
 
32
 
33
  # --- CACHE POUR LES IMAGES ---
34
  @st.cache_resource(ttl=3600)
35
  def load_image_from_s3(s3_client, bucket_name, key):
36
  local_path = f"/tmp/{key.split('/')[-1]}"
37
- s3_client.download_file(bucket_name, key, local_path)
38
- return local_path
 
 
 
 
39
 
40
  # --- CONFIG PAGE ---
41
  st.set_page_config(page_title="Dashboard Fraude", page_icon="🚨", layout="wide")
@@ -50,80 +62,52 @@ if selected_page == "Accueil":
50
  st.markdown("Bienvenue sur le dashboard de suivi du projet de détection automatisée des fraudes bancaires.")
51
  st.markdown("### Architecture du projet")
52
 
53
- # Affichage image architecture
54
- architecture_img = None
55
- if s3:
56
- try:
57
- architecture_img = load_image_from_s3(s3, S3_BUCKET_NAME, "images/architecture.png")
58
- except:
59
- st.warning("Impossible de charger l'image depuis S3")
60
-
61
  if architecture_img:
62
  st.image(architecture_img, use_container_width=False)
63
  else:
64
  st.info("Placez `architecture.png` en local ou sur S3 pour affichage.")
65
 
66
- st.markdown("---")
67
- st.markdown("""
68
- **Principes clés de l'architecture :**
69
- - Entraînement initial du modèle sur dataset de base
70
- - Stockage des modèles avec MLflow et S3
71
- - Déploiement via FastAPI
72
- - Orchestration avec Airflow
73
- - Notifications email quotidiennes
74
- """)
75
-
76
  # --- PAGE 2 : DATASET PRINCIPAL ---
77
  elif selected_page == "Dataset principal":
78
  st.header("Exploration du dataset principal")
79
 
80
- try:
81
  df = load_csv_from_s3(s3, S3_BUCKET_NAME, "data/fraudTest.csv")
82
- st.subheader("Aperçu des données")
83
- st.dataframe(df.head(5))
84
-
85
- # Répartition des paiements frauduleux
86
- fraud_counts = df["is_fraud"].value_counts()
87
- fraud_percent = df["is_fraud"].value_counts(normalize=True) * 100
88
- df_plot = pd.DataFrame({
89
- "Fraude": fraud_counts.index.astype(str),
90
- "Nombre": fraud_counts.values,
91
- "Pourcentage": fraud_percent.values
92
- })
93
- color_map = {'0': 'royalblue', '1': 'crimson'}
94
- fig = px.pie(df_plot, names='Fraude', values='Nombre', color='Fraude', color_discrete_map=color_map)
95
- fig.update_traces(textinfo='label+percent+value', pull=[0.05]*len(df_plot))
96
- st.plotly_chart(fig, use_container_width=True)
97
- st.markdown(f"👉 Taux de fraude : **{df['is_fraud'].mean()*100:.2f}%**")
98
-
99
- # Image des features principales
100
- features_img = None
101
- if s3:
102
- try:
103
- features_img = load_image_from_s3(s3, S3_BUCKET_NAME, "images/features.png")
104
- except:
105
- st.warning("Impossible de charger l'image features depuis S3")
106
- if features_img:
107
- st.image(features_img, use_container_width=False)
108
- except Exception as e:
109
- st.error(f"Erreur lors du chargement du dataset : {e}")
110
 
111
  # --- PAGE 3 : REPORTING S3 ---
112
  elif selected_page == "Reporting S3":
113
  st.header("Reporting sur un dataset S3")
114
- st.info("Téléversez le dataset ou renseignez le chemin S3")
115
 
116
- s3_key_input = st.text_input("Nom du fichier dans S3", value="backup/all_payments.csv")
117
- if s3_key_input:
118
- try:
119
- df_s3 = load_csv_from_s3(s3, S3_BUCKET_NAME, s3_key_input)
120
  st.subheader("Aperçu des données")
121
  st.dataframe(df_s3.head(5))
122
 
123
- # Histogramme des montants
124
  if "amt" in df_s3.columns:
125
  fig = px.histogram(df_s3, x="amt", nbins=50, title="Distribution des montants")
126
  st.plotly_chart(fig, use_container_width=True)
127
- except Exception as e:
128
- st.error(f"Impossible de charger le fichier S3 : {e}")
129
-
 
14
  AWS_DEFAULT_REGION = os.getenv("AWS_DEFAULT_REGION", "eu-west-3")
15
  S3_BUCKET_NAME = os.getenv("S3_BUCKET_NAME")
16
 
17
+ # --- CONFIG HUGGING FACE ---
18
+ HF_API_TOKEN = os.getenv("HF_API_TOKEN")
19
+
20
+ # --- CLIENT S3 ---
21
  s3 = None
22
  if AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY and S3_BUCKET_NAME:
23
  s3 = boto3.client(
 
31
  @st.cache_data(ttl=600)
32
  def load_csv_from_s3(s3_client, bucket_name, key):
33
  local_path = f"/tmp/{key.split('/')[-1]}"
34
+ try:
35
+ s3_client.download_file(bucket_name, key, local_path)
36
+ return pd.read_csv(local_path)
37
+ except Exception as e:
38
+ st.error(f"Erreur lors du téléchargement depuis S3 : {e}")
39
+ return pd.DataFrame()
40
 
41
  # --- CACHE POUR LES IMAGES ---
42
  @st.cache_resource(ttl=3600)
43
  def load_image_from_s3(s3_client, bucket_name, key):
44
  local_path = f"/tmp/{key.split('/')[-1]}"
45
+ try:
46
+ s3_client.download_file(bucket_name, key, local_path)
47
+ return local_path
48
+ except Exception as e:
49
+ st.warning(f"Impossible de charger l'image depuis S3 : {e}")
50
+ return None
51
 
52
  # --- CONFIG PAGE ---
53
  st.set_page_config(page_title="Dashboard Fraude", page_icon="🚨", layout="wide")
 
62
  st.markdown("Bienvenue sur le dashboard de suivi du projet de détection automatisée des fraudes bancaires.")
63
  st.markdown("### Architecture du projet")
64
 
65
+ architecture_img = load_image_from_s3(s3, S3_BUCKET_NAME, "images/architecture.png") if s3 else None
 
 
 
 
 
 
 
66
  if architecture_img:
67
  st.image(architecture_img, use_container_width=False)
68
  else:
69
  st.info("Placez `architecture.png` en local ou sur S3 pour affichage.")
70
 
 
 
 
 
 
 
 
 
 
 
71
  # --- PAGE 2 : DATASET PRINCIPAL ---
72
  elif selected_page == "Dataset principal":
73
  st.header("Exploration du dataset principal")
74
 
75
+ if s3:
76
  df = load_csv_from_s3(s3, S3_BUCKET_NAME, "data/fraudTest.csv")
77
+ if not df.empty:
78
+ st.subheader("Aperçu des données")
79
+ st.dataframe(df.head(5))
80
+
81
+ # Répartition des paiements frauduleux
82
+ fraud_counts = df["is_fraud"].value_counts()
83
+ fraud_percent = df["is_fraud"].value_counts(normalize=True) * 100
84
+ df_plot = pd.DataFrame({
85
+ "Fraude": fraud_counts.index.astype(str),
86
+ "Nombre": fraud_counts.values,
87
+ "Pourcentage": fraud_percent.values
88
+ })
89
+ color_map = {'0': 'royalblue', '1': 'crimson'}
90
+ fig = px.pie(df_plot, names='Fraude', values='Nombre', color='Fraude', color_discrete_map=color_map)
91
+ fig.update_traces(textinfo='label+percent+value', pull=[0.05]*len(df_plot))
92
+ st.plotly_chart(fig, use_container_width=True)
93
+ st.markdown(f"Taux de fraude : **{df['is_fraud'].mean()*100:.2f}%**")
94
+ else:
95
+ st.warning("Impossible de charger le dataset principal depuis S3.")
 
 
 
 
 
 
 
 
 
96
 
97
  # --- PAGE 3 : REPORTING S3 ---
98
  elif selected_page == "Reporting S3":
99
  st.header("Reporting sur un dataset S3")
100
+ st.info("Renseignez le chemin complet du fichier S3 (ex: backup/all_payments.csv)")
101
 
102
+ s3_key_input = st.text_input("S3 Key")
103
+ if s3_key_input and s3:
104
+ df_s3 = load_csv_from_s3(s3, S3_BUCKET_NAME, s3_key_input)
105
+ if not df_s3.empty:
106
  st.subheader("Aperçu des données")
107
  st.dataframe(df_s3.head(5))
108
 
 
109
  if "amt" in df_s3.columns:
110
  fig = px.histogram(df_s3, x="amt", nbins=50, title="Distribution des montants")
111
  st.plotly_chart(fig, use_container_width=True)
112
+ else:
113
+ st.warning("Impossible de charger ce fichier depuis S3.")