DavidRambeau commited on
Commit
c7a2103
·
verified ·
1 Parent(s): 2ce37bf

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +108 -0
app.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dotenv import load_dotenv
2
+ load_dotenv()
3
+
4
+ import streamlit as st
5
+ import pandas as pd
6
+ import os
7
+ from urllib.error import URLError
8
+ from sqlalchemy import create_engine, text
9
+ from datetime import datetime, timedelta
10
+
11
+ @st.cache_data
12
+ def check_table_exists() -> bool:
13
+ """Check if the transactions table exists in the database"""
14
+ try:
15
+ engine = create_engine(os.environ['BACKEND_STORE_URI'])
16
+ with engine.connect() as conn:
17
+ result = conn.execute(text("""
18
+ SELECT EXISTS (
19
+ SELECT FROM information_schema.tables
20
+ WHERE table_name = 'transactions'
21
+ );
22
+ """))
23
+ return result.scalar()
24
+ except Exception as e:
25
+ st.error(f"Error checking table existence: {str(e)}")
26
+ return False
27
+
28
+ @st.cache_data
29
+ def get_data() -> pd.DataFrame:
30
+ """Fetch transactions from the previous day"""
31
+ try:
32
+ conn = st.connection(
33
+ "postgresql",
34
+ type="sql",
35
+ url=os.environ['BACKEND_STORE_URI']
36
+ )
37
+
38
+ # Use parameterized query for better safety
39
+ yesterday = (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d')
40
+ today = datetime.now().strftime('%Y-%m-%d')
41
+
42
+ query = f"""
43
+ SELECT * FROM transactions
44
+ WHERE trans_date_trans_time >= '{yesterday} 00:00:00'
45
+ AND trans_date_trans_time < '{today} 00:00:00'
46
+ ORDER BY trans_date_trans_time DESC
47
+ """
48
+
49
+ df = conn.query(query)
50
+ return df
51
+ except Exception as e:
52
+ st.error(f"Error fetching data: {str(e)}")
53
+ return pd.DataFrame()
54
+
55
+ JOUR_HIER = (pd.Timestamp.now() - pd.Timedelta(days=1)).strftime('%Y-%m-%d')
56
+ st.title(f"Tableau des transactions bancaires du {JOUR_HIER}")
57
+
58
+ # Check if table exists
59
+ if not check_table_exists():
60
+ st.error("⚠️ La table 'transactions' n'existe pas dans la base de données!")
61
+ st.info("""
62
+ ### Pour créer la table, exécutez:
63
+ ```bash
64
+ python create_database.py
65
+ ```
66
+ Ce script va:
67
+ - Créer la table 'transactions' avec le bon schéma
68
+ - Optionnellement charger des données d'exemple
69
+ """)
70
+ st.stop()
71
+
72
+ try:
73
+ df = get_data()
74
+
75
+ print('Test')
76
+
77
+ if df.empty:
78
+ st.warning(f"⚠️ Aucune transaction trouvée pour le {JOUR_HIER}")
79
+ st.info("Assurez-vous que des transactions ont été chargées dans la base de données pour cette date.")
80
+ else:
81
+ st.success(f"✅ {len(df)} transactions trouvées")
82
+
83
+ st.dataframe(data=df, width="content", hide_index=True)
84
+
85
+ col1, col2 = st.columns(2)
86
+ with col1:
87
+ st.metric(label="Nombre de transactions", value=len(df))
88
+ st.metric(label="Montant total des transactions", value=f"${df['amt'].sum():,.2f}")
89
+ with col2:
90
+ # Check if prediction column exists
91
+ if 'prediction' in df.columns:
92
+ fraud_count = len(df[df['prediction'] == 1])
93
+ fraud_amount = df[df['prediction'] == 1]['amt'].sum()
94
+ st.metric(label="Nombre de transactions frauduleuses", value=fraud_count)
95
+ st.metric(label="Montant total des transactions frauduleuses", value=f"${fraud_amount:,.2f}")
96
+ elif 'is_fraud' in df.columns:
97
+ fraud_count = len(df[df['is_fraud'] == 1])
98
+ fraud_amount = df[df['is_fraud'] == 1]['amt'].sum()
99
+ st.metric(label="Nombre de transactions frauduleuses", value=fraud_count)
100
+ st.metric(label="Montant total des transactions frauduleuses", value=f"${fraud_amount:,.2f}")
101
+ else:
102
+ st.info("Colonne 'prediction' ou 'is_fraud' non trouvée")
103
+
104
+ except URLError as e:
105
+ st.error(f"This demo requires internet access. Connection error: {e.reason}")
106
+ except Exception as e:
107
+ st.error(f"Une erreur s'est produite: {str(e)}")
108
+ st.info("Vérifiez que la variable d'environnement BACKEND_STORE_URI est correctement définie.")