File size: 8,493 Bytes
5cda98e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
"""Gestion Base de Données via API REST Supabase"""
import requests
import pandas as pd
from datetime import datetime

from src.config import SUPABASE_CONFIG

BASE_URL = SUPABASE_CONFIG['url']
API_KEY = SUPABASE_CONFIG['key']

HEADERS = {
    'apikey': API_KEY,
    'Authorization': f'Bearer {API_KEY}',
    'Content-Type': 'application/json',
    'Prefer': 'return=representation'
}

def test_connection():
    """Teste la connexion à l'API Supabase."""
    try:
        response = requests.get(f"{BASE_URL}/rest/v1/", headers=HEADERS, timeout=10)
        if response.status_code in [200, 404]:
            print("✅ Connexion Supabase API réussie")
            return True
        else:
            print(f"❌ Erreur API : {response.status_code}")
            return False
    except Exception as e:
        print(f"❌ Erreur de connexion : {e}")
        return False

def get_create_tables_sql():
    """Retourne le SQL pour créer les tables."""
    return """
CREATE TABLE IF NOT EXISTS enregistrements (
    id BIGSERIAL PRIMARY KEY,
    date_heure TIMESTAMPTZ NOT NULL,
    quartier VARCHAR(50) NOT NULL,
    temp_celsius FLOAT NOT NULL,
    humidite_percent INTEGER NOT NULL,
    vitesse_vent FLOAT NOT NULL,
    conso_megawatt INTEGER NOT NULL,
    heure INTEGER NOT NULL,
    jour_semaine INTEGER NOT NULL,
    mois INTEGER NOT NULL,
    saison INTEGER NOT NULL,
    is_peak_hour INTEGER NOT NULL,
    coupure INTEGER NOT NULL,
    created_at TIMESTAMPTZ DEFAULT NOW()
);

CREATE TABLE IF NOT EXISTS predictions (
    id BIGSERIAL PRIMARY KEY,
    date_heure TIMESTAMPTZ NOT NULL,
    quartier VARCHAR(50) NOT NULL,
    temp_celsius FLOAT NOT NULL,
    humidite_percent INTEGER NOT NULL,
    vitesse_vent FLOAT NOT NULL,
    conso_megawatt INTEGER NOT NULL,
    proba_lgbm FLOAT NOT NULL,
    proba_lstm FLOAT NOT NULL,
    proba_moyenne FLOAT NOT NULL,
    prediction INTEGER NOT NULL,
    modele_utilise VARCHAR(50),
    seuil_decision FLOAT,
    created_at TIMESTAMPTZ DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_enregistrements_date ON enregistrements(date_heure DESC);
CREATE INDEX IF NOT EXISTS idx_predictions_quartier ON predictions(quartier);
"""

def insert_data_bulk(df, table_name='enregistrements'):
    """Insère un DataFrame en bulk via l'API REST."""
    print(f"\n📊 Insertion de {len(df):,} lignes dans '{table_name}'...")
    
    try:
        data = df.to_dict('records')
        
        for record in data:
            if 'date_heure' in record and isinstance(record['date_heure'], pd.Timestamp):
                record['date_heure'] = record['date_heure'].isoformat()
        
        batch_size = 100
        total_batches = (len(data) + batch_size - 1) // batch_size
        
        for i in range(0, len(data), batch_size):
            batch = data[i:i+batch_size]
            response = requests.post(
                f"{BASE_URL}/rest/v1/{table_name}",
                headers=HEADERS,
                json=batch,
                timeout=30
            )
            
            if response.status_code not in [200, 201]:
                print(f"❌ Erreur batch {i//batch_size + 1}")
                return False
            
            print(f"  Batch {(i//batch_size)+1}/{total_batches} : {len(batch)} lignes")
        
        print(f"✅ {len(df):,} lignes insérées !")
        return True
        
    except Exception as e:
        print(f"❌ Erreur : {e}")
        return False

def save_prediction_to_db(quartier, temp, humidite, vent, conso, proba_lgbm, 
                          proba_lstm, proba_moyenne, prediction, 
                          modele_utilise="LightGBM+LSTM", seuil_decision=50.0):
    """Sauvegarde une prédiction."""
    try:
        data = {
            'quartier': quartier,
            'temp_celsius': float(temp),
            'humidite_percent': int(humidite),
            'vitesse_vent': float(vent),
            'conso_megawatt': int(conso),
            'proba_lgbm': float(proba_lgbm),
            'proba_lstm': float(proba_lstm),
            'proba_moyenne': float(proba_moyenne),
            'prediction': int(prediction),
            'modele_utilise': modele_utilise,
            'seuil_decision': float(seuil_decision),
            'date_heure': datetime.now().isoformat()
        }
        
        response = requests.post(
            f"{BASE_URL}/rest/v1/predictions",
            headers=HEADERS,
            json=data,
            timeout=10
        )
        return response.status_code in [200, 201]
    except:
        return False

def get_predictions_history(limit=100):
    """Récupère l'historique des prédictions."""
    try:
        response = requests.get(
            f"{BASE_URL}/rest/v1/predictions",
            headers=HEADERS,
            params={'order': 'date_heure.desc', 'limit': limit},
            timeout=10
        )
        if response.status_code == 200:
            return pd.DataFrame(response.json())
        return pd.DataFrame()
    except:
        return pd.DataFrame()

def get_statistics_by_quartier(quartier_filter=None):
    """
    Récupère les statistiques par quartier depuis les ENREGISTREMENTS SYNTHÉTIQUES.
    
    Args:
        quartier_filter: Si spécifié, filtre pour un quartier particulier
    
    Returns:
        DataFrame avec les stats par quartier
    """
    try:
        # Récupérer TOUS les enregistrements (avec pagination)
        all_data = []
        offset = 0
        limit = 1000
        
        while True:
            params = {
                'select': 'quartier,coupure,temp_celsius,conso_megawatt',
                'order': 'id',
                'limit': limit,
                'offset': offset
            }
            
            # Filtrer par quartier si spécifié
            if quartier_filter:
                params['quartier'] = f'eq.{quartier_filter}'
            
            response = requests.get(
                f"{BASE_URL}/rest/v1/enregistrements",
                headers=HEADERS,
                params=params,
                timeout=15
            )
            
            if response.status_code != 200:
                break
            
            data = response.json()
            
            if not data:
                break
            
            all_data.extend(data)
            
            if len(data) < limit:
                break
            
            offset += limit
        
        if not all_data:
            return pd.DataFrame()
        
        # Créer DataFrame
        df = pd.DataFrame(all_data)
        
        # Calculer les statistiques par quartier
        stats = df.groupby('quartier').agg({
            'coupure': ['count', 'sum', 'mean'],
            'temp_celsius': 'mean',
            'conso_megawatt': 'mean'
        }).reset_index()
        
        stats.columns = ['quartier', 'total_enregistrements', 'total_coupures', 
                        'taux_coupure', 'temp_moyenne', 'conso_moyenne']
        
        # Calculer le taux en pourcentage
        stats['risque_moyen'] = stats['taux_coupure']  # Déjà entre 0 et 1
        
        # Trier par taux de coupure décroissant
        stats = stats.sort_values('risque_moyen', ascending=False)
        
        return stats
        
    except Exception as e:
        print(f"❌ Erreur get_statistics_by_quartier: {e}")
        import traceback
        traceback.print_exc()
        return pd.DataFrame()

def get_table_count(table_name):
    """Compte les lignes dans une table."""
    try:
        response = requests.get(
            f"{BASE_URL}/rest/v1/{table_name}",
            headers={**HEADERS, 'Prefer': 'count=exact'},
            params={'select': 'id', 'limit': 1},
            timeout=10
        )
        if response.status_code == 200:
            count = response.headers.get('Content-Range', '0').split('/')[-1]
            return int(count) if count != '*' else 0
        return 0
    except:
        return 0

def print_database_summary():
    """Affiche un résumé de la base de données."""
    print("\n" + "=" * 70)
    print(" 📊 RÉSUMÉ DE LA BASE DE DONNÉES SUPABASE")
    print("=" * 70)
    
    count_enr = get_table_count('enregistrements')
    count_pred = get_table_count('predictions')
    
    print(f"📋 Enregistrements : {count_enr:,} lignes")
    print(f"🔮 Prédictions : {count_pred:,} lignes")
    print("=" * 70)