Spaces:
Sleeping
Sleeping
from flask import Flask, render_template, request, jsonify, Response, stream_with_context | |
from google import genai | |
from google.genai import types | |
import os | |
import json | |
import requests | |
import time | |
from PIL import Image | |
import io | |
import base64 | |
from pathlib import Path | |
app = Flask(__name__) | |
# API Keys | |
GOOGLE_API_KEY = os.environ.get("GEMINI_API_KEY") | |
TELEGRAM_BOT_TOKEN = "8004545342:AAGcZaoDjYg8dmbbXRsR1N3TfSSbEiAGz88" | |
TELEGRAM_CHAT_ID = "-1002497861230" | |
client = genai.Client(api_key=GOOGLE_API_KEY) | |
# Prompt de base | |
BASE_PROMPT = r""" | |
# 🔍 GÉNÉRATEUR DE CORRECTION MATHÉMATIQUE (Version Directe) | |
## 🎓 VOTRE RÔLE | |
Vous êtes **Mariam-MATHEX-PRO**, un expert en mathématiques chargé de fournir des corrections. Votre objectif est d'être clair, précis et d'aller droit au but. | |
## 📊 FORMAT D'ENTRÉE ET SORTIE | |
**ENTRÉE:** L'énoncé d'un exercice mathématique (niveau Terminale/Supérieur). | |
**SORTIE:** UNIQUEMENT la correction de l'exercice **en français** avec rendu LaTeX. | |
## 🛠️ INSTRUCTIONS POUR LA CORRECTION | |
1. **STRUCTURATION DE LA RÉPONSE :** | |
Organisez la solution en étapes logiques claires. | |
Si l'exercice comporte plusieurs questions ou parties, traitez-les séquentiellement. | |
2. **DÉTAIL DU PROCÉDÉ DE CALCUL :** | |
Pour chaque étape significative, montrez les calculs. | |
Écrivez les calculs intermédiaires importants. | |
3. **EXPLICATIONS TRÈS BRÈVES :** | |
Chaque étape doit avoir une explication textuelle très concise. | |
4. **RÉSULTATS :** | |
Indiquez clairement les résultats intermédiaires et le résultat final. | |
## 🔧 RENDU MATHÉMATIQUE | |
5. **RENDU MATHÉMATIQUE :** | |
Utilisez LaTeX pour toutes les expressions mathématiques. | |
## ✅ OBJECTIF PRINCIPAL | |
Fournir une correction mathématique textuelle **en français** qui va droit au but. | |
""" | |
# Extension du prompt | |
CODE_EXTENSION = r""" | |
## 🧮 EXIGENCES TECHNIQUES (MODE CALCULATRICE ACTIVÉ) | |
6. **CALCULS ET FIGURES :** | |
Utilisez Python pour tous les calculs numériques et graphiques. | |
7. **VÉRIFICATION NUMÉRIQUE :** | |
Vérifiez vos calculs analytiques par du numérique en Python. | |
""" | |
class AgentSystem: | |
def __init__(self): | |
self.prompts_dir = Path("prompts") | |
self.prompts = self.load_prompts() | |
def load_prompts(self): | |
prompts = {} | |
try: | |
self.prompts_dir.mkdir(exist_ok=True) | |
# Prompts reproduits EXACTEMENT du PDF | |
default_prompts = { | |
"step1_initial_solution.md": r"""### Core Instructions ### | |
* **Rigor is Paramount:** Your primary goal is to produce a complete and rigorously justified solution. Every step in your solution must be logically sound and clearly explained. A correct final answer derived from flawed or incomplete reasoning is considered a failure. | |
* **Honesty About Completeness:** If you cannot find a complete solution, you must **not** guess or create a solution that appears correct but contains hidden flaws or justification gaps. Instead, you should present only significant partial results that you can rigorously prove. A partial result is considered significant if it represents a substantial advancement toward a full solution. Examples include: | |
* Proving a key lemma. | |
* Fully resolving one or more cases within a logically sound case-based proof. | |
* Establishing a critical property of the mathematical objects in the problem. | |
* For an optimization problem, proving an upper or lower bound without proving that this bound is achievable. | |
* **Use TeX for All Mathematics:** All mathematical variables, expressions, and relations must be enclosed in TeX delimiters (e.g., `Let $n$ be an integer.`). | |
### Output Format ### | |
Your response MUST be structured into the following sections, in this exact order. | |
**1. Summary** | |
Provide a concise overview of your findings. This section must contain two parts: | |
* **a. Verdict:** State clearly whether you have found a complete solution or a partial solution. | |
* **For a complete solution:** State the final answer, e.g., "I have successfully solved the problem. The final answer is..." | |
* **For a partial solution:** State the main rigorous conclusion(s) you were able to prove, e.g., "I have not found a complete solution, but I have rigorously proven that..." | |
* **b. Method Sketch:** Present a high-level, conceptual outline of your solution. This sketch should allow an expert to understand the logical flow of your argument without reading the full detail. It should include: | |
* A narrative of your overall strategy. | |
* The full and precise mathematical statements of any key lemmas or major intermediate results. | |
* If applicable, describe any key constructions or case splits that form the backbone of your argument. | |
**2. Detailed Solution** | |
Present the full, step-by-step mathematical proof. Each step must be logically justified and clearly explained. The level of detail should be sufficient for an expert to verify the correctness of your reasoning without needing to fill in any gaps. This section must contain ONLY the complete, rigorous proof, free of any internal commentary, alternative approaches, or failed attempts. | |
### Self-Correction Instruction ### | |
Before finalizing your output, carefully review your "Method Sketch" and "Detailed Solution" to ensure they are clean, rigorous, and strictly adhere to all instructions provided above. Verify that every statement contributes directly to the final, coherent mathematical argument. | |
""", | |
"step2_self_improvement.md": r"""You are a world-class mathematician reviewing your own work. You have just produced the following draft solution to a problem. Your task is to critically analyze it for clarity, logical soundness, and potential simplifications. Produce a new, improved version of the solution. The goal is to elevate it to a publication-ready standard. | |
### Draft Solution ### | |
[The initial solution attempt will be inserted here] | |
### Your Task ### | |
Provide the improved version of the solution, adhering to the original problem's constraints and focusing on enhancing rigor and elegance. | |
""", | |
"step3_verification.md": r"""You are an expert mathematician and a meticulous grader for an International Mathematical Olympiad (IMO) level exam. Your primary task is to rigorously verify the provided mathematical solution. A solution is to be judged correct **only if every step is rigorously justified.** A solution that arrives at a correct final answer through flawed reasoning, educated guesses, or with gaps in its arguments must be flagged as incorrect or incomplete. | |
### Instructions ### | |
**1. Core Instructions** | |
* Your sole task is to find and report all issues in the provided solution. You must act as a **verifier**, NOT a solver. **Do NOT attempt to correct the errors or fill the gaps you find.** | |
* You must perform a **step-by-step** check of the entire solution. This analysis will be presented in a **Detailed Verification Log**, where you justify your assessment of each step: for correct steps, a brief justification suffices; for steps with errors or gaps, you must provide a detailed explanation. | |
**2. How to Handle Issues in the Solution** | |
When you identify an issue in a step, you MUST first classify it into one of the following two categories and then follow the specified procedure. | |
* **a. Critical Error:** | |
This is any error that breaks the logical chain of the proof. This includes both **logical fallacies** (e.g., claiming that 'A>B, C>D' implies 'A-C>B-D') and **factual errors** (e.g., a calculation error like '2+3=6'). | |
* **Procedure:** | |
* Explain the specific error and state that it **invalidates the current line of reasoning**. | |
* Do NOT check any further steps that rely on this error. | |
* You MUST, however, scan the rest of the solution to identify and verify any fully independent parts. For example, if a proof is split into multiple cases, an error in one case does not prevent you from checking the other cases. | |
* **b. Justification Gap:** | |
This is for steps where the conclusion may be correct, but the provided argument is incomplete, hand-wavy, or lacks sufficient rigor. | |
* **Procedure:** | |
* Explain the gap in the justification. | |
* State that you will **assume the step's conclusion is true** for the sake of argument. | |
* Then, proceed to verify all subsequent steps to check if the remainder of the argument is sound. | |
**3. Output Format** | |
Your response MUST be structured into two main sections: a **Summary** followed by the **Detailed Verification Log**. | |
* **a. Summary** | |
This section MUST be at the very beginning of your response. It must contain two components: | |
* **Final Verdict**: A single, clear sentence declaring the overall validity of the solution. For example: "The solution is correct," "The solution contains a Critical Error and is therefore invalid," or "The solution's approach is viable but contains several Justification Gaps." | |
* **List of Findings**: A bulleted list that summarizes **every** issue you discovered. For each finding, you must provide: | |
* **Location:** A direct quote of the key phrase or equation where the issue occurs. | |
* **Issue:** A brief description of the problem and its classification (**Critical Error** or **Justification Gap**). | |
* **b. Detailed Verification Log** | |
Following the summary, provide the full, step-by-step verification log as defined in the Core Instructions. When you refer to a specific part of the solution, **quote the relevant text** to make your reference clear before providing your detailed analysis of that part. | |
""", | |
"step5_correction.md": r"""You are a brilliant mathematician working to solve a difficult problem. Your previous attempt at a solution has been reviewed, and a verification report has been generated. Your task is to carefully study the report and produce a new, corrected solution that addresses all the identified issues. | |
### Verification Report ### | |
[The full verification report will be inserted here] | |
### Previous Solution ### | |
[The previous solution attempt will be inserted here] | |
### Task ### | |
Provide a new, complete, and rigorously justified solution. Ensure that every error and justification gap mentioned in the report is resolved. If you disagree with an item in the report, revise your solution to make the reasoning clearer and less ambiguous. | |
""" | |
} | |
for filename, content in default_prompts.items(): | |
prompt_file = self.prompts_dir / filename | |
prompt_file.write_text(content.strip(), encoding='utf-8') | |
for prompt_file in self.prompts_dir.glob("*.md"): | |
prompts[prompt_file.stem] = prompt_file.read_text(encoding='utf-8') | |
except Exception as e: | |
print(f"Error loading prompts: {e}") | |
return prompts | |
def extract_problem_text(self, img_str): | |
try: | |
response = client.models.generate_content( | |
model="gemini-2.5-flash", | |
contents=[ | |
{'inline_data': {'mime_type': 'image/png', 'data': img_str}}, | |
"Extract the mathematical problem statement from this image. Provide only the problem text in LaTeX." | |
], | |
config=types.GenerateContentConfig(temperature=0.1) | |
) | |
problem_text = "" | |
for part in response.candidates[0].content.parts: | |
if hasattr(part, 'text') and part.text: | |
problem_text += part.text | |
return problem_text.strip() | |
except Exception as e: | |
print(f"Error extracting problem text: {e}") | |
return "[Problem extraction failed]" | |
def run_agent_step(self, step_name, prompt, use_calculator=False): | |
try: | |
config = types.GenerateContentConfig( | |
temperature=0.3, | |
thinking_config=types.ThinkingConfig(include_thoughts=True) | |
) | |
if use_calculator: | |
config.tools = [types.Tool(code_execution=types.ToolCodeExecution)] | |
response = client.models.generate_content_stream( | |
model="gemini-2.5-flash", | |
contents=[prompt], | |
config=config | |
) | |
result = "" | |
for chunk in response: | |
for part in chunk.candidates[0].content.parts: | |
if hasattr(part, 'text') and part.text: | |
result += part.text | |
return result.strip() | |
except Exception as e: | |
print(f"Error in agent step {step_name}: {e}") | |
return f"[Error in {step_name}: {str(e)}]" | |
def send_to_telegram(image_data, caption="Nouvelle image uploadée"): | |
try: | |
url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendPhoto" | |
files = {'photo': ('image.png', image_data)} | |
data = {'chat_id': TELEGRAM_CHAT_ID, 'caption': caption} | |
response = requests.post(url, files=files, data=data) | |
return response.status_code == 200 | |
except Exception as e: | |
print(f"Exception Telegram: {e}") | |
return False | |
def index(): | |
return render_template('index.html') | |
def solve(): | |
try: | |
image_data = request.files['image'].read() | |
use_calculator = request.form.get('use_calculator', 'false').lower() == 'true' | |
use_extended_reasoning = request.form.get('use_extended_reasoning', 'false').lower() == 'true' | |
img = Image.open(io.BytesIO(image_data)) | |
send_to_telegram(image_data, "Nouvelle image reçue") | |
buffered = io.BytesIO() | |
img.save(buffered, format="PNG") | |
img_str = base64.b64encode(buffered.getvalue()).decode() | |
def generate(): | |
try: | |
if use_extended_reasoning: | |
agent_system = AgentSystem() | |
# Étape 0: Extraction | |
yield 'data: ' + json.dumps({"mode": "thinking"}) + '\n\n' | |
# Pre-define strings with newlines to avoid f-string backslash issue | |
extraction_msg = "# 🔍 EXTRACTION DU PROBLÈME\n\nAnalyse de l'image pour extraire l'énoncé du problème...\n\n" | |
yield 'data: ' + json.dumps({"content": extraction_msg, "type": "text"}) + '\n\n' | |
problem_text = agent_system.extract_problem_text(img_str) | |
problem_msg = f"**Problème identifié:**\n{problem_text}\n\n" | |
yield 'data: ' + json.dumps({"content": problem_msg, "type": "text"}) + '\n\n' | |
# Étape 1 | |
step1_msg = "# 📝 ÉTAPE 1: SOLUTION INITIALE\n\n" | |
yield 'data: ' + json.dumps({"content": step1_msg, "type": "text"}) + '\n\n' | |
step1_prompt = agent_system.prompts["step1_initial_solution"].replace( | |
"[The mathematical problem will be inserted here]", problem_text | |
) | |
initial_solution = agent_system.run_agent_step("step1", step1_prompt, use_calculator) | |
yield 'data: ' + json.dumps({"content": initial_solution, "type": "text"}) + '\n\n' | |
# Étape 2 | |
step2_msg = "# 🔧 ÉTAPE 2: AUTO-AMÉLIORATION\n\n" | |
yield 'data: ' + json.dumps({"content": step2_msg, "type": "text"}) + '\n\n' | |
step2_prompt = agent_system.prompts["step2_self_improvement"].replace( | |
"[The initial solution attempt will be inserted here]", initial_solution | |
) | |
improved_solution = agent_system.run_agent_step("step2", step2_prompt, use_calculator) | |
yield 'data: ' + json.dumps({"content": improved_solution, "type": "text"}) + '\n\n' | |
# Étape 3 | |
step3_msg = "# ✅ ÉTAPE 3: VÉRIFICATION\n\n" | |
yield 'data: ' + json.dumps({"content": step3_msg, "type": "text"}) + '\n\n' | |
step3_prompt = agent_system.prompts["step3_verification"].replace( | |
"[The mathematical problem will be inserted here]", problem_text | |
).replace( | |
"[The solution to be verified will be inserted here]", improved_solution | |
) | |
verification_result = agent_system.run_agent_step("step3", step3_prompt, False) | |
yield 'data: ' + json.dumps({"content": verification_result, "type": "text"}) + '\n\n' | |
needs_correction = ( | |
"Critical Error" in verification_result | |
or "Justification Gap" in verification_result | |
or "invalid" in verification_result.lower() | |
) | |
if needs_correction: | |
step5_msg = "# 🛠️ ÉTAPE 5: CORRECTION\n\n" | |
yield 'data: ' + json.dumps({"content": step5_msg, "type": "text"}) + '\n\n' | |
step5_prompt = agent_system.prompts["step5_correction"].replace( | |
"[The full verification report will be inserted here]", verification_result | |
).replace( | |
"[The previous solution attempt will be inserted here]", improved_solution | |
) | |
corrected_solution = agent_system.run_agent_step("step5", step5_prompt, use_calculator) | |
final_solution = corrected_solution | |
yield 'data: ' + json.dumps({"content": corrected_solution, "type": "text"}) + '\n\n' | |
else: | |
final_solution = improved_solution | |
validated_msg = "✅ La solution a été validée sans correction.\n\n" | |
yield 'data: ' + json.dumps({"content": validated_msg, "type": "text"}) + '\n\n' | |
yield 'data: ' + json.dumps({"mode": "answering"}) + '\n\n' | |
final_msg = "# 📋 SOLUTION FINALE\n\n" | |
yield 'data: ' + json.dumps({"content": final_msg, "type": "text"}) + '\n\n' | |
yield 'data: ' + json.dumps({"content": final_solution, "type": "text"}) + '\n\n' | |
else: | |
prompt = BASE_PROMPT | |
if use_calculator: | |
prompt += CODE_EXTENSION | |
config = types.GenerateContentConfig( | |
temperature=0.3, | |
thinking_config=types.ThinkingConfig(include_thoughts=True) | |
) | |
if use_calculator: | |
config.tools = [types.Tool(code_execution=types.ToolCodeExecution)] | |
response = client.models.generate_content_stream( | |
model="gemini-2.5-flash", | |
contents=[ | |
{'inline_data': {'mime_type': 'image/png', 'data': img_str}}, | |
prompt | |
], | |
config=config | |
) | |
for chunk in response: | |
for part in chunk.candidates[0].content.parts: | |
if hasattr(part, 'text') and part.text: | |
yield 'data: ' + json.dumps({"content": part.text, "type": "text"}) + '\n\n' | |
except Exception as e: | |
print(f"Error during generation: {e}") | |
yield 'data: ' + json.dumps({"error": "Erreur inattendue"}) + '\n\n' | |
return Response( | |
stream_with_context(generate()), | |
mimetype='text/event-stream', | |
headers={'Cache-Control': 'no-cache', 'X-Accel-Buffering': 'no'} | |
) | |
except Exception as e: | |
print(f"Error in solve endpoint: {e}") | |
return jsonify({'error': 'Erreur inattendue'}), 500 | |
if __name__ == '__main__': | |
app.run(debug=True) |