ericjedha commited on
Commit
4e8729a
·
verified ·
1 Parent(s): e6c131d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +144 -14
app.py CHANGED
@@ -1,9 +1,7 @@
1
  import streamlit as st
2
  import pandas as pd
3
- import plotly.express as px
4
  import plotly.graph_objects as go
5
  from sqlalchemy import create_engine, text
6
- from datetime import datetime, timedelta
7
  import os
8
 
9
  # ========================== CONFIGURATION ==========================
@@ -55,7 +53,8 @@ def load_all_data():
55
  def load_last_24h_data():
56
  engine = get_db_connection()
57
  query = text("""
58
- SELECT trans_num, merchant, category, amt, gender, city, pred_is_fraud, created_at
 
59
  FROM fraud_predictions
60
  WHERE created_at >= NOW() - INTERVAL '24 HOURS'
61
  ORDER BY created_at DESC
@@ -68,9 +67,10 @@ def load_last_24h_data():
68
  def load_last_7_days_stats():
69
  engine = get_db_connection()
70
  query = text("""
71
- SELECT DATE(created_at) as date,
72
- SUM(CASE WHEN pred_is_fraud = 1 THEN 1 ELSE 0 END) as frauds,
73
- SUM(CASE WHEN pred_is_fraud = 0 THEN 1 ELSE 0 END) as no_frauds
 
74
  FROM fraud_predictions
75
  WHERE created_at >= NOW() - INTERVAL '7 DAYS'
76
  GROUP BY DATE(created_at)
@@ -80,18 +80,149 @@ def load_last_7_days_stats():
80
  df = pd.read_sql(query, conn)
81
  return df
82
 
83
- # ========================== PAGES ==========================
84
  def page_dashboard():
85
- # ... ton code existant pour le dashboard ...
86
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
 
 
88
  def page_frauds():
89
- # ... ton code existant pour la page fraudes ...
90
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
 
 
92
  def page_no_frauds():
93
- # ... ton code existant pour la page non-fraudes ...
94
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
 
96
  # ========================== ROUTING VIA QUERY PARAM ==========================
97
  query_params = st.query_params
@@ -121,7 +252,6 @@ def main():
121
  Dashboard de détection de fraude en temps réel.
122
 
123
  **Refresh** : Cliquez sur le bouton pour actualiser les données.
124
-
125
  **Données** : Dernières 24h pour les pages de détail.
126
  """)
127
 
 
1
  import streamlit as st
2
  import pandas as pd
 
3
  import plotly.graph_objects as go
4
  from sqlalchemy import create_engine, text
 
5
  import os
6
 
7
  # ========================== CONFIGURATION ==========================
 
53
  def load_last_24h_data():
54
  engine = get_db_connection()
55
  query = text("""
56
+ SELECT
57
+ trans_num, merchant, category, amt, gender, city, pred_is_fraud, created_at
58
  FROM fraud_predictions
59
  WHERE created_at >= NOW() - INTERVAL '24 HOURS'
60
  ORDER BY created_at DESC
 
67
  def load_last_7_days_stats():
68
  engine = get_db_connection()
69
  query = text("""
70
+ SELECT
71
+ DATE(created_at) as date,
72
+ SUM(CASE WHEN pred_is_fraud = 1 THEN 1 ELSE 0 END) as frauds,
73
+ SUM(CASE WHEN pred_is_fraud = 0 THEN 1 ELSE 0 END) as no_frauds
74
  FROM fraud_predictions
75
  WHERE created_at >= NOW() - INTERVAL '7 DAYS'
76
  GROUP BY DATE(created_at)
 
80
  df = pd.read_sql(query, conn)
81
  return df
82
 
83
+ # ========================== PAGE: DASHBOARD ==========================
84
  def page_dashboard():
85
+ st.title("🕵🏻 Fraud Detection Dashboard")
86
+
87
+ # Bouton refresh
88
+ if st.button("🔄 Refresh Data", type="primary"):
89
+ st.cache_data.clear()
90
+ st.rerun()
91
+
92
+ # Charger les données
93
+ with st.spinner("Chargement des données..."):
94
+ df_all = load_all_data()
95
+ df_7days = load_last_7_days_stats()
96
+
97
+ if df_all.empty:
98
+ st.warning("⚠️ Aucune donnée disponible dans la base de données")
99
+ return
100
+
101
+ # ========================== MÉTRIQUES ==========================
102
+ total_frauds = (df_all['pred_is_fraud'] == 1).sum()
103
+ total_no_frauds = (df_all['pred_is_fraud'] == 0).sum()
104
+
105
+ # Calcul du montant économisé
106
+ saved_amount = df_all[df_all['pred_is_fraud'] == 1]['amt'].sum() * 1.5
107
+
108
+ col1, col2, col3 = st.columns(3)
109
+
110
+ with col1:
111
+ st.markdown(f"""
112
+ <div style="background-color: {COLOR_FRAUD}; padding: 20px; border-radius: 10px; text-align: center;">
113
+ <h3 style="color: white;">🚨 Frauds</h3>
114
+ <h1 style="color: white;">{total_frauds}</h1>
115
+ </div>
116
+ """, unsafe_allow_html=True)
117
+
118
+ with col2:
119
+ st.markdown(f"""
120
+ <div style="background-color: {COLOR_NO_FRAUD}; padding: 20px; border-radius: 10px; text-align: center;">
121
+ <h3 style="color: white;">✅ No Frauds</h3>
122
+ <h1 style="color: white;">{total_no_frauds}</h1>
123
+ </div>
124
+ """, unsafe_allow_html=True)
125
+
126
+ with col3:
127
+ st.markdown(f"""
128
+ <div style="background-color: {COLOR_SAVED}; padding: 20px; border-radius: 10px; text-align: center;">
129
+ <h3 style="color: white;">💰 Saved Amount</h3>
130
+ <h1 style="color: white;">${saved_amount:,.2f}</h1>
131
+ </div>
132
+ """, unsafe_allow_html=True)
133
+
134
+ st.markdown("<br>", unsafe_allow_html=True)
135
+
136
+ # ========================== GRAPHIQUES ==========================
137
+ col_pie, col_saved_detail = st.columns([1, 1])
138
+
139
+ with col_pie:
140
+ fig_pie = go.Figure(data=[go.Pie(
141
+ labels=['Frauds', 'No Frauds'],
142
+ values=[total_frauds, total_no_frauds],
143
+ marker=dict(colors=[COLOR_FRAUD, COLOR_NO_FRAUD]),
144
+ hole=0.4,
145
+ textinfo='label+percent',
146
+ textfont_size=14
147
+ )])
148
+ fig_pie.update_layout(title="Distribution Fraud vs No Fraud", showlegend=True, height=400)
149
+ st.plotly_chart(fig_pie, use_container_width=True)
150
+
151
+ with col_saved_detail:
152
+ total_fraud_amount = df_all[df_all['pred_is_fraud'] == 1]['amt'].sum()
153
+ additional_costs = total_fraud_amount * 0.5
154
+
155
+ st.markdown("### 💵 Breakdown of Saved Amount")
156
+ st.markdown(f"""
157
+ - **Total Fraud Amounts**: ${total_fraud_amount:,.2f}
158
+ - **Estimated Additional Costs**: ${additional_costs:,.2f}
159
+ - **Total Saved**: ${saved_amount:,.2f}
160
+ """)
161
+
162
+ fig_breakdown = go.Figure(data=[
163
+ go.Bar(name='Fraud Amount', x=['Saved'], y=[total_fraud_amount], marker_color=COLOR_FRAUD),
164
+ go.Bar(name='Additional Costs', x=['Saved'], y=[additional_costs], marker_color=COLOR_SAVED)
165
+ ])
166
+ fig_breakdown.update_layout(barmode='stack', height=250, yaxis_title="Amount ($)")
167
+ st.plotly_chart(fig_breakdown, use_container_width=True)
168
+
169
+ # ========================== GRAPHIQUE EMPILÉ 7 JOURS ==========================
170
+ st.markdown("### 📊 Fraud Trend - Last 7 Days")
171
+
172
+ if not df_7days.empty:
173
+ fig_trend = go.Figure()
174
+ fig_trend.add_trace(go.Bar(name='Frauds', x=df_7days['date'], y=df_7days['frauds'], marker_color=COLOR_FRAUD))
175
+ fig_trend.add_trace(go.Bar(name='No Frauds', x=df_7days['date'], y=df_7days['no_frauds'], marker_color=COLOR_NO_FRAUD))
176
+ fig_trend.update_layout(barmode='stack', height=400, hovermode='x unified')
177
+ st.plotly_chart(fig_trend, use_container_width=True)
178
+ else:
179
+ st.info("Pas encore de données sur 7 jours")
180
 
181
+ # ========================== PAGE: FRAUDES (24h) ==========================
182
  def page_frauds():
183
+ st.title("🚨 Fraudes Détectées (Dernières 24h)")
184
+
185
+ if st.button("🔄 Refresh Data", type="primary"):
186
+ st.cache_data.clear()
187
+ st.rerun()
188
+
189
+ with st.spinner("Chargement des fraudes..."):
190
+ df = load_last_24h_data()
191
+ df_frauds = df[df['pred_is_fraud'] == 1]
192
+
193
+ st.markdown(f"""
194
+ <div style="background-color: {COLOR_FRAUD}; padding: 15px; border-radius: 10px; text-align: center;">
195
+ <h2 style="color: white;">🚨 {len(df_frauds)} Fraudes détectées</h2>
196
+ </div>
197
+ """, unsafe_allow_html=True)
198
+
199
+ if df_frauds.empty:
200
+ st.success("✅ Aucune fraude détectée dans les dernières 24h !")
201
+ else:
202
+ st.dataframe(df_frauds.sort_values('created_at', ascending=False), use_container_width=True, height=600)
203
 
204
+ # ========================== PAGE: NON FRAUDES (24h) ==========================
205
  def page_no_frauds():
206
+ st.title("✅ Transactions Légitimes (Dernières 24h)")
207
+
208
+ if st.button("🔄 Refresh Data", type="primary"):
209
+ st.cache_data.clear()
210
+ st.rerun()
211
+
212
+ with st.spinner("Chargement des transactions légitimes..."):
213
+ df = load_last_24h_data()
214
+ df_no_frauds = df[df['pred_is_fraud'] == 0]
215
+
216
+ st.markdown(f"""
217
+ <div style="background-color: {COLOR_NO_FRAUD}; padding: 15px; border-radius: 10px; text-align: center;">
218
+ <h2 style="color: white;">✅ {len(df_no_frauds)} Transactions légitimes</h2>
219
+ </div>
220
+ """, unsafe_allow_html=True)
221
+
222
+ if df_no_frauds.empty:
223
+ st.warning("⚠️ Aucune transaction légitime dans les dernières 24h")
224
+ else:
225
+ st.dataframe(df_no_frauds.sort_values('created_at', ascending=False), use_container_width=True, height=600)
226
 
227
  # ========================== ROUTING VIA QUERY PARAM ==========================
228
  query_params = st.query_params
 
252
  Dashboard de détection de fraude en temps réel.
253
 
254
  **Refresh** : Cliquez sur le bouton pour actualiser les données.
 
255
  **Données** : Dernières 24h pour les pages de détail.
256
  """)
257