Update app.py
Browse files
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
|
|
|
|
| 13 |
app = Flask(__name__)
|
|
|
|
|
|
|
|
|
|
| 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 |
-
def
|
| 79 |
-
"""
|
| 80 |
try:
|
| 81 |
-
|
| 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 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 136 |
|
| 137 |
-
#
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
"
|
| 141 |
-
"
|
| 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 |
-
|
| 156 |
-
|
| 157 |
-
all_results["summary"]["completed_requests"] += 1
|
| 158 |
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 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 |
-
#
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 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 |
-
|
| 246 |
-
|
| 247 |
|
| 248 |
-
|
| 249 |
-
|
| 250 |
|
| 251 |
except Exception as e:
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
| 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
|
| 271 |
task_id = str(uuid.uuid4())
|
| 272 |
|
| 273 |
# Sauvegarder le fichier
|
| 274 |
-
filename =
|
| 275 |
-
|
| 276 |
-
file.save(
|
| 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 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 294 |
|
| 295 |
@app.route('/status/<task_id>')
|
| 296 |
def get_status(task_id):
|
| 297 |
-
|
| 298 |
-
if not task:
|
| 299 |
return jsonify({'error': 'Tâche non trouvée'}), 404
|
| 300 |
|
| 301 |
-
|
| 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 |
-
'
|
| 313 |
-
'
|
| 314 |
-
'
|
| 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
|
| 323 |
-
|
| 324 |
-
if not task:
|
| 325 |
return jsonify({'error': 'Tâche non trouvée'}), 404
|
| 326 |
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 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 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
'
|
| 380 |
-
'
|
| 381 |
-
'
|
| 382 |
-
'
|
| 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 |
-
|
| 395 |
-
|
| 396 |
-
|
| 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('/
|
| 412 |
-
def
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 433 |
}
|
|
|
|
|
|
|
| 434 |
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 439 |
|
| 440 |
if __name__ == '__main__':
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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)
|