Spaces:
Running
Running
<html lang="fr"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>Mariam M-1 | Solution Mathématique Intelligente</title> | |
<!-- Tailwind CSS --> | |
<link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet"> | |
<!-- SweetAlert2 --> | |
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script> | |
<!-- Highlight.js pour la coloration syntaxique --> | |
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/github.min.css"> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"></script> | |
<!-- Configuration de MathJax --> | |
<script> | |
window.MathJax = { | |
tex: { | |
inlineMath: [['$', '$']], | |
displayMath: [['$$', '$$']], | |
processEscapes: true, | |
packages: {'[+]': ['autoload', 'ams']} | |
}, | |
options: { | |
enableMenu: false, | |
messageStyle: 'none' | |
}, | |
startup: { | |
pageReady: () => { window.mathJaxReady = true; } | |
} | |
}; | |
</script> | |
<script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js" id="MathJax-script" async></script> | |
<script src="https://cdn.jsdelivr.net/npm/marked@15.0.7/lib/marked.umd.min.js"></script> | |
<style> | |
@import url('https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;700&display=swap'); | |
body { font-family: 'Space Grotesk', sans-serif; } | |
.uploadArea { | |
background: #f3f4f6; | |
border: 2px dashed #d1d5db; | |
transition: border-color 0.2s ease; | |
} | |
.uploadArea:hover { border-color: #3b82f6; } | |
.blue-button { background: #3b82f6; transition: background-color 0.2s ease; } | |
.blue-button:hover:not(:disabled) { background: #2563eb; } | |
.blue-button:disabled { | |
background: #9ca3af; | |
cursor: not-allowed; | |
} | |
.green-button { background: #10b981; transition: background-color 0.2s ease; } | |
.green-button:hover:not(:disabled) { background: #059669; } | |
.green-button.active { background: #059669; } | |
.purple-button { background: #8b5cf6; transition: background-color 0.2s ease; } | |
.purple-button:hover:not(:disabled) { background: #7c3aed; } | |
.purple-button.active { background: #7c3aed; } | |
.loader { | |
width: 48px; height: 48px; border: 3px solid #3b82f6; border-bottom-color: transparent; | |
border-radius: 50%; display: inline-block; animation: rotation 1s linear infinite; | |
} | |
@keyframes rotation { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } | |
.thought-box { | |
transition: max-height 0.3s ease-out; max-height: 0; overflow: hidden; | |
} | |
.thought-box.open { max-height: 800px; } | |
#thoughtsContent, #answerContent { | |
max-height: 500px; overflow-y: auto; scroll-behavior: smooth; white-space: pre-wrap; | |
} | |
.preview-image { max-width: 300px; max-height: 300px; object-fit: contain; } | |
.timestamp { color: #3b82f6; font-size: 0.9em; margin-left: 8px; } | |
table { | |
border-collapse: collapse; width: 100%; margin-bottom: 1rem; | |
} | |
th, td { | |
border: 1px solid #d1d5db; padding: 0.5rem; text-align: left; | |
} | |
th { background-color: #f3f4f6; font-weight: 600; } | |
.table-responsive { overflow-x: auto; } | |
#saveButton { | |
background: #3b82f6; color: white; padding: 0.5rem 1rem; | |
border-radius: 0.375rem; transition: background-color 0.2s ease; | |
} | |
#saveButton:hover { background: #2563eb; } | |
/* Modal plein écran pour les sauvegardes */ | |
#savedModal { | |
display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 50; | |
} | |
#savedModal.active { display: block; } | |
#savedModalContent { | |
background: #fff; width: 100%; height: 100%; overflow-y: auto; | |
} | |
/* Styles pour le code et son exécution */ | |
pre { | |
background-color: #f8f8f8; border: 1px solid #e2e8f0; border-radius: 0.375rem; | |
padding: 1rem; margin: 1rem 0; overflow-x: auto; | |
font-family: 'Consolas', 'Monaco', 'Courier New', monospace; | |
} | |
code { | |
font-family: 'Consolas', 'Monaco', 'Courier New', monospace; | |
} | |
.code-execution-result { | |
background-color: #f0fff4; border-left: 4px solid #48bb78; | |
padding: 1rem; margin: 1rem 0; | |
font-family: 'Consolas', 'Monaco', 'Courier New', monospace; | |
white-space: pre-wrap; | |
} | |
.content-text {} | |
.content-code { padding: 0; } | |
.content-result { | |
background-color: #f0fff4; border-left: 4px solid #48bb78; | |
padding: 1rem; margin: 0.5rem 0; | |
} | |
.content-image { margin: 1rem 0; text-align: center; } | |
.content-image img { max-width: 100%; } | |
/* Styles pour les options */ | |
.option-card { | |
background: #f8fafc; border: 2px solid #e2e8f0; border-radius: 0.5rem; | |
padding: 1rem; margin: 1rem 0; transition: all 0.2s ease; | |
} | |
.option-card.enabled { | |
border-color: #10b981; | |
} | |
.option-card.enabled.calculator { | |
background: #ecfdf5; border-color: #10b981; | |
} | |
.option-card.enabled.reasoning { | |
background: #f3e8ff; border-color: #8b5cf6; | |
} | |
.toggle-switch { | |
position: relative; display: inline-block; width: 60px; height: 34px; | |
} | |
.toggle-switch input { | |
opacity: 0; width: 0; height: 0; | |
} | |
.slider { | |
position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; | |
background-color: #ccc; transition: .4s; border-radius: 34px; | |
} | |
.slider:before { | |
position: absolute; content: ""; height: 26px; width: 26px; | |
left: 4px; bottom: 4px; background-color: white; | |
transition: .4s; border-radius: 50%; | |
} | |
input:checked + .slider { | |
background-color: #10b981; | |
} | |
input:checked + .slider:before { | |
transform: translateX(26px); | |
} | |
.slider.purple:checked { | |
background-color: #8b5cf6; | |
} | |
/* Styles pour les étapes du raisonnement étendu */ | |
.reasoning-step { | |
border-left: 4px solid #8b5cf6; | |
background: #faf5ff; | |
padding: 1rem; | |
margin: 0.5rem 0; | |
border-radius: 0 0.375rem 0.375rem 0; | |
} | |
.reasoning-step h3 { | |
color: #7c3aed; | |
font-weight: 600; | |
margin-bottom: 0.5rem; | |
} | |
.progress-indicator { | |
display: flex; | |
align-items: center; | |
gap: 0.5rem; | |
margin-bottom: 1rem; | |
} | |
.step-indicator { | |
width: 2rem; | |
height: 2rem; | |
border-radius: 50%; | |
display: flex; | |
align-items: center; | |
justify-content: center; | |
font-size: 0.875rem; | |
font-weight: 600; | |
transition: all 0.3s ease; | |
} | |
.step-indicator.pending { | |
background: #e5e7eb; | |
color: #6b7280; | |
} | |
.step-indicator.active { | |
background: #8b5cf6; | |
color: white; | |
animation: pulse 2s infinite; | |
} | |
.step-indicator.completed { | |
background: #10b981; | |
color: white; | |
} | |
@keyframes pulse { | |
0%, 100% { opacity: 1; } | |
50% { opacity: 0.7; } | |
} | |
</style> | |
</head> | |
<body class="p-4"> | |
<div class="max-w-4xl mx-auto"> | |
<header class="p-6 text-center mb-8"> | |
<h1 class="text-4xl font-bold text-blue-600">Mariam M-1</h1> | |
<p class="text-gray-600">Solution Mathématique/Physique/Chimie Intelligente</p> | |
<div class="mt-4 flex justify-end"> | |
<button id="openSaved" class="blue-button px-4 py-2 text-white rounded">Sauvegardes</button> | |
</div> | |
</header> | |
<main id="mainContent"> | |
<form id="problemForm" class="space-y-6" novalidate> | |
<!-- Zone de dépôt / sélection d'image --> | |
<div class="uploadArea p-8 text-center relative" aria-label="Zone de dépôt d'image"> | |
<input type="file" id="imageInput" name="image" accept="image/*" class="absolute inset-0 w-full h-full opacity-0 cursor-pointer" aria-label="Choisir une image"> | |
<div class="space-y-3"> | |
<div class="w-16 h-16 mx-auto border-2 border-blue-400 rounded-full flex items-center justify-center"> | |
<svg class="w-8 h-8 text-blue-400" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true"> | |
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" | |
d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" /> | |
</svg> | |
</div> | |
<p class="text-gray-700 font-medium">Déposez votre image ici</p> | |
<p class="text-gray-500 text-sm">ou cliquez pour sélectionner</p> | |
</div> | |
</div> | |
<!-- Aperçu de l'image --> | |
<div id="imagePreview" class="hidden text-center"> | |
<img id="previewImage" class="preview-image mx-auto" alt="Prévisualisation de l'image"> | |
</div> | |
<!-- Option Calculatrice --> | |
<div id="calculatorOption" class="option-card calculator"> | |
<div class="flex items-center justify-between"> | |
<div class="flex items-center space-x-3"> | |
<div class="text-2xl">🧮</div> | |
<div> | |
<h3 class="font-semibold text-gray-800">Mode Calculatrice</h3> | |
<p class="text-sm text-gray-600">Active l'exécution de code Python pour les calculs numériques et graphiques</p> | |
</div> | |
</div> | |
<label class="toggle-switch"> | |
<input type="checkbox" id="calculatorToggle"> | |
<span class="slider"></span> | |
</label> | |
</div> | |
<div id="calculatorFeatures" class="mt-3 text-xs text-gray-500 hidden"> | |
<div class="grid grid-cols-2 gap-2"> | |
<div class="flex items-center space-x-1"> | |
<span>✓</span><span>Calculs numériques précis</span> | |
</div> | |
<div class="flex items-center space-x-1"> | |
<span>✓</span><span>Graphiques matplotlib</span> | |
</div> | |
<div class="flex items-center space-x-1"> | |
<span>✓</span><span>Vérification des résultats</span> | |
</div> | |
<div class="flex items-center space-x-1"> | |
<span>✓</span><span>Visualisations 2D/3D</span> | |
</div> | |
</div> | |
</div> | |
</div> | |
<!-- Option Raisonnement Étendu --> | |
<div id="reasoningOption" class="option-card reasoning"> | |
<div class="flex items-center justify-between"> | |
<div class="flex items-center space-x-3"> | |
<div class="text-2xl">🧠</div> | |
<div> | |
<h3 class="font-semibold text-gray-800">Raisonnement Étendu</h3> | |
<p class="text-sm text-gray-600">Système multi-agents avec auto-amélioration et vérification rigoureuse</p> | |
</div> | |
</div> | |
<label class="toggle-switch"> | |
<input type="checkbox" id="reasoningToggle"> | |
<span class="slider purple"></span> | |
</label> | |
</div> | |
<div id="reasoningFeatures" class="mt-3 text-xs text-gray-500 hidden"> | |
<div class="grid grid-cols-1 gap-2"> | |
<div class="flex items-center space-x-1"> | |
<span>✓</span><span>Génération de solution initiale</span> | |
</div> | |
<div class="flex items-center space-x-1"> | |
<span>✓</span><span>Auto-amélioration de la solution</span> | |
</div> | |
<div class="flex items-center space-x-1"> | |
<span>✓</span><span>Vérification rigoureuse par agent expert</span> | |
</div> | |
<div class="flex items-center space-x-1"> | |
<span>✓</span><span>Correction automatique des erreurs</span> | |
</div> | |
</div> | |
</div> | |
</div> | |
<!-- Le bouton de soumission --> | |
<button type="submit" id="submitButton" class="blue-button w-full py-3 text-white font-medium rounded-lg"> | |
Résoudre le problème | |
</button> | |
</form> | |
<!-- Indicateur de progression pour le raisonnement étendu --> | |
<div id="progressIndicator" class="hidden mt-8"> | |
<div class="progress-indicator"> | |
<div class="step-indicator pending" data-step="0">📝</div> | |
<div class="flex-1 h-1 bg-gray-300 rounded"></div> | |
<div class="step-indicator pending" data-step="1">🔧</div> | |
<div class="flex-1 h-1 bg-gray-300 rounded"></div> | |
<div class="step-indicator pending" data-step="2">✅</div> | |
<div class="flex-1 h-1 bg-gray-300 rounded"></div> | |
<div class="step-indicator pending" data-step="3">🛠️</div> | |
</div> | |
<div class="text-sm text-gray-600 mt-2"> | |
<span id="currentStepText">Préparation...</span> | |
</div> | |
</div> | |
<!-- Loader --> | |
<div id="loader" class="hidden mt-8 text-center"> | |
<span class="loader"></span> | |
<p class="mt-4 text-gray-600">Analyse en cours...</p> | |
</div> | |
<!-- Zone d'affichage de la solution --> | |
<section id="solution" class="hidden mt-8 space-y-6 relative"> | |
<div class="border-t pt-4"> | |
<button id="thoughtsToggle" type="button" class="w-full flex justify-between items-center p-2 hover:bg-gray-100 rounded"> | |
<span class="font-medium text-gray-700">Processus de Réflexion</span> | |
<span id="timestamp" class="timestamp"></span> | |
</button> | |
<div id="thoughtsBox" class="thought-box"> | |
<div id="thoughtsContent" class="p-4 text-gray-600"></div> | |
</div> | |
</div> | |
<div class="border-t pt-6"> | |
<div class="flex justify-between items-center"> | |
<h3 class="text-xl font-bold text-gray-800 mb-4">Solution</h3> | |
<button id="saveButton">Sauvegarder</button> | |
</div> | |
<div id="answerContent" class="text-gray-700 table-responsive"></div> | |
</div> | |
</section> | |
</main> | |
</div> | |
<!-- Modal plein écran pour les sauvegardes --> | |
<div id="savedModal"> | |
<div id="savedModalContent" class="p-6"> | |
<header class="flex justify-between items-center border-b pb-4"> | |
<h2 class="text-2xl font-bold">Sauvegardes</h2> | |
<button id="closeSaved" class="text-3xl text-gray-600 hover:text-gray-800">×</button> | |
</header> | |
<div id="savedListContainer" class="mt-4"> | |
<ul id="savedList" class="space-y-4"> | |
<!-- Liste des sauvegardes insérée dynamiquement --> | |
</ul> | |
</div> | |
<div class="mt-6"> | |
<button id="newExercise" class="blue-button w-full py-3 text-white font-medium rounded-lg"> | |
Résoudre un nouvel exercice | |
</button> | |
</div> | |
</div> | |
</div> | |
<script> | |
document.addEventListener('DOMContentLoaded', () => { | |
// Récupération des éléments | |
const elements = { | |
form: document.getElementById('problemForm'), | |
imageInput: document.getElementById('imageInput'), | |
submitButton: document.getElementById('submitButton'), | |
loader: document.getElementById('loader'), | |
solutionSection: document.getElementById('solution'), | |
thoughtsContent: document.getElementById('thoughtsContent'), | |
answerContent: document.getElementById('answerContent'), | |
thoughtsToggle: document.getElementById('thoughtsToggle'), | |
thoughtsBox: document.getElementById('thoughtsBox'), | |
imagePreview: document.getElementById('imagePreview'), | |
previewImage: document.getElementById('previewImage'), | |
timestamp: document.getElementById('timestamp'), | |
saveButton: document.getElementById('saveButton'), | |
openSaved: document.getElementById('openSaved'), | |
closeSaved: document.getElementById('closeSaved'), | |
savedModal: document.getElementById('savedModal'), | |
savedList: document.getElementById('savedList'), | |
newExercise: document.getElementById('newExercise'), | |
calculatorToggle: document.getElementById('calculatorToggle'), | |
calculatorOption: document.getElementById('calculatorOption'), | |
calculatorFeatures: document.getElementById('calculatorFeatures'), | |
reasoningToggle: document.getElementById('reasoningToggle'), | |
reasoningOption: document.getElementById('reasoningOption'), | |
reasoningFeatures: document.getElementById('reasoningFeatures'), | |
progressIndicator: document.getElementById('progressIndicator'), | |
currentStepText: document.getElementById('currentStepText'), | |
dropZone: document.querySelector('.uploadArea') | |
}; | |
// État de l'application | |
const state = { | |
startTime: null, | |
timerInterval: null, | |
cooldownTimerInterval: null, | |
thoughtsBuffer: '', | |
answerBuffer: '', | |
currentMode: null, | |
updateTimeout: null, | |
selectedFile: null, | |
currentStep: -1, | |
isExtendedReasoning: false | |
}; | |
// Configuration | |
const COOLDOWN_DURATION_MS = 3 * 60 * 1000; // 3 minutes | |
const LAST_SUBMISSION_TIME_KEY = 'mariamM1_lastSubmissionTime'; | |
const SUBMIT_BUTTON_ORIGINAL_TEXT = 'Résoudre le problème'; | |
const stepTexts = { | |
0: "Extraction du problème de l'image...", | |
1: "Génération de la solution initiale...", | |
2: "Auto-amélioration de la solution...", | |
3: "Vérification rigoureuse...", | |
4: "Correction des erreurs identifiées..." | |
}; | |
marked.setOptions({ | |
gfm: true, | |
breaks: true, | |
highlight: function(code, lang) { | |
if (lang && hljs.getLanguage(lang)) { | |
try { | |
return hljs.highlight(code, { language: lang }).value; | |
} catch (error) { | |
console.error("Highlighting error:", error); | |
return code; | |
} | |
} | |
try { | |
return hljs.highlightAuto(code).value; | |
} catch (error) { | |
console.error("Auto highlighting error:", error); | |
return code; | |
} | |
} | |
}); | |
// --- Helper Functions --- | |
const formatTime = (totalSeconds) => { | |
const minutes = Math.floor(totalSeconds / 60); | |
const seconds = totalSeconds % 60; | |
return `${minutes}m ${seconds < 10 ? '0' : ''}${seconds}s`; | |
}; | |
const updateTimestampDisplay = () => { | |
if (state.startTime) { | |
const seconds = Math.floor((Date.now() - state.startTime) / 1000); | |
elements.timestamp.textContent = `${seconds}s`; | |
} | |
}; | |
const startSolutionTimer = () => { | |
state.startTime = Date.now(); | |
if (state.timerInterval) clearInterval(state.timerInterval); | |
state.timerInterval = setInterval(updateTimestampDisplay, 1000); | |
updateTimestampDisplay(); | |
}; | |
const stopSolutionTimer = () => { | |
clearInterval(state.timerInterval); | |
state.timerInterval = null; | |
}; | |
const resetSolutionTimer = () => { | |
stopSolutionTimer(); | |
state.startTime = null; | |
elements.timestamp.textContent = ''; | |
}; | |
const updateProgressStep = (step) => { | |
// Marquer les étapes précédentes comme complétées | |
for (let i = 0; i < step; i++) { | |
const indicator = document.querySelector(`[data-step="${i}"]`); | |
if (indicator) { | |
indicator.className = 'step-indicator completed'; | |
} | |
} | |
// Marquer l'étape courante comme active | |
const currentIndicator = document.querySelector(`[data-step="${step}"]`); | |
if (currentIndicator) { | |
currentIndicator.className = 'step-indicator active'; | |
} | |
// Marquer les étapes suivantes comme en attente | |
for (let i = step + 1; i < 4; i++) { | |
const indicator = document.querySelector(`[data-step="${i}"]`); | |
if (indicator) { | |
indicator.className = 'step-indicator pending'; | |
} | |
} | |
// Mettre à jour le texte | |
if (stepTexts[step]) { | |
elements.currentStepText.textContent = stepTexts[step]; | |
} | |
state.currentStep = step; | |
}; | |
const resetProgressIndicator = () => { | |
const indicators = document.querySelectorAll('.step-indicator'); | |
indicators.forEach(indicator => { | |
indicator.className = 'step-indicator pending'; | |
}); | |
elements.currentStepText.textContent = 'Préparation...'; | |
state.currentStep = -1; | |
}; | |
// --- Cooldown Logic --- | |
const getLastSubmissionTime = () => parseInt(localStorage.getItem(LAST_SUBMISSION_TIME_KEY) || '0'); | |
const setLastSubmissionTime = () => localStorage.setItem(LAST_SUBMISSION_TIME_KEY, Date.now().toString()); | |
const updateSubmitButtonState = () => { | |
const lastSubmission = getLastSubmissionTime(); | |
const now = Date.now(); | |
const timeSinceLastSubmission = now - lastSubmission; | |
if (state.cooldownTimerInterval) clearInterval(state.cooldownTimerInterval); | |
if (timeSinceLastSubmission < COOLDOWN_DURATION_MS) { | |
elements.submitButton.disabled = true; | |
let remainingTimeMs = COOLDOWN_DURATION_MS - timeSinceLastSubmission; | |
const updateButtonText = () => { | |
const remainingSeconds = Math.ceil(remainingTimeMs / 1000); | |
elements.submitButton.textContent = `Attendre ${formatTime(remainingSeconds)}`; | |
remainingTimeMs -= 1000; | |
if (remainingTimeMs < 0) { | |
clearInterval(state.cooldownTimerInterval); | |
state.cooldownTimerInterval = null; | |
elements.submitButton.disabled = false; | |
elements.submitButton.textContent = SUBMIT_BUTTON_ORIGINAL_TEXT; | |
} | |
}; | |
updateButtonText(); | |
state.cooldownTimerInterval = setInterval(updateButtonText, 1000); | |
} else { | |
elements.submitButton.disabled = false; | |
elements.submitButton.textContent = SUBMIT_BUTTON_ORIGINAL_TEXT; | |
} | |
}; | |
// --- Toggle Handlers --- | |
elements.calculatorToggle.addEventListener('change', () => { | |
const isEnabled = elements.calculatorToggle.checked; | |
if (isEnabled) { | |
elements.calculatorOption.classList.add('enabled'); | |
elements.calculatorFeatures.classList.remove('hidden'); | |
} else { | |
elements.calculatorOption.classList.remove('enabled'); | |
elements.calculatorFeatures.classList.add('hidden'); | |
} | |
}); | |
elements.reasoningToggle.addEventListener('change', () => { | |
const isEnabled = elements.reasoningToggle.checked; | |
if (isEnabled) { | |
elements.reasoningOption.classList.add('enabled'); | |
elements.reasoningFeatures.classList.remove('hidden'); | |
} else { | |
elements.reasoningOption.classList.remove('enabled'); | |
elements.reasoningFeatures.classList.add('hidden'); | |
} | |
}); | |
// --- File Handling --- | |
const handleFileSelect = (file) => { | |
if (!file || !file.type.startsWith('image/')) { | |
Swal.fire('Fichier Invalide', 'Veuillez sélectionner un fichier image.', 'error'); | |
elements.imageInput.value = ''; | |
state.selectedFile = null; | |
elements.imagePreview.classList.add('hidden'); | |
return; | |
} | |
state.selectedFile = file; | |
const reader = new FileReader(); | |
reader.onload = e => { | |
elements.previewImage.src = e.target.result; | |
elements.imagePreview.classList.remove('hidden'); | |
}; | |
reader.readAsDataURL(file); | |
}; | |
// --- MathJax & Display Update --- | |
const typesetMathJaxContent = async (contentElement) => { | |
if (window.mathJaxReady && contentElement) { | |
MathJax.startup.document.elements = [contentElement]; | |
try { | |
await MathJax.typesetPromise(); | |
contentElement.scrollTop = contentElement.scrollHeight; | |
} catch(err) { | |
console.error("MathJax typesetting error:", err); | |
} | |
} else if (contentElement) { | |
setTimeout(() => typesetMathJaxContent(contentElement), 200); | |
} | |
}; | |
const applyHighlighting = () => { | |
document.querySelectorAll('pre code').forEach((block) => { | |
hljs.highlightBlock(block); | |
}); | |
}; | |
const scheduleDisplayUpdate = () => { | |
if (state.updateTimeout) clearTimeout(state.updateTimeout); | |
state.updateTimeout = setTimeout(async () => { | |
if (elements.thoughtsContent) elements.thoughtsContent.innerHTML = marked.parse(state.thoughtsBuffer); | |
if (elements.answerContent) elements.answerContent.innerHTML = marked.parse(state.answerBuffer); | |
if (state.thoughtsBuffer) await typesetMathJaxContent(elements.thoughtsContent); | |
if (state.answerBuffer) await typesetMathJaxContent(elements.answerContent); | |
applyHighlighting(); | |
state.updateTimeout = null; | |
}, 150); | |
}; | |
const resetUIForNewProblem = () => { | |
elements.form.reset(); | |
elements.imageInput.value = ''; | |
state.selectedFile = null; | |
elements.imagePreview.classList.add('hidden'); | |
elements.previewImage.src = '#'; | |
elements.solutionSection.classList.add('hidden'); | |
elements.loader.classList.add('hidden'); | |
elements.progressIndicator.classList.add('hidden'); | |
elements.thoughtsContent.innerHTML = ''; | |
elements.answerContent.innerHTML = ''; | |
state.thoughtsBuffer = ''; | |
state.answerBuffer = ''; | |
state.currentMode = null; | |
state.isExtendedReasoning = false; | |
elements.thoughtsBox.classList.remove('open'); | |
elements.form.classList.remove('hidden'); | |
resetSolutionTimer(); | |
resetProgressIndicator(); | |
updateSubmitButtonState(); | |
// Reset toggles | |
elements.calculatorToggle.checked = false; | |
elements.calculatorOption.classList.remove('enabled'); | |
elements.calculatorFeatures.classList.add('hidden'); | |
elements.reasoningToggle.checked = false; | |
elements.reasoningOption.classList.remove('enabled'); | |
elements.reasoningFeatures.classList.add('hidden'); | |
}; | |
// --- Event Listeners --- | |
elements.thoughtsToggle.addEventListener('click', () => elements.thoughtsBox.classList.toggle('open')); | |
elements.imageInput.addEventListener('change', e => handleFileSelect(e.target.files[0])); | |
// Drag & Drop | |
elements.dropZone.addEventListener('dragover', e => { | |
e.preventDefault(); | |
elements.dropZone.classList.add('border-blue-400'); | |
}); | |
elements.dropZone.addEventListener('dragleave', e => { | |
e.preventDefault(); | |
elements.dropZone.classList.remove('border-blue-400'); | |
}); | |
elements.dropZone.addEventListener('drop', e => { | |
e.preventDefault(); | |
elements.dropZone.classList.remove('border-blue-400'); | |
if (e.dataTransfer.files && e.dataTransfer.files[0]) { | |
handleFileSelect(e.dataTransfer.files[0]); | |
elements.imageInput.files = e.dataTransfer.files; | |
} | |
}); | |
// Form submission | |
elements.form.addEventListener('submit', async e => { | |
e.preventDefault(); | |
if (!state.selectedFile) { | |
Swal.fire('Aucune Image', 'Veuillez sélectionner une image.', 'warning'); | |
return; | |
} | |
const lastSubmission = getLastSubmissionTime(); | |
const now = Date.now(); | |
if (now - lastSubmission < COOLDOWN_DURATION_MS) { | |
const remainingSeconds = Math.ceil((COOLDOWN_DURATION_MS - (now - lastSubmission)) / 1000); | |
Swal.fire('Cooldown Actif', `Vous devez attendre ${formatTime(remainingSeconds)} avant de soumettre à nouveau.`, 'info'); | |
return; | |
} | |
setLastSubmissionTime(); | |
updateSubmitButtonState(); | |
const useCalculator = elements.calculatorToggle.checked; | |
const useExtendedReasoning = elements.reasoningToggle.checked; | |
state.isExtendedReasoning = useExtendedReasoning; | |
startSolutionTimer(); | |
elements.loader.classList.remove('hidden'); | |
elements.solutionSection.classList.add('hidden'); | |
elements.thoughtsContent.innerHTML = ''; | |
elements.answerContent.innerHTML = ''; | |
state.thoughtsBuffer = ''; | |
state.answerBuffer = ''; | |
state.currentMode = null; | |
elements.thoughtsBox.classList.add('open'); | |
// Afficher l'indicateur de progression pour le raisonnement étendu | |
if (useExtendedReasoning) { | |
elements.progressIndicator.classList.remove('hidden'); | |
resetProgressIndicator(); | |
} else { | |
elements.progressIndicator.classList.add('hidden'); | |
} | |
const formData = new FormData(); | |
formData.append('image', state.selectedFile); | |
formData.append('use_calculator', useCalculator.toString()); | |
formData.append('use_extended_reasoning', useExtendedReasoning.toString()); | |
try { | |
const response = await fetch('/solve', { method: 'POST', body: formData }); | |
if (!response.ok) { | |
throw new Error(`HTTP error! status: ${response.status}`); | |
} | |
const reader = response.body.getReader(); | |
const decoder = new TextDecoder(); | |
let streamBuffer = ''; | |
while (true) { | |
const { done, value } = await reader.read(); | |
if (done) { | |
if (streamBuffer.startsWith('data:')) { | |
try { | |
const data = JSON.parse(streamBuffer.slice(5)); | |
if (data.content) { | |
if (state.currentMode === 'thinking') state.thoughtsBuffer += data.content; | |
else if (state.currentMode === 'answering') state.answerBuffer += data.content; | |
} | |
} catch (parseError) { | |
console.warn("Error parsing final chunk:", parseError, "Buffer:", streamBuffer); | |
} | |
} | |
scheduleDisplayUpdate(); | |
// Marquer la dernière étape comme complétée si raisonnement étendu | |
if (state.isExtendedReasoning && state.currentStep >= 0) { | |
const finalIndicator = document.querySelector(`[data-step="${state.currentStep}"]`); | |
if (finalIndicator) { | |
finalIndicator.className = 'step-indicator completed'; | |
} | |
} | |
break; | |
} | |
streamBuffer += decoder.decode(value, { stream: true }); | |
const parts = streamBuffer.split('\n\n'); | |
streamBuffer = parts.pop(); | |
for (const part of parts) { | |
if (!part.startsWith('data:')) continue; | |
try { | |
const jsonData = part.slice(5); | |
const data = JSON.parse(jsonData); | |
if (data.mode) { | |
state.currentMode = data.mode; | |
if (!elements.loader.classList.contains('hidden')) { | |
elements.loader.classList.add('hidden'); | |
elements.solutionSection.classList.remove('hidden'); | |
} | |
} | |
if (data.content) { | |
// Détecter les étapes du raisonnement étendu | |
if (state.isExtendedReasoning && state.currentMode === 'thinking') { | |
const content = data.content; | |
if (content.includes('EXTRACTION DU PROBLÈME')) { | |
updateProgressStep(0); | |
} else if (content.includes('ÉTAPE 1') || content.includes('GÉNÉRATION DE LA SOLUTION INITIALE')) { | |
updateProgressStep(1); | |
} else if (content.includes('ÉTAPE 2') || content.includes('AUTO-AMÉLIORATION')) { | |
updateProgressStep(2); | |
} else if (content.includes('ÉTAPE 3') || content.includes('VÉRIFICATION RIGOUREUSE')) { | |
updateProgressStep(3); | |
} else if (content.includes('ÉTAPE 5') || content.includes('CORRECTION DES ERREURS')) { | |
updateProgressStep(4); | |
} | |
} | |
if (state.currentMode === 'thinking') { | |
state.thoughtsBuffer += data.content; | |
} else if (state.currentMode === 'answering') { | |
switch(data.type) { | |
case 'code': | |
state.answerBuffer += "\n```python\n" + data.content + "\n```\n"; | |
break; | |
case 'result': | |
const formattedResult = data.content.split('\n').map(line => `> ${line}`).join('\n'); | |
state.answerBuffer += "\n" + formattedResult + "\n"; | |
break; | |
case 'image': | |
state.answerBuffer += `\n\n`; | |
break; | |
case 'text': | |
default: | |
state.answerBuffer += data.content; | |
break; | |
} | |
} | |
} | |
if (data.error) { | |
if (state.currentMode === 'thinking') { | |
state.thoughtsBuffer += `\n**Erreur pendant la réflexion:** ${data.error}\n`; | |
} else { | |
state.answerBuffer += `\n**Erreur:** ${data.error}\n`; | |
} | |
} | |
} catch (e) { | |
console.error('Error parsing JSON data:', part.slice(5), e); | |
if (state.currentMode === 'thinking') { | |
state.thoughtsBuffer += `\n[Erreur de traitement du flux]`; | |
} else { | |
state.answerBuffer += `\n[Erreur de traitement du flux]`; | |
} | |
} | |
} | |
scheduleDisplayUpdate(); | |
} | |
} catch (error) { | |
console.error('Erreur de soumission:', error); | |
Swal.fire('Erreur', `Une erreur est survenue lors de la résolution: ${error.message}`, 'error'); | |
elements.loader.classList.add('hidden'); | |
elements.progressIndicator.classList.add('hidden'); | |
} finally { | |
stopSolutionTimer(); | |
} | |
}); | |
// --- Saved Solutions Logic --- | |
elements.saveButton.addEventListener('click', async () => { | |
const { value: saveName } = await Swal.fire({ | |
title: 'Nom de la sauvegarde', | |
input: 'text', | |
inputPlaceholder: 'Ex: Exercice Maths Ch.3', | |
showCancelButton: true, | |
confirmButtonText: 'Sauvegarder', | |
cancelButtonText: 'Annuler', | |
inputValidator: (value) => { | |
if (!value) return 'Vous devez entrer un nom !'; | |
const savedExercises = JSON.parse(localStorage.getItem('savedExercises') || '{}'); | |
if (savedExercises[value]) return 'Ce nom existe déjà. Choisissez-en un autre.'; | |
} | |
}); | |
if (saveName) { | |
const saveData = { | |
answer: elements.answerContent.innerHTML, | |
thinking: elements.thoughtsContent.innerHTML, | |
date: new Date().toLocaleString('fr-FR'), | |
calculatorUsed: elements.calculatorToggle.checked, | |
extendedReasoningUsed: elements.reasoningToggle.checked | |
}; | |
let savedExercises = JSON.parse(localStorage.getItem('savedExercises') || '{}'); | |
savedExercises[saveName] = saveData; | |
localStorage.setItem('savedExercises', JSON.stringify(savedExercises)); | |
Swal.fire('Sauvegardé!', 'Votre solution a été sauvegardée.', 'success'); | |
} | |
}); | |
const loadSavedList = () => { | |
elements.savedList.innerHTML = ''; | |
const savedExercises = JSON.parse(localStorage.getItem('savedExercises') || '{}'); | |
if (Object.keys(savedExercises).length === 0) { | |
elements.savedList.innerHTML = '<li class="text-gray-500">Aucune sauvegarde pour le moment.</li>'; | |
return; | |
} | |
for (const [name, data] of Object.entries(savedExercises).sort((a,b) => new Date(b[1].date) - new Date(a[1].date))) { | |
const li = document.createElement('li'); | |
li.className = 'flex justify-between items-center p-2 hover:bg-gray-100 rounded'; | |
const badges = []; | |
if (data.calculatorUsed) { | |
badges.push('<span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800 ml-2">🧮 Calculatrice</span>'); | |
} | |
if (data.extendedReasoningUsed) { | |
badges.push('<span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-purple-100 text-purple-800 ml-2">🧠 Raisonnement</span>'); | |
} | |
li.innerHTML = ` | |
<button class="text-left text-blue-600 hover:underline focus:outline-none" data-save-name="${name}"> | |
${name} ${badges.join('')}<br> | |
<span class="text-gray-500 text-xs">(${data.date})</span> | |
</button> | |
<button class="text-red-500 hover:text-red-700 text-xs p-1 focus:outline-none" data-delete-name="${name}" aria-label="Supprimer ${name}"> | |
Supprimer | |
</button> | |
`; | |
elements.savedList.appendChild(li); | |
} | |
}; | |
elements.savedList.addEventListener('click', (e) => { | |
const target = e.target.closest('button'); | |
if (!target) return; | |
const saveName = target.dataset.saveName; | |
const deleteName = target.dataset.deleteName; | |
if (saveName) { | |
const savedExercises = JSON.parse(localStorage.getItem('savedExercises') || '{}'); | |
const data = savedExercises[saveName]; | |
if (data) { | |
resetUIForNewProblem(); | |
elements.form.classList.add('hidden'); | |
elements.loader.classList.add('hidden'); | |
elements.solutionSection.classList.remove('hidden'); | |
elements.thoughtsContent.innerHTML = data.thinking; | |
elements.answerContent.innerHTML = data.answer; | |
state.thoughtsBuffer = ''; | |
state.answerBuffer = ''; | |
typesetMathJaxContent(elements.thoughtsContent).then(() => { | |
typesetMathJaxContent(elements.answerContent).then(() => { | |
applyHighlighting(); | |
}); | |
}); | |
elements.thoughtsBox.classList.add('open'); | |
elements.savedModal.classList.remove('active'); | |
resetSolutionTimer(); | |
elements.timestamp.textContent = data.date; | |
// Restore toggle states | |
if (data.calculatorUsed) { | |
elements.calculatorToggle.checked = true; | |
elements.calculatorOption.classList.add('enabled'); | |
elements.calculatorFeatures.classList.remove('hidden'); | |
} | |
if (data.extendedReasoningUsed) { | |
elements.reasoningToggle.checked = true; | |
elements.reasoningOption.classList.add('enabled'); | |
elements.reasoningFeatures.classList.remove('hidden'); | |
} | |
} | |
} else if (deleteName) { | |
Swal.fire({ | |
title: `Supprimer "${deleteName}" ?`, | |
text: "Cette action est irréversible.", | |
icon: 'warning', | |
showCancelButton: true, | |
confirmButtonColor: '#d33', | |
cancelButtonColor: '#3085d6', | |
confirmButtonText: 'Oui, supprimer !', | |
cancelButtonText: 'Annuler' | |
}).then((result) => { | |
if (result.isConfirmed) { | |
let savedExercises = JSON.parse(localStorage.getItem('savedExercises') || '{}'); | |
delete savedExercises[deleteName]; | |
localStorage.setItem('savedExercises', JSON.stringify(savedExercises)); | |
loadSavedList(); | |
Swal.fire('Supprimé!', `"${deleteName}" a été supprimé.`, 'success'); | |
} | |
}); | |
} | |
}); | |
elements.openSaved.addEventListener('click', () => { | |
loadSavedList(); | |
elements.savedModal.classList.add('active'); | |
}); | |
elements.closeSaved.addEventListener('click', () => { | |
elements.savedModal.classList.remove('active'); | |
}); | |
elements.newExercise.addEventListener('click', () => { | |
resetUIForNewProblem(); | |
elements.savedModal.classList.remove('active'); | |
}); | |
// --- Initialization --- | |
resetUIForNewProblem(); | |
}); | |
</script> | |
</body> | |
</html> |