Spaces:
Sleeping
Sleeping
File size: 31,698 Bytes
9468c91 0c39a6f 751980d 0c39a6f 7945c76 0c39a6f 7945c76 0c39a6f 7945c76 0c39a6f 7945c76 0c39a6f 7945c76 0c39a6f c35dcb1 0c39a6f c35dcb1 0c39a6f 751980d d191a18 751980d d191a18 751980d c35dcb1 0c39a6f 751980d 0c39a6f c35dcb1 0c39a6f 751980d 0c39a6f 7945c76 c35dcb1 0c39a6f 751980d 0c39a6f c35dcb1 0c39a6f 7945c76 c35dcb1 0c39a6f 751980d 0c39a6f 751980d 0c39a6f 81eb477 c35dcb1 0c39a6f 751980d 0c39a6f 7945c76 c35dcb1 7945c76 0c39a6f 751980d 0c39a6f 7945c76 0c39a6f 751980d 0c39a6f 81eb477 751980d 7945c76 751980d 7945c76 c35dcb1 0c39a6f 7945c76 0c39a6f c35dcb1 7945c76 751980d 7945c76 c35dcb1 81eb477 7945c76 751980d 0c39a6f 7945c76 c35dcb1 751980d 0c39a6f 9468c91 7945c76 751980d 0c39a6f 7945c76 0c39a6f 81eb477 7945c76 0c39a6f 7945c76 0c39a6f aaebe0a 0c39a6f 7945c76 c35dcb1 7affd69 751980d 7945c76 81eb477 751980d d191a18 0c39a6f 7945c76 0c39a6f 7945c76 751980d 0c39a6f 7945c76 0c39a6f 7945c76 7affd69 7945c76 81eb477 7945c76 0c39a6f 7945c76 0c39a6f 7945c76 751980d 0c39a6f 7945c76 0c39a6f 7945c76 0c39a6f 7945c76 81eb477 0c39a6f 7945c76 601e910 0c39a6f 7945c76 751980d d191a18 751980d d191a18 751980d d191a18 751980d d191a18 751980d d191a18 751980d d191a18 751980d d191a18 751980d 7affd69 751980d 0c39a6f 751980d 0c39a6f 751980d 0c39a6f 7affd69 751980d 81eb477 7945c76 81eb477 fb4ab9a 751980d 7945c76 7affd69 751980d 0c39a6f fb4ab9a 751980d 81eb477 751980d 7945c76 81eb477 751980d d191a18 751980d c35dcb1 0c39a6f c35dcb1 751980d d191a18 751980d 0c39a6f 751980d c35dcb1 7945c76 751980d d191a18 751980d d191a18 7945c76 751980d 7945c76 751980d 7945c76 751980d 7945c76 751980d 7945c76 751980d 7945c76 751980d d191a18 7945c76 751980d 7945c76 751980d c35dcb1 7945c76 751980d 81eb477 751980d 7945c76 751980d d191a18 751980d 7945c76 81eb477 751980d 81eb477 751980d 81eb477 d191a18 751980d d191a18 751980d d191a18 751980d 0c39a6f 751980d 81eb477 7945c76 751980d 0c39a6f 751980d 0c39a6f 751980d 81eb477 751980d 0c39a6f 751980d 7945c76 0c39a6f 1759e8b 751980d 81eb477 0c39a6f 751980d 0c39a6f 751980d 0c39a6f 751980d 0c39a6f 751980d 0c39a6f 751980d 81eb477 751980d 0c39a6f 751980d d191a18 751980d 7945c76 0c39a6f 2abfdf4 f7864af |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 |
<!DOCTYPE html>
<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/[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.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/[email protected]/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; }
.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; }
#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%; }
/* Style pour l'option calculatrice */
.calculator-option {
background: #f8fafc; border: 2px solid #e2e8f0; border-radius: 0.5rem;
padding: 1rem; margin: 1rem 0; transition: all 0.2s ease;
}
.calculator-option.enabled {
background: #ecfdf5; border-color: #10b981;
}
.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);
}
</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="calculator-option">
<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>
<!-- 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>
<!-- 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'),
dropZone: document.querySelector('.uploadArea')
};
// État de l'application
const state = {
startTime: null,
timerInterval: null,
cooldownTimerInterval: null,
thoughtsBuffer: '',
answerBuffer: '',
currentMode: null,
updateTimeout: null,
selectedFile: null
};
// 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';
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 = '';
};
// --- 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;
}
};
// --- Calculator Toggle ---
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');
}
});
// --- 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.thoughtsContent.innerHTML = '';
elements.answerContent.innerHTML = '';
state.thoughtsBuffer = '';
state.answerBuffer = '';
state.currentMode = null;
elements.thoughtsBox.classList.remove('open');
elements.form.classList.remove('hidden');
resetSolutionTimer();
updateSubmitButtonState();
// Reset calculator toggle
elements.calculatorToggle.checked = false;
elements.calculatorOption.classList.remove('enabled');
elements.calculatorFeatures.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();
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);
formData.append('use_calculator', elements.calculatorToggle.checked.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();
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') {
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');
} 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
};
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 calculatorBadge = data.calculatorUsed ?
'<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>' :
'';
li.innerHTML = `
<button class="text-left text-blue-600 hover:underline focus:outline-none" data-save-name="${name}">
${name} ${calculatorBadge}<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 calculator state
if (data.calculatorUsed) {
elements.calculatorToggle.checked = true;
elements.calculatorOption.classList.add('enabled');
elements.calculatorFeatures.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> |