cheikhaidev-ui Claude Sonnet 4.6 commited on
Commit
5ae4a65
·
1 Parent(s): c0e7040

chore: remove Supabase integration (database.py, load script, config)

Browse files

Drop src/database.py, scripts/3_load_to_supabase.py and the
SUPABASE_CONFIG block from src/config.py — the app no longer
depends on any Supabase connection.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

Files changed (3) hide show
  1. scripts/3_load_to_supabase.py +0 -111
  2. src/config.py +0 -9
  3. src/database.py +0 -261
scripts/3_load_to_supabase.py DELETED
@@ -1,111 +0,0 @@
1
- """
2
- Chargement des données dans Supabase
3
- À exécuter : python scripts/load_to_supabase.py
4
- """
5
-
6
- import pandas as pd
7
- import requests
8
- import sys
9
- import time
10
- from pathlib import Path
11
-
12
- sys.path.insert(0, str(Path(__file__).parent.parent))
13
- from src.config import SUPABASE_CONFIG
14
-
15
- print("=" * 70)
16
- print("📤 CHARGEMENT SUPABASE")
17
- print("=" * 70)
18
-
19
- # Charger les données
20
- csv_path = Path('data/synthetic/synthetic_data_v2.csv')
21
-
22
- if not csv_path.exists():
23
- print(f"\n❌ Fichier non trouvé : {csv_path}")
24
- print("Exécutez d'abord : python scripts/generate_new_data.py")
25
- sys.exit(1)
26
-
27
- print(f"\n📂 Lecture de {csv_path}...")
28
- df = pd.read_csv(csv_path)
29
- print(f"✅ {len(df)} lignes chargées")
30
-
31
- # Statistiques
32
- print("\n📊 Aperçu des données:")
33
- print(f" Quartiers : {df['quartier'].nunique()}")
34
- for q in sorted(df['quartier'].unique()):
35
- count = len(df[df['quartier'] == q])
36
- print(f" {q:25s}: {count:6d}")
37
-
38
- # Connexion Supabase
39
- url = SUPABASE_CONFIG['url']
40
- key = SUPABASE_CONFIG['key']
41
-
42
- headers = {
43
- 'apikey': key,
44
- 'Authorization': f'Bearer {key}',
45
- 'Content-Type': 'application/json',
46
- 'Prefer': 'return=minimal'
47
- }
48
-
49
- # Charger par batch de 1000 lignes
50
- batch_size = 1000
51
- total_batches = (len(df) + batch_size - 1) // batch_size
52
-
53
- print(f"\n📦 Chargement par batch de {batch_size} lignes...")
54
- print(f" Total batches : {total_batches}")
55
-
56
- success_count = 0
57
- error_count = 0
58
-
59
- for i in range(0, len(df), batch_size):
60
- batch_num = i // batch_size + 1
61
- batch = df[i:i + batch_size]
62
-
63
- # Préparer les données via rename + to_dict (pas d'iterrows)
64
- records = (
65
- batch.rename(columns={'date': 'date_heure', 'coupure': 'prediction'})
66
- [['date_heure', 'quartier', 'temp_celsius', 'humidite_percent',
67
- 'vitesse_vent', 'conso_megawatt', 'prediction']]
68
- .astype({'temp_celsius': float, 'humidite_percent': int,
69
- 'vitesse_vent': float, 'conso_megawatt': int, 'prediction': int})
70
- .to_dict('records')
71
- )
72
-
73
- # Envoyer à Supabase
74
- try:
75
- response = requests.post(
76
- f"{url}/rest/v1/enregistrements",
77
- headers=headers,
78
- json=records,
79
- timeout=30
80
- )
81
-
82
- if response.status_code in [200, 201]:
83
- success_count += len(records)
84
- print(f" ✅ Batch {batch_num}/{total_batches} : {len(records)} lignes")
85
- else:
86
- error_count += len(records)
87
- print(f" ❌ Batch {batch_num}/{total_batches} : Erreur {response.status_code}")
88
- if batch_num == 1:
89
- print(f" {response.text[:200]}")
90
- time.sleep(min(2 ** (error_count // batch_size), 30)) # backoff sur erreur uniquement
91
-
92
- except Exception as e:
93
- error_count += len(records)
94
- print(f" ❌ Batch {batch_num}/{total_batches} : {e}")
95
- time.sleep(2)
96
-
97
- print("\n" + "=" * 70)
98
- print("📊 RÉSUMÉ")
99
- print("=" * 70)
100
- print(f"✅ Succès : {success_count} lignes")
101
- print(f"❌ Erreurs : {error_count} lignes")
102
- print(f"📈 Taux réussite : {success_count / len(df) * 100:.1f}%")
103
-
104
- if success_count > 0:
105
- print("\n✅ CHARGEMENT TERMINÉ")
106
- print("\nVérifiez dans Supabase:")
107
- print(" → https://krudbbmsixrejemqqphn.supabase.co")
108
- print(" → Table Editor → enregistrements")
109
- else:
110
- print("\n❌ ÉCHEC DU CHARGEMENT")
111
- sys.exit(1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/config.py CHANGED
@@ -10,15 +10,6 @@ VERSION FINALE - 8 quartiers
10
  MODELS_DIR = 'models/'
11
  DATA_DIR = 'data/'
12
  SYNTHETIC_DIR = 'data/synthetic/'
13
- # ============================================================================
14
- # CONFIGURATION SUPABASE
15
- # ============================================================================
16
-
17
- SUPABASE_CONFIG = {
18
- 'url': 'https://krudbbmsixrejemqqphn.supabase.co',
19
- 'key': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImtydWRiYm1zaXhyZWplbXFxcGhuIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjQxNDc4NzAsImV4cCI6MjA3OTcyMzg3MH0.X4HEFRhR-WOsc0g-d70NAqLOy33qst7Z7z-EUIOnhjQ'
20
- }
21
-
22
  # ============================================================================
23
  # QUARTIERS DE DAKAR (8 quartiers)
24
  # ============================================================================
 
10
  MODELS_DIR = 'models/'
11
  DATA_DIR = 'data/'
12
  SYNTHETIC_DIR = 'data/synthetic/'
 
 
 
 
 
 
 
 
 
13
  # ============================================================================
14
  # QUARTIERS DE DAKAR (8 quartiers)
15
  # ============================================================================
src/database.py DELETED
@@ -1,261 +0,0 @@
1
- """Gestion Base de Données via API REST Supabase"""
2
- import requests
3
- import pandas as pd
4
- from datetime import datetime
5
-
6
- from src.config import SUPABASE_CONFIG
7
-
8
- BASE_URL = SUPABASE_CONFIG['url']
9
- API_KEY = SUPABASE_CONFIG['key']
10
-
11
- HEADERS = {
12
- 'apikey': API_KEY,
13
- 'Authorization': f'Bearer {API_KEY}',
14
- 'Content-Type': 'application/json',
15
- 'Prefer': 'return=representation'
16
- }
17
-
18
- def test_connection():
19
- """Teste la connexion à l'API Supabase."""
20
- try:
21
- response = requests.get(f"{BASE_URL}/rest/v1/", headers=HEADERS, timeout=10)
22
- if response.status_code in [200, 404]:
23
- print("✅ Connexion Supabase API réussie")
24
- return True
25
- else:
26
- print(f"❌ Erreur API : {response.status_code}")
27
- return False
28
- except Exception as e:
29
- print(f"❌ Erreur de connexion : {e}")
30
- return False
31
-
32
- def get_create_tables_sql():
33
- """Retourne le SQL pour créer les tables."""
34
- return """
35
- CREATE TABLE IF NOT EXISTS enregistrements (
36
- id BIGSERIAL PRIMARY KEY,
37
- date_heure TIMESTAMPTZ NOT NULL,
38
- quartier VARCHAR(50) NOT NULL,
39
- temp_celsius FLOAT NOT NULL,
40
- humidite_percent INTEGER NOT NULL,
41
- vitesse_vent FLOAT NOT NULL,
42
- conso_megawatt INTEGER NOT NULL,
43
- heure INTEGER NOT NULL,
44
- jour_semaine INTEGER NOT NULL,
45
- mois INTEGER NOT NULL,
46
- saison INTEGER NOT NULL,
47
- is_peak_hour INTEGER NOT NULL,
48
- coupure INTEGER NOT NULL,
49
- created_at TIMESTAMPTZ DEFAULT NOW()
50
- );
51
-
52
- CREATE TABLE IF NOT EXISTS predictions (
53
- id BIGSERIAL PRIMARY KEY,
54
- date_heure TIMESTAMPTZ NOT NULL,
55
- quartier VARCHAR(50) NOT NULL,
56
- temp_celsius FLOAT NOT NULL,
57
- humidite_percent INTEGER NOT NULL,
58
- vitesse_vent FLOAT NOT NULL,
59
- conso_megawatt INTEGER NOT NULL,
60
- proba_lgbm FLOAT NOT NULL,
61
- proba_lstm FLOAT NOT NULL,
62
- proba_moyenne FLOAT NOT NULL,
63
- prediction INTEGER NOT NULL,
64
- modele_utilise VARCHAR(50),
65
- seuil_decision FLOAT,
66
- created_at TIMESTAMPTZ DEFAULT NOW()
67
- );
68
-
69
- CREATE INDEX IF NOT EXISTS idx_enregistrements_date ON enregistrements(date_heure DESC);
70
- CREATE INDEX IF NOT EXISTS idx_predictions_quartier ON predictions(quartier);
71
- """
72
-
73
- def insert_data_bulk(df, table_name='enregistrements'):
74
- """Insère un DataFrame en bulk via l'API REST."""
75
- print(f"\n📊 Insertion de {len(df):,} lignes dans '{table_name}'...")
76
-
77
- try:
78
- data = df.to_dict('records')
79
-
80
- for record in data:
81
- if 'date_heure' in record and isinstance(record['date_heure'], pd.Timestamp):
82
- record['date_heure'] = record['date_heure'].isoformat()
83
-
84
- batch_size = 100
85
- total_batches = (len(data) + batch_size - 1) // batch_size
86
-
87
- for i in range(0, len(data), batch_size):
88
- batch = data[i:i+batch_size]
89
- response = requests.post(
90
- f"{BASE_URL}/rest/v1/{table_name}",
91
- headers=HEADERS,
92
- json=batch,
93
- timeout=30
94
- )
95
-
96
- if response.status_code not in [200, 201]:
97
- print(f"❌ Erreur batch {i//batch_size + 1}")
98
- return False
99
-
100
- print(f" Batch {(i//batch_size)+1}/{total_batches} : {len(batch)} lignes")
101
-
102
- print(f"✅ {len(df):,} lignes insérées !")
103
- return True
104
-
105
- except Exception as e:
106
- print(f"❌ Erreur : {e}")
107
- return False
108
-
109
- def save_prediction_to_db(quartier, temp, humidite, vent, conso, proba_lgbm,
110
- proba_lstm, proba_moyenne, prediction,
111
- modele_utilise="LightGBM+LSTM", seuil_decision=50.0):
112
- """Sauvegarde une prédiction."""
113
- try:
114
- data = {
115
- 'quartier': quartier,
116
- 'temp_celsius': float(temp),
117
- 'humidite_percent': int(humidite),
118
- 'vitesse_vent': float(vent),
119
- 'conso_megawatt': int(conso),
120
- 'proba_lgbm': float(proba_lgbm),
121
- 'proba_lstm': float(proba_lstm),
122
- 'proba_moyenne': float(proba_moyenne),
123
- 'prediction': int(prediction),
124
- 'modele_utilise': modele_utilise,
125
- 'seuil_decision': float(seuil_decision),
126
- 'date_heure': datetime.now().isoformat()
127
- }
128
-
129
- response = requests.post(
130
- f"{BASE_URL}/rest/v1/predictions",
131
- headers=HEADERS,
132
- json=data,
133
- timeout=10
134
- )
135
- return response.status_code in [200, 201]
136
- except:
137
- return False
138
-
139
- def get_predictions_history(limit=100):
140
- """Récupère l'historique des prédictions."""
141
- try:
142
- response = requests.get(
143
- f"{BASE_URL}/rest/v1/predictions",
144
- headers=HEADERS,
145
- params={'order': 'date_heure.desc', 'limit': limit},
146
- timeout=10
147
- )
148
- if response.status_code == 200:
149
- return pd.DataFrame(response.json())
150
- return pd.DataFrame()
151
- except:
152
- return pd.DataFrame()
153
-
154
- def get_statistics_by_quartier(quartier_filter=None):
155
- """
156
- Récupère les statistiques par quartier depuis les ENREGISTREMENTS SYNTHÉTIQUES.
157
-
158
- Args:
159
- quartier_filter: Si spécifié, filtre pour un quartier particulier
160
-
161
- Returns:
162
- DataFrame avec les stats par quartier
163
- """
164
- try:
165
- # Récupérer TOUS les enregistrements (avec pagination)
166
- all_data = []
167
- offset = 0
168
- limit = 1000
169
-
170
- while True:
171
- params = {
172
- 'select': 'quartier,coupure,temp_celsius,conso_megawatt',
173
- 'order': 'id',
174
- 'limit': limit,
175
- 'offset': offset
176
- }
177
-
178
- # Filtrer par quartier si spécifié
179
- if quartier_filter:
180
- params['quartier'] = f'eq.{quartier_filter}'
181
-
182
- response = requests.get(
183
- f"{BASE_URL}/rest/v1/enregistrements",
184
- headers=HEADERS,
185
- params=params,
186
- timeout=15
187
- )
188
-
189
- if response.status_code != 200:
190
- break
191
-
192
- data = response.json()
193
-
194
- if not data:
195
- break
196
-
197
- all_data.extend(data)
198
-
199
- if len(data) < limit:
200
- break
201
-
202
- offset += limit
203
-
204
- if not all_data:
205
- return pd.DataFrame()
206
-
207
- # Créer DataFrame
208
- df = pd.DataFrame(all_data)
209
-
210
- # Calculer les statistiques par quartier
211
- stats = df.groupby('quartier').agg({
212
- 'coupure': ['count', 'sum', 'mean'],
213
- 'temp_celsius': 'mean',
214
- 'conso_megawatt': 'mean'
215
- }).reset_index()
216
-
217
- stats.columns = ['quartier', 'total_enregistrements', 'total_coupures',
218
- 'taux_coupure', 'temp_moyenne', 'conso_moyenne']
219
-
220
- # Calculer le taux en pourcentage
221
- stats['risque_moyen'] = stats['taux_coupure'] # Déjà entre 0 et 1
222
-
223
- # Trier par taux de coupure décroissant
224
- stats = stats.sort_values('risque_moyen', ascending=False)
225
-
226
- return stats
227
-
228
- except Exception as e:
229
- print(f"❌ Erreur get_statistics_by_quartier: {e}")
230
- import traceback
231
- traceback.print_exc()
232
- return pd.DataFrame()
233
-
234
- def get_table_count(table_name):
235
- """Compte les lignes dans une table."""
236
- try:
237
- response = requests.get(
238
- f"{BASE_URL}/rest/v1/{table_name}",
239
- headers={**HEADERS, 'Prefer': 'count=exact'},
240
- params={'select': 'id', 'limit': 1},
241
- timeout=10
242
- )
243
- if response.status_code == 200:
244
- count = response.headers.get('Content-Range', '0').split('/')[-1]
245
- return int(count) if count != '*' else 0
246
- return 0
247
- except:
248
- return 0
249
-
250
- def print_database_summary():
251
- """Affiche un résumé de la base de données."""
252
- print("\n" + "=" * 70)
253
- print(" 📊 RÉSUMÉ DE LA BASE DE DONNÉES SUPABASE")
254
- print("=" * 70)
255
-
256
- count_enr = get_table_count('enregistrements')
257
- count_pred = get_table_count('predictions')
258
-
259
- print(f"📋 Enregistrements : {count_enr:,} lignes")
260
- print(f"🔮 Prédictions : {count_pred:,} lignes")
261
- print("=" * 70)