File size: 36,735 Bytes
7631217 7facaba 7631217 |
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 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 |
# --- IMPORTS ---
from flask import Flask, render_template, request, jsonify, Response, stream_with_context
from google import genai
import os
from google.genai import types
from PIL import Image
import io
import base64
import json
import requests
import threading
import uuid
import time
import tempfile
import subprocess
import shutil
import re
# --- FLASK APP INITIALIZATION ---
app = Flask(__name__)
# --- CONFIGURATION ---
# API Keys
GOOGLE_API_KEY = os.environ.get("GOOGLE_API_KEY")
# IMPORTANT: For production, move these to environment variables or a secure config
TELEGRAM_BOT_TOKEN = "8004545342:AAGcZaoDjYg8dmbbXRsR1N3TfSSbEiAGz88"
TELEGRAM_CHAT_ID = "-1002564204301"
# Gemini Client Initialization
if GOOGLE_API_KEY:
try:
client = genai.Client(api_key=GOOGLE_API_KEY)
except Exception as e:
print(f"Erreur lors de l'initialisation du client Gemini: {e}")
client = None
else:
print("GEMINI_API_KEY non trouvé. Le client Gemini ne sera pas initialisé.")
client = None
# Dictionnaire pour stocker les résultats des tâches en cours
task_results = {}
# --- PROMPT DEFINITIONS ---
# All prompts are now defined directly in the code instead of separate files.
def get_prompt_extract_problem():
"""Prompt pour extraire l'énoncé mathématique à partir des fichiers."""
return """
From the provided image(s) and/or PDF document, your task is to identify and extract the complete mathematical problem statement.
- Focus solely on the problem itself, including all conditions, variables, and the question being asked.
- Exclude any surrounding text like page numbers, author names, or irrelevant context.
- Format all mathematical expressions using TeX (e.g., $f(x) = x^2 - 1$, for all $x \in \mathbb{R}$).
- Your output must be ONLY the clean, extracted problem statement. Do not add any conversational text like "Here is the problem statement:".
"""
def get_prompt_light():
"""Prompt pour une solution simple et directe (style 'light')."""
return """
Vous êtes un expert en mathématiques. Votre tâche est de fournir une solution claire et concise au problème soumis.
La sortie doit être un code LaTeX complet, propre et directement compilable.
La solution doit être bien expliquée, mais sans fioritures visuelles.
Structurez la solution avec des sections logiques.
Produisez UNIQUEMENT le code LaTeX.
"""
def get_prompt_colorful():
"""Prompt pour une solution pédagogique et colorée (style 'colorful')."""
# Ce prompt est une copie directe de votre "prompt coloful".
return r"""
# 📝 GÉNÉRATEUR DE CORRECTION MATHÉMATIQUE PROFESSIONNELLE
## 🎓 VOTRE RÔLE
Vous êtes **Mariam-MATHEX-PRO**, un système d'intelligence artificielle ultra-spécialisé dans la création de documents mathématiques parfaits. Vous combinez l'expertise d'un:
* 🧠 Professeur agrégé de mathématiques avec 25 ans d'expérience
* 🖋️ Expert LaTeX de niveau international
* 👨🏫 Pédagogue reconnu pour votre clarté exceptionnelle
Votre mission: transformer un simple énoncé mathématique en une correction LaTeX impeccable, aérée et pédagogiquement parfaite.
## 📊 FORMAT D'ENTRÉE ET SORTIE
**ENTRÉE:** L'énoncé d'un exercice mathématique (niveau Terminale/Supérieur)
**SORTIE:** UNIQUEMENT le code source LaTeX complet (.tex) sans annotations externes, directement compilable avec pdfLaTeX pour produire un document PDF de qualité professionnelle.
## 🌟 PRINCIPES FONDAMENTAUX
1. **DESIGN AÉRÉ ET ÉLÉGANT**
* Utilisez généreusement l'espace vertical entre tous les éléments
* Créez un document visuellement reposant avec beaucoup d'espaces blancs
* Évitez absolument la densité visuelle et le texte compact
2. **EXCELLENCE PÉDAGOGIQUE**
* Une seule étape de raisonnement par paragraphe
* Développement méticuleux de chaque calcul sans sauts logiques
* Mise en évidence claire des points clés et des résultats
3. **ESTHÉTIQUE PROFESSIONNELLE**
* Utilisation experte de la couleur pour guider l'attention
* Boîtes thématiques élégantes pour structurer l'information
* Typographie mathématique irréprochable
## 🛠️ SPÉCIFICATIONS TECHNIQUES DÉTAILLÉES
### 📑 STRUCTURE DE BASE
```latex
\documentclass[12pt,a4paper]{article}
% --- PACKAGES FONDAMENTAUX ---
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[french]{babel}
\usepackage{lmodern}
\usepackage{microtype}
% --- PACKAGES MATHÉMATIQUES ---
\usepackage{amsmath,amssymb,amsfonts,mathtools}
\usepackage{bm} % Gras en mode mathématique
\usepackage{siunitx} % Unités SI
% --- MISE EN PAGE ---
\usepackage[a4paper,margin=2.5cm]{geometry}
\usepackage{setspace}
\usepackage{fancyhdr}
\usepackage{titlesec,titletoc}
\usepackage{multicol}
\usepackage{enumitem} % Listes personnalisées
% --- ÉLÉMENTS VISUELS ---
\usepackage{xcolor}
\usepackage[most]{tcolorbox}
\usepackage{fontawesome5}
\usepackage{graphicx}
% --- GRAPHIQUES ---
\usepackage{tikz}
\usetikzlibrary{calc,shapes,arrows.meta,positioning}
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}
\usepgfplotslibrary{fillbetween}
% --- HYPERLIENS ET MÉTADONNÉES ---
\usepackage{hyperref}
\usepackage{bookmark}
% --- ESPACEMENT EXTRA-AÉRÉ ---
\setlength{\parindent}{0pt}
\setlength{\parskip}{2.5ex plus 0.8ex minus 0.4ex} % Espacement paragraphes généreux
\onehalfspacing % Interligne 1.5
```
### 🎨 PALETTE DE COULEURS ET STYLES VISUELS
```latex
% --- DÉFINITION DES COULEURS ---
\definecolor{maincolor}{RGB}{30, 100, 180} % Bleu principal
\definecolor{secondcolor}{RGB}{0, 150, 136} % Vert-bleu
\definecolor{thirdcolor}{RGB}{140, 0, 140} % Violet
\definecolor{accentcolor}{RGB}{255, 140, 0} % Orange
\definecolor{ubgcolor}{RGB}{245, 250, 255} % Fond bleuté très clair
\definecolor{lightgray}{RGB}{248, 248, 248} % Gris très clair
\definecolor{gridcolor}{RGB}{220, 220, 220} % Gris pour grilles
\definecolor{highlightcolor}{RGB}{255, 255, 200} % Jaune clair pour surlignage
\definecolor{asymptotecolor}{RGB}{220, 0, 0} % Rouge pour asymptotes
% --- CONFIGURATION DE PAGE ---
\pagestyle{fancy}
\fancyhf{}
\fancyhead[L]{\textcolor{maincolor}{\small\textit{Correction Mathématiques}}}
\fancyhead[R]{\textcolor{maincolor}{\small\thepage}}
\renewcommand{\headrulewidth}{0.2pt}
\renewcommand{\headrule}{\hbox to\headwidth{\color{maincolor}\leaders\hrule height \headrulewidth\hfill}}
\setlength{\headheight}{15pt}
\setlength{\headsep}{25pt} % Plus d'espace sous l'en-tête
% --- CONFIGURATION DES TITRES DE SECTION ---
\titleformat{\section}
{\normalfont\Large\bfseries\color{maincolor}}
{\colorbox{maincolor}{\color{white}\thesection}}
{1em}{}[\vspace{0.2cm}\titlerule[0.8pt]\vspace{0.8cm}]
\titleformat{\subsection}
{\normalfont\large\bfseries\color{secondcolor}}
{\thesubsection}
{1em}{}[\vspace{0.5cm}]
\titlespacing*{\section}{0pt}{3.5ex plus 1ex minus .2ex}{2.3ex plus .2ex}
\titlespacing*{\subsection}{0pt}{3.25ex plus 1ex minus .2ex}{1.5ex plus .2ex}
```
### 📦 BOÎTES THÉMATIQUES AÉRÉES
```latex
% --- DÉFINITION DES BOÎTES THÉMATIQUES ---
\newtcolorbox{enoncebox}{
enhanced,
breakable,
colback=lightgray!50,
colframe=gray!70,
fonttitle=\bfseries,
top=12pt, bottom=12pt, left=12pt, right=12pt,
boxrule=0.5pt,
arc=3mm,
title={\faBook\ Énoncé},
attach boxed title to top left={xshift=0.5cm,yshift=-\tcboxedtitleheight/2},
boxed title style={colback=gray!70, colframe=gray!70},
before={\vspace{15pt}},
after={\vspace{15pt}}
}
\newtcolorbox{definitionbox}{
enhanced,
breakable,
colback=secondcolor!10,
colframe=secondcolor,
fonttitle=\bfseries,
top=12pt, bottom=12pt, left=12pt, right=12pt,
boxrule=0.5pt,
arc=3mm,
title={\faLightbulb\ Définition/Théorème},
attach boxed title to top left={xshift=0.5cm,yshift=-\tcboxedtitleheight/2},
boxed title style={colback=secondcolor, colframe=secondcolor, color=white},
before={\vspace{15pt}},
after={\vspace{15pt}}
}
\newtcolorbox{resultbox}{
enhanced,
breakable,
colback=accentcolor!10,
colframe=accentcolor,
fonttitle=\bfseries,
top=12pt, bottom=12pt, left=12pt, right=12pt,
boxrule=0.5pt,
arc=3mm,
title={\faCheckCircle\ Résultat},
attach boxed title to top left={xshift=0.5cm,yshift=-\tcboxedtitleheight/2},
boxed title style={colback=accentcolor, colframe=accentcolor, color=white},
before={\vspace{15pt}},
after={\vspace{15pt}}
}
\newtcolorbox{notebox}{
enhanced,
breakable,
colback=thirdcolor!10,
colframe=thirdcolor,
fonttitle=\bfseries,
top=12pt, bottom=12pt, left=12pt, right=12pt,
boxrule=0.5pt,
arc=3mm,
title={\faInfoCircle\ Remarque/Astuce},
attach boxed title to top left={xshift=0.5cm,yshift=-\tcboxedtitleheight/2},
boxed title style={colback=thirdcolor, colframe=thirdcolor, color=white},
before={\vspace{15pt}},
after={\vspace{15pt}}
}
\newtcolorbox{examplebox}{
enhanced,
breakable,
colback=green!10,
colframe=green!70!black,
fonttitle=\bfseries,
top=12pt, bottom=12pt, left=12pt, right=12pt,
boxrule=0.5pt,
arc=3mm,
title={\faClipboard\ Exemple/Méthode},
attach boxed title to top left={xshift=0.5cm,yshift=-\tcboxedtitleheight/2},
boxed title style={colback=green!70!black, colframe=green!70!black, color=white},
before={\vspace{15pt}},
after={\vspace{15pt}}
}
```
### 🧮 COMMANDES MATHÉMATIQUES PERSONNALISÉES
```latex
% --- COMMANDES MATHÉMATIQUES ---
\newcommand{\R}{\mathbb{R}}
\newcommand{\C}{\mathbb{C}}
\newcommand{\N}{\mathbb{N}}
\newcommand{\Z}{\mathbb{Z}}
\newcommand{\Q}{\mathbb{Q}}
\newcommand{\limx}[1]{\lim_{x \to #1}}
\newcommand{\limxp}[1]{\lim_{x \to #1^+}}
\newcommand{\limxm}[1]{\lim_{x \to #1^-}}
\newcommand{\limsinf}{\lim_{n \to +\infty}}
\newcommand{\liminf}{\lim_{x \to +\infty}}
\newcommand{\derivee}[2]{\frac{d#1}{d#2}}
\newcommand{\ddx}[1]{\frac{d}{dx}\left(#1\right)}
\newcommand{\dfdx}[1]{\frac{df}{dx}\left(#1\right)}
\newcommand{\abs}[1]{\left|#1\right|}
\newcommand{\norm}[1]{\left\|#1\right\|}
\newcommand{\vect}[1]{\overrightarrow{#1}}
\newcommand{\ds}{\displaystyle}
\newcommand{\highlight}[1]{\colorbox{highlightcolor}{$#1$}}
\newcommand{\finalresult}[1]{\colorbox{accentcolor!20}{$\displaystyle #1$}}
% Environnement pour équations importantes
\newcommand{\boxedeq}[1]{%
\begin{center}
\begin{tcolorbox}[
enhanced,
colback=ubgcolor,
colframe=maincolor,
arc=3mm,
boxrule=0.5pt,
left=10pt,right=10pt,top=6pt,bottom=6pt
]
$\displaystyle #1$
\end{tcolorbox}
\end{center}
}
% Configuration pour espacement des listes
\setlist{itemsep=8pt, parsep=4pt}
% Configuration des environnements mathématiques pour plus d'espacement
\setlength{\abovedisplayskip}{12pt plus 3pt minus 7pt}
\setlength{\belowdisplayskip}{12pt plus 3pt minus 7pt}
\setlength{\abovedisplayshortskip}{7pt plus 2pt minus 4pt}
\setlength{\belowdisplayshortskip}{7pt plus 2pt minus 4pt}
```
### 📊 CONFIGURATION DE GRAPHIQUES
```latex
% --- CONFIGURATION DE PGFPLOTS POUR GRAPHIQUES ---
\pgfplotsset{
every axis/.append style={
axis lines=middle,
xlabel={$x$},
ylabel={$y$},
xlabel style={at={(ticklabel* cs:1.05)}, anchor=west},
ylabel style={at={(ticklabel* cs:1.05)}, anchor=south},
legend pos=outer north east,
grid=both,
grid style={gridcolor, line width=0.1pt},
tick align=outside,
minor tick num=4,
enlargelimits={abs=0.2},
axis line style={-Latex, line width=0.6pt},
xmajorgrids=true,
ymajorgrids=true,
ticklabel style={font=\footnotesize}
}
}
```
### 🖌️ MODÈLE DE PAGE DE TITRE
```latex
% --- PAGE DE TITRE ÉLÉGANTE ---
\newcommand{\maketitlepage}[2]{%
\begin{titlepage}
\centering
\vspace*{2cm}
{\Huge\bfseries\color{maincolor} Correction Mathématiques\par}
\vspace{1.5cm}
{\huge\bfseries #1\par}
\vspace{1cm}
{\Large\textit{#2}\par}
\vspace{2cm}
\begin{tikzpicture}
\draw[line width=0.5pt, maincolor] (0,0) -- (12,0);
\foreach \x in {0,1,...,12} {
\draw[line width=1pt, maincolor] (\x,0) -- (\x,-0.2);
}
\draw[line width=0.5pt, secondcolor] (0,-0.6) -- (12,-0.6);
\end{tikzpicture}
\vspace{1.5cm}
{\Large\today\par}
\vfill
\begin{tcolorbox}[
enhanced,
colback=ubgcolor,
colframe=maincolor,
arc=5mm,
boxrule=0.5pt,
width=0.8\textwidth
]
\centering
\large\textit{Document généré avec soin pour une clarté et une pédagogie optimales}
\end{tcolorbox}
\vspace{1cm}
\end{titlepage}
}
% Configuration hyperref pour liens colorés
\hypersetup{
colorlinks=true,
linkcolor=maincolor,
filecolor=secondcolor,
urlcolor=thirdcolor,
pdfauthor={},
pdftitle={Correction Mathématiques},
pdfsubject={},
pdfkeywords={}
}
```
## 🔄 STRUCTURE DU DOCUMENT COMPLET
```latex
\begin{document}
% Page de titre élégante
\maketitlepage{Titre de l'Exercice}{Solution Détaillée et Commentée}
% Espacement après la page de titre
\newpage
\vspace*{1cm}
% Table des matières distincte et aérée
\begingroup
\setlength{\parskip}{8pt}
\tableofcontents
\endgroup
\vspace{2cm}
\begin{enoncebox}
[TEXTE COMPLET DE L'ÉNONCÉ]
\end{enoncebox}
\vspace{1.5cm}
\section{Première partie de la résolution}
\vspace{0.8cm}
[SOLUTION DÉTAILLÉE]
\vspace{1.2cm}
\section{Deuxième partie de la résolution}
\vspace{0.8cm}
[SUITE DE LA SOLUTION]
% Et ainsi de suite...
{Mariam AI}
\end{document}
```
## 💡 INSTRUCTIONS POUR UNE PRÉSENTATION ULTRA-AÉRÉE
1. **ESPACES VERTICAUX GÉNÉREUX**
* Utilisez `\vspace{1cm}` fréquemment entre les sections logiques
* Minimum 0.8cm d'espace après chaque titre de section
* Au moins 0.5cm d'espace avant/après chaque environnement mathématique
* Ne lésinez JAMAIS sur les espacements verticaux
2. **FORMULATION DE LA SOLUTION**
* Une seule idée par paragraphe, jamais plus
* Espacez généreusement les étapes des raisonnements
* Insérez une ligne vide avant ET après chaque équation ou bloc d'équations
* Utilisez abondamment les environnements thématiques avec leurs espacements inclus
3. **MISE EN VALEUR VISUELLE**
* Encadrez chaque résultat principal dans une `resultbox`
* Isolez les définitions et rappels théoriques dans des `definitionbox`
* Utilisez `\boxedeq{}` pour les formules clés qui méritent attention
* Alternez paragraphes textuels courts et expressions mathématiques pour créer du rythme visuel
## ⭐ RÉSULTAT FINAL ATTENDU
Le document final doit:
* Être EXTRÊMEMENT aéré, avec beaucoup plus d'espace blanc que de contenu
* Présenter un équilibre parfait entre texte explicatif et développements mathématiques
* Guider visuellement l'attention grâce aux couleurs et aux encadrements
* Faciliter la compréhension par la décomposition méthodique et l'espacement généreux
✅ PRODUISEZ UNIQUEMENT LE CODE LATEX COMPLET, rien d'autre.
"""
def get_prompt_for_style(style):
"""Retourne le prompt approprié selon le style."""
if style == 'light':
return get_prompt_light()
else: # 'colorful' par défaut
return get_prompt_colorful()
# --- MATH SOLVER PIPELINE ---
# La logique du pipeline de résolution est maintenant intégrée ici.
# Configuration du pipeline
SOLVER_MODEL_NAME = "gemini-2.5-pro"
SOLVER_MAX_ITERATIONS = 5
SOLVER_PASSES_NEEDED = 2
SOLVER_TEMPERATURE = 0.1
def _get_solver_prompt_initial(problem_statement):
return f"### Core Instructions ###\n* **Rigor is Paramount:** Your primary goal is to produce a complete and rigorously justified solution. Every step must be logically sound.\n* **Honesty About Completeness:** If you cannot find a complete solution, present only significant partial results you can rigorously prove.\n* **Use TeX for All Mathematics:** All mathematical elements must be in TeX (e.g., $n \in \mathbb{{Z}}$).\n\n### Output Format ###\nYour response MUST be structured into these sections:\n**1. Summary**\n* **a. Verdict:** State if the solution is complete or partial.\n* **b. Method Sketch:** A high-level outline of your argument.\n**2. Detailed Solution**\nThe full, step-by-step mathematical proof.\n\n### Self-Correction Instruction ###\nReview your work to ensure it is clean, rigorous, and adheres to all instructions.\n\n### Problem ###\n{problem_statement}"
def _get_solver_prompt_improve(solution_attempt):
return f"You are a world-class mathematician. Review the following draft solution for flaws, gaps, or clarity issues.\nThen, produce a new, improved, and more rigorous version. Do not comment on the changes, just provide the final, clean proof.\n\n### Draft Solution ###\n{solution_attempt}\n\n### Improved Solution ###"
def _get_solver_prompt_verifier(problem_statement, solution_to_verify):
return f"You are an expert IMO grader. Your task is to rigorously verify the provided solution. A solution is correct ONLY if every step is justified. Do NOT correct errors, only report them.\n\n### Instructions ###\n1. **Core Instructions:** Find and report all issues.\n2. **Issue Classification:**\n * **a. Critical Error:** An error that breaks the proof's logic. Stop verifying dependant steps.\n * **b. Justification Gap:** A correct but insufficiently justified step. Assume it's true and continue verifying.\n3. **Output Format:**\n * **a. Summary:**\n * **Final Verdict:** A single sentence (e.g., \"The solution is correct.\").\n * **List of Findings:** A bulleted list of every issue found.\n * **b. Detailed Verification Log:** A step-by-step analysis.\n\n---\n### Problem ###\n{problem_statement}\n\n---\n### Solution ###\n{solution_to_verify}\n---\n### Verification Task Reminder ###\nGenerate the summary and the step-by-step verification log."
def _get_solver_prompt_correction(solution_attempt, verification_report):
return f"You are a brilliant mathematician. Your previous solution has been reviewed.\nYour task is to write a new, corrected version of your solution that meticulously addresses all issues raised in the verifier's report.\n\n### Verification Report on Your Last Attempt ###\n{verification_report}\n\n### Your Previous Flawed Solution ###\n{solution_attempt}\n\n### Your Task ###\nProvide a new, complete, and rigorously correct solution that fixes all identified issues. Follow the original structured output format (Summary and Detailed Solution)."
def _call_solver_llm(prompt, task_id, step_name):
"""Fonction d'appel LLM spécifique pour le pipeline de résolution."""
print(f"Task {task_id}: [Math Solver] - {step_name}...")
try:
response = client.models.generate_content(
model=SOLVER_MODEL_NAME,
contents=[prompt],
generation_config={"temperature": SOLVER_TEMPERATURE}
)
time.sleep(2) # Éviter de surcharger l'API
return response.text
except Exception as e:
print(f"Task {task_id}: An error occurred with the LLM API during '{step_name}': {e}")
return None
def _parse_verifier_verdict(report):
if not report: return "ERROR"
report_lower = report.lower()
if "the solution is correct" in report_lower: return "CORRECT"
if "critical error" in report_lower: return "CRITICAL_ERROR"
if "justification gap" in report_lower: return "GAPS"
return "UNKNOWN"
def run_solver_pipeline(problem_statement, task_id, task_results):
"""Orchestrateur du pipeline de résolution mathématique."""
# Étape 1: Génération Initiale
task_results[task_id]['status'] = 'solving_generating'
initial_prompt = _get_solver_prompt_initial(problem_statement)
current_solution = _call_solver_llm(initial_prompt, task_id, "Initial Generation")
if not current_solution: return "Failed at initial generation."
# Étape 2: Auto-Amélioration
task_results[task_id]['status'] = 'solving_improving'
improve_prompt = _get_solver_prompt_improve(current_solution)
current_solution = _call_solver_llm(improve_prompt, task_id, "Self-Improvement")
if not current_solution: return "Failed at self-improvement."
# Étape 3-5: Boucle de Vérification et Correction
iteration = 0
consecutive_passes = 0
while iteration < SOLVER_MAX_ITERATIONS:
iteration += 1
task_results[task_id]['status'] = f'solving_verifying_iter_{iteration}'
verifier_prompt = _get_solver_prompt_verifier(problem_statement, current_solution)
verification_report = _call_solver_llm(verifier_prompt, task_id, f"Verification (Iter {iteration})")
if not verification_report: break
verdict = _parse_verifier_verdict(verification_report)
if verdict == "CORRECT":
consecutive_passes += 1
print(f"Task {task_id}: [Math Solver] - PASS! Consecutive: {consecutive_passes}/{SOLVER_PASSES_NEEDED}")
if consecutive_passes >= SOLVER_PASSES_NEEDED:
print(f"Task {task_id}: [Math Solver] - Solution verified. Exiting loop.")
return current_solution
else:
consecutive_passes = 0
task_results[task_id]['status'] = f'solving_correcting_iter_{iteration}'
correction_prompt = _get_solver_prompt_correction(current_solution, verification_report)
new_solution = _call_solver_llm(correction_prompt, task_id, f"Correction (Iter {iteration})")
if not new_solution: break
current_solution = new_solution
print(f"Task {task_id}: [Math Solver] - Solver finished. Returning last valid solution.")
return current_solution
# --- HELPER FUNCTIONS (LaTeX, Telegram, etc.) ---
def check_latex_installation():
"""Vérifie si pdflatex est installé sur le système."""
try:
subprocess.run(["pdflatex", "-version"], capture_output=True, check=True, timeout=10)
print("INFO: pdflatex est installé et accessible.")
return True
except (FileNotFoundError, subprocess.TimeoutExpired, subprocess.CalledProcessError) as e:
print(f"AVERTISSEMENT: pdflatex non installé ou non fonctionnel: {e}")
return False
IS_LATEX_INSTALLED = check_latex_installation()
def clean_latex_code(latex_code):
"""Removes markdown code block fences (```latex ... ``` or ``` ... ```) if present."""
match_latex = re.search(r"```(?:latex|tex)\s*(.*?)\s*```", latex_code, re.DOTALL | re.IGNORECASE)
if match_latex: return match_latex.group(1).strip()
match_generic = re.search(r"```\s*(\\documentclass.*?)\s*```", latex_code, re.DOTALL | re.IGNORECASE)
if match_generic: return match_generic.group(1).strip()
return latex_code.strip()
def latex_to_pdf(latex_code, output_filename_base="document"):
"""Converts LaTeX code to PDF."""
if not IS_LATEX_INSTALLED:
return None, "pdflatex n'est pas disponible sur le système."
with tempfile.TemporaryDirectory() as temp_dir_compile:
tex_path = os.path.join(temp_dir_compile, f"{output_filename_base}.tex")
pdf_path_in_compile_dir = os.path.join(temp_dir_compile, f"{output_filename_base}.pdf")
try:
with open(tex_path, "w", encoding="utf-8") as tex_file: tex_file.write(latex_code)
my_env = os.environ.copy()
my_env["LC_ALL"] = "C.UTF-8"
last_result = None
for _ in range(2): # Run twice for references
process = subprocess.run(
["pdflatex", "-interaction=nonstopmode", "-output-directory", temp_dir_compile, tex_path],
capture_output=True, text=True, check=False, encoding="utf-8", errors="replace", env=my_env
)
last_result = process
if not os.path.exists(pdf_path_in_compile_dir) and process.returncode != 0: break
if os.path.exists(pdf_path_in_compile_dir):
temp_pdf_out_file = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False)
shutil.copy(pdf_path_in_compile_dir, temp_pdf_out_file.name)
return temp_pdf_out_file.name, "PDF généré avec succès."
else:
error_log = last_result.stdout if last_result else "Aucun résultat de compilation."
print(f"Erreur de compilation PDF pour {output_filename_base}:\n{error_log}")
match_error = re.search(r"! LaTeX Error: (.*?)\n", error_log)
if match_error: return None, f"Erreur de compilation PDF: {match_error.group(1).strip()}"
return None, f"Erreur lors de la compilation du PDF. Détails dans les logs du serveur."
except Exception as e:
print(f"Exception inattendue lors de la génération du PDF ({output_filename_base}): {e}")
return None, f"Exception inattendue lors de la génération du PDF: {str(e)}"
def send_to_telegram(file_data, filename, caption="Nouveau fichier"):
"""Envoie un fichier (image ou PDF) à un chat Telegram."""
try:
if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.webp')):
url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendPhoto"
files = {'photo': (filename, file_data)}
else:
url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendDocument"
files = {'document': (filename, file_data)}
data = {'chat_id': TELEGRAM_CHAT_ID, 'caption': caption}
response = requests.post(url, files=files, data=data, timeout=30)
if response.status_code == 200:
print(f"Fichier '{filename}' envoyé avec succès à Telegram")
return True
else:
print(f"Erreur envoi Telegram: {response.status_code} - {response.text}")
return False
except Exception as e:
print(f"Exception envoi Telegram: {e}")
return False
def send_document_to_telegram(content_or_path, filename="reponse.txt", caption="Réponse", is_pdf=False):
"""Envoie un document texte ou PDF à Telegram."""
try:
url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendDocument"
data = {'chat_id': TELEGRAM_CHAT_ID, 'caption': caption}
if is_pdf:
with open(content_or_path, 'rb') as f:
files = {'document': (filename, f.read(), 'application/pdf')}
response = requests.post(url, files=files, data=data, timeout=60)
else: # Text content
files = {'document': (filename, content_or_path.encode('utf-8'), 'text/plain')}
response = requests.post(url, files=files, data=data, timeout=60)
if response.status_code == 200:
print(f"Document '{filename}' envoyé avec succès à Telegram.")
return True
else:
print(f"Erreur envoi document Telegram: {response.status_code} - {response.text}")
return False
except Exception as e:
print(f"Exception envoi document Telegram: {e}")
return False
# --- BACKGROUND FILE PROCESSING (Main Logic) ---
def process_files_background(task_id, files_data, resolution_style='colorful'):
"""Traite les fichiers, applique le pipeline de résolution et génère le PDF final."""
pdf_file_to_clean = None
uploaded_file_refs = []
try:
task_results[task_id]['status'] = 'processing'
if not client: raise ConnectionError("Client Gemini non initialisé.")
# Préparer le contenu initial pour Gemini (images/PDFs)
initial_contents = []
for file_info in files_data:
file_type = file_info['type']
file_data = file_info['data']
if file_type.startswith('image/'):
img = Image.open(io.BytesIO(file_data))
buffered = io.BytesIO()
img.save(buffered, format="PNG")
img_base64_str = base64.b64encode(buffered.getvalue()).decode()
initial_contents.append({'inline_data': {'mime_type': 'image/png', 'data': img_base64_str}})
elif file_type == 'application/pdf':
with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as temp_pdf:
temp_pdf.write(file_data)
file_ref = client.files.upload(file=temp_pdf.name)
uploaded_file_refs.append(file_ref)
initial_contents.append(file_ref)
os.unlink(temp_pdf.name)
if not initial_contents: raise ValueError("Aucun contenu valide trouvé.")
full_latex_response = ""
if resolution_style == 'colorful':
# PIPELINE AVANCÉ
task_results[task_id]['status'] = 'extracting_problem'
print(f"Task {task_id}: Étape 1 - Extraction de l'énoncé...")
extraction_response = client.models.generate_content(
model=SOLVER_MODEL_NAME, contents=[*initial_contents, get_prompt_extract_problem()])
problem_statement_text = extraction_response.text
print(f"Task {task_id}: Énoncé extrait: {problem_statement_text[:200]}...")
print(f"Task {task_id}: Étape 2 - Lancement du pipeline de résolution mathématique...")
rigorous_solution_text = run_solver_pipeline(problem_statement_text, task_id, task_results)
if not rigorous_solution_text: raise ValueError("Le pipeline de résolution n'a pas retourné de solution.")
task_results[task_id]['status'] = 'designing_pdf'
print(f"Task {task_id}: Étape 3 - Génération du document LaTeX final...")
colorful_prompt_template = get_prompt_for_style('colorful')
final_design_prompt = f"{colorful_prompt_template}\n\n---\n## CONTENU À METTRE EN FORME\n\n### ÉNONCÉ DE L'EXERCICE\n```\n{problem_statement_text}\n```\n\n### SOLUTION RIGIOUREUSE À METTRE EN PAGE\n```\n{rigorous_solution_text}\n```\n\nMaintenant, produis le code source LaTeX complet et uniquement le code."
gemini_response = client.models.generate_content(model=SOLVER_MODEL_NAME, contents=[final_design_prompt])
full_latex_response = gemini_response.text
else:
# PIPELINE SIMPLE (style 'light')
task_results[task_id]['status'] = 'generating_latex'
print(f"Task {task_id}: Génération LaTeX simple (style: {resolution_style})...")
prompt_to_use = get_prompt_for_style(resolution_style)
gemini_response = client.models.generate_content(model=SOLVER_MODEL_NAME, contents=[*initial_contents, prompt_to_use])
full_latex_response = gemini_response.text
# --- Traitement commun : Compilation PDF et envoi ---
if not full_latex_response.strip(): raise ValueError("Gemini a retourné une réponse vide.")
task_results[task_id]['status'] = 'cleaning_latex'
cleaned_latex = clean_latex_code(full_latex_response)
if not IS_LATEX_INSTALLED:
print(f"Task {task_id}: pdflatex non disponible. Envoi du .tex uniquement.")
send_document_to_telegram(cleaned_latex, f"solution_{task_id}.tex", f"Code LaTeX pour tâche {task_id}")
task_results[task_id]['status'] = 'completed_tex_only'
task_results[task_id]['response'] = cleaned_latex
return
task_results[task_id]['status'] = 'generating_pdf'
pdf_filename_base = f"solution_{task_id}"
pdf_file_to_clean, pdf_message = latex_to_pdf(cleaned_latex, output_filename_base=pdf_filename_base)
if pdf_file_to_clean:
send_document_to_telegram(pdf_file_to_clean, f"{pdf_filename_base}.pdf", f"Solution PDF pour tâche {task_id}", is_pdf=True)
task_results[task_id]['status'] = 'completed'
task_results[task_id]['response'] = cleaned_latex
else:
task_results[task_id]['status'] = 'pdf_error'
task_results[task_id]['error_detail'] = f"Erreur PDF: {pdf_message}"
send_document_to_telegram(cleaned_latex, f"solution_{task_id}.tex", f"Code LaTeX (Erreur PDF: {pdf_message[:150]})")
task_results[task_id]['response'] = cleaned_latex
except Exception as e_outer:
print(f"Task {task_id}: Exception majeure dans la tâche de fond: {e_outer}")
task_results[task_id]['status'] = 'error'
task_results[task_id]['error'] = f"Erreur système: {str(e_outer)}"
finally:
if pdf_file_to_clean and os.path.exists(pdf_file_to_clean):
try:
os.remove(pdf_file_to_clean)
except Exception as e_clean:
print(f"Task {task_id}: Erreur suppression PDF temp: {e_clean}")
# Les références de fichiers Gemini expirent automatiquement
# --- FLASK ROUTES ---
@app.route('/')
def index():
return render_template('index.html')
@app.route('/free')
def free():
return render_template('index.html')
@app.route('/solve', methods=['POST'])
def solve():
try:
if 'user_files' not in request.files: return jsonify({'error': 'Aucun fichier fourni'}), 400
uploaded_files = request.files.getlist('user_files')
if not uploaded_files or all(f.filename == '' for f in uploaded_files): return jsonify({'error': 'Aucun fichier sélectionné'}), 400
resolution_style = request.form.get('style', 'colorful')
files_data = []
for file in uploaded_files:
if file.filename != '':
file_data = file.read()
file_type = file.content_type or 'application/octet-stream'
if file_type.startswith('image/') or file_type == 'application/pdf':
files_data.append({'filename': file.filename, 'data': file_data, 'type': file_type})
send_to_telegram(file_data, file.filename, f"Mariam(Pro) - Style: {resolution_style}")
if not files_data: return jsonify({'error': 'Aucun fichier valide (images/PDF acceptés)'}), 400
task_id = str(uuid.uuid4())
task_results[task_id] = {'status': 'pending', 'response': ''}
threading.Thread(target=process_files_background, args=(task_id, files_data, resolution_style)).start()
return jsonify({'task_id': task_id, 'status': 'pending'})
except Exception as e:
print(f"Exception lors de la création de la tâche: {e}")
return jsonify({'error': f'Erreur serveur: {e}'}), 500
@app.route('/task/<task_id>', methods=['GET'])
def get_task_status(task_id):
if task_id not in task_results: return jsonify({'error': 'Tâche introuvable'}), 404
task = task_results[task_id]
return jsonify({
'status': task.get('status'),
'response': task.get('response'),
'error': task.get('error'),
'error_detail': task.get('error_detail')
})
@app.route('/stream/<task_id>', methods=['GET'])
def stream_task_progress(task_id):
def generate():
if task_id not in task_results:
yield f'data: {json.dumps({"error": "Tâche introuvable", "status": "error"})}\n\n'
return
last_status_sent = None
while True:
task = task_results.get(task_id)
if not task:
yield f'data: {json.dumps({"error": "Tâche disparue", "status": "error"})}\n\n'
break
current_status = task['status']
if current_status != last_status_sent:
data_to_send = {"status": current_status}
if current_status in ['completed', 'completed_tex_only', 'pdf_error']:
data_to_send["response"] = task.get("response", "")
if current_status in ['error', 'pdf_error']:
data_to_send["error"] = task.get("error", "Erreur")
if task.get("error_detail"): data_to_send["error_detail"] = task.get("error_detail")
yield f'data: {json.dumps(data_to_send)}\n\n'
last_status_sent = current_status
if current_status in ['completed', 'error', 'pdf_error', 'completed_tex_only']:
break
time.sleep(1)
return Response(stream_with_context(generate()), mimetype='text/event-stream')
# --- MAIN EXECUTION BLOCK ---
if __name__ == '__main__':
if not GOOGLE_API_KEY:
print("CRITICAL: GOOGLE_API_KEY non définie.")
if not TELEGRAM_BOT_TOKEN or not TELEGRAM_CHAT_ID:
print("CRITICAL: Variables Telegram non définies.")
app.run(debug=True, host='0.0.0.0', port=5000)
|