Docfile commited on
Commit
90ab9e6
·
verified ·
1 Parent(s): d359788

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +666 -387
app.py CHANGED
@@ -1,257 +1,337 @@
1
- from flask import Flask, render_template, request, jsonify, send_file
2
- import threading
3
- import time
4
  import os
5
  import json
6
- from datetime import datetime
7
- from google import genai
8
- from pydantic import BaseModel, Field
9
- import typing_extensions as typing
10
  import uuid
11
- import enum
 
 
 
 
 
 
 
 
 
 
 
 
12
 
 
13
  app = Flask(__name__)
 
 
 
14
 
15
- # Configurbation
16
- GOOGLE_API_KEY = "AIzaSyAMYpF67aqFnWDJESWOx1dC-w3sEU29VcM" # Remplacez par votre clé API
17
- MODEL_ID = "gemini-2.0-flash" # Modèle recommandé selon la documentation
18
- UPLOAD_FOLDER = 'uploads'
19
- RESULTS_FOLDER = 'results'
20
-
21
- # Créer les dossiers s'ils n'existent pas
22
- os.makedirs(UPLOAD_FOLDER, exist_ok=True)
23
- os.makedirs(RESULTS_FOLDER, exist_ok=True)
24
-
25
- # Définition des schémas Pydantic selon la documentation
26
- class TranslationPair(BaseModel):
27
- """Paire de traductions fang/français"""
28
- fang: str = Field(description="Phrase en langue fang")
29
- francais: str = Field(description="Traduction française de la phrase")
30
-
31
- class SyntheticDataResponse(BaseModel):
32
- """Réponse structurée pour la génération de données synthétiques"""
33
- request_number: int = Field(description="Numéro de la requête")
34
- generated_pairs: list[TranslationPair] = Field(
35
- description="Liste des paires de traduction générées",
36
- min_items=1
37
- )
38
- timestamp: str = Field(description="Horodatage de la génération")
39
-
40
- # Stockage des tâches en cours
41
- class TaskManager:
42
- def __init__(self):
43
- self.tasks = {}
44
-
45
- def create_task(self, task_id):
46
- self.tasks[task_id] = {
47
- 'status': 'running',
48
- 'progress': 0,
49
- 'total': 470,
50
- 'results_file': f'results_{task_id}.json',
51
- 'start_time': datetime.now(),
52
- 'errors': [],
53
- 'last_update': datetime.now(),
54
- 'all_data': []
55
- }
56
-
57
- def update_progress(self, task_id, progress, data=None):
58
- if task_id in self.tasks:
59
- self.tasks[task_id]['progress'] = progress
60
- self.tasks[task_id]['last_update'] = datetime.now()
61
- if data:
62
- self.tasks[task_id]['all_data'].append(data)
63
-
64
- def add_error(self, task_id, error):
65
- if task_id in self.tasks:
66
- self.tasks[task_id]['errors'].append(error)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
 
68
- def complete_task(self, task_id):
69
- if task_id in self.tasks:
70
- self.tasks[task_id]['status'] = 'completed'
71
- self.tasks[task_id]['last_update'] = datetime.now()
72
 
73
- def get_task(self, task_id):
74
- return self.tasks.get(task_id)
75
-
76
- task_manager = TaskManager()
 
 
 
 
77
 
78
- def generate_synthetic_data(file_path, task_id):
79
- """Fonction qui exécute les 470 requêtes en arrière-plan avec sortie JSON structurée"""
80
  try:
81
- # Initialiser le client Google AI selon la documentation
82
- client = genai.Client(api_key=GOOGLE_API_KEY)
83
-
84
- # Uploader le fichier
85
- file_ref = client.files.upload(path=file_path)
86
-
87
- # Prompt optimisé pour une sortie structurée
88
- prompt = """
89
- À partir du fichier fourni, génère exactement 400 nouvelles paires de phrases synthétiques.
90
- Chaque paire doit contenir :
91
- - Une phrase en fang (langue locale)
92
- - Sa traduction en français
93
-
94
- Les phrases doivent être variées, naturelles et représentatives de la structure linguistique
95
- présente dans le fichier source. Respecte strictement le nombre de 400 paires demandées.
96
- """
97
-
98
- # Fichier de résultats JSON
99
- results_file = os.path.join(RESULTS_FOLDER, f'results_{task_id}.json')
100
-
101
- # Structure pour stocker toutes les données
102
- all_results = {
103
- "metadata": {
104
- "task_id": task_id,
105
- "start_time": datetime.now().isoformat(),
106
- "total_requests": 470,
107
- "model_used": MODEL_ID,
108
- "expected_pairs_per_request": 400
109
- },
110
- "requests": [],
111
- "summary": {
112
- "total_pairs": 0,
113
- "completed_requests": 0,
114
- "failed_requests": 0,
115
- "errors": []
116
- }
117
- }
118
 
119
- for i in range(470):
120
- try:
121
- print(f"🔄 Démarrage requête {i+1}/470...")
122
-
123
- # Configuration selon la documentation avec schéma Pydantic
124
- response = client.models.generate_content(
125
- model=MODEL_ID,
126
- contents=[file_ref, prompt],
127
- config={
128
- 'response_mime_type': 'application/json',
129
- 'response_schema': SyntheticDataResponse,
130
- }
131
- )
132
-
133
- # Utiliser la propriété .parsed selon la documentation
134
- if hasattr(response, 'parsed') and response.parsed:
135
- parsed_response = response.parsed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
136
 
137
- # Structurer la réponse selon le schéma
138
- request_data = {
139
- "request_number": i + 1,
140
- "timestamp": datetime.now().isoformat(),
141
- "response": {
142
- "request_number": parsed_response.request_number,
143
- "generated_pairs": [
144
- {
145
- "fang": pair.fang,
146
- "francais": pair.francais
147
- } for pair in parsed_response.generated_pairs
148
- ],
149
- "timestamp": parsed_response.timestamp
150
- },
151
- "pairs_count": len(parsed_response.generated_pairs),
152
- "status": "success"
153
- }
154
 
155
- all_results["requests"].append(request_data)
156
- all_results["summary"]["total_pairs"] += request_data["pairs_count"]
157
- all_results["summary"]["completed_requests"] += 1
158
 
159
- print(f"✅ Requête {i+1} réussie - {request_data['pairs_count']} paires générées")
160
-
161
- else:
162
- # Fallback : parser le JSON manuellement si .parsed n'est pas disponible
163
- try:
164
- response_data = json.loads(response.text)
165
- request_data = {
166
- "request_number": i + 1,
167
- "timestamp": datetime.now().isoformat(),
168
- "response": response_data,
169
- "pairs_count": len(response_data.get("generated_pairs", [])),
170
- "status": "success_fallback"
171
- }
172
-
173
- all_results["requests"].append(request_data)
174
- all_results["summary"]["total_pairs"] += request_data["pairs_count"]
175
- all_results["summary"]["completed_requests"] += 1
176
-
177
- print(f"✅ Requête {i+1} réussie (fallback) - {request_data['pairs_count']} paires")
178
-
179
- except json.JSONDecodeError as json_error:
180
- raise Exception(f"Impossible de parser la réponse JSON: {json_error}")
181
-
182
- # Sauvegarder après chaque requête réussie
183
- with open(results_file, 'w', encoding='utf-8') as f:
184
- json.dump(all_results, f, ensure_ascii=False, indent=2)
185
-
186
- # Mettre à jour le progrès
187
- task_manager.update_progress(task_id, i + 1)
188
-
189
- # Pause pour respecter les limites de l'API (ajustable selon vos besoins)
190
- time.sleep(1) # Réduit à 1 seconde, ajustez selon vos limites API
191
-
192
- except Exception as e:
193
- error_msg = f"Erreur requête {i+1}: {str(e)}"
194
- print(f"❌ {error_msg}")
195
-
196
- task_manager.add_error(task_id, error_msg)
197
- all_results["summary"]["errors"].append({
198
- "request_number": i + 1,
199
- "error": error_msg,
200
- "timestamp": datetime.now().isoformat()
201
- })
202
- all_results["summary"]["failed_requests"] += 1
203
-
204
- # Créer une entrée vide pour cette requête échouée
205
- failed_request_data = {
206
- "request_number": i + 1,
207
- "timestamp": datetime.now().isoformat(),
208
- "response": None,
209
- "pairs_count": 0,
210
- "status": "failed",
211
- "error": error_msg
212
- }
213
- all_results["requests"].append(failed_request_data)
214
-
215
- # Sauvegarder même en cas d'erreur
216
- with open(results_file, 'w', encoding='utf-8') as f:
217
- json.dump(all_results, f, ensure_ascii=False, indent=2)
218
-
219
- # Mettre à jour le progrès même en cas d'erreur
220
- task_manager.update_progress(task_id, i + 1)
221
-
222
- # Pause plus longue en cas d'erreur
223
- time.sleep(5)
224
-
225
- # Finaliser le fichier JSON
226
- end_time = datetime.now()
227
- start_time = datetime.fromisoformat(all_results["metadata"]["start_time"])
228
- duration = (end_time - start_time).total_seconds()
229
-
230
- all_results["metadata"]["end_time"] = end_time.isoformat()
231
- all_results["metadata"]["duration_seconds"] = duration
232
- all_results["metadata"]["duration_minutes"] = duration / 60
233
- all_results["summary"]["success_rate"] = (
234
- all_results["summary"]["completed_requests"] / 470 * 100
235
- )
236
 
237
- # Statistiques finales
238
- print(f"\n📊 STATISTIQUES FINALES:")
239
- print(f" • Requêtes réussies: {all_results['summary']['completed_requests']}/470")
240
- print(f" • Requêtes échouées: {all_results['summary']['failed_requests']}/470")
241
- print(f" Total paires générées: {all_results['summary']['total_pairs']}")
242
- print(f" • Taux de réussite: {all_results['summary']['success_rate']:.1f}%")
243
- print(f" • Durée totale: {duration/60:.1f} minutes")
244
 
245
- with open(results_file, 'w', encoding='utf-8') as f:
246
- json.dump(all_results, f, ensure_ascii=False, indent=2)
247
 
248
- task_manager.complete_task(task_id)
249
- print(f"🎉 Tâche {task_id} terminée avec succès")
250
 
251
  except Exception as e:
252
- error_msg = f"Erreur générale: {str(e)}"
253
- task_manager.add_error(task_id, error_msg)
254
- print(f"💥 {error_msg}")
 
 
 
 
 
255
 
256
  @app.route('/')
257
  def index():
@@ -260,187 +340,386 @@ def index():
260
  @app.route('/upload', methods=['POST'])
261
  def upload_file():
262
  if 'file' not in request.files:
263
- return jsonify({'error': 'Aucun fichier sélectionné'}), 400
264
 
265
  file = request.files['file']
266
  if file.filename == '':
267
  return jsonify({'error': 'Aucun fichier sélectionné'}), 400
268
 
269
- if file:
270
- # Générer un ID unique pour cette tâche
271
  task_id = str(uuid.uuid4())
272
 
273
  # Sauvegarder le fichier
274
- filename = f"input_{task_id}.txt"
275
- file_path = os.path.join(UPLOAD_FOLDER, filename)
276
- file.save(file_path)
277
-
278
- # Créer la tâche
279
- task_manager.create_task(task_id)
280
-
281
- # Démarrer le traitement en arrière-plan
282
- thread = threading.Thread(
283
- target=generate_synthetic_data,
284
- args=(file_path, task_id)
285
- )
286
- thread.daemon = True
287
- thread.start()
288
 
289
- return jsonify({
290
- 'task_id': task_id,
291
- 'message': 'Traitement démarré en arrière-plan',
292
- 'expected_duration_minutes': 8 # Estimation bas��e sur 1s par requête
293
- })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
294
 
295
  @app.route('/status/<task_id>')
296
  def get_status(task_id):
297
- task = task_manager.get_task(task_id)
298
- if not task:
299
  return jsonify({'error': 'Tâche non trouvée'}), 404
300
 
301
- # Calculer ETA si la tâche est en cours
302
- eta_minutes = None
303
- if task['status'] == 'running' and task['progress'] > 0:
304
- elapsed = (datetime.now() - task['start_time']).total_seconds()
305
- rate = task['progress'] / elapsed # requêtes par seconde
306
- remaining = task['total'] - task['progress']
307
- eta_seconds = remaining / rate if rate > 0 else None
308
- eta_minutes = eta_seconds / 60 if eta_seconds else None
309
-
310
  return jsonify({
 
311
  'status': task['status'],
312
- 'progress': task['progress'],
313
- 'total': task['total'],
314
- 'percentage': round((task['progress'] / task['total']) * 100, 2),
315
- 'errors_count': len(task['errors']),
316
- 'start_time': task['start_time'].strftime('%Y-%m-%d %H:%M:%S'),
317
- 'last_update': task['last_update'].strftime('%Y-%m-%d %H:%M:%S'),
318
- 'eta_minutes': round(eta_minutes) if eta_minutes else None
319
  })
320
 
321
  @app.route('/download/<task_id>')
322
- def download_results(task_id):
323
- task = task_manager.get_task(task_id)
324
- if not task:
325
  return jsonify({'error': 'Tâche non trouvée'}), 404
326
 
327
- results_file = os.path.join(RESULTS_FOLDER, f'results_{task_id}.json')
328
-
329
- if not os.path.exists(results_file):
330
- return jsonify({'error': 'Fichier de résultats non trouvé'}), 404
331
-
332
- # Vérifier si c'est un téléchargement partiel
333
- is_partial = request.args.get('partial', 'false').lower() == 'true'
334
-
335
- if is_partial and task['status'] == 'running':
336
- # Créer un fichier temporaire avec les données actuelles
337
- temp_file = os.path.join(RESULTS_FOLDER, f'temp_results_{task_id}.json')
338
-
339
- try:
340
- # Charger les données actuelles
341
- with open(results_file, 'r', encoding='utf-8') as f:
342
- current_data = json.load(f)
343
-
344
- # Ajouter des métadonnées pour le téléchargement partiel
345
- current_data["partial_download"] = {
346
- "downloaded_at": datetime.now().isoformat(),
347
- "is_partial": True,
348
- "progress": f"{task['progress']}/{task['total']}",
349
- "percentage": round((task['progress'] / task['total']) * 100, 2)
350
- }
351
-
352
- # Sauvegarder le fichier temporaire
353
- with open(temp_file, 'w', encoding='utf-8') as f:
354
- json.dump(current_data, f, ensure_ascii=False, indent=2)
355
-
356
- return send_file(
357
- temp_file,
358
- as_attachment=True,
359
- download_name=f'donnees_synthetiques_partiel_{task_id}.json'
360
- )
361
- except Exception as e:
362
- return jsonify({'error': f'Erreur lors de la création du fichier partiel: {str(e)}'}), 500
363
-
364
- # Téléchargement normal (complet)
365
- download_name = f'donnees_synthetiques_{"complet" if task["status"] == "completed" else "actuel"}_{task_id}.json'
366
 
367
- return send_file(
368
- results_file,
369
- as_attachment=True,
370
- download_name=download_name
371
- )
372
 
373
  @app.route('/tasks')
374
  def list_tasks():
375
- """Liste toutes les tâches"""
376
- task_list = []
377
- for task_id, task_info in task_manager.tasks.items():
378
- task_list.append({
379
- 'id': task_id,
380
- 'status': task_info['status'],
381
- 'progress': task_info['progress'],
382
- 'total': task_info['total'],
383
- 'percentage': round((task_info['progress'] / task_info['total']) * 100, 2),
384
- 'start_time': task_info['start_time'].strftime('%Y-%m-%d %H:%M:%S'),
385
- 'last_update': task_info['last_update'].strftime('%Y-%m-%d %H:%M:%S'),
386
- 'errors_count': len(task_info['errors'])
387
  })
388
-
389
- # Trier par heure de début (plus récent en premier)
390
- task_list.sort(key=lambda x: x['start_time'], reverse=True)
391
-
392
- return jsonify(task_list)
393
 
394
- @app.route('/cleanup')
395
- def cleanup_temp_files():
396
- """Nettoyer les fichiers temporaires"""
397
- try:
398
- temp_files_deleted = 0
399
- for filename in os.listdir(RESULTS_FOLDER):
400
- if filename.startswith('temp_results_') and filename.endswith('.json'):
401
- file_path = os.path.join(RESULTS_FOLDER, filename)
402
- os.remove(file_path)
403
- temp_files_deleted += 1
404
-
405
- return jsonify({
406
- 'message': f'{temp_files_deleted} fichiers temporaires supprimés'
407
- })
408
- except Exception as e:
409
- return jsonify({'error': f'Erreur lors du nettoyage: {str(e)}'}), 500
410
 
411
- @app.route('/preview/<task_id>')
412
- def preview_results(task_id):
413
- """Aperçu des résultats JSON pour debug"""
414
- task = task_manager.get_task(task_id)
415
- if not task:
416
- return jsonify({'error': 'Tâche non trouvée'}), 404
417
-
418
- results_file = os.path.join(RESULTS_FOLDER, f'results_{task_id}.json')
419
-
420
- if not os.path.exists(results_file):
421
- return jsonify({'error': 'Fichier de résultats non trouvé'}), 404
422
-
423
- try:
424
- with open(results_file, 'r', encoding='utf-8') as f:
425
- data = json.load(f)
426
-
427
- # Retourner un aperçu des données
428
- preview = {
429
- "metadata": data.get("metadata", {}),
430
- "summary": data.get("summary", {}),
431
- "sample_requests": data.get("requests", [])[:3], # 3 premiers échantillons
432
- "total_requests": len(data.get("requests", []))
 
 
 
 
 
 
 
 
433
  }
 
 
434
 
435
- return jsonify(preview)
436
-
437
- except Exception as e:
438
- return jsonify({'error': f'Erreur lors de la lecture du fichier: {str(e)}'}), 500
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
439
 
440
  if __name__ == '__main__':
441
- print("🚀 Démarrage du serveur Flask...")
442
- print("📂 Dossiers créés:", UPLOAD_FOLDER, RESULTS_FOLDER)
443
- print("🌐 Application disponible sur: http://localhost:5000")
444
- print("📊 Sortie JSON structurée activée avec schémas Pydantic")
445
- print("🔧 Modèle utilisé:", MODEL_ID)
446
- app.run(debug=True, threaded=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
  import json
 
 
 
 
3
  import uuid
4
+ import threading
5
+ import time
6
+ from datetime import datetime
7
+ from flask import Flask, request, render_template, jsonify, send_file
8
+ from flask_socketio import SocketIO, emit
9
+ from werkzeug.utils import secure_filename
10
+ import base64
11
+ from io import BytesIO
12
+ from PIL import Image
13
+ import pytesseract
14
+ from crewai import Agent, Task, Crew, Process, LLM
15
+ import re
16
+ import logging
17
 
18
+ # Configuration Flask
19
  app = Flask(__name__)
20
+ app.config['SECRET_KEY'] = 'votre_cle_secrete_ici'
21
+ app.config['UPLOAD_FOLDER'] = 'uploads'
22
+ app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16MB max
23
 
24
+ # Configuration SocketIO pour les logs en temps réel
25
+ socketio = SocketIO(app, cors_allowed_origins="*")
26
+
27
+ # Créer les dossiers nécessaires
28
+ os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
29
+ os.makedirs('solutions', exist_ok=True)
30
+
31
+ # Extensions d'images autorisées
32
+ ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'bmp', 'tiff'}
33
+
34
+ # Configuration Gemini API
35
+ os.environ["GEMINI_API_KEY"] = os.environ.get("GEMINI_API_KEY", "your_api_key_here")
36
+
37
+ # Dictionnaire global pour stocker les tâches en cours
38
+ active_tasks = {}
39
+
40
+ # Configuration du LLM
41
+ llm = LLM(
42
+ model="gemini/gemini-2.0-flash",
43
+ temperature=0.1,
44
+ timeout=120,
45
+ max_tokens=8000,
46
+ )
47
+
48
+ # Paramètres du pipeline
49
+ MAX_ITERATIONS = 5
50
+ PASSES_NEEDED_FOR_SUCCESS = 2
51
+
52
+ # ==============================================================================
53
+ # UTILITAIRES
54
+ # ==============================================================================
55
+
56
+ def allowed_file(filename):
57
+ return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
58
+
59
+ def extract_text_from_image(image_path):
60
+ """Extrait le texte d'une image en utilisant OCR."""
61
+ try:
62
+ # Ouvrir l'image
63
+ image = Image.open(image_path)
64
+
65
+ # Convertir en RGB si nécessaire
66
+ if image.mode != 'RGB':
67
+ image = image.convert('RGB')
68
+
69
+ # Extraire le texte avec pytesseract
70
+ text = pytesseract.image_to_string(image, lang='eng')
71
+
72
+ return text.strip()
73
+ except Exception as e:
74
+ return f"Erreur lors de l'extraction du texte: {str(e)}"
75
+
76
+ def emit_log(task_id, level, message):
77
+ """Émet un log vers le client via WebSocket."""
78
+ log_data = {
79
+ 'timestamp': datetime.now().strftime('%H:%M:%S'),
80
+ 'level': level,
81
+ 'message': message
82
+ }
83
+ socketio.emit('log_update', {'task_id': task_id, 'log': log_data})
84
+
85
+ # ==============================================================================
86
+ # PROMPTS (MÊME LOGIQUE QUE L'ORIGINAL)
87
+ # ==============================================================================
88
+
89
+ def get_imo_paper_solver_prompt(problem_statement, hint=""):
90
+ full_problem = f"{problem_statement}\n{hint}" if hint else problem_statement
91
+ return f"""
92
+ ### Core Instructions ###
93
+ **Rigor is Paramount:** Your primary goal is to produce a complete and rigorously justified solution.
94
+ You are solving an International Mathematical Olympiad (IMO) level problem.
95
+
96
+ ### Problem ###
97
+ {full_problem}
98
+
99
+ ### Your Task ###
100
+ Provide a complete, rigorous mathematical proof. Structure your solution clearly with:
101
+ 1. A brief summary of your approach
102
+ 2. A detailed step-by-step proof
103
+ 3. Clear justification for each step
104
+ """
105
+
106
+ def get_self_improve_prompt(solution_attempt):
107
+ return f"""
108
+ You are a world-class mathematician. You have just produced the following draft solution.
109
+ Review it carefully for flaws, gaps, or unclear parts, then produce a new, improved, and more rigorous version.
110
+
111
+ ### Draft Solution ###
112
+ {solution_attempt}
113
+
114
+ ### Your Task ###
115
+ Provide the improved and finalized version of the solution. Only output the final, clean proof.
116
+ """
117
+
118
+ def get_imo_paper_verifier_prompt(problem_statement, solution_to_verify):
119
+ return f"""
120
+ You are an expert mathematician and a meticulous grader for an IMO level exam.
121
+
122
+ ### Problem ###
123
+ {problem_statement}
124
+
125
+ ### Solution ###
126
+ {solution_to_verify}
127
+
128
+ ### Verification Task ###
129
+ Act as an IMO grader. Analyze the solution for:
130
+ 1. Mathematical correctness
131
+ 2. Logical gaps or errors
132
+ 3. Clarity and rigor
133
+
134
+ Provide your verdict in the format:
135
+ **Final Verdict:** [The solution is correct / Critical error found / Justification gaps found]
136
+
137
+ Then provide detailed feedback on any issues found.
138
+ """
139
+
140
+ def get_correction_prompt(solution_attempt, verification_report):
141
+ return f"""
142
+ You are a brilliant mathematician. Your previous solution attempt has been reviewed by a verifier.
143
+ Your task is to write a new, corrected version of your solution that addresses all the issues raised.
144
+
145
+ ### Verification Report ###
146
+ {verification_report}
147
+
148
+ ### Your Previous Solution ###
149
+ {solution_attempt}
150
+
151
+ ### Your Task ###
152
+ Provide a new, complete, and rigorously correct solution that fixes all identified issues.
153
+ """
154
+
155
+ # ==============================================================================
156
+ # AGENTS CREWAI
157
+ # ==============================================================================
158
+
159
+ solver_agent = Agent(
160
+ role='Mathématicien de classe mondiale et résolveur de problèmes créatifs',
161
+ goal='Générer et affiner des preuves mathématiques complètes et rigoureuses pour des problèmes de niveau Olympiades.',
162
+ backstory="""Médaillé d'or des OIM, vous êtes connu pour votre capacité à trouver des solutions
163
+ à la fois non conventionnelles et impeccablement rigoureuses. Vous excellez à décomposer
164
+ des problèmes complexes et à présenter des arguments clairs, étape par étape.""",
165
+ verbose=True,
166
+ allow_delegation=False,
167
+ llm=llm
168
+ )
169
+
170
+ verifier_agent = Agent(
171
+ role='Examinateur méticuleux pour les Olympiades Internationales de Mathématiques',
172
+ goal='Analyser de manière critique une preuve mathématique pour y trouver la moindre erreur logique ou le moindre manque de justification.',
173
+ backstory="""Professeur de mathématiques réputé, membre du comité de notation des OIM. Votre devise est 'la rigueur avant tout'.
174
+ Vous ne corrigez jamais, vous ne faites que juger et rapporter les failles.""",
175
+ verbose=True,
176
+ allow_delegation=False,
177
+ llm=llm
178
+ )
179
+
180
+ # ==============================================================================
181
+ # PIPELINE DE RÉSOLUTION
182
+ # ==============================================================================
183
+
184
+ def parse_verifier_verdict(report):
185
+ if not report:
186
+ return "ERROR"
187
 
188
+ report_text = str(report)
189
+ match = re.search(r"\*\*Final Verdict:\*\* (.*)", report_text, re.IGNORECASE)
190
+ if not match:
191
+ return "UNKNOWN"
192
 
193
+ verdict_text = match.group(1).lower()
194
+ if "the solution is correct" in verdict_text:
195
+ return "CORRECT"
196
+ if "critical error" in verdict_text:
197
+ return "CRITICAL_ERROR"
198
+ if "justification gap" in verdict_text:
199
+ return "GAPS"
200
+ return "UNKNOWN"
201
 
202
+ def run_imo_pipeline_async(task_id, problem_statement, initial_hint=""):
203
+ """Version asynchrone du pipeline avec émission de logs."""
204
  try:
205
+ emit_log(task_id, 'info', "🚀 Démarrage du Pipeline de Résolution Mathématique")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
206
 
207
+ # Étape 1: Génération Initiale
208
+ emit_log(task_id, 'info', "--- ÉTAPE 1: Génération de la Solution Initiale ---")
209
+
210
+ initial_task = Task(
211
+ description=get_imo_paper_solver_prompt(problem_statement, initial_hint),
212
+ expected_output="Une ébauche de preuve mathématique structurée avec un résumé et une solution détaillée.",
213
+ agent=solver_agent
214
+ )
215
+
216
+ initial_crew = Crew(
217
+ agents=[solver_agent],
218
+ tasks=[initial_task],
219
+ process=Process.sequential,
220
+ verbose=False
221
+ )
222
+
223
+ initial_result = initial_crew.kickoff()
224
+ initial_solution = initial_result.raw if hasattr(initial_result, 'raw') else str(initial_result)
225
+
226
+ emit_log(task_id, 'success', "✅ Solution initiale générée")
227
+
228
+ # Étape 2: Auto-Amélioration
229
+ emit_log(task_id, 'info', "--- ÉTAPE 2: Auto-Amélioration de la Solution ---")
230
+
231
+ improve_task = Task(
232
+ description=get_self_improve_prompt(initial_solution),
233
+ expected_output="Une version améliorée et plus rigoureuse de la preuve.",
234
+ agent=solver_agent
235
+ )
236
+
237
+ improve_crew = Crew(
238
+ agents=[solver_agent],
239
+ tasks=[improve_task],
240
+ process=Process.sequential,
241
+ verbose=False
242
+ )
243
+
244
+ improve_result = improve_crew.kickoff()
245
+ current_solution = improve_result.raw if hasattr(improve_result, 'raw') else str(improve_result)
246
+
247
+ emit_log(task_id, 'success', "✅ Solution améliorée")
248
+
249
+ # Boucle de Vérification
250
+ iteration = 0
251
+ consecutive_passes = 0
252
+
253
+ while iteration < MAX_ITERATIONS:
254
+ iteration += 1
255
+ emit_log(task_id, 'info', f"--- CYCLE DE VÉRIFICATION {iteration}/{MAX_ITERATIONS} ---")
256
+
257
+ verify_task = Task(
258
+ description=get_imo_paper_verifier_prompt(problem_statement, current_solution),
259
+ expected_output="Un rapport de vérification complet au format OIM.",
260
+ agent=verifier_agent
261
+ )
262
+
263
+ correct_task = Task(
264
+ description=get_correction_prompt(current_solution, "Rapport du vérificateur (voir contexte)"),
265
+ expected_output="Une nouvelle version complète et corrigée de la preuve mathématique.",
266
+ agent=solver_agent,
267
+ context=[verify_task]
268
+ )
269
+
270
+ correction_crew = Crew(
271
+ agents=[verifier_agent, solver_agent],
272
+ tasks=[verify_task, correct_task],
273
+ process=Process.sequential,
274
+ verbose=False
275
+ )
276
+
277
+ cycle_result = correction_crew.kickoff()
278
+
279
+ if hasattr(cycle_result, 'tasks_output') and len(cycle_result.tasks_output) >= 2:
280
+ verification_report = cycle_result.tasks_output[0].raw
281
+ corrected_solution = cycle_result.tasks_output[1].raw
282
+ else:
283
+ verification_report = str(cycle_result)
284
+ corrected_solution = str(cycle_result)
285
+
286
+ verdict = parse_verifier_verdict(verification_report)
287
+
288
+ emit_log(task_id, 'info', f"VERDICT DU CYCLE {iteration}: {verdict}")
289
+
290
+ if verdict == "CORRECT":
291
+ consecutive_passes += 1
292
+ emit_log(task_id, 'success', f"✅ PASSAGE RÉUSSI ! Passes consécutives : {consecutive_passes}/{PASSES_NEEDED_FOR_SUCCESS}")
293
+ if consecutive_passes >= PASSES_NEEDED_FOR_SUCCESS:
294
+ emit_log(task_id, 'success', "🏆 La solution a été validée avec succès ! 🏆")
295
 
296
+ # Sauvegarder la solution
297
+ solution_file = f"solutions/solution_{task_id}.txt"
298
+ with open(solution_file, 'w', encoding='utf-8') as f:
299
+ f.write(f"Problème:\n{problem_statement}\n\n")
300
+ f.write(f"Solution finale:\n{current_solution}")
 
 
 
 
 
 
 
 
 
 
 
 
301
 
302
+ active_tasks[task_id]['status'] = 'completed'
303
+ active_tasks[task_id]['solution_file'] = solution_file
 
304
 
305
+ socketio.emit('task_completed', {'task_id': task_id})
306
+ return current_solution
307
+ else:
308
+ consecutive_passes = 0
309
+ emit_log(task_id, 'warning', "⚠️ Problèmes détectés. Correction en cours...")
310
+ current_solution = corrected_solution
311
+
312
+ emit_log(task_id, 'error', f" Échec après {MAX_ITERATIONS} itérations")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
313
 
314
+ # Sauvegarder la solution partielle
315
+ solution_file = f"solutions/solution_{task_id}_partial.txt"
316
+ with open(solution_file, 'w', encoding='utf-8') as f:
317
+ f.write(f"Problème:\n{problem_statement}\n\n")
318
+ f.write(f"Solution partielle (non validée):\n{current_solution}")
 
 
319
 
320
+ active_tasks[task_id]['status'] = 'failed'
321
+ active_tasks[task_id]['solution_file'] = solution_file
322
 
323
+ socketio.emit('task_failed', {'task_id': task_id})
324
+ return current_solution
325
 
326
  except Exception as e:
327
+ emit_log(task_id, 'error', f"Erreur critique: {str(e)}")
328
+ active_tasks[task_id]['status'] = 'error'
329
+ active_tasks[task_id]['error'] = str(e)
330
+ socketio.emit('task_error', {'task_id': task_id, 'error': str(e)})
331
+
332
+ # ==============================================================================
333
+ # ROUTES FLASK
334
+ # ==============================================================================
335
 
336
  @app.route('/')
337
  def index():
 
340
  @app.route('/upload', methods=['POST'])
341
  def upload_file():
342
  if 'file' not in request.files:
343
+ return jsonify({'error': 'Aucun fichier fourni'}), 400
344
 
345
  file = request.files['file']
346
  if file.filename == '':
347
  return jsonify({'error': 'Aucun fichier sélectionné'}), 400
348
 
349
+ if file and allowed_file(file.filename):
350
+ # Générer un ID de tâche unique
351
  task_id = str(uuid.uuid4())
352
 
353
  # Sauvegarder le fichier
354
+ filename = secure_filename(file.filename)
355
+ filepath = os.path.join(app.config['UPLOAD_FOLDER'], f"{task_id}_{filename}")
356
+ file.save(filepath)
 
 
 
 
 
 
 
 
 
 
 
357
 
358
+ # Extraire le texte de l'image
359
+ try:
360
+ extracted_text = extract_text_from_image(filepath)
361
+
362
+ # Initialiser la tâche
363
+ active_tasks[task_id] = {
364
+ 'status': 'processing',
365
+ 'problem': extracted_text,
366
+ 'started_at': datetime.now(),
367
+ 'filename': filename
368
+ }
369
+
370
+ # Lancer le pipeline en arrière-plan
371
+ thread = threading.Thread(
372
+ target=run_imo_pipeline_async,
373
+ args=(task_id, extracted_text)
374
+ )
375
+ thread.daemon = True
376
+ thread.start()
377
+
378
+ return jsonify({
379
+ 'task_id': task_id,
380
+ 'extracted_text': extracted_text,
381
+ 'message': 'Traitement commencé'
382
+ })
383
+
384
+ except Exception as e:
385
+ return jsonify({'error': f'Erreur lors du traitement de l\'image: {str(e)}'}), 500
386
+
387
+ return jsonify({'error': 'Type de fichier non autorisé'}), 400
388
 
389
  @app.route('/status/<task_id>')
390
  def get_status(task_id):
391
+ if task_id not in active_tasks:
 
392
  return jsonify({'error': 'Tâche non trouvée'}), 404
393
 
394
+ task = active_tasks[task_id]
 
 
 
 
 
 
 
 
395
  return jsonify({
396
+ 'task_id': task_id,
397
  'status': task['status'],
398
+ 'problem': task.get('problem', ''),
399
+ 'started_at': task['started_at'].isoformat(),
400
+ 'has_solution': 'solution_file' in task
 
 
 
 
401
  })
402
 
403
  @app.route('/download/<task_id>')
404
+ def download_solution(task_id):
405
+ if task_id not in active_tasks:
 
406
  return jsonify({'error': 'Tâche non trouvée'}), 404
407
 
408
+ task = active_tasks[task_id]
409
+ if 'solution_file' not in task:
410
+ return jsonify({'error': 'Aucune solution disponible'}), 404
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
411
 
412
+ return send_file(task['solution_file'], as_attachment=True, download_name=f'solution_{task_id}.txt')
 
 
 
 
413
 
414
  @app.route('/tasks')
415
  def list_tasks():
416
+ tasks_info = []
417
+ for task_id, task in active_tasks.items():
418
+ tasks_info.append({
419
+ 'task_id': task_id,
420
+ 'status': task['status'],
421
+ 'filename': task.get('filename', ''),
422
+ 'started_at': task['started_at'].isoformat(),
423
+ 'has_solution': 'solution_file' in task
 
 
 
 
424
  })
425
+ return jsonify(tasks_info)
 
 
 
 
426
 
427
+ # ==============================================================================
428
+ # TEMPLATE HTML
429
+ # ==============================================================================
 
 
 
 
 
 
 
 
 
 
 
 
 
430
 
431
+ @app.route('/template')
432
+ def get_template():
433
+ template_content = '''<!DOCTYPE html>
434
+ <html lang="fr">
435
+ <head>
436
+ <meta charset="UTF-8">
437
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
438
+ <title>Résolveur Mathématique IMO</title>
439
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.4/socket.io.js"></script>
440
+ <style>
441
+ * { margin: 0; padding: 0; box-sizing: border-box; }
442
+ body {
443
+ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
444
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
445
+ min-height: 100vh;
446
+ padding: 20px;
447
+ }
448
+ .container {
449
+ max-width: 1200px;
450
+ margin: 0 auto;
451
+ background: white;
452
+ border-radius: 15px;
453
+ box-shadow: 0 20px 40px rgba(0,0,0,0.1);
454
+ overflow: hidden;
455
+ }
456
+ .header {
457
+ background: linear-gradient(135deg, #2196F3, #21CBF3);
458
+ padding: 30px;
459
+ text-align: center;
460
+ color: white;
461
  }
462
+ .header h1 { font-size: 2.5em; margin-bottom: 10px; }
463
+ .header p { font-size: 1.1em; opacity: 0.9; }
464
 
465
+ .upload-section {
466
+ padding: 40px;
467
+ text-align: center;
468
+ border-bottom: 1px solid #eee;
469
+ }
470
+ .upload-box {
471
+ border: 3px dashed #ddd;
472
+ border-radius: 10px;
473
+ padding: 40px;
474
+ transition: all 0.3s ease;
475
+ cursor: pointer;
476
+ }
477
+ .upload-box:hover { border-color: #2196F3; background: #f8f9ff; }
478
+ .upload-box.dragover { border-color: #2196F3; background: #e3f2fd; }
479
+
480
+ .btn {
481
+ background: linear-gradient(135deg, #2196F3, #21CBF3);
482
+ color: white;
483
+ padding: 12px 30px;
484
+ border: none;
485
+ border-radius: 25px;
486
+ font-size: 16px;
487
+ cursor: pointer;
488
+ transition: all 0.3s ease;
489
+ }
490
+ .btn:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(33,150,243,0.3); }
491
+
492
+ .logs-section {
493
+ display: flex;
494
+ height: 600px;
495
+ }
496
+ .extracted-text {
497
+ flex: 1;
498
+ padding: 20px;
499
+ border-right: 1px solid #eee;
500
+ }
501
+ .logs-panel {
502
+ flex: 1;
503
+ padding: 20px;
504
+ }
505
+ .log-container {
506
+ height: 500px;
507
+ overflow-y: auto;
508
+ background: #1e1e1e;
509
+ color: #fff;
510
+ padding: 15px;
511
+ border-radius: 8px;
512
+ font-family: 'Courier New', monospace;
513
+ font-size: 13px;
514
+ }
515
+ .log-entry {
516
+ margin-bottom: 5px;
517
+ padding: 5px;
518
+ border-radius: 3px;
519
+ }
520
+ .log-info { color: #4CAF50; }
521
+ .log-success { color: #8BC34A; background: rgba(139,195,74,0.1); }
522
+ .log-warning { color: #FF9800; }
523
+ .log-error { color: #F44336; background: rgba(244,67,54,0.1); }
524
+
525
+ .status-bar {
526
+ padding: 20px;
527
+ background: #f5f5f5;
528
+ text-align: center;
529
+ }
530
+ .status-badge {
531
+ display: inline-block;
532
+ padding: 8px 16px;
533
+ border-radius: 20px;
534
+ font-weight: bold;
535
+ text-transform: uppercase;
536
+ }
537
+ .status-processing { background: #FFC107; color: #333; }
538
+ .status-completed { background: #4CAF50; color: white; }
539
+ .status-failed { background: #F44336; color: white; }
540
+
541
+ .download-section {
542
+ padding: 20px;
543
+ text-align: center;
544
+ display: none;
545
+ }
546
+ .hidden { display: none; }
547
+ </style>
548
+ </head>
549
+ <body>
550
+ <div class="container">
551
+ <div class="header">
552
+ <h1>🧮 Résolveur Mathématique IMO</h1>
553
+ <p>Uploadez une image de votre problème mathématique et obtenez une solution rigoureuse</p>
554
+ </div>
555
+
556
+ <div class="upload-section">
557
+ <div class="upload-box" id="uploadBox">
558
+ <h3>📁 Glisser-déposer votre image ici</h3>
559
+ <p>ou cliquez pour sélectionner un fichier</p>
560
+ <input type="file" id="fileInput" accept="image/*" style="display: none;">
561
+ <button class="btn" onclick="document.getElementById('fileInput').click()">
562
+ Choisir un fichier
563
+ </button>
564
+ </div>
565
+ </div>
566
+
567
+ <div class="status-bar">
568
+ <div id="statusBadge" class="status-badge" style="display: none;">En attente</div>
569
+ <div id="taskInfo" style="margin-top: 10px; display: none;"></div>
570
+ </div>
571
+
572
+ <div class="logs-section hidden" id="logsSection">
573
+ <div class="extracted-text">
574
+ <h3>📝 Texte extrait de l'image</h3>
575
+ <div id="extractedText" style="background: #f9f9f9; padding: 15px; border-radius: 8px; margin-top: 10px; white-space: pre-wrap; max-height: 450px; overflow-y: auto;"></div>
576
+ </div>
577
+ <div class="logs-panel">
578
+ <h3>📊 Logs de traitement en temps réel</h3>
579
+ <div id="logContainer" class="log-container"></div>
580
+ </div>
581
+ </div>
582
+
583
+ <div class="download-section" id="downloadSection">
584
+ <h3>✅ Solution prête !</h3>
585
+ <button class="btn" id="downloadBtn">📥 Télécharger la solution</button>
586
+ </div>
587
+ </div>
588
+
589
+ <script>
590
+ const socket = io();
591
+ let currentTaskId = null;
592
+
593
+ // Gestion de l'upload
594
+ const uploadBox = document.getElementById('uploadBox');
595
+ const fileInput = document.getElementById('fileInput');
596
+
597
+ uploadBox.addEventListener('click', () => fileInput.click());
598
+ uploadBox.addEventListener('dragover', (e) => {
599
+ e.preventDefault();
600
+ uploadBox.classList.add('dragover');
601
+ });
602
+ uploadBox.addEventListener('dragleave', () => {
603
+ uploadBox.classList.remove('dragover');
604
+ });
605
+ uploadBox.addEventListener('drop', (e) => {
606
+ e.preventDefault();
607
+ uploadBox.classList.remove('dragover');
608
+ const files = e.dataTransfer.files;
609
+ if (files.length > 0) {
610
+ uploadFile(files[0]);
611
+ }
612
+ });
613
+
614
+ fileInput.addEventListener('change', (e) => {
615
+ if (e.target.files.length > 0) {
616
+ uploadFile(e.target.files[0]);
617
+ }
618
+ });
619
+
620
+ function uploadFile(file) {
621
+ const formData = new FormData();
622
+ formData.append('file', file);
623
+
624
+ updateStatus('processing', 'Upload en cours...');
625
+
626
+ fetch('/upload', {
627
+ method: 'POST',
628
+ body: formData
629
+ })
630
+ .then(response => response.json())
631
+ .then(data => {
632
+ if (data.error) {
633
+ updateStatus('failed', data.error);
634
+ } else {
635
+ currentTaskId = data.task_id;
636
+ document.getElementById('extractedText').textContent = data.extracted_text;
637
+ document.getElementById('logsSection').classList.remove('hidden');
638
+ updateStatus('processing', 'Résolution en cours...');
639
+ }
640
+ })
641
+ .catch(error => {
642
+ updateStatus('failed', 'Erreur lors de l\'upload');
643
+ console.error('Error:', error);
644
+ });
645
+ }
646
+
647
+ function updateStatus(status, message) {
648
+ const badge = document.getElementById('statusBadge');
649
+ const info = document.getElementById('taskInfo');
650
+
651
+ badge.style.display = 'inline-block';
652
+ badge.className = `status-badge status-${status}`;
653
+ badge.textContent = status === 'processing' ? 'En cours' :
654
+ status === 'completed' ? 'Terminé' : 'Échec';
655
+
656
+ info.style.display = 'block';
657
+ info.textContent = message;
658
+ }
659
+
660
+ function addLog(timestamp, level, message) {
661
+ const container = document.getElementById('logContainer');
662
+ const logEntry = document.createElement('div');
663
+ logEntry.className = `log-entry log-${level}`;
664
+ logEntry.innerHTML = `<span style="color: #666;">[${timestamp}]</span> ${message}`;
665
+ container.appendChild(logEntry);
666
+ container.scrollTop = container.scrollHeight;
667
+ }
668
+
669
+ // WebSocket events
670
+ socket.on('log_update', (data) => {
671
+ if (data.task_id === currentTaskId) {
672
+ addLog(data.log.timestamp, data.log.level, data.log.message);
673
+ }
674
+ });
675
+
676
+ socket.on('task_completed', (data) => {
677
+ if (data.task_id === currentTaskId) {
678
+ updateStatus('completed', 'Solution générée avec succès !');
679
+ const downloadSection = document.getElementById('downloadSection');
680
+ downloadSection.style.display = 'block';
681
+
682
+ document.getElementById('downloadBtn').onclick = () => {
683
+ window.location.href = `/download/${currentTaskId}`;
684
+ };
685
+ }
686
+ });
687
+
688
+ socket.on('task_failed', (data) => {
689
+ if (data.task_id === currentTaskId) {
690
+ updateStatus('failed', 'Échec de la résolution (solution partielle disponible)');
691
+ const downloadSection = document.getElementById('downloadSection');
692
+ downloadSection.style.display = 'block';
693
+
694
+ document.getElementById('downloadBtn').onclick = () => {
695
+ window.location.href = `/download/${currentTaskId}`;
696
+ };
697
+ }
698
+ });
699
+
700
+ socket.on('task_error', (data) => {
701
+ if (data.task_id === currentTaskId) {
702
+ updateStatus('failed', `Erreur: ${data.error}`);
703
+ }
704
+ });
705
+ </script>
706
+ </body>
707
+ </html>'''
708
+ return template_content
709
 
710
  if __name__ == '__main__':
711
+ # Créer le template dans le dossier templates
712
+ os.makedirs('templates', exist_ok=True)
713
+ with open('templates/index.html', 'w', encoding='utf-8') as f:
714
+ # Récupérer le contenu du template depuis la route
715
+ from flask import Flask
716
+ temp_app = Flask(__name__)
717
+ with temp_app.app_context():
718
+ template_content = get_template()
719
+ f.write(template_content)
720
+
721
+ print("🚀 Démarrage de l'application Flask...")
722
+ print("📝 Template HTML créé dans templates/index.html")
723
+ print("🌐 Application disponible sur http://localhost:5000")
724
+
725
+ socketio.run(app, debug=True, host='0.0.0.0', port=5000)