|
import os |
|
import json |
|
import uuid |
|
import threading |
|
import time |
|
from datetime import datetime |
|
from flask import Flask, request, render_template, jsonify, send_file |
|
from flask_socketio import SocketIO, emit |
|
from werkzeug.utils import secure_filename |
|
import base64 |
|
from io import BytesIO |
|
from PIL import Image |
|
import pytesseract |
|
from crewai import Agent, Task, Crew, Process, LLM |
|
import re |
|
import logging |
|
|
|
|
|
app = Flask(__name__) |
|
app.config['SECRET_KEY'] = 'votre_cle_secrete_ici' |
|
app.config['UPLOAD_FOLDER'] = 'uploads' |
|
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 |
|
|
|
|
|
socketio = SocketIO(app, cors_allowed_origins="*") |
|
|
|
|
|
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True) |
|
os.makedirs('solutions', exist_ok=True) |
|
|
|
|
|
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'bmp', 'tiff'} |
|
|
|
|
|
os.environ["GEMINI_API_KEY"] = os.environ.get("GEMINI_API_KEY", "AIzaSyAMYpF67aqFnWDJESWOx1dC-w3sEU29VcM") |
|
|
|
|
|
active_tasks = {} |
|
|
|
|
|
llm = LLM( |
|
model="gemini/gemini-2.5-flash", |
|
temperature=0.1, |
|
|
|
) |
|
|
|
|
|
MAX_ITERATIONS = 5 |
|
PASSES_NEEDED_FOR_SUCCESS = 2 |
|
|
|
|
|
|
|
|
|
|
|
def allowed_file(filename): |
|
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS |
|
|
|
def extract_text_from_image(image_path): |
|
"""Extrait le texte d'une image en utilisant OCR.""" |
|
try: |
|
|
|
image = Image.open(image_path) |
|
|
|
|
|
if image.mode != 'RGB': |
|
image = image.convert('RGB') |
|
|
|
|
|
text = pytesseract.image_to_string(image, lang='eng') |
|
|
|
return text.strip() |
|
except Exception as e: |
|
return f"Erreur lors de l'extraction du texte: {str(e)}" |
|
|
|
def emit_log(task_id, level, message): |
|
"""Émet un log vers le client via WebSocket.""" |
|
log_data = { |
|
'timestamp': datetime.now().strftime('%H:%M:%S'), |
|
'level': level, |
|
'message': message |
|
} |
|
socketio.emit('log_update', {'task_id': task_id, 'log': log_data}) |
|
|
|
|
|
|
|
|
|
|
|
def get_imo_paper_solver_prompt(problem_statement, hint=""): |
|
full_problem = f"{problem_statement}\n{hint}" if hint else problem_statement |
|
return f""" |
|
### Core Instructions ### |
|
**Rigor is Paramount:** Your primary goal is to produce a complete and rigorously justified solution. |
|
You are solving an International Mathematical Olympiad (IMO) level problem. |
|
|
|
### Problem ### |
|
{full_problem} |
|
|
|
### Your Task ### |
|
Provide a complete, rigorous mathematical proof. Structure your solution clearly with: |
|
1. A brief summary of your approach |
|
2. A detailed step-by-step proof |
|
3. Clear justification for each step |
|
""" |
|
|
|
def get_self_improve_prompt(solution_attempt): |
|
return f""" |
|
You are a world-class mathematician. You have just produced the following draft solution. |
|
Review it carefully for flaws, gaps, or unclear parts, then produce a new, improved, and more rigorous version. |
|
|
|
### Draft Solution ### |
|
{solution_attempt} |
|
|
|
### Your Task ### |
|
Provide the improved and finalized version of the solution. Only output the final, clean proof. |
|
""" |
|
|
|
def get_imo_paper_verifier_prompt(problem_statement, solution_to_verify): |
|
return f""" |
|
You are an expert mathematician and a meticulous grader for an IMO level exam. |
|
|
|
### Problem ### |
|
{problem_statement} |
|
|
|
### Solution ### |
|
{solution_to_verify} |
|
|
|
### Verification Task ### |
|
Act as an IMO grader. Analyze the solution for: |
|
1. Mathematical correctness |
|
2. Logical gaps or errors |
|
3. Clarity and rigor |
|
|
|
Provide your verdict in the format: |
|
**Final Verdict:** [The solution is correct / Critical error found / Justification gaps found] |
|
|
|
Then provide detailed feedback on any issues found. |
|
""" |
|
|
|
def get_correction_prompt(solution_attempt, verification_report): |
|
return f""" |
|
You are a brilliant mathematician. Your previous solution attempt has been reviewed by a verifier. |
|
Your task is to write a new, corrected version of your solution that addresses all the issues raised. |
|
|
|
### Verification Report ### |
|
{verification_report} |
|
|
|
### Your Previous Solution ### |
|
{solution_attempt} |
|
|
|
### Your Task ### |
|
Provide a new, complete, and rigorously correct solution that fixes all identified issues. |
|
""" |
|
|
|
|
|
|
|
|
|
|
|
solver_agent = Agent( |
|
role='Mathématicien de classe mondiale et résolveur de problèmes créatifs', |
|
goal='Générer et affiner des preuves mathématiques complètes et rigoureuses pour des problèmes de niveau Olympiades.', |
|
backstory="""Médaillé d'or des OIM, vous êtes connu pour votre capacité à trouver des solutions |
|
à la fois non conventionnelles et impeccablement rigoureuses. Vous excellez à décomposer |
|
des problèmes complexes et à présenter des arguments clairs, étape par étape.""", |
|
verbose=True, |
|
allow_delegation=False, |
|
llm=llm |
|
) |
|
|
|
verifier_agent = Agent( |
|
role='Examinateur méticuleux pour les Olympiades Internationales de Mathématiques', |
|
goal='Analyser de manière critique une preuve mathématique pour y trouver la moindre erreur logique ou le moindre manque de justification.', |
|
backstory="""Professeur de mathématiques réputé, membre du comité de notation des OIM. Votre devise est 'la rigueur avant tout'. |
|
Vous ne corrigez jamais, vous ne faites que juger et rapporter les failles.""", |
|
verbose=True, |
|
allow_delegation=False, |
|
llm=llm |
|
) |
|
|
|
|
|
|
|
|
|
|
|
def parse_verifier_verdict(report): |
|
if not report: |
|
return "ERROR" |
|
|
|
report_text = str(report) |
|
match = re.search(r"\*\*Final Verdict:\*\* (.*)", report_text, re.IGNORECASE) |
|
if not match: |
|
return "UNKNOWN" |
|
|
|
verdict_text = match.group(1).lower() |
|
if "the solution is correct" in verdict_text: |
|
return "CORRECT" |
|
if "critical error" in verdict_text: |
|
return "CRITICAL_ERROR" |
|
if "justification gap" in verdict_text: |
|
return "GAPS" |
|
return "UNKNOWN" |
|
|
|
def run_imo_pipeline_async(task_id, problem_statement, initial_hint=""): |
|
"""Version asynchrone du pipeline avec émission de logs.""" |
|
try: |
|
emit_log(task_id, 'info', "🚀 Démarrage du Pipeline de Résolution Mathématique") |
|
|
|
|
|
emit_log(task_id, 'info', "--- ÉTAPE 1: Génération de la Solution Initiale ---") |
|
|
|
initial_task = Task( |
|
description=get_imo_paper_solver_prompt(problem_statement, initial_hint), |
|
expected_output="Une ébauche de preuve mathématique structurée avec un résumé et une solution détaillée.", |
|
agent=solver_agent |
|
) |
|
|
|
initial_crew = Crew( |
|
agents=[solver_agent], |
|
tasks=[initial_task], |
|
process=Process.sequential, |
|
verbose=False |
|
) |
|
|
|
initial_result = initial_crew.kickoff() |
|
initial_solution = initial_result.raw if hasattr(initial_result, 'raw') else str(initial_result) |
|
|
|
emit_log(task_id, 'success', "✅ Solution initiale générée") |
|
|
|
|
|
emit_log(task_id, 'info', "--- ÉTAPE 2: Auto-Amélioration de la Solution ---") |
|
|
|
improve_task = Task( |
|
description=get_self_improve_prompt(initial_solution), |
|
expected_output="Une version améliorée et plus rigoureuse de la preuve.", |
|
agent=solver_agent |
|
) |
|
|
|
improve_crew = Crew( |
|
agents=[solver_agent], |
|
tasks=[improve_task], |
|
process=Process.sequential, |
|
verbose=False |
|
) |
|
|
|
improve_result = improve_crew.kickoff() |
|
current_solution = improve_result.raw if hasattr(improve_result, 'raw') else str(improve_result) |
|
|
|
emit_log(task_id, 'success', "✅ Solution améliorée") |
|
|
|
|
|
iteration = 0 |
|
consecutive_passes = 0 |
|
|
|
while iteration < MAX_ITERATIONS: |
|
iteration += 1 |
|
emit_log(task_id, 'info', f"--- CYCLE DE VÉRIFICATION {iteration}/{MAX_ITERATIONS} ---") |
|
|
|
verify_task = Task( |
|
description=get_imo_paper_verifier_prompt(problem_statement, current_solution), |
|
expected_output="Un rapport de vérification complet au format OIM.", |
|
agent=verifier_agent |
|
) |
|
|
|
correct_task = Task( |
|
description=get_correction_prompt(current_solution, "Rapport du vérificateur (voir contexte)"), |
|
expected_output="Une nouvelle version complète et corrigée de la preuve mathématique.", |
|
agent=solver_agent, |
|
context=[verify_task] |
|
) |
|
|
|
correction_crew = Crew( |
|
agents=[verifier_agent, solver_agent], |
|
tasks=[verify_task, correct_task], |
|
process=Process.sequential, |
|
verbose=False |
|
) |
|
|
|
cycle_result = correction_crew.kickoff() |
|
|
|
if hasattr(cycle_result, 'tasks_output') and len(cycle_result.tasks_output) >= 2: |
|
verification_report = cycle_result.tasks_output[0].raw |
|
corrected_solution = cycle_result.tasks_output[1].raw |
|
else: |
|
verification_report = str(cycle_result) |
|
corrected_solution = str(cycle_result) |
|
|
|
verdict = parse_verifier_verdict(verification_report) |
|
|
|
emit_log(task_id, 'info', f"VERDICT DU CYCLE {iteration}: {verdict}") |
|
|
|
if verdict == "CORRECT": |
|
consecutive_passes += 1 |
|
emit_log(task_id, 'success', f"✅ PASSAGE RÉUSSI ! Passes consécutives : {consecutive_passes}/{PASSES_NEEDED_FOR_SUCCESS}") |
|
if consecutive_passes >= PASSES_NEEDED_FOR_SUCCESS: |
|
emit_log(task_id, 'success', "🏆 La solution a été validée avec succès ! 🏆") |
|
|
|
|
|
solution_file = f"solutions/solution_{task_id}.txt" |
|
with open(solution_file, 'w', encoding='utf-8') as f: |
|
f.write(f"Problème:\n{problem_statement}\n\n") |
|
f.write(f"Solution finale:\n{current_solution}") |
|
|
|
active_tasks[task_id]['status'] = 'completed' |
|
active_tasks[task_id]['solution_file'] = solution_file |
|
|
|
socketio.emit('task_completed', {'task_id': task_id}) |
|
return current_solution |
|
else: |
|
consecutive_passes = 0 |
|
emit_log(task_id, 'warning', "⚠️ Problèmes détectés. Correction en cours...") |
|
current_solution = corrected_solution |
|
|
|
emit_log(task_id, 'error', f"❌ Échec après {MAX_ITERATIONS} itérations") |
|
|
|
|
|
solution_file = f"solutions/solution_{task_id}_partial.txt" |
|
with open(solution_file, 'w', encoding='utf-8') as f: |
|
f.write(f"Problème:\n{problem_statement}\n\n") |
|
f.write(f"Solution partielle (non validée):\n{current_solution}") |
|
|
|
active_tasks[task_id]['status'] = 'failed' |
|
active_tasks[task_id]['solution_file'] = solution_file |
|
|
|
socketio.emit('task_failed', {'task_id': task_id}) |
|
return current_solution |
|
|
|
except Exception as e: |
|
emit_log(task_id, 'error', f"❌ Erreur critique: {str(e)}") |
|
active_tasks[task_id]['status'] = 'error' |
|
active_tasks[task_id]['error'] = str(e) |
|
socketio.emit('task_error', {'task_id': task_id, 'error': str(e)}) |
|
|
|
|
|
|
|
|
|
|
|
@app.route('/') |
|
def index(): |
|
return render_template('index.html') |
|
|
|
@app.route('/upload', methods=['POST']) |
|
def upload_file(): |
|
if 'file' not in request.files: |
|
return jsonify({'error': 'Aucun fichier fourni'}), 400 |
|
|
|
file = request.files['file'] |
|
if file.filename == '': |
|
return jsonify({'error': 'Aucun fichier sélectionné'}), 400 |
|
|
|
if file and allowed_file(file.filename): |
|
|
|
task_id = str(uuid.uuid4()) |
|
|
|
|
|
filename = secure_filename(file.filename) |
|
filepath = os.path.join(app.config['UPLOAD_FOLDER'], f"{task_id}_{filename}") |
|
file.save(filepath) |
|
|
|
|
|
try: |
|
extracted_text = extract_text_from_image(filepath) |
|
|
|
|
|
active_tasks[task_id] = { |
|
'status': 'processing', |
|
'problem': extracted_text, |
|
'started_at': datetime.now(), |
|
'filename': filename |
|
} |
|
|
|
|
|
thread = threading.Thread( |
|
target=run_imo_pipeline_async, |
|
args=(task_id, extracted_text) |
|
) |
|
thread.daemon = True |
|
thread.start() |
|
|
|
return jsonify({ |
|
'task_id': task_id, |
|
'extracted_text': extracted_text, |
|
'message': 'Traitement commencé' |
|
}) |
|
|
|
except Exception as e: |
|
return jsonify({'error': f'Erreur lors du traitement de l\'image: {str(e)}'}), 500 |
|
|
|
return jsonify({'error': 'Type de fichier non autorisé'}), 400 |
|
|
|
@app.route('/status/<task_id>') |
|
def get_status(task_id): |
|
if task_id not in active_tasks: |
|
return jsonify({'error': 'Tâche non trouvée'}), 404 |
|
|
|
task = active_tasks[task_id] |
|
return jsonify({ |
|
'task_id': task_id, |
|
'status': task['status'], |
|
'problem': task.get('problem', ''), |
|
'started_at': task['started_at'].isoformat(), |
|
'has_solution': 'solution_file' in task |
|
}) |
|
|
|
@app.route('/download/<task_id>') |
|
def download_solution(task_id): |
|
if task_id not in active_tasks: |
|
return jsonify({'error': 'Tâche non trouvée'}), 404 |
|
|
|
task = active_tasks[task_id] |
|
if 'solution_file' not in task: |
|
return jsonify({'error': 'Aucune solution disponible'}), 404 |
|
|
|
return send_file(task['solution_file'], as_attachment=True, download_name=f'solution_{task_id}.txt') |
|
|
|
@app.route('/tasks') |
|
def list_tasks(): |
|
tasks_info = [] |
|
for task_id, task in active_tasks.items(): |
|
tasks_info.append({ |
|
'task_id': task_id, |
|
'status': task['status'], |
|
'filename': task.get('filename', ''), |
|
'started_at': task['started_at'].isoformat(), |
|
'has_solution': 'solution_file' in task |
|
}) |
|
return jsonify(tasks_info) |
|
|
|
|
|
|
|
|
|
|
|
@app.route('/template') |
|
def get_template(): |
|
template_content = ''' |
|
<!DOCTYPE html> |
|
<html lang="fr"> |
|
<head> |
|
<meta charset="UTF-8"> |
|
<meta name="viewport" content="width=device-width, initial-scale=1.0"> |
|
<title>Résolveur Mathématique IMO - Version 2</title> |
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.4/socket.io.js"></script> |
|
<style> |
|
:root { |
|
--primary: #6366f1; |
|
--primary-dark: #4f46e5; |
|
--success: #10b981; |
|
--warning: #f59e0b; |
|
--error: #ef4444; |
|
--bg-light: #f8fafc; |
|
--text-dark: #1e293b; |
|
--border: #e2e8f0; |
|
} |
|
|
|
* { |
|
margin: 0; |
|
padding: 0; |
|
box-sizing: border-box; |
|
} |
|
|
|
body { |
|
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; |
|
background: var(--bg-light); |
|
color: var(--text-dark); |
|
line-height: 1.6; |
|
} |
|
|
|
.app-container { |
|
min-height: 100vh; |
|
display: flex; |
|
flex-direction: column; |
|
} |
|
|
|
.navbar { |
|
background: white; |
|
border-bottom: 1px solid var(--border); |
|
padding: 1rem 0; |
|
box-shadow: 0 1px 3px rgba(0,0,0,0.1); |
|
} |
|
|
|
.nav-content { |
|
max-width: 1200px; |
|
margin: 0 auto; |
|
padding: 0 2rem; |
|
display: flex; |
|
align-items: center; |
|
gap: 1rem; |
|
} |
|
|
|
.logo { |
|
font-size: 1.5rem; |
|
font-weight: bold; |
|
color: var(--primary); |
|
} |
|
|
|
.main-content { |
|
flex: 1; |
|
max-width: 1200px; |
|
margin: 0 auto; |
|
padding: 2rem; |
|
width: 100%; |
|
} |
|
|
|
.card { |
|
background: white; |
|
border-radius: 12px; |
|
padding: 2rem; |
|
box-shadow: 0 1px 3px rgba(0,0,0,0.1); |
|
border: 1px solid var(--border); |
|
margin-bottom: 2rem; |
|
} |
|
|
|
.upload-area { |
|
text-align: center; |
|
padding: 3rem 2rem; |
|
} |
|
|
|
.file-input-wrapper { |
|
position: relative; |
|
display: inline-block; |
|
margin: 2rem 0; |
|
} |
|
|
|
.file-input { |
|
position: absolute; |
|
opacity: 0; |
|
width: 100%; |
|
height: 100%; |
|
cursor: pointer; |
|
} |
|
|
|
.upload-btn { |
|
background: var(--primary); |
|
color: white; |
|
padding: 1rem 2rem; |
|
border: none; |
|
border-radius: 8px; |
|
font-size: 1rem; |
|
font-weight: 500; |
|
cursor: pointer; |
|
transition: all 0.2s; |
|
display: inline-flex; |
|
align-items: center; |
|
gap: 0.5rem; |
|
} |
|
|
|
.upload-btn:hover { |
|
background: var(--primary-dark); |
|
transform: translateY(-1px); |
|
} |
|
|
|
.drop-zone { |
|
border: 2px dashed var(--border); |
|
border-radius: 12px; |
|
padding: 3rem; |
|
margin: 2rem 0; |
|
transition: all 0.3s; |
|
cursor: pointer; |
|
} |
|
|
|
.drop-zone:hover { |
|
border-color: var(--primary); |
|
background: rgba(99, 102, 241, 0.05); |
|
} |
|
|
|
.drop-zone.active { |
|
border-color: var(--primary); |
|
background: rgba(99, 102, 241, 0.1); |
|
} |
|
|
|
.status-indicator { |
|
display: inline-flex; |
|
align-items: center; |
|
gap: 0.5rem; |
|
padding: 0.5rem 1rem; |
|
border-radius: 6px; |
|
font-weight: 500; |
|
margin-bottom: 1rem; |
|
} |
|
|
|
.status-processing { |
|
background: rgba(245, 158, 11, 0.1); |
|
color: var(--warning); |
|
} |
|
|
|
.status-success { |
|
background: rgba(16, 185, 129, 0.1); |
|
color: var(--success); |
|
} |
|
|
|
.status-error { |
|
background: rgba(239, 68, 68, 0.1); |
|
color: var(--error); |
|
} |
|
|
|
.content-grid { |
|
display: grid; |
|
grid-template-columns: 1fr 1fr; |
|
gap: 2rem; |
|
margin-top: 2rem; |
|
} |
|
|
|
.text-preview { |
|
background: #f1f5f9; |
|
border-radius: 8px; |
|
padding: 1.5rem; |
|
max-height: 400px; |
|
overflow-y: auto; |
|
white-space: pre-wrap; |
|
font-family: 'Courier New', monospace; |
|
font-size: 0.9rem; |
|
} |
|
|
|
.logs { |
|
background: #0f172a; |
|
color: #e2e8f0; |
|
border-radius: 8px; |
|
padding: 1rem; |
|
max-height: 400px; |
|
overflow-y: auto; |
|
font-family: 'Courier New', monospace; |
|
font-size: 0.85rem; |
|
} |
|
|
|
.log-entry { |
|
padding: 0.25rem 0; |
|
border-bottom: 1px solid rgba(255,255,255,0.1); |
|
} |
|
|
|
.log-timestamp { |
|
color: #64748b; |
|
} |
|
|
|
.log-info { color: #3b82f6; } |
|
.log-success { color: var(--success); } |
|
.log-warning { color: var(--warning); } |
|
.log-error { color: var(--error); } |
|
|
|
.download-area { |
|
text-align: center; |
|
padding: 2rem; |
|
background: rgba(16, 185, 129, 0.05); |
|
border-radius: 12px; |
|
border: 1px solid rgba(16, 185, 129, 0.2); |
|
} |
|
|
|
.download-btn { |
|
background: var(--success); |
|
color: white; |
|
padding: 1rem 2rem; |
|
border: none; |
|
border-radius: 8px; |
|
font-size: 1rem; |
|
cursor: pointer; |
|
text-decoration: none; |
|
display: inline-flex; |
|
align-items: center; |
|
gap: 0.5rem; |
|
transition: all 0.2s; |
|
} |
|
|
|
.download-btn:hover { |
|
background: #059669; |
|
} |
|
|
|
.hidden { |
|
display: none; |
|
} |
|
|
|
.spinner { |
|
width: 20px; |
|
height: 20px; |
|
border: 2px solid transparent; |
|
border-top: 2px solid currentColor; |
|
border-radius: 50%; |
|
animation: spin 1s linear infinite; |
|
} |
|
|
|
@keyframes spin { |
|
to { transform: rotate(360deg); } |
|
} |
|
|
|
@media (max-width: 768px) { |
|
.content-grid { |
|
grid-template-columns: 1fr; |
|
} |
|
.main-content { |
|
padding: 1rem; |
|
} |
|
} |
|
</style> |
|
</head> |
|
<body> |
|
<div class="app-container"> |
|
<nav class="navbar"> |
|
<div class="nav-content"> |
|
<div class="logo">🧮 Math Solver IMO</div> |
|
<div style="margin-left: auto;"> |
|
<span style="font-size: 0.9rem; color: #64748b;">Résolveur de problèmes mathématiques</span> |
|
</div> |
|
</div> |
|
</nav> |
|
|
|
<main class="main-content"> |
|
<!-- Section Upload --> |
|
<div class="card"> |
|
<div class="upload-area"> |
|
<h2 style="margin-bottom: 1rem;">📸 Uploader votre problème mathématique</h2> |
|
<p style="color: #64748b; margin-bottom: 2rem;"> |
|
Prenez une photo ou uploadez une image de votre problème mathématique |
|
</p> |
|
|
|
<!-- Zone de drop --> |
|
<div class="drop-zone" id="dropZone"> |
|
<div> |
|
<div style="font-size: 3rem; margin-bottom: 1rem;">📁</div> |
|
<h3>Glissez votre image ici</h3> |
|
<p style="color: #64748b; margin: 1rem 0;">ou</p> |
|
|
|
<div class="file-input-wrapper"> |
|
<input type="file" class="file-input" id="fileInput" accept="image/*"> |
|
<button class="upload-btn"> |
|
<span>📷</span> |
|
Choisir une image |
|
</button> |
|
</div> |
|
</div> |
|
</div> |
|
|
|
<p style="font-size: 0.85rem; color: #64748b;"> |
|
Formats supportés: PNG, JPG, JPEG, GIF, BMP, TIFF |
|
</p> |
|
</div> |
|
</div> |
|
|
|
<!-- Section Status --> |
|
<div class="card" id="statusCard" style="display: none;"> |
|
<div id="statusIndicator"></div> |
|
<div id="statusMessage"></div> |
|
</div> |
|
|
|
<!-- Section Contenu --> |
|
<div class="content-grid" id="contentGrid" style="display: none;"> |
|
<div class="card"> |
|
<h3 style="margin-bottom: 1rem;">📝 Texte extrait</h3> |
|
<div class="text-preview" id="extractedText"></div> |
|
</div> |
|
|
|
<div class="card"> |
|
<h3 style="margin-bottom: 1rem;">📊 Logs en temps réel</h3> |
|
<div class="logs" id="logsContainer"></div> |
|
</div> |
|
</div> |
|
|
|
<!-- Section Download --> |
|
<div class="card hidden" id="downloadCard"> |
|
<div class="download-area"> |
|
<h3 style="margin-bottom: 1rem;">✅ Solution prête !</h3> |
|
<p style="margin-bottom: 2rem; color: #64748b;"> |
|
Votre problème mathématique a été résolu avec succès |
|
</p> |
|
<a class="download-btn" id="downloadLink"> |
|
<span>📥</span> |
|
Télécharger la solution |
|
</a> |
|
</div> |
|
</div> |
|
</main> |
|
</div> |
|
|
|
<script> |
|
class MathSolverApp { |
|
constructor() { |
|
this.socket = io(); |
|
this.currentTaskId = null; |
|
this.initializeElements(); |
|
this.setupEventListeners(); |
|
this.setupSocketEvents(); |
|
} |
|
|
|
initializeElements() { |
|
this.dropZone = document.getElementById('dropZone'); |
|
this.fileInput = document.getElementById('fileInput'); |
|
this.statusCard = document.getElementById('statusCard'); |
|
this.statusIndicator = document.getElementById('statusIndicator'); |
|
this.statusMessage = document.getElementById('statusMessage'); |
|
this.contentGrid = document.getElementById('contentGrid'); |
|
this.extractedText = document.getElementById('extractedText'); |
|
this.logsContainer = document.getElementById('logsContainer'); |
|
this.downloadCard = document.getElementById('downloadCard'); |
|
this.downloadLink = document.getElementById('downloadLink'); |
|
} |
|
|
|
setupEventListeners() { |
|
// File input change |
|
this.fileInput.addEventListener('change', (e) => { |
|
if (e.target.files.length > 0) { |
|
this.handleFile(e.target.files[0]); |
|
} |
|
}); |
|
|
|
// Drop zone events |
|
this.dropZone.addEventListener('dragover', (e) => { |
|
e.preventDefault(); |
|
this.dropZone.classList.add('active'); |
|
}); |
|
|
|
this.dropZone.addEventListener('dragleave', (e) => { |
|
e.preventDefault(); |
|
this.dropZone.classList.remove('active'); |
|
}); |
|
|
|
this.dropZone.addEventListener('drop', (e) => { |
|
e.preventDefault(); |
|
this.dropZone.classList.remove('active'); |
|
|
|
const files = e.dataTransfer.files; |
|
if (files.length > 0) { |
|
this.handleFile(files[0]); |
|
} |
|
}); |
|
|
|
// Click on drop zone |
|
this.dropZone.addEventListener('click', () => { |
|
this.fileInput.click(); |
|
}); |
|
} |
|
|
|
setupSocketEvents() { |
|
this.socket.on('log_update', (data) => { |
|
if (data.task_id === this.currentTaskId) { |
|
this.addLog(data.log); |
|
} |
|
}); |
|
|
|
this.socket.on('task_completed', (data) => { |
|
if (data.task_id === this.currentTaskId) { |
|
this.showSuccess('Solution générée avec succès !'); |
|
this.showDownload(); |
|
} |
|
}); |
|
|
|
this.socket.on('task_failed', (data) => { |
|
if (data.task_id === this.currentTaskId) { |
|
this.showError('Échec de la résolution (solution partielle disponible)'); |
|
this.showDownload(); |
|
} |
|
}); |
|
|
|
this.socket.on('task_error', (data) => { |
|
if (data.task_id === this.currentTaskId) { |
|
this.showError(`Erreur: ${data.error}`); |
|
} |
|
}); |
|
} |
|
|
|
async handleFile(file) { |
|
if (!this.isValidFile(file)) { |
|
this.showError('Type de fichier non supporté'); |
|
return; |
|
} |
|
|
|
const formData = new FormData(); |
|
formData.append('file', file); |
|
|
|
this.showProcessing('Upload en cours...'); |
|
|
|
try { |
|
const response = await fetch('/upload', { |
|
method: 'POST', |
|
body: formData |
|
}); |
|
|
|
const data = await response.json(); |
|
|
|
if (data.error) { |
|
this.showError(data.error); |
|
} else { |
|
this.currentTaskId = data.task_id; |
|
this.extractedText.textContent = data.extracted_text; |
|
this.contentGrid.style.display = 'grid'; |
|
this.showProcessing('Résolution en cours...'); |
|
} |
|
} catch (error) { |
|
this.showError('Erreur lors de l\'upload'); |
|
console.error('Upload error:', error); |
|
} |
|
} |
|
|
|
isValidFile(file) { |
|
const allowedTypes = ['image/png', 'image/jpeg', 'image/jpg', 'image/gif', 'image/bmp', 'image/tiff']; |
|
return allowedTypes.includes(file.type); |
|
} |
|
|
|
showProcessing(message) { |
|
this.statusCard.style.display = 'block'; |
|
this.statusIndicator.innerHTML = ` |
|
<div class="status-indicator status-processing"> |
|
<div class="spinner"></div> |
|
En cours |
|
</div> |
|
`; |
|
this.statusMessage.textContent = message; |
|
} |
|
|
|
showSuccess(message) { |
|
this.statusIndicator.innerHTML = ` |
|
<div class="status-indicator status-success"> |
|
✅ Terminé |
|
</div> |
|
`; |
|
this.statusMessage.textContent = message; |
|
} |
|
|
|
showError(message) { |
|
this.statusIndicator.innerHTML = ` |
|
<div class="status-indicator status-error"> |
|
❌ Erreur |
|
</div> |
|
`; |
|
this.statusMessage.textContent = message; |
|
} |
|
|
|
addLog(log) { |
|
const logEntry = document.createElement('div'); |
|
logEntry.className = 'log-entry'; |
|
logEntry.innerHTML = ` |
|
<span class="log-timestamp">[${log.timestamp}]</span> |
|
<span class="log-${log.level}">${log.message}</span> |
|
`; |
|
|
|
this.logsContainer.appendChild(logEntry); |
|
this.logsContainer.scrollTop = this.logsContainer.scrollHeight; |
|
} |
|
|
|
showDownload() { |
|
this.downloadCard.classList.remove('hidden'); |
|
this.downloadLink.href = `/download/${this.currentTaskId}`; |
|
} |
|
} |
|
|
|
// Initialize app when DOM is loaded |
|
document.addEventListener('DOMContentLoaded', () => { |
|
new MathSolverApp(); |
|
}); |
|
</script> |
|
</body> |
|
</html> |
|
|
|
|
|
''' |
|
return template_content |
|
|
|
if __name__ == '__main__': |
|
|
|
os.makedirs('templates', exist_ok=True) |
|
with open('templates/index.html', 'w', encoding='utf-8') as f: |
|
|
|
from flask import Flask |
|
temp_app = Flask(__name__) |
|
with temp_app.app_context(): |
|
template_content = get_template() |
|
f.write(template_content) |
|
|
|
print("🚀 Démarrage de l'application Flask...") |
|
print("📝 Template HTML créé dans templates/index.html") |
|
print("🌐 Application disponible sur http://localhost:5000") |
|
|
|
socketio.run(app, debug=True, host='0.0.0.0', port=5000) |