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</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> | |
<!-- MathJax Configuration --> | |
<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 { background: #2563eb; } | |
.blue-button:disabled { background: #9ca3af; cursor: not-allowed; } | |
.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: 500px; /* Ajustez au besoin */ } | |
#thoughtsContent, #answerContent { | |
max-height: 500px; /* Ajustez au besoin */ | |
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 (style original) */ | |
#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; | |
} | |
</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> | |
<div class="uploadArea p-8 text-center relative" aria-label="Zone de dépôt d'image"> | |
<input type="file" id="imageInput" 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> | |
<div id="imagePreview" class="hidden text-center"> | |
<img id="previewImage" class="preview-image mx-auto" alt="Prévisualisation de l'image"> | |
</div> | |
<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> | |
<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> | |
<section id="solutionSection" 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 mb-4"> | |
<h3 class="text-xl font-bold text-gray-800">Solution</h3> | |
<button id="saveButton" class="blue-button">Sauvegarder</button> | |
</div> | |
<div id="answerContent" class="text-gray-700 table-responsive"></div> | |
</div> | |
</section> | |
</main> | |
</div> | |
<!-- Modal plein écran pour les sauvegardes (structure originale) --> | |
<div id="savedModal"> | |
<div id="savedModalContent" class="p-6"> <!-- p-6 est important ici pour le contenu du modal --> | |
<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"></ul> | |
</div> | |
<div class="mt-6"> | |
<button id="newExerciseButton" 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', () => { | |
// Configuration | |
const COOLDOWN_DURATION_MS = 3 * 60 * 1000; // 3 minutes | |
const LAST_SUBMISSION_TIME_KEY = 'mariamM0_lastSubmissionTime'; | |
const SUBMIT_BUTTON_ORIGINAL_TEXT = 'Résoudre le problème'; | |
// DOM Elements | |
const elements = { | |
form: document.getElementById('problemForm'), | |
imageInput: document.getElementById('imageInput'), | |
submitButton: document.getElementById('submitButton'), | |
loader: document.getElementById('loader'), | |
solutionSection: document.getElementById('solutionSection'), | |
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'), | |
newExerciseButton: document.getElementById('newExerciseButton'), // Changé l'ID pour correspondre au HTML | |
dropZone: document.querySelector('.uploadArea') | |
}; | |
// Application State | |
const state = { | |
startTime: null, | |
timerInterval: null, | |
cooldownTimerInterval: null, | |
thoughtsBuffer: '', | |
answerBuffer: '', | |
currentMode: null, // 'thinking' or 'answering' | |
updateTimeout: null, | |
selectedFile: null | |
}; | |
marked.setOptions({ gfm: true, breaks: true }); | |
// --- 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 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.thoughtsContent.innerHTML = ''; | |
elements.answerContent.innerHTML = ''; | |
state.thoughtsBuffer = ''; | |
state.answerBuffer = ''; | |
state.currentMode = null; | |
elements.thoughtsBox.classList.remove('open'); | |
elements.form.classList.remove('hidden'); | |
resetSolutionTimer(); | |
updateSubmitButtonState(); | |
}; | |
// --- 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; | |
} | |
}; | |
// --- 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 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); | |
state.updateTimeout = null; | |
}, 150); | |
}; | |
// --- Event Listeners --- | |
elements.thoughtsToggle.addEventListener('click', () => elements.thoughtsBox.classList.toggle('open')); | |
elements.imageInput.addEventListener('change', e => handleFileSelect(e.target.files[0])); | |
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; | |
} | |
}); | |
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(); | |
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'); | |
const formData = new FormData(); | |
formData.append('image', state.selectedFile); | |
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 = ''; | |
// eslint-disable-next-line no-constant-condition | |
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(); | |
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) { | |
if (state.currentMode === 'thinking') state.thoughtsBuffer += data.content; | |
else if (state.currentMode === 'answering') state.answerBuffer += data.content; | |
} | |
} catch (parseError) { | |
console.warn("Error parsing stream part:", parseError, "Part:", part); | |
} | |
} | |
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'); | |
} 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') | |
}; | |
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'; // Un peu de style pour la liste est ok | |
li.innerHTML = ` | |
<button class="text-left text-blue-600 hover:underline focus:outline-none" data-save-name="${name}"> | |
${name} <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)); | |
elements.thoughtsBox.classList.add('open'); | |
elements.savedModal.classList.remove('active'); | |
resetSolutionTimer(); | |
} | |
} 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')); | |
// Référence au bouton "Nouvel exercice" dans le modal | |
elements.newExerciseButton.addEventListener('click', () => { | |
resetUIForNewProblem(); | |
elements.savedModal.classList.remove('active'); | |
}); | |
// --- Initialization --- | |
resetUIForNewProblem(); | |
// Optionnel: Fermer le modal en cliquant à l'extérieur (si le modal n'est pas plein écran) | |
// Pour un modal plein écran, cette logique n'est pas pertinente. | |
// elements.savedModal.addEventListener('click', (e) => { | |
// if (e.target === elements.savedModal) { // Ne fonctionne bien que si savedModalContent est plus petit que savedModal | |
// elements.savedModal.classList.remove('active'); | |
// } | |
// }); | |
}); | |
</script> | |
</body> | |
</html> |