money-rain commited on
Commit
2514f97
·
verified ·
1 Parent(s): 7c76a82

Update main_app.py

Browse files
Files changed (1) hide show
  1. main_app.py +40 -304
main_app.py CHANGED
@@ -1,310 +1,46 @@
1
  #!/usr/bin/env python3
2
- import os
3
- import sys
4
- import json
5
- import time
6
- import threading
7
- import glob
8
- from collections import deque
9
- from dotenv import load_dotenv
10
-
11
- app_logs = deque(maxlen=50)
12
- _real_stdout = sys.__stdout__
13
-
14
- class LogCapture:
15
- def write(self, message):
16
- msg = message.strip()
17
- if msg:
18
- app_logs.append(msg)
19
- _real_stdout.write(message)
20
- _real_stdout.flush()
21
- def flush(self):
22
- _real_stdout.flush()
23
-
24
- sys.stdout = LogCapture()
25
-
26
- import gradio as gr
27
- import pandas as pd
28
- import plotly.graph_objects as go
29
- import config
30
- import database
31
- import ml_factory
32
- import bot
33
-
34
- db_instance = database.DatabaseManager()
35
- database.db = db_instance
36
- ml_manager = ml_factory.ModelManager(db_instance)
37
-
38
- def auth_func(username, password):
39
- return username == config.ADMIN_USER and password == config.ADMIN_PASS
40
-
41
- def get_latest_logs():
42
- return "\n".join(list(app_logs)[-30:])
43
-
44
- def get_binary_thresholds(window):
45
- thresholds = set(config.THRESHOLDS)
46
- pattern = os.path.join(config.DATASETS_BIN_DIR, f"aviator_bin_{window}_t*.db")
47
- for filepath in glob.glob(pattern):
48
- filename = os.path.basename(filepath)
49
- t_str = filename.split('_t')[-1].replace('.db', '')
50
- try: thresholds.add(float(t_str))
51
- except ValueError: pass
52
- return sorted(list(thresholds))
53
-
54
- def get_arena_visuals():
55
- df = database.db.get_main_db_last_records(100)
56
- if df is None or df.empty:
57
- html_circle = "<div style='width:80px;height:80px;border-radius:50%;background-color:gray;display:flex;align-items:center;justify-content:center;color:white;font-weight:bold;font-size:16px;'>N/A</div>"
58
- return html_circle, go.Figure()
59
- df = df[::-1].reset_index(drop=True)
60
- last_cote = float(df.iloc[-1]['cote'])
61
- if last_cote < 2.0: color = "#3b82f6"
62
- elif last_cote < 10.0: color = "#8b5cf6"
63
- else: color = "#ec4899"
64
- html_circle = f"""
65
- <div style="display:flex;flex-direction:column;align-items:center;justify-content:center;">
66
- <div style="width:90px;height:90px;border-radius:50%;background-color:{color};
67
- display:flex;align-items:center;justify-content:center;color:white;
68
- font-weight:bold;font-size:20px;box-shadow:0 4px 6px rgba(0,0,0,0.2);">
69
- {last_cote:.2f}x
70
- </div>
71
- <span style="margin-top:8px;font-size:12px;color:#666;">Dernière cote</span>
72
- </div>
73
- """
74
- fig = go.Figure()
75
- fig.add_trace(go.Scatter(x=df.index, y=df['cote'], mode='lines+markers', line=dict(color='#10b981', width=2), name='Cotes'))
76
- fig.add_trace(go.Scatter(x=[df.index[-1]], y=[last_cote], mode='markers+text', text=[f" {last_cote:.2f}x"], textposition="top center", marker=dict(size=12, color='red'), name='Dernier'))
77
- fig.update_layout(margin=dict(l=20, r=20, t=30, b=20), height=250, xaxis_title="Index", yaxis_title="Cote", showlegend=False)
78
- return html_circle, fig
79
-
80
- def reset_window(ds_type_val):
81
- if ds_type_val == "classification_binary":
82
- return gr.update(value="10", visible=True), gr.update(choices=get_binary_thresholds(10), value=2.0, visible=True)
83
- else:
84
- return gr.update(value="10", visible=True), gr.update(visible=False)
85
-
86
- def update_thresholds(window_val, ds_type_val):
87
- if ds_type_val == "classification_binary":
88
- return gr.update(choices=get_binary_thresholds(int(window_val)), visible=True)
89
- return gr.update(visible=False)
90
-
91
- def toggle_threshold_visibility(m_type):
92
- return gr.update(visible=(m_type == "binary"))
93
-
94
- def load_model_state(name):
95
- if not name:
96
- return gr.update(visible=False), gr.update(value=False), "### 👈 Créez ou sélectionnez un modèle"
97
- return gr.update(visible=True), gr.update(value=ml_manager.get_model_state(name)), ml_manager.get_model_dashboard(name)
98
-
99
- def create_model_ui(name, m_type, window, threshold, framework):
100
- if not name or not name.strip(): return "❌ Entrez un nom.", gr.update()
101
- result, new_name = ml_manager.create_manual_model(name.strip().replace(" ", "_"), m_type, int(window), float(threshold), framework)
102
- return result, gr.update(choices=ml_manager.get_model_names(), value=new_name)
103
-
104
- def generate_custom_db(window, threshold):
105
- count, msg = database.db.generate_custom_binary_db(int(window), float(threshold))
106
- return msg, gr.update(choices=get_binary_thresholds(int(window)))
107
-
108
- def sync_selector(current):
109
- available = ml_manager.get_model_names()
110
- if current and current in available:
111
- return gr.update(choices=available, value=current)
112
- return gr.update(choices=available)
113
-
114
- def update_dataset(current_type, window, threshold):
115
- required_size = int(window) + 1
116
- dataset_status = f"**Statut Système :** {database.db.status}\n\n"
117
- stats_md = "### ⏳ En attente de données..."
118
- df = pd.DataFrame(columns=["Heure", "Cible", "Historique"])
119
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
  try:
121
- if current_type == "main_db":
122
- stats = database.db.get_main_db_stats()
123
- if stats:
124
- dataset_status += f"**Statut Dataset :** En cours d'enregistrement\n\n"
125
- stats_md = (
126
- f"### 📊 Statistiques Main DB\n"
127
- f"| Métrique | Valeur |\n|---|---|\n"
128
- f"| **Total** | **{stats['total']}** |\n"
129
- f"| **Cote Moyenne** | {stats['avg']:.2f}x |\n"
130
- f"| **Cote Min** | {stats['min']:.2f}x |\n"
131
- f"| **Cote Max** | {stats['max']:.2f}x |"
132
- )
133
- table = database.db.get_main_db_last_records(10)
134
- if table is not None and not table.empty:
135
- df = table
136
-
137
- elif current_type == "regression":
138
- stats = database.db.get_reg_stats(int(window))
139
- if stats:
140
- if stats['total'] < required_size:
141
- dataset_status += f"**Statut Dataset :** Initialisation {stats['total']}/{required_size} cotes\n\n"
142
- else:
143
- dataset_status += f"**Statut Dataset :** En cours d'enregistrement\n\n"
144
- stats_md = (
145
- f"### 📊 Statistiques Régression (Fenêtre {window})\n"
146
- f"| Métrique | Valeur |\n|---|---|\n"
147
- f"| **Total Enregistrements** | **{stats['total']}** |\n"
148
- f"| **Cote Moyenne** | {stats['avg']:.2f}x |\n"
149
- f"| **Cote Min** | {stats['min']:.2f}x |\n"
150
- f"| **Cote Max** | {stats['max']:.2f}x |"
151
- )
152
- else:
153
- dataset_status += f"**Statut Dataset :** Initialisation 0/{required_size} cotes\n\n"
154
- table = database.db.get_reg_last_records(int(window), 10)
155
- if table is not None and not table.empty:
156
- table = table.copy()
157
- table['historique'] = table['historique'].apply(json.loads).astype(str)
158
- table['Heure'] = pd.to_datetime(table['timestamp'], unit='s').dt.strftime('%H:%M:%S')
159
- df = table[['Heure', 'cote', 'historique']]
160
- df.columns = ["Heure", "Cote", "Historique"]
161
- df = df[::-1]
162
-
163
- else:
164
- stats = database.db.get_bin_stats(int(window), float(threshold))
165
- if stats:
166
- if stats['total'] < required_size:
167
- dataset_status += f"**Statut Dataset :** Initialisation {stats['total']}/{required_size} cotes\n\n"
168
- else:
169
- dataset_status += f"**Statut Dataset :** En cours d'enregistrement\n\n"
170
- total = stats['total']
171
- count_0 = stats['count_0']
172
- count_1 = stats['count_1']
173
- pct_0 = (count_0 / total) * 100 if total else 0
174
- pct_1 = (count_1 / total) * 100 if total else 0
175
- stats_md = (
176
- f"### 📊 Statistiques (Fenêtre {window} | Seuil {threshold}x)\n"
177
- f"| Métrique | Valeur |\n|---|---|\n"
178
- f"| **Total** | **{total}** |\n"
179
- f"| **0 (> {threshold}x)** | {count_0} (**{pct_0:.2f}%**) |\n"
180
- f"| **1 (<= {threshold}x)** | {count_1} (**{pct_1:.2f}%**) |"
181
- )
182
- else:
183
- dataset_status += f"**Statut Dataset :** Initialisation 0/{required_size} cotes\n\n"
184
- df_raw = database.db.get_bin_last_records(int(window), float(threshold), 10)
185
- if df_raw is not None and not df_raw.empty:
186
- df_raw = df_raw.copy()
187
- df_raw['historique'] = df_raw['historique'].apply(json.loads).astype(str)
188
- df_raw['label'] = df_raw['label'].apply(lambda x: f"{x} ({'> ' + str(threshold) + 'x' if x == 0 else '<= ' + str(threshold) + 'x'})")
189
- df_raw['Heure'] = pd.to_datetime(df_raw['timestamp'], unit='s').dt.strftime('%H:%M:%S')
190
- df = df_raw[['Heure', 'label', 'historique']]
191
- df.columns = ["Heure", "Cible", "Historique"]
192
- df = df[::-1]
193
  except Exception as e:
194
- stats_md = f"❌ Erreur de chargement des données : {e}"
195
-
196
- return dataset_status + stats_md, df
197
-
198
-
199
- with gr.Blocks() as demo:
200
- gr.Markdown("# 🧠 DWS 2.0 - Data & AI Engine")
201
-
202
- with gr.Tabs() as tabs:
203
- with gr.Tab("Arena"):
204
- with gr.Row():
205
- gr.Markdown("### 🏆 Arène des Modèles (Comparaison en temps réel)\n*Les modèles sont triés automatiquement par leurs meilleures métriques.*")
206
- latest_cote_circle = gr.HTML()
207
- arena_plot = gr.Plot()
208
-
209
- with gr.Tab("📈 Régression"):
210
- with gr.Row():
211
- reg_sort_metric = gr.Dropdown(choices=["MAE (Erreur Moy)", "RMSE"], value="MAE (Erreur Moy)", label="Trier par")
212
- reg_sort_order = gr.Radio(choices=["Croissant", "Décroissant"], value="Croissant", label="Ordre")
213
- with gr.Tabs():
214
- with gr.Tab("Tableau"):
215
- arena_reg_table = gr.Dataframe(
216
- headers=["Modèle", "Fenêtre (W)", "MAE", "RMSE", "Taille Données", "Statut"],
217
- datatype=["str", "number", "str", "str", "str", "str"], interactive=False
218
- )
219
- with gr.Tab("Graphique"):
220
- with gr.Row():
221
- reg_plot_mae = gr.Plot()
222
- reg_plot_rmse = gr.Plot()
223
-
224
- with gr.Tab("🧠 Classification Binaire"):
225
- with gr.Row():
226
- bin_sort_metric = gr.Dropdown(choices=["Exactitude %", "F1-Score %", "MCC"], value="F1-Score %", label="Trier par")
227
- bin_sort_order = gr.Radio(choices=["Croissant", "Décroissant"], value="Décroissant", label="Ordre")
228
- with gr.Tabs():
229
- with gr.Tab("Tableau"):
230
- arena_bin_table = gr.Dataframe(
231
- headers=["Modèle", "Fenêtre (W)", "Seuil (T)", "Exactitude %", "F1-Score %", "MCC", "Taille Données", "Statut"],
232
- datatype=["str", "number", "str", "str", "str", "str", "str", "str"], interactive=False
233
- )
234
- with gr.Tab("Graphique"):
235
- with gr.Row():
236
- bin_plot_f1 = gr.Plot()
237
- bin_plot_acc = gr.Plot()
238
-
239
- with gr.Tab("Dataset"):
240
- with gr.Row():
241
- with gr.Column(scale=1):
242
- gr.Markdown("### 📥 Gestion de l'Affichage")
243
- ds_type = gr.Radio(choices=["main_db", "classification_binary", "regression"], value="classification_binary", label="Type de Dataset")
244
- ds_window = gr.Radio(choices=[str(w) for w in config.WINDOWS], value="10", label="Fenêtre d'historique (W)")
245
- ds_threshold = gr.Dropdown(choices=get_binary_thresholds(10), value=2.0, label="Seuil de bascule (T)", allow_custom_value=True)
246
- gr.Markdown("### 📋 Logs Système")
247
- logs_output = gr.Textbox(label="", lines=22, max_lines=25, autoscroll=True, interactive=False)
248
-
249
- with gr.Column(scale=2):
250
- with gr.Row():
251
- ds_stats = gr.Markdown(value="### ⏳ Sélectionnez un type et une fenêtre...", scale=2)
252
- with gr.Column(scale=1, min_width=250):
253
- gr.Markdown("### ⚙️ Générateur de DB")
254
- gen_window = gr.Dropdown(choices=[str(w) for w in config.WINDOWS], value="10", label="Fenêtre (W)")
255
- gen_threshold = gr.Dropdown(choices=get_binary_thresholds(10), value=2.0, label="Seuil (T)", allow_custom_value=True)
256
- btn_gen_db = gr.Button("🔄 Générer DB Binaire", variant="primary")
257
- gen_log = gr.Textbox(label="", lines=1, interactive=False)
258
- gr.Markdown("### 💾 10 Derniers Enregistrements")
259
- ds_table = gr.Dataframe(headers=["Heure", "Cible", "Historique (10)"], datatype=["str", "str", "str"], interactive=False)
260
-
261
- with gr.Tab("Lab"):
262
- with gr.Row():
263
- with gr.Column(scale=1):
264
- gr.Markdown("### 🛠️ 1. Créer un Modèle Expérimental")
265
- m_name = gr.Textbox(label="Nom du modèle", placeholder="Ex: MonTest_MLP")
266
- m_type = gr.Radio(choices=["regression", "binary"], value="binary", label="Type de Modèle")
267
- m_window = gr.Dropdown(choices=[str(w) for w in config.WINDOWS], value="10", label="Fenêtre (W)")
268
- m_threshold = gr.Dropdown(choices=get_binary_thresholds(10), value=2.0, label="Seuil (T) (Si Binaire)", allow_custom_value=True)
269
- m_framework = gr.Dropdown(choices=["river", "sklearn"], value="river", label="Moteur ML")
270
- btn_create = gr.Button("🚀 Lancer l'entraînement initial", variant="primary")
271
- creation_log = gr.Textbox(label="Statut Création", lines=4, interactive=False)
272
- gr.Markdown("---")
273
- gr.Markdown("### ⚙️ 2. Contrôle du Modèle Sélectionné")
274
- m_selector = gr.Dropdown(label="Sélectionner un modèle actif", interactive=True, allow_custom_value=False)
275
- m_train_toggle = gr.Checkbox(label="Entraînement en ligne (Online Learning) Actif", value=True)
276
- btn_toggle = gr.Button("Appliquer", variant="secondary")
277
- toggle_log = gr.Textbox(label="Statut", lines=2, interactive=False)
278
- with gr.Column(scale=2):
279
- gr.Markdown("### 📊 3. Dashboard Détaillé")
280
- model_dashboard = gr.Markdown(value="### 👈 Créez ou sélectionnez un modèle")
281
-
282
- ds_type.change(fn=reset_window, inputs=[ds_type], outputs=[ds_window, ds_threshold])
283
- ds_window.change(fn=update_thresholds, inputs=[ds_window, ds_type], outputs=[ds_threshold])
284
- m_type.change(fn=toggle_threshold_visibility, inputs=[m_type], outputs=[m_threshold])
285
- btn_gen_db.click(fn=generate_custom_db, inputs=[gen_window, gen_threshold], outputs=[gen_log, gen_threshold])
286
- m_selector.change(fn=load_model_state, inputs=[m_selector], outputs=[m_train_toggle, btn_toggle, model_dashboard])
287
- btn_create.click(fn=create_model_ui, inputs=[m_name, m_type, m_window, m_threshold, m_framework], outputs=[creation_log, m_selector])
288
- btn_toggle.click(fn=ml_manager.toggle_training, inputs=[m_selector, m_train_toggle], outputs=[toggle_log])
289
-
290
- timer_logs = gr.Timer(value=1, active=True)
291
- timer_logs.tick(fn=get_latest_logs, outputs=[logs_output])
292
-
293
- timer_ds = gr.Timer(value=5, active=True)
294
- timer_ds.tick(fn=update_dataset, inputs=[ds_type, ds_window, ds_threshold], outputs=[ds_stats, ds_table])
295
-
296
- timer_arena = gr.Timer(value=10, active=True)
297
- timer_arena.tick(fn=get_arena_visuals, outputs=[latest_cote_circle, arena_plot])
298
- timer_arena.tick(fn=ml_manager.get_leaderboards, inputs=[reg_sort_metric, reg_sort_order, bin_sort_metric, bin_sort_order], outputs=[arena_reg_table, arena_bin_table, reg_plot_mae, reg_plot_rmse, bin_plot_f1, bin_plot_acc])
299
-
300
- timer_lab = gr.Timer(value=5, active=True)
301
- timer_lab.tick(fn=ml_manager.get_model_dashboard, inputs=[m_selector], outputs=[model_dashboard])
302
- timer_lab.tick(fn=sync_selector, inputs=[m_selector], outputs=[m_selector])
303
 
304
  if __name__ == "__main__":
305
- sys.stdout = _real_stdout
306
- print("🤖 Démarrage du bot de collecte...")
307
- bot_thread = threading.Thread(target=bot.run_bot_pipeline, args=(database.db, ml_manager), daemon=True)
308
- bot_thread.start()
309
- print("🌐 Lancement de l'interface web DWS 2.0...")
310
- demo.launch(server_name="0.0.0.0", server_port=7860, show_error=True, auth=auth_func, theme=gr.themes.Soft(primary_hue="emerald"))
 
1
  #!/usr/bin/env python3
2
+ """
3
+ ⚠️ SCRIPT DE SUPPRESSION TOTALE DU BUCKET ⚠️
4
+ Ce script supprime TOUT le contenu du dossier /data (ou BUCKET_PATH)
5
+ Utilisation : python clear_bucket.py
6
+ """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
+ import os
9
+ import shutil
10
+
11
+ # Chemin du bucket (identique à ton config.py)
12
+ BUCKET_PATH = os.path.abspath(os.getenv('BUCKET_PATH', './data'))
13
+
14
+ def clear_bucket():
15
+ print(f"🗑️ Suppression du contenu de : {BUCKET_PATH}")
16
+ print("-" * 50)
17
+
18
+ if not os.path.exists(BUCKET_PATH):
19
+ print("✅ Le dossier n'existe pas, rien à supprimer.")
20
+ return
21
+
22
+ # Compter les éléments avant suppression
23
+ total_files = 0
24
+ total_dirs = 0
25
+ for root, dirs, files in os.walk(BUCKET_PATH):
26
+ total_files += len(files)
27
+ total_dirs += len(dirs)
28
+
29
+ print(f"📊 Éléments à supprimer : {total_files} fichiers, {total_dirs} dossiers")
30
+
31
+ # Confirmation
32
+ confirm = "OUI"
33
+
34
+ if confirm != "OUI":
35
+ print("❌ Annulé.")
36
+ return
37
+
38
+ # Suppression
39
  try:
40
+ shutil.rmtree(BUCKET_PATH)
41
+ print(f"\n✅ Bucket vidé avec succès !")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  except Exception as e:
43
+ print(f"\n❌ Erreur lors de la suppression : {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
  if __name__ == "__main__":
46
+ clear_bucket()