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/[email protected]/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.9.0/styles/github.min.css"> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script> | |
<!-- Include Python language if needed --> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/python.min.js"></script> | |
<!-- Marked.js for Markdown parsing --> | |
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/marked.umd.min.js"></script> | |
<!-- MathJax Configuration --> | |
<script> | |
window.MathJax = { | |
tex: { | |
inlineMath: [['$', '$']], | |
displayMath: [['$$', '$$']], | |
processEscapes: true, | |
packages: {'[+]': ['autoload', 'ams']} // Using autoload package | |
}, | |
options: { | |
enableMenu: false, | |
messageStyle: 'none', | |
skipHtmlTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code'] // Ensure MathJax skips code blocks | |
}, | |
startup: { | |
// Use async ready function to ensure MathJax is fully loaded | |
ready: () => { | |
console.log('MathJax is ready'); | |
MathJax.startup.defaultReady(); | |
window.mathJaxReady = true; // Set flag when ready | |
} | |
} | |
}; | |
</script> | |
<script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js" id="MathJax-script" async></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; } | |
.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, opacity 0.3s ease-out; | |
max-height: 0; | |
overflow: hidden; | |
opacity: 0; | |
border: 1px solid #e5e7eb; /* Add border for clarity */ | |
border-radius: 0.375rem; /* Rounded corners */ | |
margin-top: 0.5rem; /* Spacing */ | |
} | |
.thought-box.open { | |
max-height: 500px; /* Or a larger value if needed */ | |
opacity: 1; | |
} | |
#thoughtsContent, #answerContent { | |
max-height: 60vh; /* Use viewport height for better scaling */ | |
overflow-y: auto; | |
scroll-behavior: smooth; | |
white-space: pre-wrap; /* Allow text wrapping */ | |
word-wrap: break-word; /* Break long words */ | |
background-color: #f9fafb; /* Slight background tint */ | |
padding: 1rem; /* Padding inside content areas */ | |
} | |
#answerContent { | |
background-color: white; /* Keep answer content white */ | |
} | |
.preview-image { max-width: 300px; max-height: 300px; object-fit: contain; } | |
.timestamp { color: #6b7280; font-size: 0.8em; margin-left: 8px; } | |
table { | |
border-collapse: collapse; | |
width: 100%; | |
margin-bottom: 1rem; | |
border: 1px solid #d1d5db; | |
} | |
th, td { | |
border: 1px solid #e5e7eb; /* Lighter border */ | |
padding: 0.75rem; /* More padding */ | |
text-align: left; | |
} | |
th { background-color: #f3f4f6; font-weight: 600; } | |
.table-responsive { overflow-x: auto; } | |
#saveButton { | |
background: #10b981; /* Green button */ | |
color: white; | |
padding: 0.5rem 1rem; | |
border-radius: 0.375rem; | |
transition: background-color 0.2s ease; | |
font-weight: 500; | |
} | |
#saveButton:hover { background: #059669; } | |
#savedModal { | |
display: none; | |
position: fixed; | |
inset: 0; | |
background: rgba(0,0,0,0.6); /* Darker overlay */ | |
z-index: 50; | |
overflow-y: auto; /* Allow modal scroll */ | |
} | |
#savedModal.active { display: flex; align-items: center; justify-content: center; } | |
#savedModalContent { | |
background: #fff; | |
width: 90%; | |
max-width: 800px; /* Limit max width */ | |
max-height: 90vh; /* Limit max height */ | |
border-radius: 0.5rem; | |
overflow: hidden; /* Hide inner overflow initially */ | |
display: flex; | |
flex-direction: column; | |
} | |
#savedModalContent header { padding: 1.5rem; border-bottom: 1px solid #e5e7eb; } | |
#savedModalContent #savedListContainer { padding: 1.5rem; overflow-y: auto; flex-grow: 1; } | |
#savedModalContent footer { padding: 1rem 1.5rem; border-top: 1px solid #e5e7eb; background-color: #f9fafb; } | |
/* Styles specific to code blocks generated by marked.js and highlighted by highlight.js */ | |
#answerContent pre code.hljs { /* Target highlighted code blocks */ | |
display: block; | |
overflow-x: auto; | |
padding: 1em; | |
background: #f3f4f6; /* Background matching Tailwind gray */ | |
color: #1f2937; /* Dark text */ | |
border-radius: 0.375rem; | |
border: 1px solid #e5e7eb; | |
} | |
/* Style for blockquotes used for code execution results */ | |
#answerContent blockquote { | |
background-color: #eff6ff; /* Lighter blue background */ | |
border-left: 4px solid #3b82f6; /* Blue left border */ | |
padding: 0.75rem 1rem; | |
margin: 1rem 0; | |
color: #1e40af; /* Darker blue text */ | |
white-space: pre-wrap; /* Preserve line breaks and spaces */ | |
word-wrap: break-word; /* Break long lines */ | |
font-style: italic; /* Italicize results */ | |
} | |
#answerContent blockquote p { | |
margin: 0; /* Remove default paragraph margins inside blockquote */ | |
} | |
/* Styles for images within the answer */ | |
#answerContent img { | |
max-width: 100%; | |
height: auto; /* Maintain aspect ratio */ | |
display: block; /* Prevent extra space below image */ | |
margin: 1rem auto; /* Center images with margin */ | |
border: 1px solid #d1d5db; /* Optional border */ | |
border-radius: 0.25rem; /* Optional rounded corners */ | |
} | |
/* Tabs styling */ | |
.tabs { | |
display: flex; | |
border-bottom: 1px solid #e2e8f0; | |
margin-bottom: 1.5rem; /* More space below tabs */ | |
} | |
.tab { | |
padding: 0.75rem 1.5rem; /* More padding */ | |
cursor: pointer; | |
border-bottom: 3px solid transparent; | |
color: #4b5563; /* Gray text */ | |
font-weight: 500; | |
transition: border-color 0.2s ease, color 0.2s ease; | |
} | |
.tab:hover { | |
color: #1f2937; /* Darker text on hover */ | |
} | |
.tab.active { | |
border-bottom: 3px solid #3b82f6; | |
color: #3b82f6; /* Blue text */ | |
font-weight: 600; | |
} | |
</style> | |
</head> | |
<body class="bg-gray-50 p-4 min-h-screen flex items-center justify-center"> | |
<div class="max-w-4xl mx-auto w-full bg-white p-8 rounded-lg shadow-md"> | |
<header class="p-6 text-center mb-6 border-b border-gray-200"> | |
<h1 class="text-4xl font-bold text-blue-600">Mariam M-1</h1> | |
<p class="text-gray-600 mt-2">Solution Mathématique/Physique/Chimie Intelligente</p> | |
<div class="mt-4 flex justify-end"> | |
<button id="openSaved" class="text-sm blue-button px-4 py-2 text-white rounded-md shadow-sm"> | |
Voir Sauvegardes | |
</button> | |
</div> | |
</header> | |
<main id="mainContent"> | |
<form id="problemForm" class="space-y-6" novalidate> | |
<!-- Tabs for model selection --> | |
<div class="tabs"> | |
<div class="tab active" data-endpoint="solve">Gemini 1.5 Pro</div> <!-- Updated Name --> | |
<div class="tab" data-endpoint="solved">Gemini 1.5 Flash</div> <!-- Updated Name --> | |
</div> | |
<!-- Image upload area --> | |
<div class="uploadArea p-8 text-center relative rounded-md" 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 bg-blue-50"> | |
<svg class="w-8 h-8 text-blue-500" 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 (PNG, JPG, WEBP...)</p> | |
</div> | |
</div> | |
<!-- Image preview --> | |
<div id="imagePreview" class="hidden text-center mt-4"> | |
<img id="previewImage" class="preview-image mx-auto border border-gray-300 rounded" alt="Prévisualisation de l'image"> | |
</div> | |
<button type="submit" class="blue-button w-full py-3 text-white font-medium rounded-lg shadow-md hover:shadow-lg transition duration-200"> | |
Résoudre le problème | |
</button> | |
</form> | |
<!-- Loader --> | |
<div id="loader" class="hidden mt-8 text-center"> | |
<span class="loader"></span> | |
<p class="mt-4 text-gray-600 font-medium">Analyse en cours...</p> | |
</div> | |
<!-- Solution display area --> | |
<section id="solution" class="hidden mt-8 space-y-6"> | |
<!-- Thinking Process Toggle and Content --> | |
<div class="border rounded-md overflow-hidden"> | |
<button id="thoughtsToggle" type="button" class="w-full flex justify-between items-center p-3 bg-gray-100 hover:bg-gray-200 transition duration-150"> | |
<span class="font-medium text-gray-700">Processus de Réflexion</span> | |
<div class="flex items-center"> | |
<span id="timestamp" class="timestamp"></span> | |
<!-- Simple chevron icon --> | |
<svg id="toggleIcon" class="w-5 h-5 text-gray-600 ml-2 transform transition-transform duration-300" fill="none" stroke="currentColor" viewBox="0 0 24 24"> | |
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path> | |
</svg> | |
</div> | |
</button> | |
<div id="thoughtsBox" class="thought-box"> <!-- Content goes inside the box --> | |
<div id="thoughtsContent" class="p-4 text-sm text-gray-600"></div> | |
</div> | |
</div> | |
<!-- Answer Content --> | |
<div class="border rounded-md"> | |
<div class="flex justify-between items-center p-3 border-b bg-white"> | |
<h3 class="text-xl font-semibold text-gray-800">Solution Détaillée</h3> | |
<button id="saveButton">Sauvegarder</button> | |
</div> | |
<div id="answerContent" class="p-4 text-gray-700 table-responsive"> | |
<!-- Content will be rendered here --> | |
</div> | |
</div> | |
</section> | |
</main> | |
</div> | |
<!-- Saved Solutions Modal --> | |
<div id="savedModal"> | |
<div id="savedModalContent"> | |
<header class="flex justify-between items-center"> | |
<h2 class="text-2xl font-bold text-gray-800">Solutions Sauvegardées</h2> | |
<button id="closeSaved" class="text-3xl text-gray-500 hover:text-gray-700">×</button> | |
</header> | |
<div id="savedListContainer"> | |
<ul id="savedList" class="space-y-4"> | |
<!-- Saved items will be listed here --> | |
</ul> | |
</div> | |
<footer class="text-center"> | |
<button id="newExercise" class="blue-button w-full py-3 text-white font-medium rounded-lg"> | |
Résoudre un nouvel exercice | |
</button> | |
</footer> | |
</div> | |
</div> | |
<script> | |
// Ensure Marked and Highlight.js are loaded before configuring | |
// Note: hljs might already be available if scripts load synchronously | |
// but deferring configuration is safer. | |
function configureMarked() { | |
if (typeof marked === 'undefined' || typeof hljs === 'undefined') { | |
console.log("Waiting for Marked and Highlight.js..."); | |
setTimeout(configureMarked, 100); // Check again shortly | |
return; | |
} | |
console.log("Configuring Marked.js"); | |
marked.setOptions({ | |
gfm: true, // Enable GitHub Flavored Markdown | |
breaks: true, // Use GFM line breaks (single newline = <br>) | |
pedantic: false, // Don't be strict about syntax errors | |
smartLists: true, // Use smarter list behavior | |
smartypants: false, // Don't auto-correct quotes, dashes, etc. | |
highlight: function (code, lang) { | |
const language = hljs.getLanguage(lang) ? lang : 'plaintext'; | |
try { | |
return hljs.highlight(code, { language: language, ignoreIllegals: true }).value; | |
} catch (error) { | |
console.error("Highlighting error:", error); | |
return hljs.highlight(code, { language: 'plaintext', ignoreIllegals: true }).value; // Fallback | |
} | |
} | |
}); | |
window.markedConfigured = true; // Flag that configuration is done | |
} | |
configureMarked(); // Start configuration attempt | |
document.addEventListener('DOMContentLoaded', () => { | |
// Element retrieval | |
const form = document.getElementById('problemForm'); | |
const imageInput = document.getElementById('imageInput'); | |
const loader = document.getElementById('loader'); | |
const solutionSection = document.getElementById('solution'); | |
const thoughtsContent = document.getElementById('thoughtsContent'); | |
const answerContent = document.getElementById('answerContent'); | |
const thoughtsToggle = document.getElementById('thoughtsToggle'); | |
const thoughtsBox = document.getElementById('thoughtsBox'); | |
const toggleIcon = document.getElementById('toggleIcon'); | |
const imagePreview = document.getElementById('imagePreview'); | |
const previewImage = document.getElementById('previewImage'); | |
const timestamp = document.getElementById('timestamp'); | |
const saveButton = document.getElementById('saveButton'); | |
const openSaved = document.getElementById('openSaved'); | |
const closeSaved = document.getElementById('closeSaved'); | |
const savedModal = document.getElementById('savedModal'); | |
const savedList = document.getElementById('savedList'); | |
const newExercise = document.getElementById('newExercise'); | |
const mainContent = document.getElementById('mainContent'); // Not used currently, but kept | |
const tabs = document.querySelectorAll('.tab'); | |
const dropZone = document.querySelector('.uploadArea'); | |
// State variables | |
let startTime = null; | |
let timerInterval = null; | |
let thoughtsBuffer = ''; | |
let answerBuffer = ''; | |
let currentMode = null; // 'thinking', 'answering' | |
let updateTimeout = null; | |
let currentEndpoint = 'solve'; // Default endpoint | |
let eventSource = null; // To hold the EventSource object for potential closing | |
// --- Helper Functions --- | |
// Update elapsed time | |
const updateTimestamp = () => { | |
if (startTime) { | |
const seconds = Math.floor((Date.now() - startTime) / 1000); | |
timestamp.textContent = `(${seconds}s)`; | |
} else { | |
timestamp.textContent = ''; | |
} | |
}; | |
const startTimer = () => { startTime = Date.now(); updateTimestamp(); timerInterval = setInterval(updateTimestamp, 1000); }; | |
const stopTimer = () => { clearInterval(timerInterval); updateTimestamp(); /* Keep final time */ }; // Keep showing final time | |
// Handle file selection (preview) | |
const handleFileSelect = file => { | |
if (!file || !file.type.startsWith('image/')) { | |
if(file) { // Only show error if a file was actually selected/dropped | |
Swal.fire('Erreur', 'Veuillez sélectionner un fichier image valide.', 'error'); | |
} | |
imagePreview.classList.add('hidden'); | |
previewImage.src = ''; | |
imageInput.value = ''; // Clear the input | |
return false; // Indicate failure | |
} | |
const reader = new FileReader(); | |
reader.onload = e => { | |
previewImage.src = e.target.result; | |
imagePreview.classList.remove('hidden'); | |
}; | |
reader.readAsDataURL(file); | |
return true; // Indicate success | |
}; | |
// Toggle thoughts box visibility | |
const toggleThoughts = () => { | |
thoughtsBox.classList.toggle('open'); | |
toggleIcon.classList.toggle('rotate-180'); // Rotate chevron | |
} | |
thoughtsToggle.addEventListener('click', toggleThoughts); | |
// Apply syntax highlighting to code blocks | |
const applyHighlighting = () => { | |
// Check if hljs is available | |
if (typeof hljs !== 'undefined') { | |
document.querySelectorAll('#answerContent pre code:not(.hljs)').forEach((block) => { | |
try { | |
hljs.highlightElement(block); | |
} catch (error) { | |
console.error("Error applying highlight.js:", error, block); | |
} | |
}); | |
} else { | |
console.warn("highlight.js not ready for highlighting."); | |
} | |
}; | |
// Render MathJax and update display (debounced) | |
const typesetMathJax = async () => { | |
if (window.mathJaxReady && typeof MathJax !== 'undefined') { | |
console.log("Typesetting MathJax..."); | |
try { | |
// Clear previous typesetting state if necessary before re-typesetting | |
// MathJax.startup.document.reset(); // Use cautiously, might have side effects | |
// MathJax.startup.document.clear(); // Alternative | |
await MathJax.typesetPromise([answerContent]); // Target specific container | |
console.log("MathJax typesetting complete."); | |
} catch (error) { | |
console.error('MathJax typesetting error:', error); | |
} | |
} else { | |
console.log("MathJax not ready, deferring typesetting."); | |
// No need for setTimeout here, updateDisplay handles debouncing | |
} | |
}; | |
// Update content display (debounced) | |
const updateDisplay = async () => { | |
if (!window.markedConfigured) { | |
console.log("Marked not configured, deferring display update."); | |
scheduleUpdate(); // Reschedule | |
return; | |
} | |
console.log("Updating display..."); | |
// Use try-catch for parsing as large/complex markdown can sometimes cause issues | |
try { | |
thoughtsContent.innerHTML = marked.parse(thoughtsBuffer); | |
answerContent.innerHTML = marked.parse(answerBuffer); | |
// Apply Highlighting *after* setting innerHTML from marked | |
applyHighlighting(); | |
// Typeset MathJax *after* highlighting (or concurrently if no dependencies) | |
await typesetMathJax(); | |
// Scroll to bottom (optional) | |
answerContent.scrollTop = answerContent.scrollHeight; | |
thoughtsContent.scrollTop = thoughtsContent.scrollHeight; | |
} catch (error) { | |
console.error("Error parsing Markdown:", error); | |
// Display error message to user? | |
answerContent.innerHTML = "<p class='text-red-500'>Erreur lors de l'affichage de la réponse.</p>"; | |
} | |
updateTimeout = null; // Clear timeout flag | |
}; | |
// Schedule display update (debounce mechanism) | |
const scheduleUpdate = () => { | |
if (!updateTimeout) { | |
updateTimeout = setTimeout(updateDisplay, 250); // Debounce time (250ms) | |
} | |
}; | |
// --- Event Listeners --- | |
// Tab switching | |
tabs.forEach(tab => { | |
tab.addEventListener('click', () => { | |
if (eventSource) { // Prevent switching during generation | |
Swal.fire('Attention', 'Veuillez attendre la fin de la génération actuelle avant de changer de modèle.', 'warning'); | |
return; | |
} | |
tabs.forEach(t => t.classList.remove('active')); | |
tab.classList.add('active'); | |
currentEndpoint = tab.dataset.endpoint; | |
console.log("Switched to endpoint:", currentEndpoint); | |
}); | |
}); | |
// File input change | |
imageInput.addEventListener('change', e => handleFileSelect(e.target.files[0])); | |
// Drag and Drop | |
dropZone.addEventListener('dragover', e => { e.preventDefault(); dropZone.classList.add('border-blue-400', 'bg-blue-100'); }); | |
dropZone.addEventListener('dragleave', e => { e.preventDefault(); dropZone.classList.remove('border-blue-400', 'bg-blue-100'); }); | |
dropZone.addEventListener('drop', e => { | |
e.preventDefault(); | |
dropZone.classList.remove('border-blue-400', 'bg-blue-100'); | |
if (e.dataTransfer.files.length > 0) { | |
// Pass the file to the input and the handler | |
imageInput.files = e.dataTransfer.files; | |
handleFileSelect(e.dataTransfer.files[0]); | |
} | |
}); | |
// Form submission (main logic) | |
form.addEventListener('submit', async e => { | |
e.preventDefault(); | |
const file = imageInput.files[0]; | |
if (!file) { | |
Swal.fire('Image manquante', 'Veuillez sélectionner ou déposer une image.', 'warning'); | |
return; | |
} | |
// Ensure the preview is updated if a file was selected but not dropped | |
if (!handleFileSelect(file)) return; // Re-validate just in case | |
// --- Reset UI --- | |
startTimer(); | |
loader.classList.remove('hidden'); | |
solutionSection.classList.add('hidden'); | |
thoughtsContent.innerHTML = ''; | |
answerContent.innerHTML = ''; | |
thoughtsBuffer = ''; | |
answerBuffer = ''; | |
currentMode = null; | |
if (!thoughtsBox.classList.contains('open')) { // Open thoughts box automatically | |
toggleThoughts(); | |
} | |
if (eventSource) { // Close previous connection if any | |
eventSource.close(); | |
console.log("Previous EventSource closed."); | |
} | |
// --- Prepare and Send Request --- | |
const formData = new FormData(); | |
formData.append('image', file); | |
const url = `/${currentEndpoint}`; // Use the selected endpoint | |
console.log(`Sending request to: ${url}`); | |
eventSource = new EventSource(url + `?t=${Date.now()}`, { // Use GET for EventSource traditionally, or adapt backend if POST needed via fetch stream | |
method: 'POST', // NOTE: EventSource standard doesn't support POST body, this might require a fetch-based stream reader instead | |
body: formData // This body part is NON-STANDARD for EventSource and likely won't work directly | |
}); | |
// --- Use Fetch API for Streaming with POST --- | |
// Replace the EventSource code above with this Fetch-based approach: | |
fetch(url, { | |
method: 'POST', | |
body: formData | |
}) | |
.then(response => { | |
if (!response.ok) { | |
// Try to read error message from server if available | |
return response.json().then(errData => { | |
throw new Error(errData.error || `Erreur serveur: ${response.statusText}`); | |
}).catch(() => { | |
// Fallback if response is not JSON or reading fails | |
throw new Error(`Erreur HTTP ${response.status} - ${response.statusText}`); | |
}); | |
} | |
if (!response.body) { | |
throw new Error("La réponse du serveur n'a pas de corps de flux."); | |
} | |
const reader = response.body.getReader(); | |
const decoder = new TextDecoder(); | |
let buffer = ''; | |
function processStream() { | |
reader.read().then(({ done, value }) => { | |
if (done) { | |
console.log("Stream terminé."); | |
stopTimer(); | |
if (buffer) { // Process any remaining data in the buffer | |
try { | |
const data = JSON.parse(buffer.slice(5)); // Assuming "data: " prefix | |
processData(data); | |
} catch (parseError){ | |
console.warn("Could not parse trailing buffer data:", buffer, parseError); | |
} | |
} | |
// Ensure final update is displayed | |
if(updateTimeout) clearTimeout(updateTimeout); | |
updateDisplay(); | |
return; | |
} | |
buffer += decoder.decode(value, { stream: true }); | |
// Process buffer line by line (SSE format: data: {...}\n\n) | |
const lines = buffer.split('\n\n'); | |
buffer = lines.pop() || ''; // Keep the last (potentially incomplete) line | |
lines.forEach(line => { | |
if (line.startsWith('data: ')) { | |
try { | |
const jsonData = line.substring(5); // Remove "data: " | |
const data = JSON.parse(jsonData); | |
processData(data); | |
} catch (parseError) { | |
console.error('Erreur de parsing JSON:', parseError, 'Data received:', line); | |
} | |
} else if (line.trim()) { | |
console.warn("Ligne SSE reçue non reconnue:", line); | |
} | |
}); | |
scheduleUpdate(); // Schedule UI update after processing chunk | |
processStream(); // Continue reading the stream | |
}).catch(streamError => { | |
console.error('Erreur de lecture du flux:', streamError); | |
Swal.fire('Erreur de Connexion', `Impossible de lire la réponse: ${streamError.message}`, 'error'); | |
loader.classList.add('hidden'); | |
stopTimer(); | |
}); | |
} | |
processStream(); // Start processing the stream | |
}) | |
.catch(error => { | |
console.error('Erreur Fetch:', error); | |
Swal.fire('Erreur Réseau', `Impossible de contacter le serveur: ${error.message}`, 'error'); | |
loader.classList.add('hidden'); | |
stopTimer(); | |
}); | |
// --- Process Received Data --- | |
const processData = (data) => { | |
// console.log("Received data:", data); // Debug log | |
if (data.mode) { | |
currentMode = data.mode; | |
console.log("Mode changed to:", currentMode); | |
if (currentMode === 'answering' && loader.classList.contains('hidden') === false) { | |
loader.classList.add('hidden'); | |
solutionSection.classList.remove('hidden'); | |
} | |
} | |
if (data.content) { | |
const content = data.content; | |
const type = data.type; | |
if (currentMode === 'thinking') { | |
// Accumulate all thinking content as simple text (or handle types if needed) | |
thoughtsBuffer += content; | |
} else if (currentMode === 'answering') { | |
// Handle different content types for the main answer | |
switch(type) { | |
case 'text': | |
answerBuffer += content; | |
break; | |
case 'code': | |
// Wrap code in Markdown fences with language hint if possible (defaulting to python) | |
answerBuffer += `\n\n\`\`\`python\n${content}\n\`\`\`\n\n`; | |
break; | |
case 'result': | |
// Format result as a Markdown blockquote | |
const formattedResult = content.split('\n').map(line => `> ${line}`).join('\n'); | |
answerBuffer += `\n\n${formattedResult}\n\n`; | |
break; | |
case 'image': | |
// --- IMAGE HANDLING CORRECTION --- | |
const mimeType = data.mime_type || 'image/png'; // Get MIME type or default | |
// Use Markdown image syntax with the correct data URI | |
answerBuffer += `\n\n\n\n`; | |
// --- END IMAGE HANDLING CORRECTION --- | |
break; | |
default: | |
console.warn("Type de contenu inconnu reçu:", type, content); | |
answerBuffer += content; // Append as text by default | |
} | |
} | |
} | |
if (data.error) { | |
console.error("Erreur reçue du serveur:", data.error); | |
// Display error prominently in the answer section | |
answerBuffer += `\n\n<p class="text-red-600 font-bold">Erreur du serveur: ${data.error}</p>\n\n`; | |
stopTimer(); // Stop timer on error | |
// Consider stopping the stream/fetch here if possible | |
} | |
}; | |
}); // End form submit listener | |
// --- Local Storage & Modal Logic --- | |
// Save solution | |
saveButton.addEventListener('click', () => { | |
Swal.fire({ | |
title: 'Sauvegarder la solution', | |
input: 'text', | |
inputLabel: 'Nom de la sauvegarde', | |
inputPlaceholder: 'Ex: Exercice Intégrales', | |
showCancelButton: true, | |
confirmButtonText: 'Sauvegarder', | |
cancelButtonText: 'Annuler', | |
inputValidator: (value) => { | |
if (!value) { | |
return 'Veuillez entrer un nom !' | |
} | |
const savedExercises = JSON.parse(localStorage.getItem('savedExercises') || '{}'); | |
if (savedExercises[value]) { | |
return 'Ce nom existe déjà. Choisissez-en un autre.' | |
} | |
} | |
}).then((result) => { | |
if (result.isConfirmed && result.value) { | |
const saveName = result.value.trim(); | |
const saveData = { | |
answer: answerContent.innerHTML, // Save rendered HTML | |
thinking: thoughtsContent.innerHTML, // Save rendered HTML | |
date: new Date().toLocaleString('fr-FR') // Use French locale for date | |
}; | |
let savedExercises = JSON.parse(localStorage.getItem('savedExercises') || '{}'); | |
savedExercises[saveName] = saveData; | |
try { | |
localStorage.setItem('savedExercises', JSON.stringify(savedExercises)); | |
Swal.fire({ icon: 'success', title: 'Sauvegardé !', text: `Solution enregistrée sous "${saveName}".`, timer: 2000, showConfirmButton: false }); | |
} catch (e) { | |
console.error("Error saving to localStorage:", e); | |
// Handle potential storage limits | |
Swal.fire('Erreur', 'Impossible de sauvegarder. Le stockage local est peut-être plein.', 'error'); | |
} | |
} | |
}); | |
}); | |
// Load saved list into modal | |
const loadSavedList = () => { | |
savedList.innerHTML = ''; // Clear previous list | |
const savedExercises = JSON.parse(localStorage.getItem('savedExercises') || '{}'); | |
const sortedKeys = Object.keys(savedExercises).sort((a, b) => { | |
// Sort by date descending (newest first) if possible | |
try { | |
return new Date(savedExercises[b].date.split('/').reverse().join('-')) - new Date(savedExercises[a].date.split('/').reverse().join('-')); | |
} catch { return 0; } // Fallback sort | |
}); | |
if (sortedKeys.length === 0) { | |
savedList.innerHTML = '<li class="text-gray-500 text-center py-8">Aucune sauvegarde disponible</li>'; | |
return; | |
} | |
sortedKeys.forEach(name => { | |
const data = savedExercises[name]; | |
const li = document.createElement('li'); | |
li.className = 'border-b border-gray-200 pb-3 mb-3'; // Styling for list items | |
li.innerHTML = ` | |
<div class="flex justify-between items-center"> | |
<button class="text-left text-blue-600 hover:underline focus:outline-none" data-save="${encodeURIComponent(name)}"> | |
<span class="font-medium">${name}</span> | |
<span class="block text-gray-500 text-xs mt-1">(${data.date})</span> | |
</button> | |
<button class="text-red-500 hover:text-red-700 p-1 rounded focus:outline-none focus:ring-2 focus:ring-red-400" data-delete="${encodeURIComponent(name)}" aria-label="Supprimer ${name}"> | |
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor"> | |
<path fill-rule="evenodd" d="M9 2a1 1 0 00-.894.553L7.382 4H4a1 1 0 000 2v10a2 2 0 002 2h8a2 2 0 002-2V6a1 1 0 100-2h-3.382l-.724-1.447A1 1 0 0011 2H9zM7 8a1 1 0 012 0v6a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v6a1 1 0 102 0V8a1 1 0 00-1-1z" clip-rule="evenodd" /> | |
</svg> | |
</button> | |
</div> | |
`; | |
savedList.appendChild(li); | |
}); | |
}; | |
// Handle clicks within the saved list (load or delete) | |
savedList.addEventListener('click', (e) => { | |
const loadButton = e.target.closest('[data-save]'); | |
const deleteButton = e.target.closest('[data-delete]'); | |
// Load saved solution | |
if (loadButton) { | |
const saveName = decodeURIComponent(loadButton.dataset.save); | |
const savedExercises = JSON.parse(localStorage.getItem('savedExercises') || '{}'); | |
const data = savedExercises[saveName]; | |
if (data) { | |
form.classList.add('hidden'); // Hide form | |
loader.classList.add('hidden'); | |
solutionSection.classList.remove('hidden'); // Show solution section | |
thoughtsContent.innerHTML = data.thinking; // Load saved HTML | |
answerContent.innerHTML = data.answer; // Load saved HTML | |
// Re-apply MathJax and Highlighting to the loaded content | |
// Need slight delay for elements to be in DOM reliably? | |
setTimeout(async () => { | |
applyHighlighting(); | |
await typesetMathJax(); | |
// Ensure thoughts box is open if it has content | |
if(data.thinking && !thoughtsBox.classList.contains('open')) { | |
toggleThoughts(); | |
} else if (!data.thinking && thoughtsBox.classList.contains('open')) { | |
toggleThoughts(); // Close if no thinking content was saved | |
} | |
}, 100); // Small delay | |
savedModal.classList.remove('active'); // Close modal | |
} | |
} | |
// Delete saved solution | |
if (deleteButton) { | |
const deleteName = decodeURIComponent(deleteButton.dataset.delete); | |
Swal.fire({ | |
title: 'Êtes-vous sûr ?', | |
text: `Supprimer la sauvegarde "${deleteName}" ? Cette action est irréversible.`, | |
icon: 'warning', | |
showCancelButton: true, | |
confirmButtonColor: '#d33', // Red for delete | |
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)); | |
Swal.fire( 'Supprimé !', `La sauvegarde "${deleteName}" a été supprimée.`, 'success' ); | |
loadSavedList(); // Refresh list in modal | |
} | |
}); | |
} | |
}); | |
// Modal open/close | |
openSaved.addEventListener('click', () => { loadSavedList(); savedModal.classList.add('active'); }); | |
closeSaved.addEventListener('click', () => { savedModal.classList.remove('active'); }); | |
// Close modal if clicking outside the content area | |
savedModal.addEventListener('click', (e) => { | |
if (e.target === savedModal) { // Check if the click is on the backdrop itself | |
savedModal.classList.remove('active'); | |
} | |
}); | |
// Reset UI for a new exercise (from modal) | |
newExercise.addEventListener('click', () => { | |
form.reset(); // Reset form fields | |
form.classList.remove('hidden'); // Show form | |
solutionSection.classList.add('hidden'); // Hide solution | |
loader.classList.add('hidden'); // Hide loader | |
imagePreview.classList.add('hidden'); // Hide preview | |
previewImage.src = ''; | |
thoughtsContent.innerHTML = ''; | |
answerContent.innerHTML = ''; | |
thoughtsBuffer = ''; | |
answerBuffer = ''; | |
stopTimer(); // Reset timer display | |
if (thoughtsBox.classList.contains('open')) { // Close thoughts box | |
toggleThoughts(); | |
} | |
savedModal.classList.remove('active'); // Close modal | |
}); | |
// Initial check: If MathJax is already ready, set the flag | |
if (typeof MathJax !== 'undefined' && MathJax.startup?.promise) { | |
MathJax.startup.promise.then(() => { | |
window.mathJaxReady = true; | |
console.log("MathJax startup promise resolved on load."); | |
}); | |
} | |
}); // End DOMContentLoaded | |
</script> | |
</body> | |
</html> |