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 pour la correction mathĂ©matique 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 en indiquant clairement Ă  quelle partie/question vous rĂ©pondez. 2. **DÉTAIL DU PROCÉDÉ DE CALCUL :** * Pour chaque Ă©tape significative du raisonnement ou du calcul, montrez le dĂ©veloppement. * Ne sautez pas d'Ă©tapes de calcul cruciales pour la comprĂ©hension. Écrivez les calculs intermĂ©diaires importants. 3. **EXPLICATIONS TRÈS BRÈVES :** * Accompagnez chaque Ă©tape clĂ© du calcul ou du raisonnement d'une explication textuelle trĂšs concise et directe. Par exemple : "Pour trouver la dĂ©rivĂ©e, nous appliquons la rĂšgle du produit...", "En substituant x=2 dans l'Ă©quation...", "AprĂšs simplification des termes, on obtient...". * Une seule idĂ©e principale ou Ă©tape de calcul par segment de texte. 4. **RÉSULTATS :** * Indiquez clairement les rĂ©sultats intermĂ©diaires si pertinent, et Ă©noncez distinctement le rĂ©sultat final de chaque question ou sous-question. ## 🔧 RENDU MATHÉMATIQUE 5. **RENDU MATHÉMATIQUE :** * Utilisez le rendu LaTeX pour toutes les expressions mathĂ©matiques, Ă©quations et formules. * Formatez correctement les calculs avec la syntaxe LaTeX appropriĂ©e. ## ✅ OBJECTIF PRINCIPAL Fournir une correction mathĂ©matique textuelle **en français** qui va **droit au but**. Chaque Ă©tape de calcul doit ĂȘtre dĂ©taillĂ©e avec rendu LaTeX, chaque explication doit ĂȘtre **trĂšs brĂšve** et se concentrer sur le "comment" ou le "pourquoi" immĂ©diat de l'opĂ©ration mathĂ©matique. """ # Extension du prompt pour l'exĂ©cution de code CODE_EXTENSION = r""" ## 🧼 EXIGENCES TECHNIQUES (MODE CALCULATRICE ACTIVÉ) 6. **CALCULS ET FIGURES :** * Utilisez Python pour effectuer tous les calculs numĂ©riques et crĂ©er les graphiques nĂ©cessaires. * Pour chaque figure ou graphique : gĂ©nĂ©rez-le avec Python, sauvegardez-le comme fichier image, puis affichez l'image. * IntĂ©grez le code Python dans la correction pour montrer la dĂ©marche de calcul. * Utilisez des bibliothĂšques comme numpy, matplotlib, sympy selon les besoins. 7. **VÉRIFICATION NUMÉRIQUE :** * VĂ©rifiez vos calculs analytiques avec des calculs numĂ©riques en Python. * CrĂ©ez des visualisations graphiques pour illustrer les concepts mathĂ©matiques. """ class AgentSystem: def __init__(self): self.prompts_dir = Path("prompts") self.prompts = self.load_prompts() def load_prompts(self): """Load all agent prompts from files""" prompts = {} try: # Create prompts directory if it doesn't exist self.prompts_dir.mkdir(exist_ok=True) # Define default prompts if files don't exist default_prompts = { "step1_initial_solution.md": """### 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. * **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. ### Problem ### [The mathematical problem will be inserted here]""", "step2_self_improvement.md": """You are a world-class mathematician. You have just produced the following draft solution. Your task is to review it carefully, identify any potential flaws, gaps in logic, or areas that could be explained more clearly. Then, produce a new, improved, and more rigorous version of the solution. ### Draft Solution ### [The initial solution attempt will be inserted here] ### Your Task ### Provide the improved and finalized version of the solution. Do not include comments about the changes, just the final, clean proof.""", "step3_verification.md": """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. --- ### Problem ### [The mathematical problem will be inserted here] --- ### Solution ### [The solution to be verified will be inserted here] --- ### Verification Task Reminder ### Your task is to act as an IMO grader. Now, generate the **summary** and the **step-by-step verification log** for the solution above. In your log, justify each correct step and explain in detail any errors or justification gaps you find, as specified in the instructions above.""", "step5_correction.md": """You are a brilliant mathematician attempting to solve a difficult problem. Your previous solution attempt has been reviewed by a verifier, who produced the report below. Your task is to write a new, corrected version of your solution that meticulously addresses all the issues raised in the report. ### Verification Report on Your Last Attempt ### [The full verification report will be inserted here] ### Your Previous Flawed Solution ### [The previous solution attempt will be inserted here] ### Your Task ### Provide a new, complete, and rigorously correct solution that fixes all identified issues. Remember to follow the structured output format (Summary and Detailed Solution) requested in the original problem.""" } # Create prompt files if they don't exist for filename, content in default_prompts.items(): prompt_file = self.prompts_dir / filename if not prompt_file.exists(): prompt_file.write_text(content, encoding='utf-8') prompts[filename.replace('.md', '')] = content # Load existing prompts 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}") # Fallback to hardcoded prompts prompts = { "step1_initial_solution": default_prompts["step1_initial_solution.md"], "step2_self_improvement": default_prompts["step2_self_improvement.md"], "step3_verification": default_prompts["step3_verification.md"], "step5_correction": default_prompts["step5_correction.md"] } return prompts def extract_problem_text(self, img_str): """Extract problem text from image using Gemini""" 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 format where appropriate, without any solution or commentary." ], 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): """Run a single agent step""" 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"): """Envoie l'image Ă  un chat Telegram spĂ©cifiĂ©""" 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) if response.status_code == 200: print("Image envoyĂ©e avec succĂšs Ă  Telegram") return True else: print(f"Erreur lors de l'envoi Ă  Telegram: {response.text}") return False except Exception as e: print(f"Exception lors de l'envoi Ă  Telegram: {e}") return False @app.route('/') def index(): return render_template('index.html') @app.route('/solve', methods=['POST']) def solve(): try: # RĂ©cupĂ©ration des donnĂ©es 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)) # Envoyer l'image Ă  Telegram avec indication du mode mode_info = [] if use_calculator: mode_info.append("calculatrice") if use_extended_reasoning: mode_info.append("rĂ©flexion Ă©tendue") caption = f"Nouvelle image pour rĂ©solution ({', '.join(mode_info) if mode_info else 'mode standard'})" send_to_telegram(image_data, caption) # Traitement pour Gemini buffered = io.BytesIO() img.save(buffered, format="PNG") img_str = base64.b64encode(buffered.getvalue()).decode() def generate(): mode = 'starting' try: if use_extended_reasoning: # Mode rĂ©flexion Ă©tendue - systĂšme d'agents agent_system = AgentSystem() # Étape 0: Extraction du problĂšme yield f'data: {json.dumps({"mode": "thinking"})}\n\n' yield f'data: {json.dumps({"content": "# 🔍 EXTRACTION DU PROBLÈME\n\nAnalyse de l\'image pour extraire l\'Ă©noncĂ© du problĂšme...\n\n", "type": "text"})}\n\n' problem_text = agent_system.extract_problem_text(img_str) yield f'data: {json.dumps({"content": f"**ProblĂšme identifiĂ©:**\n{problem_text}\n\n", "type": "text"})}\n\n' # Étape 1: Solution initiale yield f'data: {json.dumps({"content": "---\n\n# 📝 ÉTAPE 1: GÉNÉRATION DE LA SOLUTION INITIALE\n\n", "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 f'data: {json.dumps({"content": f"{initial_solution}\n\n", "type": "text"})}\n\n' # Étape 2: Auto-amĂ©lioration yield f'data: {json.dumps({"content": "---\n\n# 🔧 ÉTAPE 2: AUTO-AMÉLIORATION\n\n", "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 f'data: {json.dumps({"content": f"{improved_solution}\n\n", "type": "text"})}\n\n' # Étape 3: VĂ©rification yield f'data: {json.dumps({"content": "---\n\n# ✅ ÉTAPE 3: VÉRIFICATION RIGOUREUSE\n\n", "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 f'data: {json.dumps({"content": f"{verification_result}\n\n", "type": "text"})}\n\n' # VĂ©rifier si des corrections sont nĂ©cessaires needs_correction = ( "Critical Error" in verification_result or "Justification Gap" in verification_result or "invalid" in verification_result.lower() ) if needs_correction: # Étape 5: Correction yield f'data: {json.dumps({"content": "---\n\n# đŸ› ïž ÉTAPE 5: CORRECTION DES ERREURS IDENTIFIÉES\n\n", "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) yield f'data: {json.dumps({"content": f"{corrected_solution}\n\n", "type": "text"})}\n\n' final_solution = corrected_solution else: yield f'data: {json.dumps({"content": "✅ **La solution a passĂ© la vĂ©rification avec succĂšs!**\n\n", "type": "text"})}\n\n' final_solution = improved_solution # Passage Ă  la rĂ©ponse finale yield f'data: {json.dumps({"mode": "answering"})}\n\n' yield f'data: {json.dumps({"content": "# 📋 SOLUTION FINALE\n\n", "type": "text"})}\n\n' yield f'data: {json.dumps({"content": final_solution, "type": "text"})}\n\n' else: # Mode standard 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: # Gestion des pensĂ©es if hasattr(part, 'thought') and part.thought: if mode != "thinking": yield f'data: {json.dumps({"mode": "thinking"})}\n\n' mode = "thinking" yield f'data: {json.dumps({"content": part.text, "type": "text"})}\n\n' else: if mode != "answering": yield f'data: {json.dumps({"mode": "answering"})}\n\n' mode = "answering" # Gestion des diffĂ©rents types de contenu if hasattr(part, 'text') and part.text is not None: yield f'data: {json.dumps({"content": part.text, "type": "text"})}\n\n' if hasattr(part, 'executable_code') and part.executable_code is not None: yield f'data: {json.dumps({"content": part.executable_code.code, "type": "code"})}\n\n' if hasattr(part, 'code_execution_result') and part.code_execution_result is not None: yield f'data: {json.dumps({"content": part.code_execution_result.output, "type": "result"})}\n\n' if hasattr(part, 'inline_data') and part.inline_data is not None: img_data = base64.b64encode(part.inline_data.data).decode('utf-8') yield f'data: {json.dumps({"content": img_data, "type": "image"})}\n\n' except Exception as e: print(f"Error during generation: {e}") yield f'data: {json.dumps({"error": "Une erreur inattendue est survenue"})}\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': 'Une erreur inattendue est survenue'}), 500 if __name__ == '__main__': app.run(debug=True)