Docfile commited on
Commit
d8ece29
·
verified ·
1 Parent(s): 04942cf

Create maj.html

Browse files
Files changed (1) hide show
  1. templates/maj.html +587 -0
templates/maj.html ADDED
@@ -0,0 +1,587 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="fr">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Mariam | Solution Mathématique (Corrigé)</title>
7
+ <!-- Tailwind CSS via CDN -->
8
+ <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/tailwind.min.css" rel="stylesheet">
9
+
10
+ <!-- Configuration MathJax Optimisée -->
11
+ <script>
12
+ window.MathJax = {
13
+ tex: {
14
+ inlineMath: [['$', '$']], // Délimiteurs maths en ligne
15
+ displayMath: [['$$', '$$']], // Délimiteurs maths en bloc
16
+ processEscapes: true, // Permet \$ pour un dollar littéral
17
+ // Packages TeX courants pour maths/physique/chimie complexes
18
+ // 'autoload': Charge dynamiquement les commandes inconnues (flexible)
19
+ // 'ams': Environnements AMSMath (align, gather, matrix...)
20
+ // 'mhchem': Notation chimique (\ce{})
21
+ // 'physics': Notations physiques (\vec, \abs, \dv, \qty...)
22
+ // 'boldsymbol': Pour \boldsymbol{}
23
+ packages: {'[+]': ['autoload', 'ams', 'mhchem', 'physics', 'boldsymbol']}
24
+ },
25
+ chtml: {
26
+ // Options pour le rendu CommonHTML (généralement le plus rapide)
27
+ // fontURL: 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/output/chtml/fonts/woff-v2' // Optionnel: URL des polices
28
+ },
29
+ options: {
30
+ enableMenu: false, // Désactive menu contextuel MathJax
31
+ messageStyle: 'none', // Supprime messages statut MathJax
32
+ skipHtmlTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code'], // Tags à ignorer
33
+ ignoreHtmlClass: 'tex2jax_ignore', // Classe CSS pour ignorer éléments
34
+ processHtmlClass: 'tex2jax_process' // Classe CSS pour forcer traitement
35
+ },
36
+ startup: {
37
+ // Callback quand MathJax est prêt
38
+ pageReady: () => {
39
+ console.log('MathJax est complètement chargé et prêt.');
40
+ window.mathJaxReady = true; // Drapeau global
41
+ }
42
+ }
43
+ };
44
+ </script>
45
+ <!-- Chargement MathJax (tex-mml-chtml pour compatibilité maximale) -->
46
+ <script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js" id="MathJax-script" async></script>
47
+ <!-- Chargement Marked.js (pour rendu Markdown) -->
48
+ <script src="https://cdn.jsdelivr.net/npm/marked/lib/marked.umd.min.js"></script>
49
+
50
+ <style>
51
+ /* Importation Google Font */
52
+ @import url('https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;500;700&display=swap');
53
+
54
+ body {
55
+ font-family: 'Space Grotesk', sans-serif;
56
+ -webkit-font-smoothing: antialiased;
57
+ -moz-osx-font-smoothing: grayscale;
58
+ }
59
+
60
+ /* Zone d'upload */
61
+ .uploadArea {
62
+ background: #f9fafb; /* bg-gray-50 */
63
+ border: 2px dashed #d1d5db; /* border-gray-300 */
64
+ transition: border-color 0.2s ease-in-out, background-color 0.2s ease-in-out;
65
+ cursor: pointer;
66
+ }
67
+ .uploadArea:hover, .uploadArea.dragover { /* Ajout classe pour dragover */
68
+ border-color: #3b82f6; /* border-blue-500 */
69
+ background-color: #eff6ff; /* bg-blue-50 */
70
+ }
71
+
72
+ /* Bouton principal */
73
+ .blue-button {
74
+ background-color: #3b82f6; /* bg-blue-500 */
75
+ transition: background-color 0.2s ease-in-out, box-shadow 0.2s ease-in-out;
76
+ }
77
+ .blue-button:hover {
78
+ background-color: #2563eb; /* bg-blue-600 */
79
+ box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06); /* shadow-md */
80
+ }
81
+ .blue-button:disabled {
82
+ background-color: #9ca3af; /* bg-gray-400 */
83
+ cursor: not-allowed;
84
+ box-shadow: none;
85
+ }
86
+
87
+
88
+ /* Indicateur chargement */
89
+ .loader {
90
+ width: 40px; height: 40px; border: 4px solid #3b82f6; border-bottom-color: transparent;
91
+ border-radius: 50%; display: inline-block; box-sizing: border-box;
92
+ animation: rotation 1s linear infinite;
93
+ }
94
+ @keyframes rotation { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
95
+
96
+ /* Boîte de réflexion (accordéon) */
97
+ .thought-box {
98
+ transition: max-height 0.3s ease-out, border-top-width 0.3s ease-out;
99
+ max-height: 0; overflow: hidden; background-color: #f9fafb; /* bg-gray-50 */
100
+ border-radius: 0 0 0.5rem 0.5rem; border-top: 0px solid #e5e7eb; /* border-gray-200 */
101
+ }
102
+ .thought-box.open {
103
+ max-height: 600px; /* Ajustable */ border-top-width: 1px;
104
+ }
105
+
106
+ /* Zones de contenu (réflexion, réponse) */
107
+ #thoughtsContent, #answerContent {
108
+ max-height: 600px; /* Ajustable */ overflow-y: auto; scroll-behavior: smooth;
109
+ white-space: pre-wrap; word-wrap: break-word;
110
+ background-color: #ffffff; padding: 1rem; border-radius: 0.375rem; /* rounded-md */
111
+ border: 1px solid #e5e7eb; /* border-gray-200 */
112
+ line-height: 1.6; /* Améliore lisibilité */
113
+ }
114
+ #thoughtsContent { background-color: #f9fafb; /* bg-gray-50 */ }
115
+
116
+ /* Image prévisualisation */
117
+ .preview-image {
118
+ max-width: 100%; height: auto; max-height: 300px; object-fit: contain;
119
+ margin-top: 0.5rem; border: 1px solid #e5e7eb; border-radius: 0.375rem;
120
+ }
121
+
122
+ /* Timestamp */
123
+ .timestamp { color: #6b7280; font-size: 0.8em; margin-left: 10px; font-weight: 500; }
124
+
125
+ /* Tableaux */
126
+ table { border-collapse: collapse; width: 100%; margin-bottom: 1rem; border: 1px solid #d1d5db; }
127
+ th, td { border: 1px solid #d1d5db; padding: 0.75rem; text-align: left; }
128
+ th { background-color: #f3f4f6; font-weight: 600; }
129
+ .table-responsive { overflow-x: auto; }
130
+
131
+ /* Avertissement Performance */
132
+ .performance-warning {
133
+ color: #991b1b; /* text-red-800 */ font-weight: 500; font-size: 0.9em;
134
+ margin-top: 1rem; margin-bottom: 1.5rem; padding: 0.75rem;
135
+ background-color: #fee2e2; /* bg-red-100 */ border: 1px solid #fca5a5; /* border-red-300 */
136
+ border-radius: 0.375rem; text-align: center;
137
+ }
138
+ </style>
139
+ </head>
140
+ <body class="p-4 bg-gray-100 min-h-screen">
141
+ <!-- Conteneur principal centré -->
142
+ <div class="max-w-4xl mx-auto bg-white p-5 md:p-8 rounded-lg shadow-lg">
143
+ <header class="text-center mb-6 md:mb-8">
144
+ <h1 class="text-3xl md:text-4xl font-bold text-blue-600">Mariam - M-0</h1>
145
+ <p class="text-gray-600 mt-2">Solution Mathématique/Physique/Chimie Intelligente</p>
146
+ <p class="performance-warning">
147
+ Vous utilisez les modèles/performances standards. Passez à Premium pour une résolution plus rapide et précise !
148
+ </p>
149
+ </header>
150
+
151
+ <main>
152
+ <form id="problemForm" class="space-y-6" novalidate>
153
+ <!-- Zone d'Upload -->
154
+ <div id="uploadArea" class="uploadArea p-6 md:p-8 text-center relative rounded-lg" aria-label="Zone de dépôt d'image du problème">
155
+ {/* Input fichier caché, mais lié par le clic sur la div */}
156
+ <input type="file" id="imageInput" accept="image/*" class="absolute inset-0 w-full h-full opacity-0 cursor-pointer" aria-label="Choisir une image" aria-describedby="upload-instructions">
157
+ <div class="flex flex-col items-center justify-center space-y-3 pointer-events-none" id="upload-instructions"> {/* pointer-events-none pour laisser passer le clic vers l'input */}
158
+ {/* Icone SVG */}
159
+ <svg class="w-12 h-12 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>
160
+ <p class="text-gray-700 font-medium">Déposez l'image du problème ici</p>
161
+ <p class="text-gray-500 text-sm">ou cliquez pour sélectionner</p>
162
+ <p class="text-xs text-gray-400 mt-1">(Formats: JPG, PNG, WEBP, etc.)</p>
163
+ </div>
164
+ </div>
165
+
166
+ <!-- Prévisualisation Image -->
167
+ <div id="imagePreview" class="hidden text-center border border-gray-200 p-3 rounded-lg">
168
+ <p class="text-sm font-medium text-gray-700 mb-2">Image sélectionnée :</p>
169
+ <img id="previewImage" class="preview-image mx-auto" alt="Prévisualisation de l'image sélectionnée">
170
+ <button type="button" id="removeImageBtn" class="mt-3 text-sm text-red-600 hover:text-red-800 font-medium" aria-label="Retirer l'image sélectionnée">
171
+ Retirer l'image
172
+ </button>
173
+ </div>
174
+
175
+ <!-- Bouton Soumettre -->
176
+ <button type="submit" id="submitButton" class="blue-button w-full py-3 text-white font-medium rounded-lg text-lg">
177
+ Résoudre le problème
178
+ </button>
179
+ </form>
180
+
181
+ <!-- Indicateur de Chargement -->
182
+ <div id="loader" class="hidden mt-8 text-center" aria-busy="true" aria-label="Analyse en cours">
183
+ <span class="loader"></span>
184
+ <p class="mt-3 text-gray-600 font-medium">Analyse en cours...</p>
185
+ </div>
186
+
187
+ <!-- Section Solution -->
188
+ <section id="solution" class="hidden mt-10 space-y-8">
189
+ <!-- Accordéon Réflexion -->
190
+ <div class="border rounded-lg shadow-sm overflow-hidden">
191
+ <button id="thoughtsToggle" type="button" class="w-full flex justify-between items-center p-3 bg-gray-100 hover:bg-gray-200 transition-colors duration-150 ease-in-out focus:outline-none focus:ring-2 focus:ring-blue-300" aria-expanded="true" aria-controls="thoughtsBox">
192
+ <span class="font-medium text-gray-800 text-lg">Processus de Réflexion</span>
193
+ <div class="flex items-center">
194
+ <span id="timestamp" class="timestamp"></span>
195
+ {/* Icône Chevron */}
196
+ <svg id="toggleIcon" class="w-5 h-5 text-gray-600 ml-2 transform transition-transform duration-200 rotate-180" 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>
197
+ </div>
198
+ </button>
199
+ <div id="thoughtsBox" class="thought-box open" role="region" aria-labelledby="thoughtsToggle">
200
+ {/* aria-live="polite" annonce les MAJ aux lecteurs d'écran */}
201
+ <div id="thoughtsContent" class="p-4 text-gray-700 text-sm" aria-live="polite"></div>
202
+ </div>
203
+ </div>
204
+
205
+ <!-- Section Solution Détaillée -->
206
+ <div class="border-t pt-6">
207
+ <h3 class="text-xl font-bold text-gray-800 mb-4">Solution Détaillée</h3>
208
+ <div id="answerContent" class="text-gray-800 table-responsive" aria-live="polite">
209
+ {/* Le contenu généré par Markdown et rendu par MathJax ira ici */}
210
+ </div>
211
+ </div>
212
+ </section>
213
+ </main>
214
+
215
+ <footer class="text-center mt-12 pt-6 border-t border-gray-200">
216
+ <p class="text-sm text-gray-500">© 2024 Mariam AI. Tous droits réservés.</p>
217
+ </footer>
218
+ </div>
219
+
220
+ <script>
221
+ document.addEventListener('DOMContentLoaded', () => {
222
+ // --- DOM Element References ---
223
+ const form = document.getElementById('problemForm');
224
+ const imageInput = document.getElementById('imageInput');
225
+ const loader = document.getElementById('loader');
226
+ const solutionSection = document.getElementById('solution');
227
+ const thoughtsContent = document.getElementById('thoughtsContent');
228
+ const answerContent = document.getElementById('answerContent');
229
+ const thoughtsToggle = document.getElementById('thoughtsToggle');
230
+ const thoughtsBox = document.getElementById('thoughtsBox');
231
+ const toggleIcon = document.getElementById('toggleIcon');
232
+ const imagePreview = document.getElementById('imagePreview');
233
+ const previewImage = document.getElementById('previewImage');
234
+ const removeImageBtn = document.getElementById('removeImageBtn');
235
+ const timestamp = document.getElementById('timestamp');
236
+ const uploadArea = document.getElementById('uploadArea');
237
+ const submitButton = document.getElementById('submitButton');
238
+
239
+ // --- State Variables ---
240
+ let startTime = null;
241
+ let timerInterval = null;
242
+ let thoughtsBuffer = '';
243
+ let answerBuffer = '';
244
+ let currentMode = null; // 'thinking' or 'answering'
245
+ let updateTimeout = null; // For debouncing/throttling UI updates
246
+ let mathJaxProcessing = false; // Flag to prevent concurrent MathJax calls
247
+
248
+ // --- Marked.js Configuration ---
249
+ marked.setOptions({
250
+ gfm: true, // Enable GitHub Flavored Markdown (tables, etc.)
251
+ breaks: true, // Convert single line breaks to <br>
252
+ mangle: false, // Disable email address obfuscation
253
+ headerIds: false, // Disable automatic header ID generation
254
+ });
255
+
256
+ // --- Utility Functions ---
257
+
258
+ // Updates the timestamp display
259
+ const updateTimestamp = () => {
260
+ if (startTime) {
261
+ const seconds = Math.floor((Date.now() - startTime) / 1000);
262
+ timestamp.textContent = `${seconds}s`;
263
+ } else {
264
+ timestamp.textContent = '';
265
+ }
266
+ };
267
+
268
+ // Starts the timer
269
+ const startTimer = () => {
270
+ startTime = Date.now();
271
+ timestamp.textContent = '0s'; // Initial display
272
+ updateTimestamp(); // Update immediately
273
+ timerInterval = setInterval(updateTimestamp, 1000);
274
+ };
275
+
276
+ // Stops the timer
277
+ const stopTimer = () => {
278
+ clearInterval(timerInterval);
279
+ timerInterval = null;
280
+ if (startTime) updateTimestamp(); // Final update
281
+ // startTime = null; // Keep startTime to show final duration
282
+ };
283
+
284
+ // Resets the UI state before a new request or after an error
285
+ const resetUI = (clearImage = false) => {
286
+ loader.classList.add('hidden');
287
+ loader.removeAttribute('aria-busy');
288
+ solutionSection.classList.add('hidden');
289
+ thoughtsContent.innerHTML = '';
290
+ answerContent.innerHTML = '';
291
+ thoughtsBuffer = '';
292
+ answerBuffer = '';
293
+ currentMode = null;
294
+ if (!thoughtsBox.classList.contains('open')) { // Re-open if closed
295
+ thoughtsBox.classList.add('open');
296
+ toggleIcon.classList.add('rotate-180');
297
+ thoughtsToggle.setAttribute('aria-expanded', 'true');
298
+ }
299
+ stopTimer(); // Ensure any previous timer is stopped
300
+ updateTimestamp(); // Clear or show final time based on startTime
301
+ startTime = null; // Reset startTime for next run
302
+ submitButton.disabled = false; // Re-enable submit button
303
+ submitButton.textContent = 'Résoudre le problème'; // Reset button text
304
+ if(clearImage) clearImagePreview(); // Optionally clear image
305
+ };
306
+
307
+ // Handles file selection and displays preview
308
+ const handleFileSelect = file => {
309
+ if (!file || !file.type.startsWith('image/')) {
310
+ alert('Veuillez sélectionner un fichier image valide (JPG, PNG, WEBP, etc.).');
311
+ clearImagePreview();
312
+ return;
313
+ }
314
+ const reader = new FileReader();
315
+ reader.onload = e => {
316
+ previewImage.src = e.target.result;
317
+ imagePreview.classList.remove('hidden');
318
+ uploadArea.classList.add('hidden'); // Hide upload zone
319
+ };
320
+ reader.onerror = () => {
321
+ alert('Erreur lors de la lecture du fichier image.');
322
+ clearImagePreview();
323
+ };
324
+ reader.readAsDataURL(file);
325
+ };
326
+
327
+ // Clears the image preview and related input
328
+ const clearImagePreview = () => {
329
+ imageInput.value = ''; // Crucial to allow re-selecting the same file
330
+ previewImage.src = '';
331
+ imagePreview.classList.add('hidden');
332
+ uploadArea.classList.remove('hidden'); // Show upload zone again
333
+ };
334
+
335
+ // Typesets the answer content using MathJax if ready
336
+ const typesetAnswerIfReady = async () => {
337
+ if (!window.mathJaxReady) {
338
+ console.warn("MathJax not ready, deferring typesetting.");
339
+ setTimeout(typesetAnswerIfReady, 200); // Retry later
340
+ return;
341
+ }
342
+ if (mathJaxProcessing) {
343
+ console.log("MathJax is already processing, skipping this typeset call.");
344
+ return; // Avoid concurrent processing
345
+ }
346
+
347
+ const answerElement = document.getElementById('answerContent');
348
+ if (!answerElement || !answerElement.innerHTML.trim()) {
349
+ // console.log("No content in answerElement to typeset.");
350
+ return; // Nothing to typeset
351
+ }
352
+
353
+ mathJaxProcessing = true;
354
+ // console.log("Starting MathJax typesetting...");
355
+ try {
356
+ // Clear previous typesetting state for the element (important for dynamic content)
357
+ // MathJax.startup.document.clear(); // Use cautiously, might be too broad
358
+ // MathJax.startup.document.clearMath(answerElement); // Safer alternative if needed
359
+
360
+ // Typeset only the answer content
361
+ await MathJax.typesetPromise([answerElement]);
362
+ // console.log("MathJax typesetting finished.");
363
+
364
+ // Scroll to bottom after typesetting to show latest content
365
+ answerElement.scrollTop = answerElement.scrollHeight;
366
+
367
+ } catch (error) {
368
+ console.error("Error during MathJax typesetting:", error);
369
+ // Optionally display an error message to the user
370
+ } finally {
371
+ mathJaxProcessing = false;
372
+ // console.log("MathJax processing flag set to false.");
373
+ }
374
+ };
375
+
376
+ // Updates the display with buffered content (Markdown parsing + MathJax trigger)
377
+ const updateDisplay = async (forceMathJax = false) => {
378
+ // console.log("updateDisplay called");
379
+ clearTimeout(updateTimeout); // Clear pending timeout
380
+ updateTimeout = null; // Reset timeout ID
381
+
382
+ thoughtsContent.innerHTML = marked.parse(thoughtsBuffer);
383
+ answerContent.innerHTML = marked.parse(answerBuffer);
384
+
385
+ // Scroll thoughts/answer to bottom (optional, useful during streaming)
386
+ // thoughtsContent.scrollTop = thoughtsContent.scrollHeight;
387
+ // answerContent.scrollTop = answerContent.scrollHeight; // Moved after typeset
388
+
389
+ // Trigger MathJax typesetting for the answer section
390
+ // Use await only if forced (e.g., at the very end), otherwise let it run async
391
+ if (forceMathJax) {
392
+ await typesetAnswerIfReady();
393
+ } else {
394
+ typesetAnswerIfReady(); // Don't wait, let it run async
395
+ }
396
+ };
397
+
398
+ // Schedules a UI update (throttling)
399
+ const scheduleUpdate = () => {
400
+ // If a timeout is already pending, do nothing (throttle)
401
+ if (updateTimeout) return;
402
+ // Schedule updateDisplay after a short delay (e.g., 150ms)
403
+ updateTimeout = setTimeout(() => updateDisplay(false), 150);
404
+ };
405
+
406
+ // --- Event Listeners Setup ---
407
+
408
+ // Toggle thoughts box visibility
409
+ thoughtsToggle.addEventListener('click', () => {
410
+ const isOpen = thoughtsBox.classList.toggle('open');
411
+ thoughtsToggle.setAttribute('aria-expanded', isOpen);
412
+ toggleIcon.classList.toggle('rotate-180', isOpen);
413
+ });
414
+
415
+ // Handle file input change
416
+ imageInput.addEventListener('change', e => {
417
+ if (e.target.files && e.target.files.length > 0) {
418
+ handleFileSelect(e.target.files[0]);
419
+ } else {
420
+ clearImagePreview(); // Handle cancellation
421
+ }
422
+ });
423
+
424
+ // Remove image button
425
+ removeImageBtn.addEventListener('click', clearImagePreview);
426
+
427
+ // Drag & Drop listeners for upload area
428
+ ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
429
+ uploadArea.addEventListener(eventName, e => {
430
+ e.preventDefault();
431
+ e.stopPropagation();
432
+ }, false);
433
+ });
434
+ ['dragenter', 'dragover'].forEach(eventName => {
435
+ uploadArea.addEventListener(eventName, () => uploadArea.classList.add('dragover'), false);
436
+ });
437
+ ['dragleave', 'drop'].forEach(eventName => {
438
+ uploadArea.addEventListener(eventName, () => uploadArea.classList.remove('dragover'), false);
439
+ });
440
+ uploadArea.addEventListener('drop', e => {
441
+ if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
442
+ const file = e.dataTransfer.files[0];
443
+ imageInput.files = e.dataTransfer.files; // Assign dropped file(s) to input
444
+ handleFileSelect(file);
445
+ }
446
+ }, false);
447
+
448
+ // Form submission handler
449
+ form.addEventListener('submit', async e => {
450
+ e.preventDefault();
451
+ const file = imageInput.files[0];
452
+
453
+ if (!file) {
454
+ alert('Veuillez sélectionner une image contenant le problème.');
455
+ return;
456
+ }
457
+
458
+ resetUI(); // Reset UI elements and state (keeps image preview by default)
459
+ startTimer();
460
+ loader.classList.remove('hidden');
461
+ loader.setAttribute('aria-busy', 'true');
462
+ submitButton.disabled = true;
463
+ submitButton.textContent = 'Analyse en cours...';
464
+
465
+ const formData = new FormData();
466
+ formData.append('image', file);
467
+
468
+ try {
469
+ const response = await fetch('/solved', { // Ensure '/solved' is your correct API endpoint
470
+ method: 'POST',
471
+ body: formData,
472
+ });
473
+
474
+ // --- Handle HTTP Errors ---
475
+ if (!response.ok) {
476
+ let errorMsg = `Erreur serveur ${response.status}: ${response.statusText}`;
477
+ try {
478
+ // Try to get more details from response body
479
+ const errorData = await response.json();
480
+ errorMsg += `\n\nDétails: ${JSON.stringify(errorData.error || errorData.message || errorData, null, 2)}`;
481
+ } catch (parseError) {
482
+ errorMsg += "\n(Impossible de lire les détails de l'erreur depuis la réponse)";
483
+ }
484
+ throw new Error(errorMsg);
485
+ }
486
+
487
+ // --- Process Streaming Response (SSE) ---
488
+ const reader = response.body?.getReader();
489
+ if (!reader) {
490
+ throw new Error("Impossible d'obtenir le lecteur de flux de la réponse.");
491
+ }
492
+ const decoder = new TextDecoder(); // Defaults to UTF-8
493
+ let sseBuffer = ''; // Buffer for incomplete SSE messages
494
+
495
+ while (true) {
496
+ const { done, value } = await reader.read();
497
+
498
+ if (done) {
499
+ // Process any remaining data in the buffer if needed (unlikely for well-formed SSE)
500
+ if (sseBuffer.startsWith('data:')) {
501
+ console.warn("Processing remaining SSE buffer:", sseBuffer);
502
+ try {
503
+ const finalJsonData = sseBuffer.slice(5).trim();
504
+ if (finalJsonData) {
505
+ const finalData = JSON.parse(finalJsonData);
506
+ if (finalData.content) {
507
+ if (currentMode === 'thinking') thoughtsBuffer += finalData.content;
508
+ else if (currentMode === 'answering') answerBuffer += finalData.content;
509
+ }
510
+ }
511
+ } catch (finalParseError) {
512
+ console.error('Error parsing final SSE buffer:', finalParseError, 'Buffer:', sseBuffer);
513
+ }
514
+ }
515
+ break; // Exit loop when stream is finished
516
+ }
517
+
518
+ // Decode chunk and add to buffer
519
+ sseBuffer += decoder.decode(value, { stream: true });
520
+
521
+ // Process complete messages in the buffer (separated by '\n\n')
522
+ let boundaryIndex;
523
+ while ((boundaryIndex = sseBuffer.indexOf('\n\n')) >= 0) {
524
+ const message = sseBuffer.slice(0, boundaryIndex);
525
+ sseBuffer = sseBuffer.slice(boundaryIndex + 2); // Remove message + '\n\n'
526
+
527
+ if (!message.startsWith('data:')) continue; // Ignore non-data lines/comments
528
+
529
+ try {
530
+ const jsonData = message.slice(5).trim(); // Extract JSON payload
531
+ if (!jsonData) continue; // Ignore empty data messages
532
+
533
+ const data = JSON.parse(jsonData);
534
+
535
+ // Handle mode change
536
+ if (data.mode && data.mode !== currentMode) {
537
+ currentMode = data.mode;
538
+ // Show solution section and hide loader on first message
539
+ if (loader.classList.contains('hidden') === false) {
540
+ loader.classList.add('hidden');
541
+ loader.removeAttribute('aria-busy');
542
+ solutionSection.classList.remove('hidden');
543
+ }
544
+ }
545
+
546
+ // Append content to the correct buffer
547
+ if (data.content) {
548
+ if (currentMode === 'thinking') {
549
+ thoughtsBuffer += data.content;
550
+ } else if (currentMode === 'answering') {
551
+ answerBuffer += data.content;
552
+ }
553
+ // Schedule a UI update (throttled)
554
+ scheduleUpdate();
555
+ }
556
+ } catch (parseError) {
557
+ console.error('Error parsing SSE JSON data:', parseError, 'Message:', message);
558
+ // Decide how to handle: skip message, show error, etc.
559
+ }
560
+ } // End while(boundaryIndex)
561
+ } // End while(true) reading stream
562
+
563
+ // --- Final Actions After Stream ---
564
+ stopTimer();
565
+ submitButton.textContent = 'Résolu !';
566
+ // Force a final update and MathJax rendering
567
+ await updateDisplay(true); // true forces awaiting MathJax
568
+
569
+ } catch (error) {
570
+ console.error('Erreur lors de la résolution:', error);
571
+ alert(`Une erreur est survenue:\n${error.message}`);
572
+ // Reset UI, potentially clearing the image if it caused the error
573
+ resetUI(false); // Keep image preview in case user wants to retry
574
+ } finally {
575
+ // Ensure button is re-enabled even if something unexpected happens after success
576
+ // (already handled in resetUI, but as a safeguard)
577
+ if (!submitButton.disabled) { // If not already enabled by resetUI in error case
578
+ // Might need a slight delay if called right after stopTimer/final update
579
+ // setTimeout(() => { submitButton.disabled = false; }, 100);
580
+ }
581
+ }
582
+ }); // End form submit listener
583
+
584
+ }); // End DOMContentLoaded listener
585
+ </script>
586
+ </body>
587
+ </html>