wilenPxs commited on
Commit
77a0a72
·
0 Parent(s):

Deploiement app pythonisation (cache FAISS reconstruit au boot)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .dockerignore +14 -0
  2. .env.example +5 -0
  3. .gitignore +24 -0
  4. Dockerfile +34 -0
  5. README.md +15 -0
  6. app/__init__.py +45 -0
  7. app/__main__.py +6 -0
  8. app/config.py +78 -0
  9. app/corpus/Classes_Extensions.py +1953 -0
  10. app/corpus/Mes_fctions_d_alg_lineaire_bis.py +0 -0
  11. app/corpus/Mes_fctions_d_analyse_bis.py +1193 -0
  12. app/corpus/Mes_fctions_generalistes_bis.py +0 -0
  13. app/corpus/Mes_fctions_probabilistes_bis.py +1162 -0
  14. app/keys.py +22 -0
  15. app/knowledge/__init__.py +0 -0
  16. app/knowledge/fewshots/equations.md +128 -0
  17. app/knowledge/fewshots/figure.md +226 -0
  18. app/knowledge/fewshots/integration.md +465 -0
  19. app/knowledge/fewshots/logexp.md +86 -0
  20. app/knowledge/fewshots/quadratique.md +128 -0
  21. app/knowledge/fewshots/systemes.md +173 -0
  22. app/knowledge/functions_catalogue.md +124 -0
  23. app/knowledge/prompts_v1_archive.md +1047 -0
  24. app/knowledge/pythonisation_rules.md +1062 -0
  25. app/knowledge/rules_digest.py +138 -0
  26. app/llm/__init__.py +0 -0
  27. app/llm/client.py +166 -0
  28. app/llm/cost.py +263 -0
  29. app/pipeline/__init__.py +0 -0
  30. app/pipeline/analyze.py +115 -0
  31. app/pipeline/audit.py +266 -0
  32. app/pipeline/fewshots.py +81 -0
  33. app/pipeline/generate.py +211 -0
  34. app/pipeline/orchestrator.py +406 -0
  35. app/pipeline/postprocess.py +676 -0
  36. app/pipeline/prompts.py +563 -0
  37. app/pipeline/solutions.py +108 -0
  38. app/pipeline/translate.py +123 -0
  39. app/rag/__init__.py +0 -0
  40. app/rag/catalogue.py +93 -0
  41. app/rag/formatter.py +229 -0
  42. app/rag/functions.py +1093 -0
  43. app/rag/notions.py +526 -0
  44. app/server.py +284 -0
  45. app/validation/__init__.py +0 -0
  46. app/validation/harness.py +293 -0
  47. app/validation/sandbox.py +587 -0
  48. app/web/templates/index.html +827 -0
  49. data/notions.xlsx +0 -0
  50. requirements-deploy.txt +18 -0
.dockerignore ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Ne JAMAIS embarquer les secrets ni le venv dans l'image.
2
+ .env
3
+ .venv/
4
+ venv/
5
+ __pycache__/
6
+ *.pyc
7
+ *.log
8
+ tests/
9
+
10
+ # Caches FAISS inutiles en déploiement (embeddings locaux non utilisés).
11
+ # On GARDE uniquement openai-3-small (défaut, ~1,2 Mo).
12
+ data/faiss_cache/sources/codesearch-distilroberta/
13
+ data/faiss_cache/sources/mpnet-multilingual/
14
+ data/faiss_cache/sources/openai-3-large/
.env.example ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # OpenRouter — used for all LLM calls (https://openrouter.ai/keys)
2
+ OPENROUTER_API_KEY=
3
+
4
+ # OpenAI — used by the RAG embeddings (openai-3-small) (https://platform.openai.com/api-keys)
5
+ OPENAI_API_KEY=
.gitignore ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Secrets
2
+ .env
3
+
4
+ # Python
5
+ __pycache__/
6
+ *.py[cod]
7
+ *$py.class
8
+ *.so
9
+ .Python
10
+ .venv/
11
+ venv/
12
+ env/
13
+ *.egg-info/
14
+ .pytest_cache/
15
+
16
+ # OS / editor
17
+ .DS_Store
18
+ .vscode/
19
+ .idea/
20
+ *.swp
21
+
22
+ # Runtime
23
+ *.log
24
+ static/uploads/
Dockerfile ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Image de déploiement pour Hugging Face Spaces (SDK Docker).
2
+ # Slim : pas de torch/sentence-transformers (le défaut openai-3-small passe par
3
+ # l'API ; l'import HuggingFace est devenu paresseux). Cache FAISS openai-3-small
4
+ # (~1,2 Mo) embarqué → aucune reconstruction au démarrage.
5
+
6
+ FROM python:3.11-slim
7
+
8
+ # libgomp1 : requis par faiss-cpu.
9
+ RUN apt-get update && apt-get install -y --no-install-recommends libgomp1 \
10
+ && rm -rf /var/lib/apt/lists/*
11
+
12
+ # HF Spaces exécute le conteneur en utilisateur 1000 (bonne pratique).
13
+ RUN useradd -m -u 1000 user
14
+ USER user
15
+ ENV HOME=/home/user \
16
+ PATH=/home/user/.local/bin:$PATH \
17
+ HOST=0.0.0.0 \
18
+ PORT=7860 \
19
+ MPLCONFIGDIR=/tmp/mpl \
20
+ PYTHONUNBUFFERED=1
21
+
22
+ WORKDIR /home/user/app
23
+
24
+ COPY --chown=user requirements-deploy.txt .
25
+ RUN pip install --no-cache-dir --user -r requirements-deploy.txt
26
+
27
+ COPY --chown=user . .
28
+
29
+ EXPOSE 7860
30
+
31
+ # UN SEUL worker (job store en mémoire + threads d'arrière-plan partagés),
32
+ # plusieurs threads pour que le polling et un job tournent en parallèle.
33
+ CMD ["gunicorn", "-w", "1", "--threads", "8", "--timeout", "120", \
34
+ "-b", "0.0.0.0:7860", "run:app"]
README.md ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Pythonise Exercice
3
+ emoji: 🐍
4
+ colorFrom: gray
5
+ colorTo: indigo
6
+ sdk: docker
7
+ app_port: 7860
8
+ pinned: false
9
+ ---
10
+
11
+ # Pythonise Exercice — PyxiScience
12
+
13
+ App interne de pythonisation d'exercices MyST. **Protégée par mot de passe**
14
+ (variable `APP_PASSWORD`). Configurer les Secrets du Space :
15
+ `OPENROUTER_API_KEY`, `OPENAI_API_KEY`, `APP_PASSWORD` (et `APP_USER`, optionnel).
app/__init__.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ App « Pythonise Exercice v2 » — package applicatif.
3
+
4
+ from app import create_app
5
+ app = create_app()
6
+
7
+ Lancement : `python run.py` (ou `python -m app`).
8
+ """
9
+
10
+ import logging
11
+ from pathlib import Path
12
+
13
+
14
+ def _load_env() -> None:
15
+ """Charge .env AVANT tout import qui lit les clés."""
16
+ try:
17
+ from dotenv import load_dotenv
18
+ load_dotenv(Path(__file__).resolve().parent.parent / ".env")
19
+ except ImportError:
20
+ logging.getLogger(__name__).warning(
21
+ "python-dotenv absent ; variables d'environnement du shell utilisées.")
22
+
23
+
24
+ def _setup_logging() -> None:
25
+ logging.basicConfig(
26
+ level=logging.INFO,
27
+ format="%(asctime)s %(levelname)-7s %(name)s — %(message)s",
28
+ datefmt="%H:%M:%S",
29
+ )
30
+ logging.getLogger("urllib3").setLevel(logging.WARNING)
31
+ logging.getLogger("werkzeug").setLevel(logging.WARNING)
32
+
33
+
34
+ def create_app():
35
+ _setup_logging()
36
+ _load_env()
37
+
38
+ from flask import Flask
39
+ from app.config import TEMPLATES_DIR
40
+ from app.server import register_routes
41
+
42
+ flask_app = Flask(__name__, template_folder=str(TEMPLATES_DIR))
43
+ flask_app.config["JSON_SORT_KEYS"] = False
44
+ register_routes(flask_app)
45
+ return flask_app
app/__main__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ """`python -m app` → serveur de dev (reloader OFF : FAISS/HF lourds à charger)."""
2
+
3
+ from app import create_app
4
+ from app.config import HOST, PORT
5
+
6
+ create_app().run(host=HOST, port=PORT, debug=True, use_reloader=False)
app/config.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ config.py
3
+ ─────────
4
+ Configuration centrale de l'app « Pythonise Exercice v2 ».
5
+ Toutes les constantes réglables vivent ici — une seule source de vérité.
6
+ """
7
+
8
+ import os
9
+ from pathlib import Path
10
+
11
+ # ── Chemins ──────────────────────────────────────────────────────────────────
12
+ PACKAGE_DIR = Path(__file__).resolve().parent # …/pythonisation_app/app
13
+ BASE_DIR = PACKAGE_DIR.parent # …/pythonisation_app
14
+ DATA_DIR = BASE_DIR / "data"
15
+ NOTIONS_XLSX = DATA_DIR / "notions.xlsx"
16
+ FAISS_CACHE = DATA_DIR / "faiss_cache" / "sources"
17
+ CORPUS_DIR = PACKAGE_DIR / "corpus" # 5 fichiers de fonctions PyxiScience
18
+ KNOWLEDGE_DIR = PACKAGE_DIR / "knowledge"
19
+ RULES_MD = KNOWLEDGE_DIR / "pythonisation_rules.md"
20
+ FEWSHOTS_DIR = KNOWLEDGE_DIR / "fewshots"
21
+ TEMPLATES_DIR = PACKAGE_DIR / "web" / "templates"
22
+
23
+ # ── Convention MyST (vérifiée empiriquement : 222/222 exemples plateforme) ───
24
+ # Bloc {python} = 4 backticks ; enveloppe {exercise} = 5 backticks.
25
+ PYTHON_FENCE_BACKTICKS = 4
26
+ EXERCISE_FENCE_BACKTICKS = 5
27
+
28
+ # ── Modèles LLM (IDs vérifiés sur l'API OpenRouter le 2026-06-12) ────────────
29
+ AVAILABLE_MODELS = {
30
+ 0: "anthropic/claude-opus-4.8",
31
+ 1: "anthropic/claude-sonnet-4.6",
32
+ 2: "anthropic/claude-fable-5",
33
+ 3: "anthropic/claude-haiku-4.5",
34
+ 4: "google/gemini-2.5-pro",
35
+ 5: "openai/gpt-5.2",
36
+ }
37
+ DEFAULT_MODEL_IDX = 1 # claude-sonnet-4.6
38
+
39
+ # Modèle de l'étape d'analyse : None = suivre le modèle choisi par l'utilisateur
40
+ # (corrige le model_idx=2 codé en dur de l'ancienne version) ; un int force un
41
+ # modèle dédié pour l'analyse.
42
+ ANALYSIS_MODEL_IDX: int | None = None
43
+
44
+ # Modèle du juge de notions (appel léger, JSON court). DOIT supporter
45
+ # response_format=json_object côté OpenRouter (modèles OpenAI — les Claude
46
+ # le rejettent et le retriever dégrade en contexte vide).
47
+ NOTIONS_MODEL = "openai/gpt-5-mini"
48
+
49
+ # Prix $/M tokens (fallback si l'API generation ne renvoie pas le coût réel).
50
+ # Relevés sur openrouter.ai le 2026-06-12.
51
+ MODEL_PRICING = {
52
+ "anthropic/claude-opus-4.8": {"input": 5.0, "output": 25.0},
53
+ "anthropic/claude-sonnet-4.6": {"input": 3.0, "output": 15.0},
54
+ "anthropic/claude-fable-5": {"input": 10.0, "output": 50.0},
55
+ "anthropic/claude-haiku-4.5": {"input": 1.0, "output": 5.0},
56
+ "google/gemini-2.5-pro": {"input": 1.25, "output": 10.0},
57
+ "openai/gpt-5.2": {"input": 1.75, "output": 14.0},
58
+ }
59
+
60
+ # ── Pipeline ─────────────────────────────────────────────────────────────────
61
+ RAG_TOP_K = 10 # catalogue RAG (était 3 — trop étroit)
62
+ RAG_EMBEDDING_MODEL = "openai-3-small"
63
+ MAX_AUDIT_ITERATIONS = 2
64
+ USE_REASONING = False # extended thinking sur les appels de génération
65
+ REASONING_CONFIG = {"max_tokens": 4000} # utilisé seulement si USE_REASONING
66
+ MULTI_SEED_NUM = 100 # graines de la validation d'invariants (règle 4.3)
67
+ HARNESS_GATE_SEEDS = 100 # graines de la porte harnais en fin de pipeline
68
+ HARNESS_REPAIR_MAX = 2 # boucles de réparation LLM si la porte est rouge
69
+
70
+ # ── Langue cible ─────────────────────────────────────────────────────────────
71
+ DEFAULT_LANG = "fr" # "fr" | "en" | "both"
72
+
73
+ # ── Serveur / jobs ───────────────────────────────────────────────────────────
74
+ JOB_TTL = 1800 # s avant purge d'un job terminé
75
+ # HOST/PORT pilotables par l'environnement (déploiement). En local : 127.0.0.1.
76
+ # En conteneur (Hugging Face Spaces) : HOST=0.0.0.0, PORT=7860 (imposé par HF).
77
+ HOST = os.getenv("HOST", "127.0.0.1")
78
+ PORT = int(os.getenv("PORT", "5000"))
app/corpus/Classes_Extensions.py ADDED
@@ -0,0 +1,1953 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Importation des modules nécessaires
2
+
3
+ import re # Module pour les expressions régulières
4
+ from sympy import symbols, oo, latex, Interval # Importation des classes SymPy
5
+ from sympy import *
6
+ import random as rd
7
+ import math as m
8
+ from sympy.series.sequences import RecursiveSeq
9
+ from src.scripts.Mes_fctions.Mes_fctions_d_alg_lineaire_bis import pxsl_pow
10
+ import re
11
+ from src.scripts.pxs_runtime import get_pxs_lang, myst
12
+
13
+ class pxs_Interval(Interval):
14
+ """
15
+ Classe personnalisée héritant de Interval de SymPy
16
+ Permet un affichage formaté des intervalles avec :
17
+ - Séparateurs de milliers pour les grands nombres
18
+ - Notation française pour l'infini et les intervalles
19
+
20
+ :pxs_trigger: |
21
+ intervalle mathématique, domaine de définition, domaine d'étude,
22
+ ensemble solution, ensemble image, image d'un intervalle par une fonction,
23
+ tableau de variations intervalle, tableau de signes, borne,
24
+ ]a;b[, [a;b], ]-\infty, +\infty[, intervalle ouvert fermé semi-ouvert,
25
+ notation française intervalle, TVI intervalle de continuité,
26
+ f\left(\left]...\\right]\\right), domaine de continuité, domaine de dérivabilité,
27
+ intervalle de convexité, intervalle de monotonie,
28
+ croissante sur I, décroissante sur I, continue sur I
29
+ :pxs_returns: |
30
+ Instance de classe héritant de sympy.Interval. À utiliser comme
31
+ un Interval SymPy classique mais avec la méthode .print() pour
32
+ obtenir l'affichage LaTeX francisé.
33
+ :pxs_example: |
34
+ I = pxs_Interval(-oo, 5, True, False) # ]-∞ ; 5]
35
+ # Dans MyST : $D = \\py{I.print()}$
36
+ :pxs_antipattern: Utiliser sympy.Interval(...) puis latex() qui produit la notation anglo-saxonne (a, b].
37
+ """
38
+ @classmethod
39
+ def from_Interval(cls, interval):
40
+ """
41
+ Convertit un Interval standard en pxs_Interval.
42
+
43
+ :pxs_trigger: conversion Interval SymPy vers pxs_Interval, upcast intervalle, résultat solveset/domain
44
+ :pxs_returns: |
45
+ Une instance pxs_Interval reprenant les mêmes bornes et
46
+ ouvertures que l'Interval SymPy fourni.
47
+ :pxs_example: |
48
+ I_sympy = Interval(0, 1, True, False)
49
+ I_pxs = pxs_Interval.from_Interval(I_sympy)
50
+ # Dans MyST : $\\py{I_pxs.print()}$
51
+ :pxs_antipattern: Recréer manuellement pxs_Interval(I.start, I.end, I.left_open, I.right_open).
52
+ """
53
+ if not isinstance(interval, Interval):
54
+ raise TypeError("L'objet fourni n'est pas un Interval")
55
+ return cls(interval.start, interval.end,
56
+ left_open=interval.left_open,
57
+ right_open=interval.right_open)
58
+
59
+
60
+ def print(self):
61
+ """
62
+ Méthode pour générer une représentation LaTeX formatée de l'intervalle
63
+
64
+ Returns:
65
+ str: Chaîne LaTeX formatée selon les conventions françaises
66
+
67
+ :pxs_trigger: intervalle français, notation ]a,b[, borne infinie, affichage LaTeX intervalle, séparateur milliers intervalle
68
+ :pxs_returns: |
69
+ Chaîne LaTeX (objet myst) représentant l'intervalle avec délimiteurs
70
+ français (]a,b[) ou anglais ((a,b)) selon pxs_lang, séparateurs de
71
+ milliers pour les grands entiers, et \\infty pour les bornes infinies.
72
+ À injecter dans MyST via \\py{...}.
73
+ :pxs_example: |
74
+ I = pxs_Interval(-oo, 1000, True, False)
75
+ intervalle_latex = I.print()
76
+ # Dans MyST : $x \\in \\py{intervalle_latex}$
77
+ # Rendu FR : $x \\in \\left]-\\infty;1\\ 000\\right]$
78
+ :pxs_antipattern: Concaténer manuellement f"]{a};{b}[" ou utiliser latex(Interval(...)) qui donne la notation anglo-saxonne (a, b).
79
+ """
80
+
81
+ # Formatage de la borne gauche si elle n'est pas -∞
82
+ if self.left != -oo:
83
+ # Exemple: 1000 devient "1\ 000"
84
+ if isinstance(self.left, (int, Integer)):
85
+ left_formate = f"{int(self.left):,}".replace(",", r"\ ")
86
+ else:
87
+ left_formate = latex(self.left)
88
+ else:
89
+ left_formate = myst(r""" -\infty """)
90
+
91
+
92
+ # Formatage de la borne gauche si elle n'est pas -∞
93
+ if self.right != oo:
94
+ # Exemple: 1000 devient "1\ 000"
95
+ if isinstance(self.right, (int, Integer)):
96
+ right_formate = f"{int(self.right):,}".replace(",", r"\ ")
97
+ else:
98
+ right_formate = latex(self.right)
99
+ else:
100
+ right_formate = myst(r""" \inftys """)
101
+ # Application des conventions françaises si la langue est française
102
+ # Note: pxs_lang doit être définie ailleurs dans le programme
103
+ pxs_lang = get_pxs_lang()
104
+ if pxs_lang == "fr":
105
+ l_delim = r'\left[' if not self.left_open else r'\left]'
106
+ r_delim = r'\right]' if not self.right_open else r'\right['
107
+ if pxs_lang == "en":
108
+ l_delim = r'\left[' if not self.left_open else r'\left('
109
+ r_delim = r'\right]' if not self.right_open else r'\right)'
110
+
111
+ # Conversion des crochets selon la notation française
112
+ # En français: ]a,b[ au lieu de (a,b) pour les intervalles ouverts
113
+ if pxs_lang == "fr":
114
+ Inter_latex = myst(r""" \py{l_delim}\py{left_formate};\py{right_formate}\py{r_delim} """, globals(), locals())
115
+ else:
116
+ Inter_latex = myst(r""" \py{l_delim}\py{left_formate},\py{right_formate}\py{r_delim} """, globals(), locals())
117
+
118
+ # Retour de la chaîne LaTeX formatée
119
+ return Inter_latex
120
+
121
+
122
+ # Tests
123
+ # \begin{python}
124
+ # # Code Python : Ecrivez ci-dessous votre code Python
125
+ # import sympy
126
+ # import random as rd
127
+ # from sympy import *
128
+
129
+ # from pyxiscience.Mes_fctions_d_alg_generale import *
130
+ # from pyxiscience.Classes_Extensions import *
131
+
132
+ # \end{python}
133
+
134
+
135
+ # ## Test de la classe interval de Sympy versus l'extension de PyxiScience
136
+
137
+
138
+
139
+ # \begin{python}
140
+ # I1 = Interval(1, oo, True, True)
141
+ # I2 = Interval(1, oo, False, True)
142
+ # I3 = Interval(1, oo, False, False)
143
+ # I4 = Interval(1, oo, False, False)
144
+
145
+ # Id1 = Interval(1, 2, True, True)
146
+ # Id2 = Interval(1, 2, False, True)
147
+ # Id3 = Interval(1, 2, True, False)
148
+ # Id4 = Interval(1, 2, False, False)
149
+
150
+
151
+
152
+ # I1_latex = latex(I1)
153
+ # I2_latex = latex(I2)
154
+ # I3_latex = latex(I3)
155
+ # I4_latex = latex(I4)
156
+
157
+
158
+
159
+
160
+
161
+ # Inter_1 = pxs_Interval(1, oo, True, True)
162
+ # Inter_2 = pxs_Interval(1, oo, False, True)
163
+ # Inter_3 = pxs_Interval(1, oo, False, False)
164
+ # Inter_4 = pxs_Interval(1, oo, False, False)
165
+
166
+ # Interd_1 = pxs_Interval(1, 2, True, True)
167
+ # Interd_2 = pxs_Interval(1, 2, False, True)
168
+ # Interd_3 = pxs_Interval(1, 2, True, False)
169
+ # Interd_4 = pxs_Interval(1, 2, False, False)
170
+
171
+
172
+ # \end{python}
173
+
174
+ # $I = \py{I1}$
175
+
176
+ # C'est normal car on appelle l'objet python directement...
177
+
178
+
179
+
180
+
181
+ # ## Avec interval de Sympy
182
+
183
+
184
+ # \begin{equation*}
185
+ # &I_1 = \py{I1_latex}&
186
+ # &I_2 = \py{I2_latex}&
187
+ # &I_3 = \py{I3_latex}&
188
+ # &I_4 = \py{I4_latex}&\\
189
+
190
+ # &Id_1 = \py{Interd_1.print()}&
191
+ # &Id_2 = \py{Interd_2.print()}&
192
+ # &Id_3 = \py{Interd_3.print()}&
193
+ # &Id_4 = \py{Interd_4.print()}&
194
+ # \end{equation*}
195
+
196
+
197
+
198
+ # ## Avec pxs_interval
199
+ # \begin{equation*}
200
+ # &I_1 = \py{Inter_1.print()}&
201
+ # &I_2 = \py{Inter_2.print()}&
202
+ # &I_3 = \py{Inter_3.print()}&
203
+ # &I_4 = \py{Inter_4.print()}&\\
204
+
205
+ # &Id_1 = \py{Interd_1.print()}&
206
+ # &Id_2 = \py{Interd_2.print()}&
207
+ # &Id_3 = \py{Interd_3.print()}&
208
+ # &Id_4 = \py{Interd_4.print()}&
209
+ # \end{equation*}
210
+
211
+
212
+
213
+
214
+
215
+
216
+ #from sympy import *
217
+
218
+ class ReverseString:
219
+ """
220
+ Classe utilitaire pour inverser l'ordre de tri des chaînes de caractères.
221
+ Utilisée pour trier les variables dans l'ordre inverse alphabétique.
222
+
223
+ :pxs_trigger: tri inverse alphabétique, ordre descendant variables, clé de tri personnalisée polynôme
224
+ :pxs_returns: |
225
+ Wrapper autour d'une chaîne dont __lt__ est inversé, à utiliser comme
226
+ key dans sorted() pour trier de z vers a au lieu de a vers z.
227
+ :pxs_example: |
228
+ vars_sorted = sorted(["y", "x", "z"], key=ReverseString)
229
+ # → ["z", "y", "x"]
230
+ :pxs_antipattern: Utiliser sorted(..., reverse=True) qui inverse TOUT le tri y compris la clé principale (puissance).
231
+ """
232
+ def __init__(self, string):
233
+ """
234
+ Initialise le wrapper autour de la chaîne à inverser.
235
+
236
+ :pxs_trigger: instanciation interne classe ReverseString
237
+ :pxs_returns: |
238
+ Instance ReverseString encapsulant la chaîne fournie.
239
+ :pxs_example: |
240
+ wrap = ReverseString("x")
241
+ # Utilisé typiquement via sorted(..., key=ReverseString)
242
+ :pxs_antipattern: Appeler ReverseString directement dans du code pédagogique — c'est un utilitaire interne de tri.
243
+ """
244
+ self.string = string
245
+
246
+ def __lt__(self, other):
247
+ """
248
+ Comparaison inversée pour le tri descendant.
249
+
250
+ :pxs_trigger: comparaison tri inverse interne
251
+ :pxs_returns: |
252
+ bool : True si self.string > other.string (comparaison inversée).
253
+ :pxs_example: |
254
+ ReverseString("a") < ReverseString("b") # False (car 'a' < 'b' devient inversé)
255
+ :pxs_antipattern: Appeler __lt__ directement au lieu de laisser Python l'utiliser via sorted().
256
+ """
257
+ return self.string > other.string # Inversion de la comparaison
258
+
259
+ def __eq__(self, other):
260
+ """
261
+ Égalité standard entre chaînes.
262
+
263
+ :pxs_trigger: égalité interne ReverseString
264
+ :pxs_returns: |
265
+ bool : True si les deux chaînes encapsulées sont identiques.
266
+ :pxs_example: |
267
+ ReverseString("x") == ReverseString("x") # True
268
+ :pxs_antipattern: Appeler __eq__ directement au lieu d'utiliser ==.
269
+ """
270
+ return self.string == other.string
271
+
272
+ class pxs_Poly(Poly):
273
+ """
274
+ Extension de la classe Poly de SymPy avec une méthode d'affichage personnalisée.
275
+ Permet d'afficher les polynômes avec un formatage LaTeX personnalisé et une factorisation optionnelle.
276
+
277
+ :pxs_trigger: polynôme pédagogique, trinôme second degré, affichage LaTeX polynôme, discriminant racines factorisation
278
+ :pxs_returns: |
279
+ Classe héritant de sympy.Poly, avec méthodes pxsl_print, pxsl_discriminant,
280
+ pxsl_solution, pxs_factor et pxs_generate pour usage pédagogique en MyST.
281
+ :pxs_example: |
282
+ p = pxs_Poly(x**2 + 3*x - 4, x)
283
+ # Dans MyST : $P(x) = \\py{p.pxsl_print()}$
284
+ :pxs_antipattern: Utiliser sympy.Poly puis latex() et écrire à la main le calcul du discriminant ou des racines.
285
+ """
286
+
287
+ @classmethod
288
+ def pxs_generate(cls, x = Symbol("x"), lim_coeff = 9, nb_root = None):
289
+ """
290
+ Génère un polynôme du second degré avec des coefficients aléatoires non nuls,
291
+ en contrôlant optionnellement le nombre de racines réelles.
292
+
293
+ Args:
294
+ x: Variable symbolique du polynôme (par défaut Symbol("x"))
295
+ lim_coeff: Valeur maximale absolue des coefficients (par défaut 9)
296
+ nb_root: Nombre de racines réelles souhaité (0, 1, 2 ou None pour aléatoire)
297
+
298
+ Returns:
299
+ Un objet pxs_Poly représentant le polynôme ax² + bx + c généré
300
+
301
+ :pxs_trigger: générer trinôme aléatoire, exercice second degré avec n racines, discriminant positif/négatif/nul contrôlé
302
+ :pxs_returns: |
303
+ Un objet pxs_Poly de la forme ax² + bx + c avec a, b, c entiers
304
+ non nuls, et discriminant contrôlé selon nb_root (0, 1, 2 ou aléatoire).
305
+ :pxs_example: |
306
+ p = pxs_Poly.pxs_generate(nb_root=2)
307
+ # Trinôme à 2 racines réelles distinctes, coeffs dans [-9,9]\\{0}
308
+ # Dans MyST : $P(x) = \\py{p.pxsl_print()}$
309
+ :pxs_antipattern: Tirer a, b, c au hasard avec random.randint puis vérifier le signe du discriminant dans une boucle while.
310
+ """
311
+ # Génération aléatoire des signes pour chaque coefficient
312
+ sign_coeff = [rd.choice([-1,1]), rd.choice([-1,1]), rd.choice([-1,1])]
313
+
314
+ # Génération des coefficients a, b, c (tous non nuls)
315
+ # Valeurs entre 1 et lim_coeff, multipliées par leur signe
316
+ a = sign_coeff[0] * rd.randint(1, lim_coeff)
317
+ b = sign_coeff[1] * rd.randint(1, lim_coeff)
318
+ c = sign_coeff[2] * rd.randint(1, lim_coeff)
319
+
320
+ # Création du polynôme initial
321
+ p = Poly(a * x**2 + b * x + c, x)
322
+
323
+ # Si aucune contrainte sur le nombre de racines, retourner le polynôme tel quel
324
+ if nb_root is None:
325
+ return p
326
+
327
+ # CAS 1 : On veut 0 racine réelle (Δ < 0)
328
+ # Condition : b² < 4ac, donc a et c doivent être de même signe
329
+ if nb_root == 0 and p.discriminant() >= 0:
330
+ # Forcer a et c à avoir le même signe (on utilise sign[0] pour les deux)
331
+ c = sign_coeff[0] * rd.randint(1,9)
332
+ # Choisir b tel que b < 2√(ac) pour garantir Δ < 0
333
+ b = sign_coeff[1] * rd.randint(1, int(2 * m.sqrt(a * c)-1))
334
+
335
+ # CAS 2 : On veut 1 racine double (Δ = 0)
336
+ # Condition : b² = 4ac, donc b = ±2√(ac)
337
+ if nb_root == 1 and p.discriminant() != 0:
338
+ # Pour faciliter, on choisit a et c comme des carrés parfaits
339
+ a = sign_coeff[0] * rd.randint(1, int(m.sqrt(lim_coeff)))**2
340
+ c = sign_coeff[0] * rd.randint(1, int(m.sqrt(lim_coeff)))**2
341
+
342
+ # Vérifier qu'on ne dépasse pas la limite des coefficients
343
+ if a >= lim_coeff and c >= lim_coeff:
344
+ # Si les deux sont trop grands, prendre des valeurs égales plus petites
345
+ a = sign_coeff[0] * rd.randint(1, lim_coeff)
346
+ c = a
347
+
348
+ # Calculer b pour avoir exactement Δ = 0
349
+ b = rd.choice([-1,1]) * int(2 * m.sqrt(a * c))
350
+
351
+ # CAS 3 : On veut 2 racines distinctes (Δ > 0)
352
+ # Condition : b² > 4ac, donc c < b²/(4a)
353
+ if nb_root == 2 and p.discriminant() <= 0 :
354
+ # Choisir c dans l'intervalle qui garantit Δ > 0
355
+ # c doit être inférieur à b²/(4a) - 1 pour avoir une marge
356
+ c = sign_coeff[2] * rd.randint(-lim_coeff, min(int(b**2 / (4 * a)) - 1, lim_coeff))
357
+
358
+ # S'assurer que c n'est pas nul (tous les coefficients doivent être non nuls)
359
+ while c == 0:
360
+ c = sign_coeff[0] * rd.randint(-lim_coeff, int(b**2 / (4 * a)) - 1)
361
+
362
+ # Retourner le polynôme avec les coefficients ajustés
363
+ return cls(a * x**2 + b * x + c, x)
364
+
365
+ def pxsl_print(self, variable=None, ascending=False, displaystyle=True, factor=False):
366
+ """
367
+ Affiche le polynôme avec un formatage LaTeX personnalisé.
368
+
369
+ Paramètres:
370
+ - variable: Variable principale pour l'organisation/factorisation (None = auto-détection)
371
+ - ascending: Si True, trie par puissances croissantes, sinon décroissantes
372
+ - displaystyle: Si True, utilise le style d'affichage LaTeX étendu
373
+ - factor: Si True, factorise le polynôme par rapport à la variable spécifiée
374
+
375
+ Retourne:
376
+ - String: Expression LaTeX formatée
377
+
378
+ :pxs_trigger: afficher polynôme pédagogique, ordre puissances croissantes/décroissantes, factoriser par variable, polynôme deux variables
379
+ :pxs_returns: |
380
+ Chaîne LaTeX (str) représentant le polynôme avec termes triés selon
381
+ 'variable' et 'ascending', coefficients 1/-1 simplifiés, et
382
+ optionnellement factorisé par 'variable' si factor=True.
383
+ :pxs_example: |
384
+ p = pxs_Poly(3*x*y - x**2 + y**2 + x + 2)
385
+ # Dans MyST : $P = \\py{p.pxsl_print(variable=x)}$
386
+ # Avec factor=True : $P = \\py{p.pxsl_print(variable=x, factor=True)}$
387
+ :pxs_antipattern: Utiliser latex(poly.as_expr()) qui trie mal les termes multi-variables et n'offre pas la factorisation par variable.
388
+ """
389
+
390
+ def is_numeric_key(key):
391
+ """
392
+ Vérifie si une clé est numérique (pour filtrer les constantes).
393
+ Utilisée pour séparer les variables des constantes numériques.
394
+ """
395
+ try:
396
+ float(key)
397
+ return True
398
+ except (ValueError, TypeError):
399
+ return False
400
+
401
+ # Convertir le polynôme en expression SymPy
402
+ expr = self.as_expr()
403
+
404
+ # Auto-détection de la variable si non spécifiée
405
+ if variable is None:
406
+ variables = sorted(expr.free_symbols, key=str)
407
+ if not variables:
408
+ return latex(expr) # Retourne directement si pas de variables
409
+ else:
410
+ variables = variable
411
+
412
+ # MODE FACTORISATION : traitement spécial quand factor=True
413
+ if factor and variable is not None:
414
+ # Utilise la fonction collect() de SymPy pour factoriser par la variable
415
+ factored_expr = collect(expr, variable)
416
+
417
+ # Dictionnaire pour organiser les termes par puissance de la variable
418
+ terms_by_power = {}
419
+ constant_terms = [] # Termes qui ne contiennent pas la variable
420
+
421
+ # Analyser chaque terme de l'expression factorisée
422
+ for term in Add.make_args(factored_expr):
423
+ if term.has(variable):
424
+ # Trouver la puissance de la variable dans ce terme
425
+ power = 0
426
+ coeff = term
427
+
428
+ # Recherche de la puissance (de 10 à 1 pour prendre la plus haute)
429
+ for p in range(10, 0, -1):
430
+ c = term.coeff(variable, p) # Coefficient de variable^p
431
+ if c != 0:
432
+ power = p
433
+ coeff = c
434
+ break
435
+
436
+ # Stocker le coefficient pour cette puissance
437
+ if power > 0:
438
+ terms_by_power[power] = coeff
439
+ else:
440
+ # Terme constant (ne contient pas la variable)
441
+ constant_terms.append(term)
442
+
443
+ # Construction de l'affichage avec la variable APRÈS le coefficient
444
+ result_terms = []
445
+
446
+ # Traiter les termes par puissance décroissante
447
+ for power in sorted(terms_by_power.keys(), reverse=True):
448
+ coeff = terms_by_power[power]
449
+
450
+ if power == 1:
451
+ # Cas spécial : puissance 1 (pas d'exposant affiché)
452
+ if coeff == 1:
453
+ result_terms.append(f"{latex(variable)}")
454
+ elif coeff == -1:
455
+ result_terms.append(f"-{latex(variable)}")
456
+ else:
457
+ coeff_str = latex(coeff)
458
+ # Ajouter des parenthèses si le coefficient est complexe
459
+ if len(str(coeff).split()) > 1 or '+' in coeff_str or '-' in coeff_str[1:]:
460
+ result_terms.append(f"({coeff_str}){latex(variable)}")
461
+ else:
462
+ result_terms.append(f"{coeff_str}{latex(variable)}")
463
+ else:
464
+ # Puissances supérieures à 1
465
+ if coeff == 1:
466
+ result_terms.append(f"{latex(variable)}^{{{power}}}")
467
+ elif coeff == -1:
468
+ result_terms.append(f"-{latex(variable)}^{{{power}}}")
469
+ else:
470
+ coeff_str = latex(coeff)
471
+ # Ajouter des parenthèses si le coefficient est complexe
472
+ if len(str(coeff).split()) > 1 or '+' in coeff_str or '-' in coeff_str[1:]:
473
+ result_terms.append(f"({coeff_str}){latex(variable)}^{{{power}}}")
474
+ else:
475
+ result_terms.append(f"{coeff_str}{latex(variable)}^{{{power}}}")
476
+
477
+ # Ajouter les termes constants à la fin
478
+ for term in constant_terms:
479
+ result_terms.append(latex(term))
480
+
481
+ # Assemblage final avec gestion des signes
482
+ if not result_terms:
483
+ return "0"
484
+
485
+ result = result_terms[0]
486
+ for term in result_terms[1:]:
487
+ if term.startswith('-'):
488
+ result += term # Pas de '+' avant un terme négatif
489
+ else:
490
+ result += f"+{term}"
491
+
492
+ return result
493
+
494
+ # MODE NORMAL : affichage standard sans factorisation
495
+ terms = []
496
+
497
+ # Analyser chaque terme de l'expression pour extraire puissances et coefficients
498
+ for term in Add.make_args(expr):
499
+ power = 0 # Puissance de la variable principale (0 pour les constantes)
500
+ rest = 1 # Coefficient/reste du terme
501
+
502
+ # Traitement quand aucune variable n'est spécifiée (auto-détection)
503
+ if variable is None:
504
+ powers = 0 # Somme de toutes les puissances du terme (pour le tri)
505
+ entire_power_dict = term.as_powers_dict()
506
+
507
+ # Filtrer les clés numériques (constantes)
508
+ keys_to_remove = []
509
+ for key in entire_power_dict.keys():
510
+ try:
511
+ float(key)
512
+ keys_to_remove.append(key)
513
+ except (ValueError, TypeError):
514
+ pass # La clé n'est pas numérique, on la garde
515
+
516
+ # Créer un dictionnaire sans les constantes numériques
517
+ power_dict = {k: v for k, v in entire_power_dict.items() if not is_numeric_key(k)}
518
+
519
+ try:
520
+ # Choisir la variable "principale" (la plus grande alphabétiquement)
521
+ variable = max(power_dict.keys())
522
+ power = power_dict[variable]
523
+ rest = term / (variable ** power) if variable else term
524
+ except (ValueError, TypeError):
525
+ # Pas de variable trouvée, c'est un terme constant
526
+ variable = None
527
+ rest = term
528
+
529
+ # Calculer la somme totale des puissances pour le tri
530
+ powers = sum(power_dict.values())
531
+ terms.append((powers, power, variable, False, rest))
532
+ variable = None # Reset pour le prochain terme
533
+
534
+ else:
535
+ # Variable spécifiée : analyser chaque facteur du terme
536
+ for factor in Mul.make_args(term):
537
+ if factor.has(variable):
538
+ # Ce facteur contient la variable
539
+ power_dict = factor.as_powers_dict()
540
+ power = power_dict[variable]
541
+ # Diviser par la variable à la puissance pour isoler le coefficient
542
+ rest *= factor / (variable ** power)
543
+ else:
544
+ # Ce facteur ne contient pas la variable, c'est part du coefficient
545
+ rest *= factor
546
+
547
+ # Déterminer si le terme contient d'autres variables (pour le tri)
548
+ if variable is not None:
549
+ has_other_var = False
550
+ if len(expr.free_symbols) > 1:
551
+ # Vérifie si le coefficient contient d'autres variables
552
+ has_other_var = len(rest.free_symbols) > 0
553
+
554
+ terms.append((power, power, variable, has_other_var, rest))
555
+
556
+ # TRI DES TERMES selon les paramètres spécifiés
557
+ if variable is None:
558
+ # Tri global par somme des puissances, puis par puissance individuelle, puis par nom de variable
559
+ if ascending:
560
+ terms.sort(key=lambda x: (x[0], x[1], ReverseString(str(x[2]))))
561
+ else:
562
+ terms.sort(key=lambda x: (x[0], x[1], ReverseString(str(x[2]))), reverse=True)
563
+ else:
564
+ # Tri par puissance de la variable spécifiée
565
+ if ascending:
566
+ # Ordre croissant des puissances, termes avec autres variables après
567
+ terms.sort(key=lambda x: (x[1], x[3]))
568
+ else:
569
+ # Ordre décroissant des puissances, termes avec autres variables après
570
+ terms.sort(key=lambda x: (x[1], x[3]), reverse=True)
571
+
572
+ # CONSTRUCTION DE L'EXPRESSION LATEX FINALE
573
+ result = ""
574
+
575
+ for i, (powers, power, variable, has_other_var, coeff) in enumerate(terms):
576
+ # Analyse du coefficient pour la gestion des signes
577
+ is_negative = latex(coeff).startswith('-')
578
+
579
+ # Vérification si le coefficient est +1 ou -1 (pour simplifier l'affichage)
580
+ try:
581
+ is_One = coeff == 1
582
+ except TypeError:
583
+ is_One = False
584
+ try:
585
+ is_minus_One = coeff == -1
586
+ except TypeError:
587
+ is_minus_One = False
588
+
589
+ # CONSTRUCTION DU TERME selon sa puissance
590
+ if power == 0:
591
+ # Terme constant (pas de variable)
592
+ term = f"{latex(coeff)}"
593
+ elif power == 1:
594
+ # Puissance 1 (variable sans exposant)
595
+ if is_One:
596
+ term = f"{latex(variable)}"
597
+ elif is_minus_One:
598
+ term = f"-{latex(variable)}"
599
+ else:
600
+ if displaystyle:
601
+ term = f"\\displaystyle {latex(coeff)}{latex(variable)}"
602
+ else:
603
+ term = f"{latex(coeff)}{latex(variable)}"
604
+ else:
605
+ # Puissances supérieures à 1
606
+ if is_One:
607
+ term = f"{latex(variable)}^{power}"
608
+ elif is_minus_One:
609
+ term = f"-{latex(variable)}^{power}"
610
+ else:
611
+ if displaystyle:
612
+ term = f"\\displaystyle {latex(coeff)}{latex(variable)}^{power}"
613
+ else:
614
+ term = f"{latex(coeff)}{latex(variable)}^{power}"
615
+
616
+ # GESTION DES SIGNES pour l'assemblage final
617
+ if i == 0 or is_negative:
618
+ # Premier terme ou terme négatif : pas de '+' devant
619
+ result += term
620
+ else:
621
+ # Terme positif : ajouter un '+'
622
+ result += f" +{term}"
623
+
624
+ # Retourner l'expression LaTeX complète
625
+ return result
626
+
627
+ def pxsl_discriminant(self, mult = "\\times", formula = True):
628
+ """
629
+ Calcule et affiche le discriminant d'une équation du second degré au format LaTeX.
630
+
631
+ Args:
632
+ mult: Symbole de multiplication à utiliser (par défaut \times en LaTeX)
633
+
634
+ Returns:
635
+ Un objet myst contenant l'affichage LaTeX du calcul du discriminant
636
+
637
+ :pxs_trigger: calcul discriminant, Delta = b²-4ac, étapes substitution trinôme, exercice second degré
638
+ :pxs_returns: |
639
+ Objet myst contenant le calcul multi-lignes du discriminant au
640
+ format LaTeX aligné (utilisable dans un environnement equation*+split),
641
+ avec ou sans la formule littérale Δ = b²-4ac en première ligne.
642
+ :pxs_example: |
643
+ p = pxs_Poly(x**2 - 5*x + 6, x)
644
+ calc = p.pxsl_discriminant()
645
+ # Dans MyST :
646
+ # \\begin{equation*}\\begin{split}
647
+ # \\py{calc}
648
+ # \\end{split}\\end{equation*}
649
+ :pxs_antipattern: Écrire à la main "\\Delta = b^2-4ac = {b**2} - 4*{a}*{c} = ..." avec f-strings et risquer les signes négatifs mal parenthésés.
650
+ """
651
+ # Récupération de tous les coefficients de l'équation (a, b, c)
652
+ coeffs = self.all_coeffs()
653
+
654
+ # Génération de l'affichage LaTeX du calcul du discriminant
655
+ # avec les étapes de substitution et de calcul
656
+ if formula:
657
+ return myst(r"""
658
+ \Delta &= b^2-4ac\\
659
+ &= \py{pxsl_pow(coeffs[1],2)} - 4 \py{mult}\py{pxsl_pow(coeffs[0],1)} \py{mult}\py{pxsl_pow(coeffs[2],1)}\\
660
+ &=\py{latex(self.discriminant())}"""
661
+ ,globals(), locals())
662
+ else:
663
+ return myst(r"""
664
+ \Delta &= \py{pxsl_pow(coeffs[1],2)} - 4 \py{mult}\py{pxsl_pow(coeffs[0],1)} \py{mult}\py{pxsl_pow(coeffs[2],1)}\\
665
+ &=\py{latex(self.discriminant())}"""
666
+ ,globals(), locals())
667
+
668
+ def pxsl_solution(self, mult = "\\times", formula = True):
669
+ """
670
+ Affiche la ou les solutions d'une équation du second degré au format LaTeX.
671
+
672
+ Args:
673
+ mult: Symbole de multiplication à utiliser (par défaut \times en LaTeX)
674
+
675
+ Returns:
676
+ Un tuple de 4 éléments (x1_complet, x2_complet, x1_final, x2_final) où :
677
+ - x1_complet, x2_complet : calculs détaillés étape par étape
678
+ - x1_final, x2_final : formes finales simplifiées
679
+ Retourne (None, None, None, None) si pas de solution réelle
680
+
681
+ :pxs_trigger: résoudre équation second degré, racines trinôme, x1 x2, formule (-b±√Δ)/2a, solution double
682
+ :pxs_returns: |
683
+ Tuple (x_1_complet, x_2_complet, x_1_final, x_2_final) d'objets myst :
684
+ les deux premiers contiennent le calcul détaillé étape par étape,
685
+ les deux derniers la forme simplifiée finale. Si Δ=0, les deux
686
+ solutions sont égales. Si Δ<0, retourne (None, None, None, None).
687
+ :pxs_example: |
688
+ p = pxs_Poly.pxs_generate(nb_root=2)
689
+ expr_x1, expr_x2, x1, x2 = p.pxsl_solution()
690
+ # Dans MyST :
691
+ # $x_1 = \\py{expr_x1}$, $x_2 = \\py{expr_x2}$
692
+ # Finalement : $x_1 = \\py{x1}$ et $x_2 = \\py{x2}$
693
+ :pxs_antipattern: Calculer sqrt(disc) puis composer une f-string "-b - sqrt(D) / 2a" à la main, en oubliant la simplification des fractions ou la réduction de √Δ.
694
+ """
695
+ # Récupération de tous les coefficients de l'équation (a, b, c)
696
+ coeffs = self.all_coeffs()
697
+
698
+ # Vérifier si le discriminant peut être simplifié (contient des facteurs carrés)
699
+ factors = factorint(self.discriminant())
700
+ is_reducible = False
701
+ for prime, power in factors.items():
702
+ if power >= 2:
703
+ is_reducible = True
704
+
705
+ # Préparer l'affichage des coefficients avec parenthèses si négatifs
706
+ if self.discriminant() >= 0:
707
+ coeff_fin = [pxsl_pow(coeff, 1) for coeff in coeffs]
708
+
709
+ # CAS 1 : Discriminant strictement positif (2 solutions distinctes)
710
+ if self.discriminant() > 0:
711
+ # Calcul détaillé de x1 = (-b - √Δ) / 2a
712
+ if formula:
713
+ x_1 = myst(r""" \displaystyle{\frac{-b-\sqrt{\Delta}}{2a}}=\displaystyle{\frac{-\py{coeff_fin[1]}-\sqrt{\py{self.discriminant()}}}{2\py{mult}\py{coeff_fin[0]}}}=\displaystyle{\frac{\py{-coeffs[1]}-\py{latex(sqrt(self.discriminant()))}}{\py{2*coeffs[0]}}}""",globals(), locals())
714
+ else:
715
+ x_1 = myst(r""" \displaystyle{\frac{-\py{coeff_fin[1]}-\sqrt{\py{self.discriminant()}}}{2\py{mult}\py{coeff_fin[0]}}}=\displaystyle{\frac{\py{-coeffs[1]}-\py{latex(sqrt(self.discriminant()))}}{\py{2*coeffs[0]}}}""",globals(), locals())
716
+
717
+ # Calcul détaillé de x2 = (-b + √Δ) / 2a
718
+ if formula:
719
+ x_2 = myst(r""" \displaystyle{\frac{-b+\sqrt{\Delta}}{2a}}=\displaystyle{\frac{-\py{coeff_fin[1]}+\sqrt{\py{self.discriminant()}}}{2\py{mult}\py{coeff_fin[0]}}}=\displaystyle{\frac{\py{-coeffs[1]}+\py{latex(sqrt(self.discriminant()))}}{\py{2*coeffs[0]}}}""",globals(), locals())
720
+ else:
721
+ x_2 = myst(r""" \displaystyle{\frac{-\py{coeff_fin[1]}+\sqrt{\py{self.discriminant()}}}{2\py{mult}\py{coeff_fin[0]}}}=\displaystyle{\frac{\py{-coeffs[1]}+\py{latex(sqrt(self.discriminant()))}}{\py{2*coeffs[0]}}}""",globals(), locals())
722
+
723
+ # Si √Δ est un entier (carré parfait), calculer directement les fractions
724
+ if isinstance(sqrt(self.discriminant()),Integer) or isinstance(sqrt(self.discriminant()),Rational):
725
+ x_1 += myst(r""" =\displaystyle{\frac{\py{latex(-coeffs[1]-sqrt(self.discriminant()))}}{\py{2*coeffs[0]}}}""",globals(), locals())
726
+ x_1final = myst(r"""\displaystyle{\py{latex(Rational(-coeffs[1]-sqrt(self.discriminant()),2*coeffs[0]))}} """,globals(), locals())
727
+ x_2 += myst(r""" =\displaystyle{\frac{\py{latex(-coeffs[1]+sqrt(self.discriminant()))}}{\py{2*coeffs[0]}}}""",globals(), locals())
728
+ x_2final = myst(r"""\displaystyle{\py{latex(Rational(-coeffs[1]+sqrt(self.discriminant()),2*coeffs[0]))}} """,globals(), locals())
729
+ return x_1 + myst(r"""= """) + x_1final, x_2 + myst(r""" = """) + x_2final, x_1final, x_2final
730
+
731
+ # Si √Δ n'est pas un entier, essayer de simplifier l'expression
732
+ else:
733
+ # Si a > 0 et qu'on peut simplifier (PGCD ou racine réductible)
734
+ if coeffs[0] > 0 and (gcd(-coeffs[1],2*coeffs[0]) != 1 or is_reducible):
735
+ # Séparer la partie rationnelle et la partie irrationnelle
736
+ x_1final = myst(r"""\displaystyle{\py{latex(Rational(-coeffs[1],2*coeffs[0]))}-\py{latex(sqrt(self.discriminant())/(2*coeffs[0]))}}""", globals(), locals())
737
+ x_2final = myst(r"""\displaystyle{\py{latex(Rational(-coeffs[1],2*coeffs[0]))}+\py{latex(sqrt(self.discriminant())/(2*coeffs[0]))}}""", globals(), locals())
738
+ return x_1 + myst(r"""=""") + x_1final, x_2 + myst(r"""=""") + x_2final, x_1final, x_2final
739
+
740
+ # Si a < 0, ajuster les signes pour un affichage plus propre
741
+ elif coeffs[0] < 0 :
742
+ x_1final = myst(r"""\displaystyle{\py{latex(Rational(-coeffs[1],2*coeffs[0]))}+\py{latex(sqrt(self.discriminant())/(-2*coeffs[0]))}}""", globals(), locals())
743
+ x_2final = myst(r"""\displaystyle{\py{latex(Rational(-coeffs[1],2*coeffs[0]))}-\py{latex(sqrt(self.discriminant())/(-2*coeffs[0]))}}""", globals(), locals())
744
+ return x_1 + myst(r"""= """) + x_1final, x_2 + myst(r"""= """) + x_2final, x_1final, x_2final
745
+
746
+ # Cas par défaut : garder la forme fractionnaire complète
747
+ else:
748
+ x_1final = myst(r"""\displaystyle{\frac{\py{-coeffs[1]}-\py{latex(sqrt(self.discriminant()))}}{\py{2*coeffs[0]}}}""",globals(), locals())
749
+ x_2final = myst(r"""\displaystyle{\frac{\py{-coeffs[1]}+\py{latex(sqrt(self.discriminant()))}}{\py{2*coeffs[0]}}}""",globals(), locals())
750
+ return x_1, x_2, x_1final, x_2final
751
+
752
+ # CAS 2 : Discriminant nul (1 solution double)
753
+ if self.discriminant() == 0:
754
+ # Calcul détaillé de x0 = -b / 2a
755
+ x_0 = myst(r""" \displaystyle{\frac{-b}{2a}}=\displaystyle{\frac{-\py{coeff_fin[1]}}{2\py{mult}\py{coeff_fin[0]}}}=\displaystyle{\frac{\py{-coeffs[1]}}{\py{2*coeffs[0]}}}""",globals(), locals())
756
+
757
+ # Si on peut simplifier la fraction (PGCD > 1 ou a < 0)
758
+ if coeffs[0] > 0 and gcd(-coeffs[1],2*coeffs[0]) != 1:
759
+ x_0final = myst(r"""\displaystyle{\py{latex(Rational(-coeffs[1],2*coeffs[0]))}}""", globals(), locals())
760
+ return x_0 + myst(r"""= """) + x_0final, x_0 + myst(r"""= """) + x_0final, x_0final, x_0final
761
+ elif coeffs[0] < 0 :
762
+ x_0final = myst(r"""\displaystyle{\py{latex(Rational(-coeffs[1],2*coeffs[0]))}}""", globals(), locals())
763
+ return x_0 + myst(r"""= """) + x_0final, x_0 + myst(r"""= """) + x_0final, x_0final, x_0final
764
+
765
+ # Cas par défaut : garder la forme fractionnaire
766
+ else:
767
+ x_0final = myst(r"""\displaystyle{\frac{\py{-coeffs[1]}}{\py{2*coeffs[0]}}}""",globals(), locals())
768
+ return x_0, x_0, x_0final, x_0final
769
+
770
+ # CAS 3 : Discriminant négatif (pas de solution réelle)
771
+ if self.discriminant() < 0:
772
+ return None, None, None, None
773
+
774
+ def pxs_factor(self, variable = None, display = "\displaystyle"):
775
+ """
776
+ Factorise un polynôme en utilisant sympy.Poly.
777
+ Prend un objet Poly en argument.
778
+
779
+ :pxs_trigger: factoriser polynôme par variable dominante, mise en facteur x^n, x²(1 + 1/x + 1/x²), factorisation forcée par plus haut degré
780
+ :pxs_returns: |
781
+ Tuple (myst_expr, factor, term) :
782
+ - myst_expr : chaîne LaTeX "x^n (1 + a/x + ... )" prête à injecter en MyST
783
+ - factor : expression sympy du facteur sorti (variable ** degré)
784
+ - term : expression sympy du contenu entre parenthèses
785
+ :pxs_example: |
786
+ p = pxs_Poly(3*x**2 + 2*x + 1, x)
787
+ expr, fact, term = p.pxs_factor(variable=x)
788
+ # Dans MyST : $P = \\py{expr}$ → $x^2(3 + 2/x + 1/x^2)$
789
+ :pxs_antipattern: Utiliser sympy.factor() qui cherche une factorisation complète sur Q, ou construire la mise en facteur de x^n à la main avec des f-strings.
790
+ """
791
+
792
+ # Récupérer la variable (premier générateur)
793
+ if variable is None and len(self.gens) != 1:
794
+ raise ValueError("Il faut spécifier une variable pour factoriser un polynôme à plusieurs variables")
795
+ if variable is None:
796
+ variable = self.gens[0] # si variable n'est précisé c'est qu'il n'y en a qu'une, on la récupère
797
+
798
+ p = pxs_Poly(self, variable)
799
+
800
+ # Récupérer tous les coefficients (SymPy gère automatiquement l'ordre)
801
+ coeffs = p.all_coeffs() # Coefficients dans l'ordre décroissant des puissances
802
+ degree_poly = p.degree()
803
+
804
+ if degree_poly == 0:
805
+ return str(coeffs[0])
806
+
807
+ # renvoyer le même terme si y en a qu'un
808
+
809
+ # Construire la factorisation
810
+ factorized_form = myst(r"""""")
811
+ term = 0
812
+
813
+ # Parcourir tous les coefficients depuis la plus haute puissance
814
+ for i, coeff in enumerate(coeffs):
815
+ if coeff == 0:
816
+ continue
817
+ current_power = degree_poly - i
818
+
819
+ # Coefficient relatif au terme principal
820
+ power_diff = degree_poly - current_power
821
+
822
+ # Gestion du signe
823
+ try:
824
+ if coeff > 0 and i != 0:
825
+ sign_coeff = "+"
826
+ else:
827
+ sign_coeff = ""
828
+ except:
829
+ coeff_str = str(coeff)
830
+ if i != 0 and not coeff_str.startswith('-'):
831
+ sign_coeff = "+"
832
+ else:
833
+ sign_coeff = ""
834
+
835
+ # Formatage selon la différence de puissance
836
+ if i == 0:
837
+ term +=coeff
838
+ factorized_form += myst(r"""\py{latex(coeff)}""", globals(), locals())
839
+ continue
840
+ if power_diff == 1:
841
+ term += coeff/variable
842
+ # Division par variable
843
+ if coeff == 1:
844
+ factorized_form += myst(r"""\py{sign_coeff}\py{display}\py{latex(1/variable)}""", globals(), locals())
845
+ elif coeff == -1:
846
+ factorized_form += myst(r"""-\py{display}\py{latex(1/variable)}""", globals(), locals())
847
+ else:
848
+ factorized_form += myst(r"""\py{sign_coeff} \py{display}\py{latex(coeff/variable)}""", globals(), locals())
849
+ else:
850
+ term += coeff/(variable**power_diff)
851
+ # Division par variable^power_diff
852
+ if coeff == 1:
853
+ factorized_form += myst(r"""\py{sign_coeff}\py{display}\py{latex(1/variable**power_diff)}""", globals(), locals())
854
+ elif coeff == -1:
855
+ factorized_form += myst(r"""-\py{display}\py{latex(1/variable**power_diff)}""", globals(), locals())
856
+ else:
857
+ factorized_form += myst(r"""\py{sign_coeff}\py{display}\py{latex(coeff/variable**power_diff)}""", globals(), locals())
858
+
859
+ # Construire le facteur principal
860
+ factor = variable**degree_poly
861
+ factor_latex = myst(r"""\py{pxsl_pow(variable, degree_poly)}""", globals(), locals())
862
+
863
+ return myst(r"""\py{factor_latex}\left(\py{factorized_form}\right) """, globals(), locals()), factor, term
864
+
865
+ """ X = Symbol('X')
866
+ y = Symbol('y')
867
+ x = Symbol('x')
868
+ poly = pxs_Poly(3*x**4*y**2+Rational(2,3)*x**2*y+3, x)
869
+ poly2 = pxs_Poly(3*x**4*y**2+Rational(2,3)*x**2*y+3)
870
+
871
+ p1 = pxs_Poly.pxs_generate(nb_root = 2)
872
+ p2 = pxs_Poly.pxs_generate(nb_root = 1)
873
+ p3 = pxs_Poly.pxs_generate(nb_root = 0)
874
+
875
+ expr1 = pxs_Poly(1 + x + x**2)
876
+ expr2 = pxs_Poly(3*x**2 - 5*x + 7 - 2*x**3)
877
+ expr3 = pxs_Poly(3*x*y - x**2 + y**2 + x + 2)
878
+ expr4 = pxs_Poly(x/2 - x**2/3 + 5)
879
+ expr5 = pxs_Poly(3*X*y + 2*X**2 + y**2 + X + 2)
880
+ expr6 = pxs_Poly(3*x**4*y**2+Rational(2,3)*x**2 +x**2*y+3,x)
881
+
882
+ poly = pxs_Poly.pxs_generate(nb_root = 2)
883
+ [expr_x1, expr_x2, x1, x2] = poly.pxsl_solution()
884
+ poly = pxs_Poly.pxs_generate(nb_root = 1)
885
+ [expr_x0, expr_x0, x0, x0] = poly.pxsl_solution()
886
+
887
+ \end{python}
888
+
889
+ Méthode pxs_generate(cls, x = Symbol("x"), lim_coeff = 9, nb_root = None)
890
+
891
+ $\py{latex(pxs_Poly.pxs_generate().as_expr())}$
892
+
893
+ $\py{latex(pxs_Poly.pxs_generate(y).as_expr())}$
894
+
895
+ Modifier la limite des coefficients : $\py{latex(pxs_Poly.pxs_generate(lim_coeff = 2).as_expr())}$
896
+
897
+ 2 racines : $\py{latex(p1.as_expr())}$ $\longrightarrow$ $\Delta = \py{p1.discriminant()}$
898
+
899
+ 1 racine : $\py{latex(p2.as_expr())}$ $\longrightarrow$ $\Delta = \py{p2.discriminant()}$
900
+
901
+ 0 racine : $\py{latex(p3.as_expr())}$ $\longrightarrow$ $\Delta = \py{p3.discriminant()}$
902
+
903
+ ________________________________________________
904
+
905
+ Méthode pxsl_print(self, variable=None, ascending=False, displaystyle=True, factor = False)
906
+
907
+ expr1: $\py{expr1.pxsl_print()}$
908
+
909
+ expr1 en ordre croissant: $\py{expr1.pxsl_print(ascending = True)}$
910
+
911
+ expr2: $\py{expr2.pxsl_print()}$
912
+
913
+ expr3: $\py{expr3.pxsl_print()}$
914
+
915
+ Par rapport à x : $\py{expr3.pxsl_print(variable = x)}$
916
+
917
+ Par rapport à y : $\py{expr3.pxsl_print(variable = y)}$
918
+
919
+ expr4: $\py{expr4.pxsl_print()}$
920
+
921
+ expr4, sans displaystyle: $\py{expr4.pxsl_print(displaystyle = False)}$
922
+
923
+ expr5: $\py{expr5.pxsl_print()}$
924
+
925
+ Par rapport à X : $\py{expr5.pxsl_print(variable = X)}$
926
+
927
+ expr6, Forme développée : $\py{expr6.pxsl_print(factor=False, variable=x)}$
928
+
929
+ expr6, Forme factorisée en x : $\py{expr6.pxsl_print(factor=True, variable=x)}$
930
+ _________________________________________________________
931
+
932
+ Méthode pxsl_discriminant(self, mult = "\\times")
933
+
934
+ expr1:
935
+ \begin{equation*}
936
+ \begin{split}
937
+ \py{expr1.pxsl_discriminant()}
938
+ \end{split}
939
+ \end{equation*}
940
+
941
+ expr4:
942
+ \begin{equation*}
943
+ \begin{split}
944
+ \py{expr4.pxsl_discriminant()}
945
+ \end{split}
946
+ \end{equation*}
947
+
948
+ en modifiant le signe multiplié :
949
+ \begin{equation*}
950
+ \begin{split}
951
+ \py{expr4.pxsl_discriminant("\cdot")}
952
+ \end{split}
953
+ \end{equation*}
954
+ _____________________________________________________________
955
+
956
+ Méthode pxsl_solution(self, mult = "\\times")
957
+
958
+ 2 racines :
959
+
960
+ \begin{equation*}
961
+ x_1 = \py{expr_x1}
962
+ \end{equation*}
963
+ et
964
+ \begin{equation*}
965
+ x_2 = \py{expr_x2}.
966
+ \end{equation*}
967
+
968
+ \begin{equation*}
969
+ x_1 =\py{x1}\textrm{ et }x_2 = \py{x2}.
970
+ \end{equation*}
971
+
972
+ 1 racine :
973
+
974
+ \begin{equation*}
975
+ x_0 = \py{expr_x0}
976
+ \end{equation*}
977
+
978
+ \begin{equation*}
979
+ x_0 =\py{x0}.
980
+ \end{equation*}
981
+ ____________________________________________________________
982
+
983
+ Méthode pxs_factor(self, variable = None, display = "\displaystyle")
984
+
985
+ expr1 : $\py{expr1.pxs_factor()[0]}$
986
+
987
+ factor : $\py{latex(expr1.pxs_factor(variable = x)[1])}$
988
+
989
+ term : $\py{latex(expr1.pxs_factor(variable = x)[2])}$
990
+
991
+ expr3: $\py{expr3.pxsl_print()}$
992
+
993
+ expr3 par rapport à $x$: $\py{expr3.pxs_factor(variable = x)[0]}$
994
+
995
+ factor : $\py{latex(expr3.pxs_factor(variable = x)[1])}$
996
+
997
+ term : $\py{latex(expr3.pxs_factor(variable = x)[2])}$
998
+
999
+ expr3 par rapport à $y$: $\py{expr3.pxs_factor(variable = y)[0]}$
1000
+
1001
+ factor : $\py{latex(expr3.pxs_factor(variable = y)[1])}$
1002
+
1003
+ term : $\py{latex(expr3.pxs_factor(variable = y)[2])}$
1004
+ """
1005
+
1006
+
1007
+
1008
+ class pxs_SeqFormula(SeqFormula):
1009
+ """
1010
+ Sous-classe de SeqFormula offrant une méthode de sommation des coefficients.
1011
+ La méthode pxsl_summation produit une expression (myst) représentant
1012
+ la somme des coefficients de la suite entre deux indices, soit en valeur
1013
+ numérique, soit en notation symbolique.
1014
+
1015
+ :pxs_trigger: suite numérique, suite avec somme, SeqFormula pédagogique, somme développée termes successifs
1016
+ :pxs_returns: |
1017
+ Classe héritant de sympy.SeqFormula, offrant en plus la méthode
1018
+ pxsl_summation pour afficher la somme u_min + u_{min+1} + ... + u_{max-1}
1019
+ en LaTeX (valeurs numériques ou notation symbolique u_i).
1020
+ :pxs_example: |
1021
+ u = pxs_SeqFormula(n**2, (n, 0, oo))
1022
+ # Dans MyST : $S = \\py{u.pxsl_summation(0, 5)}$
1023
+ :pxs_antipattern: Utiliser sympy.SeqFormula puis écrire la somme à la main sans simplification des signes.
1024
+ """
1025
+ def pxsl_summation(self, min=0, max=9, symbolic=None):
1026
+ """
1027
+ Génère l'expression de la somme des coefficients u_min + u_{min+1} + ... + u_{max-1}.
1028
+
1029
+ Paramètres:
1030
+ - min (int) : indice de départ de la sommation (inclu).
1031
+ - max (int) : indice de fin de la sommation (exclu).
1032
+ - symbolic (str ou None) : nom du symbole à utiliser pour la notation symbolique;
1033
+ si None, on utilise self.coeff(i) pour extraire les valeurs numériques.
1034
+
1035
+ Retourne:
1036
+ - expr : un objet myst contenant la somme formatée.
1037
+
1038
+ :pxs_trigger: somme développée suite, u_0 + u_1 + ... + u_n, écriture symbolique ou numérique d'une somme partielle
1039
+ :pxs_returns: |
1040
+ Objet myst (LaTeX) de la somme développée : soit les valeurs
1041
+ numériques des termes avec gestion correcte des signes (+/-),
1042
+ soit la notation symbolique "symbolic_0 + symbolic_1 + ...".
1043
+ :pxs_example: |
1044
+ u = pxs_SeqFormula(2*n + 1, (n, 0, oo))
1045
+ somme = u.pxsl_summation(0, 4) # "1 +3 +5 +7"
1046
+ somme_sym = u.pxsl_summation(0, 4, symbolic="u") # "u_0 + u_1 + u_2 + u_3"
1047
+ # Dans MyST : $\\py{somme}$
1048
+ :pxs_antipattern: Boucler manuellement en f-string sans gérer le signe (produit "1 + -3" au lieu de "1 - 3").
1049
+ """
1050
+ if symbolic is None:
1051
+ # Cas numérique : on ajoute la valeur de chaque coefficient
1052
+ expr = myst(r"""\py{self.coeff(min)} """, globals(), locals())
1053
+ for i in range(min + 1, max):
1054
+ coeff_i = self.coeff(i) # on récupère le coefficient numérique
1055
+ if coeff_i >= 0:
1056
+ # Ajoute '+ coeff_i' si coefficient positif
1057
+ expr += myst(r""" +\py{coeff_i} """, globals(), locals())
1058
+ else:
1059
+ # Ajoute '- |coeff_i|' si coefficient négatif
1060
+ expr += myst(r""" -\py{abs(coeff_i)} """, globals(), locals())
1061
+ return expr # retourne l'expression complète
1062
+ else:
1063
+ # Cas symbolique : on génère u_min = symbolic_0 puis + symbolic_i
1064
+ expr = myst(r"""\py{symbolic}_0 """, globals(), locals())
1065
+ for i in range(min + 1, max):
1066
+ # On concatène '+ symbolic_i' pour chaque terme suivant
1067
+ expr += myst(r"""+\py{symbolic}_\py{i} """, globals(), locals())
1068
+ return expr # retourne la somme symbolique
1069
+
1070
+ class pxs_Set:
1071
+ """
1072
+ Wrapper pédagogique pour l'affichage LaTeX d'ensembles SymPy (Interval, Union,
1073
+ Intersection, Complement, Range, ensembles usuels N, N*, Z, R) avec notation
1074
+ française et délimiteurs \\llbracket \\rrbracket pour les intervalles entiers.
1075
+
1076
+ :pxs_trigger: ensemble mathématique LaTeX, union intersection complément, N*, Reals, Integers, intervalle d'entiers ⟦a,b⟧, notation française ensembles
1077
+ :pxs_returns: |
1078
+ Wrapper autour d'un ensemble SymPy (Set) avec une méthode .print()
1079
+ produisant une chaîne LaTeX respectant les conventions pédagogiques
1080
+ françaises (N*, ]a;b[, ⟦a;b⟧, A ∪ B, A ∩ B, A \\ B).
1081
+ :pxs_example: |
1082
+ S = pxs_Set(Union(Interval(-oo, 0), Interval(1, 5, False, True)))
1083
+ # Dans MyST : $D = \\py{S.print()}$
1084
+ :pxs_antipattern: Utiliser directement latex(ensemble) qui donne la notation anglo-saxonne et ne gère pas N*, ⟦a,b⟧, ni les conventions françaises.
1085
+ """
1086
+ def __init__(self, st):
1087
+ """
1088
+ Initialise le wrapper autour d'un ensemble SymPy.
1089
+
1090
+ :pxs_trigger: instanciation wrapper pxs_Set autour d'un Set sympy
1091
+ :pxs_returns: |
1092
+ Instance pxs_Set encapsulant l'ensemble SymPy fourni, prête à
1093
+ être affichée via .print().
1094
+ :pxs_example: |
1095
+ S = pxs_Set(Interval(0, 1))
1096
+ latex_str = S.print()
1097
+ :pxs_antipattern: Passer une expression qui n'est pas un Set SymPy — la méthode print() suppose la présence d'attributs args cohérents.
1098
+ """
1099
+ self.s = st
1100
+
1101
+ def print(self):
1102
+ """
1103
+ Produit la représentation LaTeX de l'ensemble selon les conventions
1104
+ pédagogiques françaises PyxiScience.
1105
+
1106
+ :pxs_trigger: afficher ensemble en LaTeX, notation française ensembles, union intersection, ⟦a,b⟧, N*, Reals, domaine de définition composé
1107
+ :pxs_returns: |
1108
+ Chaîne LaTeX (str) représentant l'ensemble : Reals pour ]-∞,+∞[,
1109
+ N, N*, Z pour les ensembles usuels, ⟦a,b⟧ pour les intervalles
1110
+ entiers (Range), et A ∪ B / A ∩ B / A \\ B avec parenthésage
1111
+ automatique des sous-ensembles composés.
1112
+ :pxs_example: |
1113
+ D = pxs_Set(Complement(Reals, FiniteSet(0))).print()
1114
+ # Dans MyST : $D_f = \\py{D}$
1115
+ :pxs_antipattern: Composer manuellement la représentation d'une union/intersection sans gérer le parenthésage des sous-ensembles composés (A ∪ (B ∩ C)).
1116
+ """
1117
+
1118
+ def __pxs_parentheses(st):
1119
+ #Déterminer si st est composé de plusieurs ensembles
1120
+ pxs_st = pxs_Set(st)
1121
+ compose = st.args # tuple des composantes de st, et False si aucune
1122
+ for x in st.args:
1123
+ if not isinstance(x, Set):
1124
+ compose = False
1125
+
1126
+ if compose:
1127
+ return fr"\big({pxs_st.print()}\big)"
1128
+ return pxs_st.print()
1129
+
1130
+ if isinstance(self.s, Interval) and self.s.left == -oo and self.s.right == oo:
1131
+ return latex(Reals)
1132
+ elif isinstance(self.s, Interval):
1133
+ pxs_st = pxs_Interval.from_Interval(self.s)
1134
+ return pxs_st.print()
1135
+ if isinstance(self.s, Complement):
1136
+ return r" \setminus ".join(map(__pxs_parentheses, self.s.args))
1137
+ if isinstance(self.s, (Union, Intersection)):
1138
+ op = r" \cap " if isinstance(self.s, Intersection) else r" \cup "
1139
+ return fr"{op}".join(map(__pxs_parentheses, self.s.args))
1140
+ if isinstance(self.s, Range) and self.s.args[2] == 1:
1141
+ if self.s.args[0] == -oo and self.s.args[1] == oo:
1142
+ return latex(Integers)
1143
+ elif self.s.args[0] == 0 and self.s.args[1] == oo:
1144
+ return latex(Naturals)
1145
+ elif self.s.args[0] == 1 and self.s.args[1] == oo:
1146
+ return r"\N^*"
1147
+ else:
1148
+ return pxs_Interval(self.s.args[0], self.s.args[1] - 1).print().replace(r"\left[", r"\llbracket").replace(r"\left]", r"\rrbracket").replace(r"\right[", r"\llbracket").replace(r"\right]", r"\rrbracket")
1149
+ if self.s == Naturals:
1150
+ return r"\N^*"
1151
+ if self.s == Naturals0:
1152
+ return latex(Naturals)
1153
+ else:
1154
+ return latex(self.s)
1155
+
1156
+
1157
+ # =========================================================================
1158
+ # CLASSE pxs_Plotable POUR LA REPRÉSENTATION GRAPHIQUE D'EXPRESSIONS SYMPY
1159
+ # =========================================================================
1160
+
1161
+ """ PISTES D'AMÉLIORATION :
1162
+ - Gestion des singularités : retirer les singularités de la liste des abscisses, voire éventuellement plafonner les valeurs extrêmes de la fonction. P. ex :
1163
+ if max(ordo) > seuil: # (seuil = 100 par défaut ?)
1164
+ # ...limiter l'axe des ordonnées à +seuil
1165
+ if min(ordo) < - seuil:
1166
+ # ... limiter l'axe des ordonnées à - seuil.
1167
+
1168
+ - vérifier mais je crois que plot_vars n'est pas utile (sauf peut-être pour les vérifs)
1169
+ dans plot_surface_partial et contour_partial. Peut sans doute être enlevée des variables de sortie de la fonction auxiliaire associée.
1170
+
1171
+ - ajouter une colorbar (peut-être en option) sur les contour.
1172
+ """
1173
+
1174
+ import matplotlib.pyplot as plt
1175
+ import sympy as sp
1176
+ import numpy as np
1177
+
1178
+
1179
+ # # finalement inutile si l'on est obligés d'utiliser numpy pour les tracés 3d...
1180
+ # def pxs_meshgrid(x, y):
1181
+ # """Pour remplacer le meshgrid de Numpy"""
1182
+ # n, p = len(x), len(y)
1183
+ # X = [x for _ in range(p)]
1184
+ # Y = [[yi] * n for yi in y]
1185
+ # return X, Y
1186
+
1187
+
1188
+ class pxs_Plotable:
1189
+ """
1190
+ Cette classe permet de représenter graphiquement des fonctions ou suites mathématiques d'une ou plusieurs variables définies par des expressions SymPy (fraphes 2D, 3D, fonctions partielles, suites).
1191
+
1192
+ Voir la documentation de chaque fonction, et la fonction tests_visuels_pxs_Plotable() du fichier de test correspondant
1193
+ pour un aperçu graphique général.
1194
+
1195
+ :pxs_trigger: représentation graphique expression SymPy, tracé fonction matplotlib pédagogique, courbe surface contour nuage suite
1196
+ :pxs_returns: |
1197
+ Classe wrappant une expression SymPy et offrant les méthodes plot,
1198
+ plot_partial, plot_surface, plot_surface_partial, contour,
1199
+ contour_partial, plot_corde, scatter pour tous les besoins graphiques
1200
+ pédagogiques (2D, 3D, suites, fonctions partielles).
1201
+ :pxs_example: |
1202
+ pex = pxs_Plotable("cos(x)")
1203
+ pex.plot(interv=pxs_Interval(0, 2*pi))
1204
+ # La figure matplotlib courante est modifiée par effet de bord.
1205
+ :pxs_antipattern: Combiner sympy.lambdify + np.linspace + plt.plot à la main, avec titre LaTeX et gestion des bornes infinies réécrits à chaque exercice.
1206
+ """
1207
+
1208
+ def __init__(self, expr):
1209
+ """
1210
+ Initialise un objet pxs_Plotable pour le tracé de fonctions SymPy.
1211
+
1212
+ Cette classe permet de représenter graphiquement des fonctions ou suites mathématiques d'une ou plusieurs variables définies par des expressions SymPy (fraphes 2D, 3D, fonctions partielles, suites).
1213
+
1214
+ Paramètres
1215
+ ----------
1216
+ expr : str, sympy.Expr
1217
+ L'expression mathématique à tracer. Peut être une chaîne de caractères
1218
+ (qui sera convertie automatiquement) ou une expression SymPy.
1219
+
1220
+ Exemples
1221
+ --------
1222
+ >>> from sympy.abc import x, y
1223
+ >>> pex1 = pxs_Plotable("cos(x)")
1224
+ >>> pex2 = pxs_Plotable(x**2 + y**2)
1225
+ >>> pex3 = pxs_Plotable(5) # fonction constante
1226
+
1227
+ :pxs_trigger: créer objet traçable depuis expression sympy ou chaîne, conversion automatique sympify
1228
+ :pxs_returns: |
1229
+ Instance pxs_Plotable avec attributs .expr (expression SymPy) et
1230
+ .vars (set des variables libres), prête pour l'appel à plot,
1231
+ plot_surface, contour, scatter, etc.
1232
+ :pxs_example: |
1233
+ pex = pxs_Plotable("x**2 + y**2")
1234
+ pex.plot_surface()
1235
+ :pxs_antipattern: Stocker l'expression sous forme de chaîne et la reconvertir à chaque tracé.
1236
+ """
1237
+
1238
+ expr = sp.sympify(expr) # si p. ex expr est une chaîne en entrée
1239
+ self.expr = expr
1240
+ self.vars = expr.free_symbols
1241
+
1242
+ def plot(self, interv = pxs_Interval(-5, 5), pas = None, ymin = None, ymax = None, title = True, fast = False, **kwargs):
1243
+
1244
+ """
1245
+ Trace la courbe représentative d'une fonction d'une variable.
1246
+
1247
+ Cette méthode trace le graphe d'une fonction à une variable ou d'une constante.
1248
+ Elle gère automatiquement les bornes infinies et les intervalles ouverts.
1249
+
1250
+ Paramètres
1251
+ ----------
1252
+ interv : pxs_Interval, optionnel
1253
+ L'intervalle de tracé. Par défaut [-5, 5].
1254
+ pas : float, optionnel
1255
+ Le pas d'échantillonnage. Par défaut (b-a)/1000.
1256
+ title : bool, optionnel
1257
+ Afficher ou non le titre avec l'expression LaTeX. Par défaut True.
1258
+ fast : bool, optionnel
1259
+ Mode de tracé rapide utilisant plt directement. Par défaut False.
1260
+ **kwargs
1261
+ Arguments supplémentaires passés à matplotlib.pyplot.plot.
1262
+
1263
+ Lève
1264
+ ----
1265
+ ValueError
1266
+ Si l'expression contient plus d'une variable libre.
1267
+
1268
+ Exemples
1269
+ --------
1270
+ >>> from sympy.abc import x
1271
+ >>> pex = pxs_Plotable("cos(x)")
1272
+ >>> pex.plot() # Trace cos(x) sur [-5, 5]
1273
+ >>> pex.plot(interv=pxs_Interval(0, 2*pi), color="red")
1274
+ >>>
1275
+ >>> # Intervalle ouvert
1276
+ >>> pex_log = pxs_Plotable("log(x)")
1277
+ >>> pex_log.plot(interv=pxs_Interval.open(0, 5))
1278
+
1279
+ :pxs_trigger: tracer courbe fonction une variable, graphe f(x) sur intervalle, représentation graphique exercice
1280
+ :pxs_returns: |
1281
+ None (effet de bord). Dessine la courbe sur l'axe matplotlib
1282
+ courant (plt.gca() ou plt.plot si fast=True), avec titre LaTeX
1283
+ automatique "Courbe représentative de la fonction x ↦ f(x)".
1284
+ :pxs_example: |
1285
+ pex = pxs_Plotable("x**2 - 1")
1286
+ pex.plot(interv=pxs_Interval(-3, 3), color="blue")
1287
+ # Sauvegarde via plt.savefig(...)
1288
+ :pxs_antipattern: Utiliser np.linspace + sp.lambdify + plt.plot et composer manuellement le titre LaTeX à chaque exercice.
1289
+ """
1290
+
1291
+ a, b = interv.left, interv.right
1292
+
1293
+ # /!\ GADGET DE CLAUDE : Gestion des bornes infinies, est-il bien utile de le garder ?
1294
+ if a == -sp.oo:
1295
+ a = -100 # Grande valeur négative par défaut
1296
+ elif a == sp.oo:
1297
+ a = 100 # Grande valeur positive par défaut
1298
+
1299
+ if b == sp.oo:
1300
+ b = 100 # Grande valeur positive par défaut
1301
+ elif b == -sp.oo:
1302
+ b = -100 # Grande valeur négative par défaut
1303
+
1304
+
1305
+ # pas par défaut : 1000 subdivisions
1306
+ if pas is None:
1307
+ pas = (b - a) / 1000
1308
+
1309
+ nb_vars = len(self.vars)
1310
+ # Fonction constante
1311
+ if nb_vars == 0:
1312
+ x = sp.Symbol("x")
1313
+ var = x # pour le titre
1314
+ absc = [a, b]
1315
+ c = self.expr.evalf()
1316
+ ordo = [c, c]
1317
+ # Fonction d'exactement deux variables
1318
+ elif nb_vars == 1:
1319
+ var = list(self.vars)[0]
1320
+ fonction = sp.lambdify(var, self.expr, "math")
1321
+ absc = [a + k * pas for k in range(int( (b-a) / pas) + 1)]
1322
+
1323
+ # Cas d'un intervalle ouvert : retrait des bornes
1324
+ if interv.left_open:
1325
+ absc.pop(0)
1326
+ if interv.right_open:
1327
+ absc.pop()
1328
+
1329
+ ordo = [fonction(xk) for xk in absc]
1330
+
1331
+ # Cas d'une fonction de plus de deux variables : erreur
1332
+ elif nb_vars == 2:
1333
+ raise ValueError("Trop de variables dans l'expression. Utiliser plot_partial ou plot_surface")
1334
+ else:
1335
+ raise ValueError("Trop de variables dans l'expression. Utiliser plot_partial ou plot_surface_partial")
1336
+
1337
+ if fast: # Pour une seule figure, sans avoir à définir des subplots et des axes
1338
+ # plt.clf()
1339
+ plt.plot(absc, ordo, **kwargs)
1340
+ if title:
1341
+ plt.title(fr"Courbe représentative de la fonction ${var} \mapsto {sp.latex(self.expr)}$ sur l'intervalle ${sp.latex(interv)}$")
1342
+ # plt.show()
1343
+ else:
1344
+ ax = plt.gca()
1345
+ ax.plot(absc, ordo, **kwargs)
1346
+ if title:
1347
+ ax.set_title(fr"Courbe représentative de la fonction ${var} \mapsto {sp.latex(self.expr)}$ sur l'intervalle ${sp.latex(interv)}$")
1348
+
1349
+ # Si l'utilisateur spécifie des valeurs limites en ordonnées
1350
+ if ymin is not None:
1351
+ ax.set_ylim(bottom = ymin)
1352
+ if ymax is not None:
1353
+ ax.set_ylim(top = ymax)
1354
+
1355
+ def plot_partial(self, plot_var = None, fixes = None, **kwargs):
1356
+
1357
+ """
1358
+ Trace la courbe d'une fonction partielle en fixant certaines variables.
1359
+
1360
+ Cette méthode permet de tracer une fonction de plusieurs variables en fixant
1361
+ toutes les variables sauf une. La figure obtenue est une courbe dans le plan.
1362
+
1363
+ Paramètres
1364
+ ----------
1365
+ plot_var : sympy.Symbol, optionnel
1366
+ La variable selon laquelle tracer. Par défaut, la première variable
1367
+ de l'expression.
1368
+ fixes : dict, optionnel
1369
+ Dictionnaire {variable: valeur} fixant les autres variables.
1370
+ Par défaut, toutes les autres variables sont fixées à 0.
1371
+ **kwargs
1372
+ Arguments supplémentaires passés à la méthode plot().
1373
+
1374
+ Lève
1375
+ ----
1376
+ ValueError
1377
+ Si l'expression est constante, si plot_var n'appartient pas aux variables
1378
+ de l'expression, si certaines variables ne sont pas fixées, ou si une
1379
+ valeur fixée correspond à une singularité.
1380
+
1381
+ Exemples
1382
+ --------
1383
+ >>> from sympy.abc import x, y, t
1384
+ >>> pex = pxs_Plotable(2*x**2 + 3*y/t)
1385
+ >>> # Trace selon x avec y=1, t=1
1386
+ >>> pex.plot_partial(x, {y: 1, t: 1})
1387
+ >>> # Trace selon t avec x=1, y=1, évite t=0 (singularité)
1388
+ >>> pex.plot_partial(t, {x: 1, y: 1}, interv=pxs_Interval.open(0, 5))
1389
+
1390
+ :pxs_trigger: fonction partielle, fixer variables, tracer f(x,y,t) selon x avec y et t fixés, coupe 1D d'une fonction multivariable
1391
+ :pxs_returns: |
1392
+ None (effet de bord matplotlib). Substitue les variables de fixes
1393
+ par leurs valeurs, puis trace la courbe de la fonction partielle
1394
+ résultante selon plot_var via pxs_Plotable.plot.
1395
+ :pxs_example: |
1396
+ pex = pxs_Plotable(2*x**2 + 3*y/t)
1397
+ pex.plot_partial(x, {y: 1, t: 1})
1398
+ # Trace x ↦ 2x² + 3
1399
+ :pxs_antipattern: Faire self.expr.subs({y:1, t:1}) à la main puis reconstruire un pxs_Plotable et appeler plot sans vérifier les singularités ni l'appartenance des variables.
1400
+ """
1401
+
1402
+ if fixes is None:
1403
+ const_vars = self.vars.copy()
1404
+ # Vérification avant suppression
1405
+ try:
1406
+ const_vars.remove(plot_var)
1407
+ except:
1408
+ raise ValueError(f"La variable {plot_var} ne fait pas partie des variables de l'expression")
1409
+ fixes = {v : 0 for v in const_vars} # par défaut toutes les var fixées valent 0
1410
+
1411
+ if len(self.vars) == 0:
1412
+ raise ValueError("L'expression est constante")
1413
+ elif plot_var is not None and plot_var not in self.vars:
1414
+ raise ValueError(f"La variable {plot_var} ne fait pas partie des variables de l'expression")
1415
+
1416
+ if not self.vars.issubset( set(fixes.keys()).union({plot_var}) ):
1417
+ raise ValueError("Certaines variables de l'expression n'ont pas été fixées")
1418
+
1419
+ for k, v in fixes.items():
1420
+ if v in sp.singularities(self.expr, k):
1421
+ raise ValueError(f"La valeur {v} est une singularité de l'expression par rapport à la variable {k}")
1422
+
1423
+
1424
+ # Définition des valeurs par défaut de plot_var et fixes (impossible d'appeler self
1425
+ # dans les arguments par défaut)
1426
+ if plot_var is None:
1427
+ plot_var = list(self.vars)[0]
1428
+
1429
+ if fixes is None:
1430
+ const_vars = self.vars.copy()
1431
+ # Vérification avant suppression
1432
+ try:
1433
+ const_vars.remove(plot_var)
1434
+ except:
1435
+ raise ValueError(f"La variable {plot_var} ne fait pas partie des variables de l'expression")
1436
+ fixes = {v : 0 for v in const_vars} # par défaut toutes les var fixées valent 0
1437
+
1438
+ fonction_partielle = pxs_Plotable(self.expr.subs(fixes))
1439
+ fonction_partielle.plot(**kwargs)
1440
+
1441
+ def __aux_2var(self, interv1, interv2, nb_points):
1442
+ """
1443
+ Fonction auxiliaire privée utilisée dans les fonctions plot_surface et contour pour discrétiser une fonction de deux variables.
1444
+
1445
+ :pxs_trigger: interne — discrétisation fonction 2 variables pour plot_surface et contour
1446
+ :pxs_returns: |
1447
+ Tuple (X, Y, Z) de np.ndarray : grille meshgrid des abscisses et
1448
+ ordonnées, plus l'évaluation vectorisée de l'expression sur cette grille.
1449
+ :pxs_example: |
1450
+ # Appelé uniquement en interne par plot_surface et contour
1451
+ # X, Y, Z = self.__aux_2var(interv1, interv2, 30)
1452
+ :pxs_antipattern: Appeler cette méthode privée directement depuis un exercice au lieu d'utiliser plot_surface ou contour.
1453
+ """
1454
+
1455
+ if len(self.vars) != 2:
1456
+ raise ValueError("La fonction à tracer doit être une fonction d'exactement deux variables")
1457
+ # Convertir les bornes en float "normaux"
1458
+ a1, b1 = float(interv1.left), float(interv1.right)
1459
+ a2, b2 = float(interv2.left), float(interv2.right)
1460
+
1461
+ x = np.linspace(a1, b1, nb_points)
1462
+ y = np.linspace(a2, b2, nb_points)
1463
+ # Cas d'un intervalle ouvert
1464
+ if interv1.left_open:
1465
+ x.pop(0)
1466
+ if interv1.right_open:
1467
+ x.pop()
1468
+ if interv2.left_open:
1469
+ y.pop(0)
1470
+ if interv2.right_open:
1471
+ y.pop()
1472
+
1473
+ X, Y = np.meshgrid(x, y)
1474
+ liste_vars = list(self.vars)
1475
+ f = sp.lambdify(liste_vars, self.expr, "numpy")
1476
+ Z = f(X, Y)
1477
+
1478
+ return X, Y, Z
1479
+
1480
+ def __aux_verif_partial_2var(self, plot_vars, fixes):
1481
+ """
1482
+ Vérifications à effectuer avant l'utilisation des méthodes de tracé de fonctions partielles à plus de deux variables.
1483
+
1484
+ :pxs_trigger: interne — validation arguments plot_surface_partial et contour_partial
1485
+ :pxs_returns: |
1486
+ Le dictionnaire fixes complété avec les valeurs par défaut (0)
1487
+ pour toutes les variables non explicitement fixées et non présentes
1488
+ dans plot_vars. Lève ValueError en cas d'incohérence.
1489
+ :pxs_example: |
1490
+ # Appelé uniquement en interne par plot_surface_partial et contour_partial
1491
+ # fixes = self.__aux_verif_partial_2var([x, y], {z: 1})
1492
+ :pxs_antipattern: Dupliquer cette logique de validation dans plot_surface_partial et contour_partial au lieu de centraliser.
1493
+ """
1494
+
1495
+ if plot_vars is None:
1496
+ lis_vars = list(self.vars)
1497
+ plot_vars = lis_vars[:2]
1498
+
1499
+ if len(plot_vars) != 2:
1500
+ raise ValueError("plot_vars doit contenir exactement 2 variables")
1501
+
1502
+ if fixes is None:
1503
+ const_vars = self.vars.copy()
1504
+ # Vérifications avant suppression
1505
+ for var in plot_vars:
1506
+ try:
1507
+ const_vars.remove(var)
1508
+ except:
1509
+ raise ValueError(f"La variable {var} ne fait pas partie des variables de l'expression")
1510
+
1511
+ fixes = {v : 0 for v in const_vars} # par défaut toutes les var fixées valent 0
1512
+
1513
+ for var in plot_vars:
1514
+ if var not in self.vars:
1515
+ raise ValueError(f"La variable {var} ne fait pas partie des variables de l'expression")
1516
+
1517
+ if fixes is not None:
1518
+ for k, v in fixes.items():
1519
+ if v in sp.singularities(self.expr, k):
1520
+ raise ValueError(f"La valeur {v} est une singularité de l'expression par rapport à la variable {k}")
1521
+
1522
+ if not self.vars.issubset( set(fixes.keys()).union(set(plot_vars)) ):
1523
+ raise ValueError("Certaines variables de l'expression n'ont pas été fixées")
1524
+
1525
+ return fixes
1526
+
1527
+
1528
+ def plot_surface(self, interv1 = pxs_Interval(-5, 5), interv2 = pxs_Interval(-5, 5), nb_points = 30, cmap = "viridis", title = True, **kwargs):
1529
+ """
1530
+ Trace la surface représentative d'une fonction de deux variables.
1531
+
1532
+ Cette méthode génère un tracé 3D de la surface définie par une fonction
1533
+ à exactement deux variables.
1534
+
1535
+ Paramètres
1536
+ ----------
1537
+ interv1 : pxs_Interval, optionnel
1538
+ Intervalle pour la première variable. Par défaut [-5, 5].
1539
+ interv2 : pxs_Interval, optionnel
1540
+ Intervalle pour la deuxième variable. Par défaut [-5, 5].
1541
+ nb_points : int, optionnel
1542
+ Nombre de points par axe pour la grille. Par défaut 30.
1543
+ cmap : str, optionnel
1544
+ Colormap matplotlib pour la surface. Par défaut "viridis".
1545
+ title : bool, optionnel
1546
+ Afficher ou non le titre avec l'expression LaTeX. Par défaut True.
1547
+ **kwargs
1548
+ Arguments supplémentaires passés à matplotlib.Axes3D.plot_surface.
1549
+
1550
+ Lève
1551
+ ----
1552
+ ValueError
1553
+ Si l'expression ne contient pas exactement deux variables libres.
1554
+
1555
+ Exemples
1556
+ --------
1557
+ >>> from sympy.abc import x, y
1558
+ >>> surf1 = pxs_Plotable(x**2 + y**2) # Paraboloïde
1559
+ >>> fig, ax = plt.subplots(subplot_kw={"projection": "3d"})
1560
+ >>> surf1.plot_surface(cmap="plasma")
1561
+ >>>
1562
+ >>> surf2 = pxs_Plotable("sin(x)*cos(y)") # Surface trigonométrique
1563
+ >>> surf2.plot_surface(nb_points=50, cmap="coolwarm")
1564
+
1565
+ :pxs_trigger: surface 3D fonction deux variables, paraboloïde selle de cheval, tracé tridimensionnel matplotlib, z=f(x,y)
1566
+ :pxs_returns: |
1567
+ None (effet de bord). Dessine la surface 3D sur l'axe 3D courant
1568
+ (nécessite subplot_kw={"projection": "3d"}), avec titre LaTeX
1569
+ automatique et colormap configurable.
1570
+ :pxs_example: |
1571
+ surf = pxs_Plotable(x**2 + y**2)
1572
+ fig, ax = plt.subplots(subplot_kw={"projection": "3d"})
1573
+ surf.plot_surface(cmap="plasma")
1574
+ :pxs_antipattern: Construire meshgrid + lambdify + Axes3D.plot_surface à la main pour chaque exercice, sans titre LaTeX normalisé.
1575
+ """
1576
+
1577
+ # l'utilisation de numpy semble obligatoire ici :
1578
+ # (et si on s'en sert autant le faire partout où ça simplifie les choses non ?)
1579
+
1580
+ # --- ci-dessous : tentative infructueuse de ne pas utiliser numpy... ---
1581
+
1582
+ # a1, b1 = interv1.left.evalf(), interv1.right.evalf() # evalf() pour convetir en float "normaux"
1583
+ # h1 = (b1 - a1) / (nb_points - 1)
1584
+ # a2, b2 = interv2.left.evalf(), interv2.right.evalf() # idem
1585
+ # h2 = (b2 - a2) / (nb_points - 1)
1586
+ # x = [a1 + k * h1 for k in range(nb_points)]
1587
+ # y = [a2 + k * h2 for k in range(nb_points)]
1588
+ # X, Y = pxs_meshgrid(x, y)
1589
+ # liste_vars = list(self.vars)
1590
+ # f = sp.lambdify(liste_vars, self.expr, "math")
1591
+ # Z = [[f(xi, yj).evalf() for xi in x] for yj in y]
1592
+
1593
+ X, Y, Z = self.__aux_2var(interv1, interv2, nb_points)
1594
+ liste_vars = list(self.vars)
1595
+ ax = plt.gca()
1596
+ ax.plot_surface(X, Y, Z, cmap = cmap, **kwargs)
1597
+
1598
+ if title:
1599
+ var1, var2 = liste_vars[0], liste_vars[1]
1600
+ ax.set_title(fr"Surface représentative de la fonction $({var1}, {var2}) \mapsto {sp.latex(self.expr)}$")
1601
+
1602
+
1603
+
1604
+ def plot_surface_partial(self, plot_vars = None, fixes = None, **kwargs):
1605
+ """
1606
+ Trace la surface d'une fonction partielle en fixant certaines variables.
1607
+
1608
+ Cette méthode permet de tracer une fonction de plus de deux variables en fixant
1609
+ toutes les variables sauf deux, générant ainsi une surface 3D. Elle effectue
1610
+ automatiquement les vérifications de cohérence.
1611
+
1612
+ Paramètres
1613
+ ----------
1614
+ plot_vars : list of sympy.Symbol, optionnel
1615
+ Liste de deux variables pour les axes de la surface. Par défaut,
1616
+ les deux premières variables de l'expression.
1617
+ fixes : dict, optionnel
1618
+ Dictionnaire {variable: valeur} fixant les autres variables.
1619
+ Par défaut, toutes les autres variables sont fixées à 0.
1620
+ **kwargs
1621
+ Arguments supplémentaires passés à la méthode plot_surface().
1622
+
1623
+ Lève
1624
+ ----
1625
+ ValueError
1626
+ Si plot_vars ne contient pas exactement 2 variables, si les variables
1627
+ de plot_vars n'appartiennent pas à l'expression, si certaines variables
1628
+ ne sont pas fixées, ou si une valeur fixée correspond à une singularité.
1629
+
1630
+ Exemples
1631
+ --------
1632
+ >>> from sympy.abc import x, y, z, t
1633
+ >>> pex = pxs_Plotable(x**2 + y**2 + z + t)
1634
+ >>> fig, ax = plt.subplots(subplot_kw={"projection": "3d"})
1635
+ >>> # Surface x-y avec z=1, t=0
1636
+ >>> pex.plot_surface_partial([x, y], {z: 1, t: 0})
1637
+ >>> # Surface x-z avec y=0, t=1
1638
+ >>> pex.plot_surface_partial([x, z], {y: 0, t: 1}, cmap="plasma")
1639
+
1640
+ :pxs_trigger: surface 3D fonction partielle plus de 2 variables, coupe 2D en 3D, fixer certaines variables pour tracer surface, section surface
1641
+ :pxs_returns: |
1642
+ None (effet de bord). Fixe les variables de fixes, puis trace la
1643
+ surface 3D de la fonction partielle sur les deux variables restantes
1644
+ (plot_vars) via pxs_Plotable.plot_surface.
1645
+ :pxs_example: |
1646
+ pex = pxs_Plotable(x**2 + y**2 + z + t)
1647
+ fig, ax = plt.subplots(subplot_kw={"projection": "3d"})
1648
+ pex.plot_surface_partial([x, y], {z: 1, t: 0})
1649
+ :pxs_antipattern: Faire self.expr.subs puis reconstruire un pxs_Plotable et appeler plot_surface sans valider que plot_vars contient exactement 2 variables ni repérer les singularités.
1650
+ """
1651
+
1652
+ fixes = self.__aux_verif_partial_2var(plot_vars, fixes)
1653
+
1654
+ fonction_partielle = pxs_Plotable(self.expr.subs(fixes))
1655
+ fonction_partielle.plot_surface(**kwargs)
1656
+
1657
+ def contour(self, interv1 = pxs_Interval(-5, 5), interv2 = pxs_Interval(-5, 5), nb_points = 30, levels = 10, title = True, **kwargs):
1658
+ """
1659
+ Trace les lignes de niveau d'une fonction de deux variables.
1660
+
1661
+ Cette méthode génère un tracé 2D des courbes de niveau d'une fonction
1662
+ à exactement deux variables.
1663
+
1664
+ Paramètres
1665
+ ----------
1666
+ interv1 : pxs_Interval, optionnel
1667
+ Intervalle pour la première variable. Par défaut [-5, 5].
1668
+ interv2 : pxs_Interval, optionnel
1669
+ Intervalle pour la deuxième variable. Par défaut [-5, 5].
1670
+ nb_points : int, optionnel
1671
+ Nombre de points par axe pour la grille. Par défaut 30.
1672
+ levels : int ou array-like, optionnel
1673
+ Nombre de niveaux ou valeurs spécifiques pour les lignes de niveau.
1674
+ Par défaut 10.
1675
+ cmap : str, optionnel
1676
+ Colormap matplotlib pour les lignes de niveau. Par défaut "viridis".
1677
+ title : bool, optionnel
1678
+ Afficher ou non le titre avec l'expression LaTeX. Par défaut True.
1679
+ **kwargs
1680
+ Arguments supplémentaires passés à matplotlib.pyplot.contour ou contourf.
1681
+
1682
+ Lève
1683
+ ----
1684
+ ValueError
1685
+ Si l'expression ne contient pas exactement deux variables libres.
1686
+
1687
+ Exemples
1688
+ --------
1689
+ >>> from sympy.abc import x, y
1690
+ >>> import matplotlib.pyplot as plt
1691
+ >>>
1692
+ >>> # Lignes de niveau d'un paraboloïde
1693
+ >>> parab = pxs_Plotable(x**2 + y**2)
1694
+ >>> parab.contour(levels=15)
1695
+ >>> plt.show()
1696
+ >>>
1697
+ >>> # Lignes de niveau avec couleurs personnalisées
1698
+ >>> gaussian = pxs_Plotable(sp.exp(-(x**2 + y**2)/2))
1699
+ >>> gaussian.contour(cmap="hot", levels=20)
1700
+ >>>
1701
+ >>> # Niveaux spécifiques pour une fonction trigonométrique
1702
+ >>> trig = pxs_Plotable(sp.sin(x)*sp.cos(y))
1703
+ >>> levels_custom = [-0.8, -0.4, 0, 0.4, 0.8]
1704
+ >>> trig.contour(levels=levels_custom, colors="black", linewidths=2)
1705
+ >>> plt.clabel(cs, inline=True, fontsize=10) # Ajouter des labels
1706
+ >>>
1707
+ >>> # Selle de cheval avec intervalle personnalisé
1708
+ >>> selle = pxs_Plotable(x**2 - y**2)
1709
+ >>> selle.contour(interv1=pxs_Interval(-3, 3),
1710
+ ... interv2=pxs_Interval(-3, 3),
1711
+ ... levels=25, cmap="RdBu_r")
1712
+
1713
+ :pxs_trigger: lignes de niveau, courbes de niveau, isolignes, carte topographique, contour 2D fonction deux variables, f(x,y)=c
1714
+ :pxs_returns: |
1715
+ None (effet de bord). Dessine les courbes de niveau sur l'axe
1716
+ matplotlib courant, avec titre LaTeX, labels des axes, et ratio
1717
+ d'aspect "equal" pour une représentation fidèle.
1718
+ :pxs_example: |
1719
+ parab = pxs_Plotable(x**2 + y**2)
1720
+ parab.contour(levels=15)
1721
+ plt.show()
1722
+ :pxs_antipattern: Construire meshgrid + lambdify + plt.contour à la main sans normaliser le titre ni verrouiller l'aspect ratio.
1723
+ """
1724
+
1725
+ X, Y, Z = self.__aux_2var(interv1, interv2, nb_points)
1726
+ liste_vars = list(self.vars)
1727
+ # Tracé des lignes de niveau
1728
+ ax = plt.gca()
1729
+ cs = ax.contour(X, Y, Z, levels=levels, **kwargs)
1730
+
1731
+ # Ajout du titre
1732
+ if title:
1733
+ var1, var2 = liste_vars[0], liste_vars[1]
1734
+ ax.set_title(fr"Lignes de niveau de $({var1}, {var2}) \mapsto {sp.latex(self.expr)}$")
1735
+
1736
+
1737
+ # Labels des axes
1738
+ ax.set_xlabel(f"${liste_vars[0]}$")
1739
+ ax.set_ylabel(f"${liste_vars[1]}$")
1740
+
1741
+ # Assurer un ratio d'aspect égal pour une représentation fidèle
1742
+ ax.set_aspect('equal', adjustable='box')
1743
+
1744
+
1745
+ def contour_partial(self, plot_vars = None, fixes = None, **kwargs):
1746
+ """
1747
+ Trace les lignes de niveau d'une fonction partielle en fixant certaines variables.
1748
+
1749
+ Cette méthode permet de tracer les lignes de niveau d'une fonction de plus de deux
1750
+ variables en fixant toutes les variables sauf deux, générant ainsi un tracé 2D de
1751
+ lignes de niveau. Elle effectue automatiquement les vérifications de cohérence.
1752
+
1753
+ Paramètres
1754
+ ----------
1755
+ plot_vars : lise de sympy.Symbol, optionnel
1756
+ Liste de deux variables pour les axes du tracé de contour. Par défaut,
1757
+ les deux premières variables de l'expression.
1758
+ fixes : dict, optionnel
1759
+ Dictionnaire {variable: valeur} fixant les autres variables.
1760
+ Par défaut, toutes les autres variables sont fixées à 0.
1761
+ **kwargs
1762
+ Arguments supplémentaires passés à la méthode contour().
1763
+
1764
+ Retourne
1765
+ --------
1766
+ matplotlib.contour.QuadContourSet
1767
+ L'objet contour retourné par matplotlib, utile pour ajouter des labels
1768
+ ou personnaliser l'affichage.
1769
+
1770
+ Lève
1771
+ ----
1772
+ ValueError
1773
+ Si plot_vars ne contient pas exactement 2 variables, si les variables
1774
+ de plot_vars n'appartiennent pas à l'expression, si certaines variables
1775
+ ne sont pas fixées, ou si une valeur fixée correspond à une singularité.
1776
+
1777
+ Exemples
1778
+ --------
1779
+ >>> from sympy.abc import x, y, z, t
1780
+ >>> import matplotlib.pyplot as plt
1781
+ >>>
1782
+ >>> # Fonction de 4 variables
1783
+ >>> pex = pxs_Plotable(x**2 + y**2 + z*t)
1784
+ >>>
1785
+ >>> # Lignes de niveau dans le plan x-y avec z=1, t=2
1786
+ >>> pex.contour_partial([x, y], {z: 1, t: 2}, levels=15)
1787
+ >>>
1788
+ >>> # Lignes de niveau dans le plan x-z avec y=0, t=1
1789
+ >>> pex.contour_partial([x, z], {y: 0, t: 1}, cmap="plasma")
1790
+ >>>
1791
+ >>> # Niveaux personnalisés pour une fonction trigonométrique
1792
+ >>> trig_3d = pxs_Plotable(sp.sin(x)*sp.cos(y) + z)
1793
+ >>> levels_custom = [0, 0.5, 1.0, 1.5, 2.0]
1794
+ >>> trig_3d.contour_partial([x, y], {z: 1}, levels=levels_custom,
1795
+ ... colors="black", linewidths=2)
1796
+
1797
+ :pxs_trigger: lignes de niveau fonction partielle plus de 2 variables, contour 2D avec variables fixées, section isolignes
1798
+ :pxs_returns: |
1799
+ None (effet de bord). Fixe les variables de fixes, puis trace les
1800
+ courbes de niveau de la fonction partielle sur les deux variables
1801
+ restantes (plot_vars) via pxs_Plotable.contour.
1802
+ :pxs_example: |
1803
+ pex = pxs_Plotable(x**2 + y**2 + z*t)
1804
+ pex.contour_partial([x, y], {z: 1, t: 2}, levels=15)
1805
+ :pxs_antipattern: Faire expr.subs puis contour à la main sans vérifier la cohérence de plot_vars ni détecter les singularités.
1806
+ """
1807
+
1808
+ fixes = self.__aux_verif_partial_2var(plot_vars, fixes)
1809
+
1810
+ fonction_partielle = pxs_Plotable(self.expr.subs(fixes))
1811
+ fonction_partielle.contour(**kwargs)
1812
+
1813
+
1814
+
1815
+ def plot_corde(self, absc_corde, fast = False, color = "black", linestyle = "dashed", marker = ".", **kwargs):
1816
+ """
1817
+ Trace la corde reliant deux points d'une courbe.
1818
+
1819
+ Cette méthode trace un segment de droite reliant deux points de la courbe
1820
+ représentative de la fonction.
1821
+
1822
+ Paramètres
1823
+ ----------
1824
+ absc_corde : tuple ou list
1825
+ Tuple ou liste de deux abscisses (a, b) définissant les extrémités
1826
+ de la corde.
1827
+ fast : bool, optionnel
1828
+ Mode de tracé rapide utilisant plt directement. Par défaut False.
1829
+ color : str, optionnel
1830
+ Couleur de la corde. Par défaut "black".
1831
+ linestyle : str, optionnel
1832
+ Style de ligne. Par défaut "dashed".
1833
+ marker : str, optionnel
1834
+ Marqueur aux extrémités. Par défaut ".".
1835
+ **kwargs
1836
+ Arguments supplémentaires passés à matplotlib.pyplot.plot.
1837
+
1838
+ Lève
1839
+ ----
1840
+ ValueError
1841
+ Si l'expression ne contient pas exactement une variable libre.
1842
+
1843
+ Exemples
1844
+ --------
1845
+ >>> from sympy.abc import x
1846
+ >>> pex = pxs_Plotable("x**3 - 2*x")
1847
+ >>> pex.plot(color="blue")
1848
+ >>> # Corde entre x=-1 et x=2
1849
+ >>> pex.plot_corde((-1, 2), color="red", linewidth=2)
1850
+ >>> # Plusieurs cordes
1851
+ >>> pex.plot_corde((0, 1), color="green", marker="o")
1852
+
1853
+ :pxs_trigger: corde courbe, taux d'accroissement visuel, sécante, segment reliant (a,f(a)) et (b,f(b)), illustration dérivée
1854
+ :pxs_returns: |
1855
+ None (effet de bord). Trace un segment en pointillés noirs reliant
1856
+ les points (a, f(a)) et (b, f(b)) sur l'axe matplotlib courant.
1857
+ Typiquement superposé à un appel pxs_Plotable.plot préalable.
1858
+ :pxs_example: |
1859
+ pex = pxs_Plotable("x**3 - 2*x")
1860
+ pex.plot(color="blue")
1861
+ pex.plot_corde((-1, 2), color="red", linewidth=2)
1862
+ :pxs_antipattern: Calculer f(a) et f(b) via sympy.subs puis plt.plot([a,b],[fa,fb]) à la main à chaque exercice.
1863
+ """
1864
+
1865
+ # Vérification du nombre de variables
1866
+ if len(self.vars) != 1:
1867
+ raise ValueError("La fonction plot_corde ne peut être utilisée que pour des fonctions d'une seule variable")
1868
+
1869
+ # ci-dessous on suppose que c'est OK
1870
+ a, b = absc_corde
1871
+ var = list(self.vars)[0]
1872
+ fa, fb = self.expr.subs(var, a), self.expr.subs(var, b)
1873
+ if fast:
1874
+ plt.plot([a, b], [fa, fb], color = color, linestyle = linestyle, marker = marker, **kwargs)
1875
+ else:
1876
+ ax = plt.gca()
1877
+ ax.plot([a, b], [fa, fb], color = color, linestyle = linestyle, marker = marker, **kwargs)
1878
+
1879
+ def scatter(self, n_terms=20, start_index=0, fast=False, **kwargs):
1880
+ """
1881
+ Trace les termes d'une suite numérique sous forme de nuage de points.
1882
+
1883
+ Cette méthode évalue l'expression pour des valeurs entières consécutives
1884
+ de la variable et affiche les résultats sous forme de nuage de points.
1885
+
1886
+ Paramètres
1887
+ ----------
1888
+ n_terms : int, optionnel
1889
+ Nombre de termes de la suite à tracer. Doit être un entier positif.
1890
+ Par défaut 20.
1891
+ start_index : int, optionnel
1892
+ Indice de départ de la suite. Peut être négatif, nul ou positif
1893
+ selon la définition de la suite. Par défaut 0.
1894
+ fast : bool, optionnel
1895
+ Mode de tracé rapide utilisant plt directement sans axes personnalisés.
1896
+ Si False, ajoute automatiquement les labels et le titre. Par défaut False.
1897
+ **kwargs
1898
+ Arguments supplémentaires passés à matplotlib.pyplot.scatter.
1899
+ Exemples : color, s (taille), alpha, marker, etc.
1900
+
1901
+ Lève
1902
+ ----
1903
+ ValueError
1904
+ Si l'expression ne contient pas exactement une variable libre.
1905
+ Message : "La fonction scatter ne peut être utilisée que
1906
+ pour des suites (fonction d'une seule variable)".
1907
+
1908
+ Exemples
1909
+ --------
1910
+ >>> from sympy.abc import n
1911
+ >>> import matplotlib.pyplot as plt
1912
+ >>>
1913
+ >>> # Suite arithmétique : u_n = 2n + 1
1914
+ >>> suite1 = pxs_Plotable(2*n + 1)
1915
+ >>> suite1.scatter(n_terms=15, color="blue", s=50)
1916
+ >>> plt.show()
1917
+ >>>
1918
+ >>> # Suite géométrique : u_n = (1/2)^n
1919
+ >>> suite2 = pxs_Plotable("(1/2)**n")
1920
+ >>> suite2.scatter(n_terms=20, start_index=1, color="red", s=40)
1921
+ >>>
1922
+ >>> # Suite alternée : u_n = (-1)^n / n
1923
+ >>> suite4 = pxs_Plotable((-1)**n / n)
1924
+ >>> suite4.scatter(n_terms=20, start_index=1, color="purple", alpha=0.7)
1925
+ >>>
1926
+ >>> # Mode fast pour tracé rapide sans labels
1927
+ >>> suite1.scatter(fast=True, n_terms=10, color="cyan", s=80)
1928
+
1929
+ :pxs_trigger: suite numérique, nuage de points, termes u_n graphique, représentation points isolés indice/valeur, suite arithmétique géométrique alternée
1930
+ :pxs_returns: |
1931
+ None (effet de bord). Évalue l'expression pour les indices entiers
1932
+ de start_index à start_index+n_terms-1, puis trace un scatter avec
1933
+ labels et titre LaTeX de la forme "(u_n)_{n ≥ start_index}".
1934
+ :pxs_example: |
1935
+ suite = pxs_Plotable(2*n + 1)
1936
+ suite.scatter(n_terms=15, color="blue", s=50)
1937
+ :pxs_antipattern: Faire une boucle for + sympy.subs + plt.scatter à la main sans labels normalisés ni titre LaTeX pédagogique.
1938
+ """
1939
+ if len(self.vars) != 1:
1940
+ raise ValueError("La fonction plot_scatter_sequence ne peut être utilisée que pour des suites (fonction d'une seule variable)")
1941
+
1942
+ var = list(self.vars)[0]
1943
+ indices = list(range(start_index, start_index + n_terms))
1944
+ values = [float(self.expr.subs(var, n)) for n in indices]
1945
+
1946
+ if fast:
1947
+ plt.scatter(indices, values, **kwargs)
1948
+ else:
1949
+ ax = plt.gca()
1950
+ ax.scatter(indices, values, **kwargs)
1951
+ ax.set_xlabel(f"${var}$ (indice)")
1952
+ ax.set_ylabel(f"${sp.latex(self.expr)}$")
1953
+ ax.set_title(fr"Termes de la suite de $\left({sp.latex(self.expr)}\right)_{{ {var} \geq {start_index} }}$")
app/corpus/Mes_fctions_d_alg_lineaire_bis.py ADDED
The diff for this file is too large to render. See raw diff
 
app/corpus/Mes_fctions_d_analyse_bis.py ADDED
@@ -0,0 +1,1193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ Created on Thu Mar 17 19:11:52 2022
5
+
6
+ @author: jlebovits
7
+ """
8
+
9
+ from __future__ import division
10
+ import sys
11
+ import random
12
+ from copy import deepcopy
13
+
14
+ import src.scripts.Mes_fctions.Mes_fctions_deterministes
15
+ from src.scripts.Mes_fctions.Mes_fctions_deterministes import *
16
+
17
+ import src.scripts.Mes_fctions.Mes_fctions_generalistes
18
+ from src.scripts.Mes_fctions.Mes_fctions_generalistes import *
19
+
20
+ import src.scripts.Mes_fctions.Mes_fctions_probabilistes
21
+ from src.scripts.Mes_fctions.Mes_fctions_probabilistes import *
22
+
23
+ import src.scripts.Mes_fctions.Mes_fctions_d_ecriture_Latex
24
+ from src.scripts.Mes_fctions.Mes_fctions_d_ecriture_Latex import *
25
+
26
+ import src.scripts.Mes_fctions.Mes_fctions_d_alg_lineaire_bis
27
+ from src.scripts.Mes_fctions.Mes_fctions_d_alg_lineaire_bis import *
28
+
29
+ import src.scripts.Mes_fctions.Mes_fctions_generalistes_bis
30
+ from src.scripts.Mes_fctions.Mes_fctions_generalistes_bis import *
31
+
32
+ import src.scripts.Mes_fctions.Mes_fctions_utilitaires
33
+ from src.scripts.Mes_fctions.Mes_fctions_utilitaires import _pxs_add_letter
34
+
35
+ from sympy import *
36
+ from src.scripts.pxs_runtime import get_pxs_lang, myst
37
+
38
+
39
+
40
+ def pxsl_par(expr, minus = False, add = False):
41
+ """
42
+ Wraps a LaTeX expression in parentheses if it starts with a minus sign or if it is an Add.
43
+
44
+ Parameters
45
+ ----------
46
+ expr : sympy expression or numeric
47
+ The expression to be displayed.
48
+ minus : bool
49
+ If True, wrap when the expression extracts a minus sign.
50
+ add : bool
51
+ If True, wrap when the expression is a sympy ``Add``.
52
+
53
+ Returns
54
+ -------
55
+ myst : LaTeX-formatted object (via the myst function)
56
+ The LaTeX string, wrapped in parentheses if negative or Add.
57
+
58
+ :pxs_trigger: affichage d'une expression dans une formule, parenthèses conditionnelles autour d'un terme, éviter ambiguïté de signe, protéger un coefficient négatif ou une somme dans un produit LaTeX
59
+ :pxs_returns: |
60
+ chaîne MyST/LaTeX prête à être injectée dans une équation : soit
61
+ ``\\left(<latex>\\right)`` si l'expression est négative ou un ``Add``,
62
+ soit simplement ``<latex>`` sinon.
63
+ :pxs_example: |
64
+ from sympy import Symbol
65
+ x = Symbol('x')
66
+ expr = -x + 1
67
+ txt = pxsl_par(expr, add=True, minus=True)
68
+ # injection : a \\cdot {txt} → a \\cdot \\left(-x + 1\\right)
69
+ :pxs_antipattern: Concaténer manuellement r"\\left(" + latex(expr) + r"\\right)" sans vérifier si les parenthèses sont vraiment nécessaires.
70
+ """
71
+ config_standard = pxs_config()
72
+ # Vérifie si l'expression, convertie en chaîne, commence par un signe '-'
73
+ # Cela permet d'identifier les expressions négatives (par exemple -x, -3, -sin(x)...)
74
+ if minus and add:
75
+ if str(expr).startswith('-') or expr.could_extract_minus_sign() or isinstance(expr, Add):
76
+ # Si l'expression est négative, on ajoute des parenthèses autour de son affichage LaTeX
77
+ # Exemple : -x → \left(-x\right)
78
+ # myst() est ici utilisée pour insérer la version LaTeX dynamique de l'expression
79
+ return myst(
80
+ r"""\left(\py{latex(expr, **config_standard)}\right) """,
81
+ globals(), locals()
82
+ )
83
+ elif minus:
84
+ if str(expr).startswith('-') or expr.could_extract_minus_sign():
85
+ # Si l'expression est négative, on ajoute des parenthèses autour de son affichage LaTeX
86
+ # Exemple : -x → \left(-x\right)
87
+ # myst() est ici utilisée pour insérer la version LaTeX dynamique de l'expression
88
+ return myst(
89
+ r"""\left(\py{latex(expr, **config_standard)}\right) """,
90
+ globals(), locals()
91
+ )
92
+ elif add:
93
+ if isinstance(expr, Add):
94
+ # Si l'expression est négative, on ajoute des parenthèses autour de son affichage LaTeX
95
+ # Exemple : -x → \left(-x\right)
96
+ # myst() est ici utilisée pour insérer la version LaTeX dynamique de l'expression
97
+ return myst(
98
+ r"""\left(\py{latex(expr, **config_standard)}\right) """,
99
+ globals(), locals()
100
+ )
101
+ # Si l'expression n’est pas négative, on la renvoie simplement en LaTeX sans parenthèses
102
+ return myst(
103
+ r"""\py{latex(expr, **config_standard)} """,
104
+ globals(), locals()
105
+ )
106
+
107
+
108
+
109
+
110
+ def _pxsl_choose_udv(sol, u, du, v, dv, var = Symbol('x')):
111
+ """
112
+ Generates bilingual LaTeX text (English/French) explaining the choice of
113
+ functions u and v' in an integration by parts setup.
114
+
115
+ Parameters
116
+ ----------
117
+ u : sympy expression
118
+ Function chosen as u(x).
119
+ du : sympy expression
120
+ Derivative of u(x).
121
+ v : sympy expression
122
+ Function chosen as v(x).
123
+ dv : sympy expression
124
+ Derivative of v(x), i.e., v'(x).
125
+
126
+ Returns
127
+ -------
128
+ str
129
+ A LaTeX-formatted bilingual text describing u, v', and their derivatives.
130
+
131
+ :pxs_trigger: intégration par parties, annonce du choix de u et v', phrase "on choisit u et v' tels que", mise en place initiale d'une IBP quand l'utilisateur donne (u, dv)
132
+ :pxs_returns: |
133
+ chaîne MyST bilingue (FR/EN) contenant deux blocs ``\\begin{equation*}`` :
134
+ l'un pour u(x) et v'(x), l'autre pour u'(x) et v(x). Également stockée
135
+ dans ``sol["choice"]`` pour réutilisation ultérieure.
136
+ :pxs_example: |
137
+ from sympy import Symbol, exp, diff, integrate
138
+ x = Symbol('x')
139
+ u, dv = x, exp(x)
140
+ du, v = diff(u, x), integrate(dv, x)
141
+ txt = _pxsl_choose_udv(sol, u, du, v, dv, x)
142
+ # injection dans le corrigé : {txt}
143
+ :pxs_antipattern: Rédiger à la main les deux blocs ``\\begin{equation*}`` en FR+EN pour annoncer u, u', v, v' à chaque nouvel exercice.
144
+ """
145
+ config_standard = pxs_config()
146
+ text = ""
147
+
148
+ # Introduction : phrase bilingue annonçant le choix de u et v'
149
+ text = myst(r"""
150
+ \en{with}\fr{On choisit $u$ et $v'$ tels que :}
151
+ """, globals(), locals())
152
+
153
+ # Bloc d'équations affichant les expressions de u(x) et v'(x)
154
+ text += myst(r"""
155
+ \en{\begin{equation*}
156
+ &u = \py{latex(u, **config_standard)}&
157
+ &\textrm{and}&
158
+ &v' = \py{latex(dv, **config_standard)}&
159
+ \end{equation*}}
160
+ \fr{\begin{equation*}
161
+ &u(\py{var}) = \py{latex(u, **config_standard)}&
162
+ &\textrm{et}&
163
+ &v'(\py{var}) = \py{latex(dv, **config_standard)}.&
164
+ \end{equation*}}
165
+ """, globals(), locals())
166
+
167
+ # Transition bilingue vers les dérivées et primitives correspondantes
168
+ text += myst(r"""
169
+ \en{gives}\fr{On en déduit donc}
170
+ """)
171
+
172
+ # Bloc d'équations affichant u'(x) et v(x)
173
+ text += myst(r"""
174
+ \en{\begin{equation*}
175
+ &u' = \py{latex(du, **config_standard)}&
176
+ &\textrm{and}&
177
+ &v = \py{latex(v, **config_standard)}.&
178
+ \end{equation*}}
179
+ \fr{\begin{equation*}
180
+ &u'(\py{var}) = \py{latex(du, **config_standard)}&
181
+ &\textrm{et}&
182
+ &v(\py{var}) = \py{latex(v, **config_standard)}.&
183
+ \end{equation*}}
184
+ """, globals(), locals())
185
+
186
+ # Retourne le texte LaTeX complet (mélange de phrases et équations)
187
+ sol["choice"] = text
188
+ return text
189
+
190
+ def _pxsl_choose_vdu(sol, u, du, v, dv, var = Symbol('x')):
191
+ """
192
+ Generates bilingual LaTeX text (English/French) explaining the choice of
193
+ functions u' and v in an integration by parts setup.
194
+
195
+ Parameters
196
+ ----------
197
+ u : sympy expression
198
+ Function corresponding to u(x).
199
+ du : sympy expression
200
+ Derivative of u(x), i.e., u'(x).
201
+ v : sympy expression
202
+ Function chosen as v(x).
203
+ dv : sympy expression
204
+ Derivative of v(x), i.e., v'(x).
205
+
206
+ Returns
207
+ -------
208
+ str
209
+ A LaTeX-formatted bilingual text describing u', v, and their corresponding
210
+ functions and derivatives.
211
+
212
+ :pxs_trigger: intégration par parties avec choix inversé, annonce "on choisit u' et v tels que", IBP partant d'une dérivée et d'une primitive déjà connues
213
+ :pxs_returns: |
214
+ chaîne MyST bilingue (FR/EN) avec deux blocs ``\\begin{equation*}`` :
215
+ u'(x) et v(x), puis u(x) et v'(x). Également stockée dans ``sol["choice"]``.
216
+ :pxs_example: |
217
+ from sympy import Symbol, sin, cos, diff, integrate
218
+ x = Symbol('x')
219
+ du, v = cos(x), x
220
+ u, dv = integrate(du, x), diff(v, x)
221
+ txt = _pxsl_choose_vdu(sol, u, du, v, dv, x)
222
+ :pxs_antipattern: Copier-coller _pxsl_choose_udv et inverser à la main l'ordre des lignes pour obtenir l'annonce "u' et v".
223
+ """
224
+ config_standard = pxs_config()
225
+ text = ""
226
+
227
+ # Introduction : phrase bilingue annonçant le choix de u' et v
228
+ text = myst(r"""
229
+ \en{with}\fr{On choisit $u'$ et $v$ tels que :}
230
+ """, globals(), locals())
231
+
232
+ # Bloc d'équations affichant u'(x) et v(x)
233
+ text += myst(r"""
234
+ \en{\begin{equation*}
235
+ &u' = \py{latex(du, **config_standard)}&
236
+ &\textrm{and}&
237
+ &v = \py{latex(v, **config_standard)}&
238
+ \end{equation*}}
239
+ \fr{\begin{equation*}
240
+ &u'(\py{var}) = \py{latex(du, **config_standard)}&
241
+ &\textrm{et}&
242
+ &v(\py{var}) = \py{latex(v, **config_standard)}.&
243
+ \end{equation*}}
244
+ """, globals(), locals())
245
+
246
+ # Transition bilingue vers les primitives et dérivées correspondantes
247
+ text += myst(r"""
248
+ \en{gives}\fr{On en déduit donc}
249
+ """)
250
+
251
+ # Bloc d’équations affichant u(x) et v'(x)
252
+ text += myst(r"""
253
+ \en{\begin{equation*}
254
+ &u = \py{latex(u, **config_standard)}&
255
+ &\textrm{and}&
256
+ &v' = \py{latex(dv, **config_standard)}.&
257
+ \end{equation*} }
258
+ \fr{\begin{equation*}
259
+ &u(\py{var}) = \py{latex(u, **config_standard)}&
260
+ &\textrm{et}&
261
+ &v'(\py{var}) = \py{latex(dv, **config_standard)}.&
262
+ \end{equation*} }
263
+ """, globals(), locals())
264
+
265
+ # Retourne le texte LaTeX complet (phrases bilingues et équations)
266
+ sol["choice"] = text
267
+ return text
268
+
269
+
270
+ def _pxsl_sentence1(sol, u, du, v, dv, type_int, var = Symbol('x'), bl = None, br = None, intf = None):
271
+ """
272
+ Generates the bilingual LaTeX formula showing the integration by parts
273
+ resolution in the case of an *indefinite integral* (primitive).
274
+
275
+ Depending on the type of pair chosen ("udv" or "vdu"),
276
+ the function builds the appropriate LaTeX equation for:
277
+ ∫ u·v' dx = u·v − ∫ u'·v dx
278
+ or
279
+ ∫ u'·v dx = u·v − ∫ u·v' dx
280
+
281
+ Parameters
282
+ ----------
283
+ u : sympy expression
284
+ Function u(x).
285
+ du : sympy expression
286
+ Derivative of u(x).
287
+ v : sympy expression
288
+ Function v(x).
289
+ dv : sympy expression
290
+ Derivative of v(x), i.e., v'(x).
291
+ type_int : str
292
+ Type of integration by parts ("udv" or "vdu").
293
+
294
+ Returns
295
+ -------
296
+ str
297
+ A LaTeX-formatted bilingual text representing the integration by parts formula.
298
+
299
+ :pxs_trigger: première ligne de l'IBP, écriture de l'égalité ∫u·v' = [uv] − ∫u'·v, ouverture du begin{equation*} du calcul
300
+ :pxs_returns: |
301
+ chaîne LaTeX commençant un ``\\begin{equation*}`` avec le label ``eq``
302
+ et la première égalité de l'IBP ; parenthèses sur u, v, u', v' déjà
303
+ gérées via ``pxsl_par``. Également stockée dans ``sol["sentence1"]``.
304
+ :pxs_example: |
305
+ bl, br, intf = _pxs_bounds(a=None, b=None)
306
+ txt = _pxsl_sentence1(sol, u, du, v, dv, "udv", x, bl, br, intf)
307
+ :pxs_antipattern: Écrire à la main "\\int u \\cdot v' dx &= uv - \\int u' \\cdot v dx" sans passer par pxsl_par pour les signes et les Add.
308
+ """
309
+
310
+ # Cas où l'utilisateur a fourni (u, dv)
311
+ # Construction de la formule : ∫u·v' dx = u·v − ∫u'·v dx
312
+ if type_int == "udv":
313
+ text = myst(r"""
314
+ \begin{equation*}
315
+ \label{eq}
316
+ \py{intf} \py{pxsl_par(u, add = True)}\cdot \py{pxsl_par(dv, add = True, minus = True)} \ d\py{var}
317
+ &= \py{bl}\py{pxsl_par(u, add = True)}\cdot \py{pxsl_par(v, add = True, minus = True)}\py{br} - \py{intf} \py{pxsl_par(du, add = True)} \cdot \py{pxsl_par(v, add = True, minus = True)} \ d\py{var}\\
318
+ """, globals(), locals())
319
+
320
+ # Cas où l'utilisateur a fourni (du, v)
321
+ # Construction de la formule : ∫u'·v dx = u·v − ∫u·v' dx
322
+ if type_int == "vdu":
323
+ text = myst(r"""
324
+ \begin{equation*}
325
+ \label{eq}
326
+ \py{intf} \py{pxsl_par(du, add = True)}\cdot \py{pxsl_par(v, add = True, minus = True)} \ d\py{var}
327
+ &=\py{bl} \py{pxsl_par(u, add = True)}\cdot \py{pxsl_par(v, add = True, minus = True)} \py{br}- \py{intf} \py{pxsl_par(u, add = true)} \cdot \py{pxsl_par(dv, add = True, minus = True)} \ d\py{var}\\
328
+ """, globals(), locals())
329
+
330
+ # Retourne le texte LaTeX de la résolution par parties
331
+ sol["sentence1"] = text
332
+ return text
333
+
334
+
335
+
336
+
337
+ def _pxsl_sentence2(sol, uv, expr, nb_IBP, a = None, b = None, var = Symbol('x')):
338
+ """
339
+ Builds LaTeX fragments for the integration by parts process when handling
340
+ sign changes and coefficients, with or without integration bounds.
341
+
342
+ Parameters
343
+ ----------
344
+ uv : sympy expression
345
+ The product term u·v from integration by parts.
346
+ expr : sympy expression
347
+ The remaining integral expression after applying integration by parts.
348
+ nb_IBP : int
349
+ The number of successive integrations by parts already applied (used to adjust display).
350
+ a, b : numeric or symbolic, optional
351
+ Lower and upper bounds of integration. If None, the integral is indefinite.
352
+
353
+ Returns
354
+ -------
355
+ tuple
356
+ text : LaTeX string representing intermediate and simplified steps
357
+ of the integration by parts process, with correct sign and coefficient handling.
358
+
359
+ :pxs_trigger: deuxième ligne de l'IBP, simplification du terme [uv] et factorisation de l'intégrale résiduelle, gestion du coefficient et du signe devant la seconde intégrale
360
+ :pxs_returns: |
361
+ tuple ``(text, expr, sol)`` :
362
+ - ``text`` : chaîne LaTeX de la ligne "= [uv] ± coef·∫..."
363
+ - ``expr`` : expression résiduelle factorisée (coef déjà extrait)
364
+ - ``sol`` : dictionnaire enrichi avec ``sol["uv"]``, ``sol["coeff"]``, ``sol["sentence2"]``.
365
+ :pxs_example: |
366
+ txt, expr_res, sol = _pxsl_sentence2(sol, u*v, v*du, nb_IBP=1,
367
+ a=None, b=None, var=x)
368
+ :pxs_antipattern: Appeler latex(uv) puis latex(expr) séparément et recoller manuellement le signe sans pxs_separate_factors/pxsl_par.
369
+ """
370
+ config_standard = pxs_config()
371
+ # Si les bornes a et b ne sont pas données → intégrale indéfinie
372
+ bl, br, intf = _pxs_bounds(a, b)
373
+
374
+ # Extraction du coefficient numérique de expr (partie indépendante de x)
375
+ # puis gestion du signe et de la valeur absolue
376
+ expr = factor(-simplify(-expr))
377
+ if a is None and b is None:
378
+ text = myst(r"""
379
+ &= \py{bl}\py{latex(uv, **config_standard)}\py{br}
380
+ """, globals(), locals())
381
+ sol["uv"] = uv
382
+ else:
383
+ text = myst(r"""
384
+ &= \py{latex(uv.subs(var,b), **config_standard)} - \py{pxsl_par(uv.subs(var,a), minus = True, add = True)}
385
+ """, globals(), locals())
386
+ sol["uv"] = uv.subs(var,b) - uv.subs(var,a)
387
+ text += myst(r""" \py{pxsl_latex_coefficient(-pxs_separate_factors(expr, var)[0], sign = True)}\py{intf} \py{pxsl_par(pxs_separate_factors(expr, var)[1], add = True, minus = True)} \ d\py{var}
388
+ """, globals(), locals())
389
+
390
+ sol["coeff"] = pxs_separate_factors(expr, var)[0]
391
+ if nb_IBP == 2 and a is not None and b is not None:
392
+ if uv.subs(var,a).could_extract_minus_sign():
393
+ text += myst(r"""
394
+ \\&=\py{latex(uv.subs(var,b) - uv.subs(var,a), **config_standard)} \py{pxsl_latex_coefficient(pxs_separate_factors(expr, var)[0], sign = True)}\py{intf} \py{pxsl_par(pxs_separate_factors(expr, var)[1], add = True, minus = True)} \ d\py{var}
395
+ """, globals(), locals())
396
+ sol["sentence2"] = text
397
+ return text, pxs_separate_factors(expr, var)[1], sol
398
+ sol["sentence2"] = text
399
+ return text, expr, sol
400
+
401
+
402
+ def _pxsl_explain(sol, u, du, v, dv, type_int, nb_IBP, a = None, b = None, var = Symbol('x'), bl = None, br = None, intf = None):
403
+ """
404
+ Builds a bilingual LaTeX explanation for the integration by parts process,
405
+ using either the primitive form or the definite integral form.
406
+
407
+ The function combines:
408
+ - the core integration by parts equation (via _pxsl_resolution_prim or _pxsl_resolution_int)
409
+ - the corresponding minus/plus term adjustments (via _pxsl_minus)
410
+ depending on the integration type ("udv" or "vdu") and the presence of bounds.
411
+
412
+ Parameters
413
+ ----------
414
+ u : sympy expression
415
+ Function u(x).
416
+ du : sympy expression
417
+ Derivative of u(x).
418
+ v : sympy expression
419
+ Function v(x).
420
+ dv : sympy expression
421
+ Derivative of v(x), i.e., v'(x).
422
+ type_int : str
423
+ Integration by parts type: "udv" for (u, dv) or "vdu" for (du, v).
424
+ nb_IBP : int
425
+ Number of integration by parts steps performed (for formatting purposes).
426
+ a, b : numeric or symbolic, optional
427
+ Integration bounds. If None, the integral is indefinite.
428
+
429
+ Returns
430
+ -------
431
+ tuple
432
+ text : LaTeX string representing the detailed explanation
433
+ and simplified version of the integration by parts process.
434
+
435
+ :pxs_trigger: rédaction des deux premières lignes d'une IBP (formule + simplification), orchestration interne de sentence1 + sentence2, prise en compte du type (udv/vdu) et des bornes
436
+ :pxs_returns: |
437
+ tuple ``(text, expr, sol)`` :
438
+ - ``text`` : chaîne LaTeX concaténée (sentence1 suivi de sentence2)
439
+ - ``expr`` : intégrale résiduelle simplifiée
440
+ - ``sol`` : dictionnaire enrichi par les deux sous-fonctions.
441
+ :pxs_example: |
442
+ bl, br, intf = _pxs_bounds(a, b)
443
+ txt, expr_res, sol = _pxsl_explain(sol, u, du, v, dv,
444
+ "udv", nb_IBP=1,
445
+ a=a, b=b, var=x,
446
+ bl=bl, br=br, intf=intf)
447
+ :pxs_antipattern: Appeler _pxsl_sentence1 puis _pxsl_sentence2 à la main dans chaque exercice en gérant soi-même le swap udv/vdu.
448
+ """
449
+
450
+ # Étape 1 : construire la résolution pour une primitive
451
+ text = _pxsl_sentence1(sol, u, du, v, dv, type_int, var, bl, br, intf)
452
+
453
+ # Étape 2 : ajouter les termes avec le bon signe selon le type d’intégration
454
+ if type_int == "udv":
455
+ txt, expr, sol = _pxsl_sentence2(sol, u*v, v*du, nb_IBP, a = a, b = b, var = var)
456
+ text += txt
457
+ else:
458
+ txt, expr, sol = _pxsl_sentence2(sol, u*v, u*dv, nb_IBP, a = a, b = b, var = var)
459
+ text += txt
460
+
461
+ # Retourne le texte complet et sa version simplifiée
462
+ return text, expr, sol
463
+
464
+
465
+
466
+ def _pxsl_conclude(sol, uv, expr, origin_int, var = Symbol('x')):
467
+ """
468
+ Generates the final bilingual LaTeX step that concludes the integration by parts
469
+ process, displaying the complete evaluated primitive with constant C.
470
+
471
+ Parameters
472
+ ----------
473
+ uv : sympy expression
474
+ The product term u·v obtained during integration by parts.
475
+ expr : sympy expression
476
+ The remaining part of the expression (integral to be evaluated or simplified).
477
+ origin_int : sympy expression
478
+ The original integral expression (used for final verification and display).
479
+
480
+ Returns
481
+ -------
482
+ str
483
+ A LaTeX-formatted bilingual text showing the final result of the integration,
484
+ including the constant of integration.
485
+
486
+ :pxs_trigger: conclusion d'une IBP sur une primitive (pas de bornes), ligne finale "= primitive + C", fermeture du begin{equation*}, ajout de la mention "C constante réelle"
487
+ :pxs_returns: |
488
+ chaîne LaTeX terminant le calcul : ligne "= [uv] ± coef·primitive + C",
489
+ puis ligne "= résultat sympy + C" et fermeture ``\\end{equation*}``.
490
+ Également stockée dans ``sol["conclude"]``.
491
+ :pxs_example: |
492
+ txt = _pxsl_conclude(sol, u*v, v*du, u*dv, var=x)
493
+ # Fermeture propre du corrigé IBP indéfini.
494
+ :pxs_antipattern: Terminer à la main avec "+ C" et ``integrate(origin_int, var)`` sans gérer le signe du coefficient ni la phrase bilingue "where C is a real constant".
495
+ """
496
+ config_standard = pxs_config()
497
+ expr = factor(-simplify(-expr))
498
+ # Extraction du coefficient numérique de l’expression (partie indépendante de x)
499
+ # Gestion du signe et des cas particuliers (valeurs 1 ou -1 ignorées)
500
+
501
+ if pxs_separate_factors(expr, var)[0] < 0 and pxs_separate_factors(expr, var)[0] != -1:
502
+ coeff = myst(r"""\py{latex(-pxs_separate_factors(expr, var)[0], **config_standard)} """, globals(), locals())
503
+ dot = myst(r"""\cdot """)
504
+ elif pxs_separate_factors(expr, var)[0] > 0 and pxs_separate_factors(expr, var)[0] != 1:
505
+ coeff = myst(r"""\py{latex(pxs_separate_factors(expr, var)[0], **config_standard)} """, globals(), locals())
506
+ dot = myst(r"""\cdot """)
507
+ else:
508
+ coeff = myst(r""" """, globals(), locals())
509
+
510
+ # Si l’expression commence par un signe négatif
511
+ if str(expr).startswith('-'):
512
+ # Cas où le signe devient "plus" après simplification
513
+
514
+
515
+ text = myst(r""" \\&=
516
+ \py{latex(uv, **config_standard)} + \py{coeff}\py{dot} \py{pxsl_par(integrate(pxs_separate_factors(expr, var)[1], x), add = True, minus = True)} + C
517
+
518
+ """, globals(), locals())
519
+ else:
520
+ # Cas standard : on garde le signe négatif devant le terme intégré
521
+ text = myst(r""" \\&=
522
+ \py{latex(uv, **config_standard)} - \py{coeff}\py{dot}\py{pxsl_par(integrate(pxs_separate_factors(expr, var)[1], var), add = True, minus = True)} + C
523
+
524
+ """, globals(), locals())
525
+
526
+ # Ajout de la ligne finale donnant la primitive complète de l’intégrale d’origine
527
+ text += myst(r"""\\
528
+ & = \py{latex(integrate(origin_int, var), **config_standard)} + C, \textrm{ \en{with}\fr{où} }C\textrm{ \en{a real constant}\fr{est une constante réelle}}.
529
+ \end{equation*}
530
+ """, globals(), locals())
531
+
532
+ # Retourne le texte LaTeX complet de conclusion
533
+ sol["conclude"] = text
534
+ return text
535
+
536
+
537
+ def _pxsl_conclude_int(sol, uv, expr, origin_int, a, b, var = Symbol('x')):
538
+ """
539
+ Generates the final bilingual LaTeX step concluding the integration by parts
540
+ process for a *definite integral* between bounds a and b.
541
+
542
+ This function evaluates and formats the expression:
543
+ [u·v]_a^b ± coefficient × [∫f(x)dx]_a^b
544
+ and shows the fully evaluated result of the original definite integral.
545
+
546
+ Parameters
547
+ ----------
548
+ uv : sympy expression
549
+ The product term u·v obtained during integration by parts.
550
+ expr : sympy expression
551
+ The remaining part of the expression (integral to be evaluated or simplified).
552
+ origin_int : sympy expression
553
+ The original integral expression (used for final comparison and display).
554
+ a, b : numeric or symbolic
555
+ Lower and upper bounds of the definite integral.
556
+
557
+ Returns
558
+ -------
559
+ str
560
+ A LaTeX-formatted bilingual text showing the final step of the definite
561
+ integration by parts, with all evaluations and signs displayed correctly.
562
+
563
+ :pxs_trigger: conclusion d'une IBP sur une intégrale définie, évaluation ``[uv]_a^b`` et ``[primitive]_a^b``, ligne finale donnant la valeur numérique/symbolique de ∫_a^b
564
+ :pxs_returns: |
565
+ chaîne LaTeX terminant le ``\\begin{equation*}`` avec les évaluations
566
+ aux bornes, le développement du terme ``u(a)v(a)`` (Add géré terme à
567
+ terme), puis l'égalité avec ``integrate(origin_int, (var, a, b))``.
568
+ Également stockée dans ``sol["conclude"]``.
569
+ :pxs_example: |
570
+ txt = _pxsl_conclude_int(sol, u*v, v*du, u*dv, a=0, b=1, var=x)
571
+ :pxs_antipattern: Écrire à la main ``f(b) - f(a)`` en oubliant de gérer séparément les Add négatifs de ``u(a)v(a)`` et les signes de coef.
572
+ """
573
+ config_standard = pxs_config()
574
+ bl, br, intf = _pxs_bounds(a, b)
575
+ expr = factor(-simplify(-expr))
576
+ # Définit les crochets et notations bilingues pour les bornes d’intégration
577
+
578
+ # Extraction du coefficient numérique et gestion du signe
579
+ # On ajoute aussi les symboles nécessaires selon la présence d’un coefficient
580
+ if pxs_separate_factors(expr, var)[0] < 0 and pxs_separate_factors(expr, var)[0] != -1:
581
+ coeff = myst(r"""\py{latex(-pxs_separate_factors(expr, var)[0], **config_standard)} """, globals(), locals())
582
+ dot = myst(r"""\cdot """)
583
+ l_par = myst(r"""\left( """)
584
+ r_par = myst(r"""\right) """)
585
+ elif pxs_separate_factors(expr, var)[0] > 0 and pxs_separate_factors(expr, var)[0] != 1:
586
+ coeff = myst(r"""\py{latex(pxs_separate_factors(expr, var)[0], **config_standard)} """, globals(), locals())
587
+ dot = myst(r"""\cdot """)
588
+ l_par = myst(r"""\left( """)
589
+ r_par = myst(r"""\right) """)
590
+ else:
591
+ coeff = myst(r""" """, globals(), locals())
592
+ dot = myst(r""" """)
593
+ l_par = myst(r""" """)
594
+ r_par = myst(r""" """)
595
+ text = ""
596
+ # Si l’expression commence par un signe négatif
597
+ if expr.could_extract_minus_sign():
598
+ # Cas où le signe devient "plus" après simplification
599
+
600
+ if isinstance(uv.subs(var,a), Add):
601
+ text += myst(r"""
602
+ \\&=\py{latex(uv.subs(var,b), **config_standard)}""", globals(), locals())
603
+ for term in uv.subs(var,a).as_ordered_terms():
604
+ if term.could_extract_minus_sign():
605
+ text += myst(r""" + \py{latex(-term, **config_standard)}""", globals(), locals())
606
+ else:
607
+ text += myst(r""" - \py{latex(abs(term), **config_standard)}""", globals(), locals())
608
+ text += myst(r""" + \py{coeff} \py{dot}\py{bl}\py{pxsl_par(integrate(pxs_separate_factors(expr, var)[1], var), minus = True)}\py{br}
609
+ """, globals(), locals())
610
+ text += myst(r""" + \py{coeff} \py{dot}\py{l_par}\py{latex(integrate(pxs_separate_factors(expr, var)[1], var).subs(var,b), **config_standard)} - \py{pxsl_par(integrate(pxs_separate_factors(expr, var)[1], var).subs(var,a), add = True, minus = True)}\py{r_par}
611
+ """, globals(), locals())
612
+ elif uv.subs(var,a).could_extract_minus_sign():
613
+ text += myst(r"""
614
+ \\&=\py{latex(uv.subs(var,b), **config_standard)} + \py{latex(-uv.subs(var,a), **config_standard)} + \py{coeff} \py{dot}\py{bl}\py{pxsl_par(integrate(pxs_separate_factors(expr, var)[1], var), minus = True)}\py{br}
615
+ """, globals(), locals())
616
+ text += myst(r"""
617
+ \\&=\py{latex(uv.subs(var,b), **config_standard)} + \py{latex(-uv.subs(var,a), **config_standard)} + \py{coeff} \py{dot}\py{l_par}\py{pxsl_par(integrate(pxs_separate_factors(expr, var)[1], var).subs(var,b), minus = True, add = True)} - \py{pxsl_par(integrate(pxs_separate_factors(expr, var)[1], var).subs(var,a), minus = True, add = True)}\py{r_par}
618
+ """, globals(), locals())
619
+ else:
620
+ text += myst(r"""
621
+ \\&=\py{latex(uv.subs(var,b) - uv.subs(var,a), **config_standard)} + \py{coeff} \py{dot}\py{bl}\py{pxsl_par(integrate(pxs_separate_factors(expr, var)[1], var), minus = True)}\py{br}
622
+ """, globals(), locals())
623
+ text += myst(r"""
624
+ \\&=\py{latex(uv.subs(var,b) - uv.subs(var,a), **config_standard)} + \py{coeff} \py{dot}\py{l_par}\py{pxsl_par(integrate(pxs_separate_factors(expr, var)[1], var).subs(var,b))} - \py{pxsl_par(integrate(pxs_separate_factors(expr, var)[1], var).subs(var,a), add = True, minus = True)}\py{r_par}
625
+ """, globals(), locals())
626
+ else:
627
+ # Cas standard : le signe reste négatif devant la deuxième intégrale
628
+ text = myst(r""" \\&=
629
+ \py{latex(uv.subs(var,b), **config_standard)} - \py{pxsl_par(uv.subs(var,a), add = True, minus = True)} - \py{coeff}\py{dot}\py{bl}\py{pxsl_par(integrate(pxs_separate_factors(expr, var)[1], var), minus = True)}\py{br}""", globals(), locals())
630
+ if isinstance(uv.subs(var,a), Add):
631
+ text += myst(r"""
632
+ \\&=\py{latex(uv.subs(var,b), **config_standard)}""", globals(), locals())
633
+ for term in uv.subs(var,a).as_ordered_terms():
634
+ if term.could_extract_minus_sign():
635
+ text += myst(r""" + \py{latex(-term, **config_standard)}""", globals(), locals())
636
+ else:
637
+ text += myst(r""" - \py{latex(term, **config_standard)}""", globals(), locals())
638
+ text += myst(r""" - \py{coeff} \py{dot}\left(\py{latex(integrate(pxs_separate_factors(expr, var)[1], var).subs(var,b), **config_standard)} - \py{pxsl_par(integrate(pxs_separate_factors(expr, var)[1], var).subs(var,a), minus = True, add = True)}\right)
639
+ """, globals(), locals())
640
+ elif uv.subs(var,a).could_extract_minus_sign():
641
+ text += myst(r"""
642
+ \\&=\py{latex(uv.subs(var,b), **config_standard)} + \py{latex(-uv.subs(var,a), **config_standard)} - \py{coeff} \py{dot}\left(\py{latex(integrate(pxs_separate_factors(expr, var)[1], var).subs(var,b), **config_standard)} - \py{pxsl_par(integrate(pxs_separate_factors(expr, var)[1], var).subs(var,a), add = True, minus = True)}\right)
643
+ """, globals(), locals())
644
+ else:
645
+ text += myst(r"""
646
+ \\&=\py{latex(uv.subs(var,b), **config_standard)} - \py{latex(uv.subs(var,a), **config_standard)} - \py{coeff} \py{dot}\left(\py{latex(integrate(pxs_separate_factors(expr, var)[1], var).subs(var,b), **config_standard)} - \py{pxsl_par(integrate(pxs_separate_factors(expr, var)[1], var).subs(var,a), add = True, minus = True)}\right)
647
+ """, globals(), locals())
648
+
649
+ # Ligne finale : égalité avec l’intégrale définie complète d’origine
650
+ text += myst(r"""\\
651
+ & =\py{latex(integrate(origin_int, (var, a, b)), **config_standard)}.
652
+ \end{equation*}
653
+ """, globals(), locals())
654
+
655
+ # Retourne le texte LaTeX complet de conclusion (forme avec bornes)
656
+ sol["conclude"] = text
657
+ return text
658
+
659
+
660
+
661
+
662
+ def _pxs_bounds(a, b):
663
+ """
664
+ Builds the LaTeX fragments needed to render either an indefinite integral
665
+ or a definite integral with bounds ``a`` and ``b``.
666
+
667
+ Parameters
668
+ ----------
669
+ a, b : numeric or symbolic, optional
670
+ Lower and upper bounds of integration. If both are ``None`` the
671
+ integral is treated as indefinite.
672
+
673
+ Returns
674
+ -------
675
+ tuple
676
+ ``(bl, br, intf)`` where ``bl`` is the left bracket (or empty),
677
+ ``br`` is the right bracket / evaluation bar, and ``intf`` is the
678
+ integral symbol with or without bounds.
679
+
680
+ :pxs_trigger: génération conjointe des crochets d'évaluation et du symbole intégrale, bascule FR (\\left[...\\right]_a^b) / EN (\\bigg|_a^b), distinction primitive vs intégrale définie
681
+ :pxs_returns: |
682
+ tuple ``(bl, br, intf)`` :
683
+ - ``bl`` : crochet gauche ``\\left[`` en FR, vide en EN, vide si primitive
684
+ - ``br`` : crochet droit ``\\right]_a^b`` en FR, ``\\bigg|_a^b`` en EN, vide si primitive
685
+ - ``intf`` : ``\\int`` ou ``\\int_a^b`` selon la présence des bornes.
686
+ :pxs_example: |
687
+ bl, br, intf = _pxs_bounds(0, 1)
688
+ # utilisables directement dans \\py{intf} ... \\py{bl} uv \\py{br}
689
+ :pxs_antipattern: Tester à la main ``if a is None`` dans chaque fonction et recréer les chaînes ``\\left[`` / ``\\bigg|`` à chaque endroit.
690
+ """
691
+ config_standard = pxs_config()
692
+ if a is None and b is None:
693
+ bl = myst(r""" """)
694
+ br = myst(r""" """)
695
+ intf = myst(r""" \int """)
696
+ else:
697
+ bl = myst(r"""\en{}\fr{\left[} """, globals(), locals())
698
+ br = myst(r"""\en{\bigg|_{\py{latex(a, **config_standard)}}^{\py{latex(b, **config_standard)}}}\fr{\right]_{\py{latex(a, **config_standard)}}^{\py{latex(b, **config_standard)}}} """, globals(), locals())
699
+ intf = myst(r""" \int_{\py{latex(a, **config_standard)}}^{\py{latex(b, **config_standard)}} """, globals(), locals())
700
+ return bl, br, intf
701
+
702
+
703
+
704
+ def _pxs_explain_IBP(sol, var = Symbol('x'), f1 = None, f2 = None, type_int = None, nb_IBP = 1, a = None, b = None):
705
+ """
706
+ Builds a complete bilingual LaTeX correction text for the Integration by Parts (IBP) process,
707
+ handling both single and double applications, and supporting definite or indefinite integrals.
708
+
709
+ Depending on the number of integrations by parts (`nb_IBP`) and the type (`type_int`),
710
+ this function calls all the appropriate sub-functions:
711
+ - _pxs_resolve_pairs → identifies (u, du, v, dv)
712
+ - _pxsl_choose_udv/vdu → generates the introduction LaTeX text
713
+ - _pxsl_explain → generates the main formula
714
+ - _pxsl_conclude/_int → final step (primitive or definite)
715
+ - recursively calls itself if nb_IBP = 2
716
+
717
+ Parameters
718
+ ----------
719
+ x : sympy Symbol
720
+ The integration variable.
721
+ f1, f2 : sympy expressions
722
+ The two parts of the integrand provided by the user.
723
+ type_int : str
724
+ Integration by parts type: "udv" for (u, dv) or "vdu" for (du, v).
725
+ nb_IBP : int, optional
726
+ Number of integration by parts steps (1 or 2). Default is 1.
727
+ a, b : numeric or symbolic, optional
728
+ Lower and upper bounds of integration (if given, produces a definite integral).
729
+
730
+ Returns
731
+ -------
732
+ str
733
+ A LaTeX-formatted bilingual text that fully explains the integration by parts
734
+ procedure, with all symbolic steps, coefficients, and final results.
735
+
736
+ :pxs_trigger: orchestration complète d'un corrigé IBP interne, IBP simple ou double, intégrale définie ou indéfinie, enchaînement choose → explain → conclude
737
+ :pxs_returns: |
738
+ tuple ``(text, u, du, v, dv, expr, sol)`` :
739
+ - ``text`` : corrigé LaTeX complet (intro + formule + simplification + conclusion éventuelle)
740
+ - ``u, du, v, dv`` : les quatre fonctions de l'IBP, prêtes pour une 2e IBP
741
+ - ``expr`` : intégrale résiduelle à traiter ensuite
742
+ - ``sol`` : dictionnaire enrichi à chaque étape.
743
+ :pxs_example: |
744
+ text, u, du, v, dv, expr, sol = _pxs_explain_IBP(
745
+ sol, var=x, f1=x, f2=exp(x), type_int="udv", nb_IBP=1)
746
+ :pxs_antipattern: Réécrire dans chaque exercice l'enchaînement choose_udv → sentence1 → sentence2 → conclude au lieu d'appeler la fonction passerelle.
747
+ """
748
+ config_standard = pxs_config()
749
+ text = ""
750
+
751
+ # --- Définition des éléments de mise en forme selon la présence de bornes ---
752
+ bl, br, intf = _pxs_bounds(a, b)
753
+
754
+ # === Première intégration par parties ===
755
+
756
+ # Retrouver u, du, v et dv en fonction des informations de départ
757
+ if type_int == "udv":
758
+ u, du, v, dv = f1, diff(f1, var), integrate(f2, var), f2
759
+ if type_int == "vdu":
760
+ u, du, v, dv = integrate(f2, var), f2, f1, diff(f1, var)
761
+
762
+ # Introduction selon le type choisi (u,dv) ou (du,v)
763
+ if type_int == "udv":
764
+ text += _pxsl_choose_udv(sol, u, du, v, dv, var)
765
+ else:
766
+ text += _pxsl_choose_vdu(sol, u, du, v, dv, var)
767
+
768
+ # Phrase bilingue avant l’application de la formule
769
+ text += myst(r"""
770
+ \en{So integration by parts gives us:}\fr{En appliquant la formule, on obtient : }""")
771
+
772
+ # Construction de la formule selon la présence ou non de bornes
773
+ txt, expr, sol = _pxsl_explain(sol, u, du, v, dv, type_int, nb_IBP, var = var, a = a, b = b, bl = bl, br = br, intf = intf)
774
+ text += txt
775
+
776
+
777
+ # === Conclusion si une seule intégration par parties ===
778
+ if nb_IBP == 1 and a is None and b is None:
779
+ if type_int == "udv":
780
+ text += _pxsl_conclude(sol, u*v, v*du, u*dv, var = var)
781
+ if type_int == "vdu":
782
+ text += _pxsl_conclude(sol, u*v, u*dv, v*du, var = var)
783
+ elif nb_IBP == 1:
784
+ if type_int == "udv":
785
+ text += _pxsl_conclude_int(sol, u*v, v*du, u*dv, a, b, var = var)
786
+ if type_int == "vdu":
787
+ text += _pxsl_conclude_int(sol, u*v, u*dv, v*du, a, b, var = var)
788
+
789
+ # === Cas où une deuxième intégration par parties est demandée (primitive) ===
790
+ if nb_IBP == 2 :
791
+ text += myst(r"""
792
+ \end{equation*}
793
+ """)
794
+
795
+ # Retourne le texte LaTeX complet expliquant les étapes de l’IBP
796
+ return text, u, du, v, dv, expr, sol
797
+
798
+
799
+ def pxs_explain_IBP(var = Symbol('x'), f1 = None, f2 = None, type_int = "udv", a = None, b = None, nb_IBP = 1, intro = True, conclude = True, link = "https://app.pyxiscience.com/teacher/dashboard/module/7e0b271d-92f9-11f0-a777-0e37881c19a9/chapter/258e5825-9de5-11f0-a5a8-0e37881c19a9#quotient-fini#IBP2"):
800
+ """
801
+ Creates a complete bilingual LaTeX explanation for computing an integral
802
+ using the Integration by Parts (IBP) method.
803
+
804
+ This is the main public-facing function that introduces the IBP concept,
805
+ calls the internal recursive explanation generator `_pxs_explain_IBP`, and
806
+ concludes by showing the final boxed result of the integral (definite or
807
+ indefinite).
808
+
809
+ Parameters
810
+ ----------
811
+ var : sympy Symbol
812
+ The integration variable.
813
+ f1, f2 : sympy expressions
814
+ The two parts of the integrand (used as u and dv or du and v).
815
+ type_int : str, optional
816
+ Type of integration by parts ("udv" or "vdu"). Default is "udv".
817
+ a, b : numeric or symbolic, optional
818
+ Lower and upper bounds of the integral. If None, it’s treated as an
819
+ indefinite integral.
820
+ nb_IBP : int, optional
821
+ Number of integrations by parts to perform (1 or 2). Default is 1.
822
+
823
+ Returns
824
+ -------
825
+ str
826
+ A bilingual LaTeX-formatted text containing the full reasoning,
827
+ step-by-step explanation, and final boxed conclusion of the IBP process.
828
+
829
+ :pxs_trigger: calcul d'une intégrale par intégration par parties, corrigé automatique d'un ∫ f(x)g(x)dx ou ∫_a^b f(x)g(x)dx, énoncé "calculer cette intégrale en utilisant une IBP", primitive de x·e^x, ln(x), x·cos(x), etc.
830
+ :pxs_returns: |
831
+ dictionnaire ``sol`` prêt à être injecté dans un corrigé MyST :
832
+ - ``sol["text"]`` : corrigé LaTeX bilingue complet (intro + déroulé + conclusion encadrée)
833
+ - ``sol["int"]`` : valeur sympy de l'intégrale (définie ou indéfinie)
834
+ - ``sol["u"]``, ``sol["du"]``, ``sol["v"]``, ``sol["dv"]`` : fonctions choisies
835
+ - ``sol["choice"]``, ``sol["sentence1"]``, ``sol["sentence2"]``, ``sol["conclude"]`` : fragments réutilisables
836
+ - ``sol["a"]``, ``sol["b"]``, ``sol["var"]``, ``sol["expr"]`` : contexte de l'exercice.
837
+ :pxs_example: |
838
+ from sympy import Symbol, exp, ln
839
+ x = Symbol('x')
840
+ sol = pxs_explain_IBP(var=x, f1=ln(x), f2=1, type_int="udv")
841
+ # dans le .md : {sol["text"]}
842
+ # ou juste la valeur : \\(\\py{{latex(sol["int"])}}\\)
843
+ :pxs_antipattern: Rédiger à la main un corrigé IBP avec ``\\begin{equation*}``, ``\\int``, ``[uv]_a^b``, la conclusion encadrée et la phrase bilingue "C constante réelle".
844
+ """
845
+ config_standard = pxs_config()
846
+ sol = {}
847
+ # Introduction bilingue avec lien interactif vers le chapitre concerné
848
+ if intro:
849
+ text = myst(r"""
850
+ ```{fr}
851
+ On calcule cette intégrale en réalisant une [{color:blue}`intégration par parties`]({{link}}) :
852
+ ```
853
+ ```{en}
854
+ Using [{color:blue}`integration by parts`]({link}) :
855
+ ```
856
+ """, globals(), locals())
857
+ else:
858
+ text = myst(r""" """)
859
+
860
+ sol["intro"] = text
861
+ # Appel de la fonction principale interne qui rédige les étapes détaillées
862
+ txt, u, du, v, dv, expr, sol = _pxs_explain_IBP(sol, var, f1, f2, type_int, nb_IBP, a, b)
863
+ text += txt
864
+ sol["u"], sol["du"], sol["v"], sol["dv"] = u, du, v, dv
865
+ sol["a"], sol["b"], sol["var"] = a, b, var
866
+
867
+
868
+ # === Cas (u, dv) sans bornes ===
869
+ if conclude and type_int == "udv" and a is None and b is None and nb_IBP == 1:
870
+ text += myst(r"""
871
+ \en{Thus,}\fr{On a donc montré :}
872
+ \begin{equation*}
873
+ \fbox{$\displaystyle{\int \py{latex(u*dv, **config_standard)} \;d\py{var} = \py{latex(integrate(u*dv, var), **config_standard)}} + C$, \en{with}\fr{où} $C$ \en{a real constant}\fr{est une constante réelle}.}
874
+ \end{equation*}""", globals(), locals())
875
+ elif type_int == "udv" and a is None and b is None and nb_IBP == 1:
876
+ sol["int"] = integrate(u*dv, var)
877
+
878
+ # === Cas (u, dv) avec bornes ===
879
+ elif conclude and type_int == "udv" and nb_IBP == 1:
880
+ text += myst(r"""
881
+ \en{Thus,}\fr{On a donc montré :}
882
+ \begin{equation*}
883
+ \fbox{$\displaystyle{\int_{\py{latex(a, **config_standard)}}^{\py{latex(b, **config_standard)}} \py{latex(u*dv, **config_standard)} \;d\py{var} = \py{latex(integrate(u*dv, (var, a, b)), **config_standard)}}$}
884
+ \end{equation*}""", globals(), locals())
885
+ sol["int"] = integrate(u*dv, (var, a, b))
886
+ elif type_int == "udv" and nb_IBP == 1:
887
+ sol["int"] = integrate(u*dv, (var, a, b))
888
+
889
+ # === Cas (du, v) sans bornes ===
890
+ if conclude and type_int == "vdu" and a is None and b is None and nb_IBP == 1:
891
+ text += myst(r"""
892
+ \en{Thus,}\fr{On a donc montré :}
893
+ \begin{equation*}
894
+ \fbox{$\displaystyle{\int \py{latex(v*du, **config_standard)} \;d\py{var} = \py{latex(integrate(v*du, var), **config_standard)}} + C$, \en{with}\fr{où} $C$ \en{a real constant}\fr{est une constante réelle}.}
895
+ \end{equation*}""", globals(), locals())
896
+ sol["int"] = integrate(v*du, var)
897
+ elif type_int == "vdu" and a is None and b is None and nb_IBP == 1:
898
+ sol["int"] = integrate(v*du, var)
899
+
900
+ # === Cas (du, v) avec bornes ===
901
+ elif conclude and type_int == "vdu" and nb_IBP == 1:
902
+ text += myst(r"""
903
+ \en{Thus,}\fr{On a donc montré :}
904
+ \begin{equation*}
905
+ \fbox{$\displaystyle{\int_{\py{latex(a, **config_standard)}}^{\py{latex(b, **config_standard)}} \py{latex(v*du, **config_standard)}\;d\py{var} = \py{latex(integrate(v*du, (var, a, b)), **config_standard)}}$}
906
+ \end{equation*}""", globals(), locals())
907
+ sol["int"] = integrate(v*du, (var, a, b))
908
+ elif type_int == "vdu" and nb_IBP == 1:
909
+ sol["int"] = integrate(v*du, (var, a, b))
910
+
911
+ sol["text"] = text
912
+ sol["expr"] = expr
913
+ # Retourne le texte complet, incluant l’introduction, le déroulé et la conclusion
914
+ return sol
915
+
916
+ def pxsl_final_sentence(sol, a, b, var, mult, *args):
917
+ """
918
+ Recombine the intermediate ``sol`` dictionaries from successive integrations
919
+ by parts into a single bilingual LaTeX conclusion, showing how the two
920
+ partial results collapse into the final value of the original integral.
921
+
922
+ Parameters
923
+ ----------
924
+ sol : dict
925
+ Master solution dictionary (the final LaTeX is stored in
926
+ ``sol["final_sentence"]``).
927
+ a, b : numeric or symbolic, optional
928
+ Integration bounds. If both are ``None`` a ``+C`` is appended.
929
+ var : sympy Symbol
930
+ Integration variable.
931
+ mult : str
932
+ Multiplication symbol used between coefficient and remaining integral.
933
+ *args : dict
934
+ Successive per-step dictionaries produced by ``pxs_explain_IBP``
935
+ (each contains ``"uv"``, ``"coeff"``, ``"int"``, ``"u"``, ``"dv"``).
936
+
937
+ Returns
938
+ -------
939
+ str
940
+ A LaTeX string (also stored in ``sol["final_sentence"]``) wrapping up
941
+ the full multi-IBP computation in a single ``\\begin{equation*}``.
942
+
943
+ :pxs_trigger: conclusion d'une double (ou multiple) intégration par parties, recollage des résultats partiels, égalité finale "∫ f(x)g(x)dx = ... + C", synthèse de deux IBP successives
944
+ :pxs_returns: |
945
+ chaîne LaTeX contenue dans un ``\\begin{equation*}`` qui part de
946
+ l'intégrale originale ``∫ u·dv`` et enchaîne les égalités jusqu'à la
947
+ valeur finale (avec ``+ C`` si intégrale indéfinie). Également stockée
948
+ dans ``sol["final_sentence"]``.
949
+ :pxs_example: |
950
+ sol1 = pxs_explain_IBP(var=x, f1=x**2, f2=exp(x),
951
+ type_int="udv", conclude=False, nb_IBP=2)
952
+ sol2 = pxs_explain_IBP(var=x, f1=sol1["expr"], f2=1,
953
+ type_int="udv", intro=False, conclude=False)
954
+ pxsl_final_sentence(sol, a=None, b=None, var=x,
955
+ mult=r"\\cdot", sol1, sol2)
956
+ # injection : {sol["final_sentence"]}
957
+ :pxs_antipattern: Concaténer à la main ``sol1["uv"] + sol2["int"]`` dans une f-string LaTeX sans gérer les signes, le ``+C`` et la réduction finale via ``integrate``.
958
+ """
959
+ config_standard = pxs_config()
960
+ bl, br, intf = _pxs_bounds(a, b)
961
+
962
+ final_sol = myst(r"""
963
+ \begin{equation*}
964
+ \py{intf}\py{latex(args[0]["u"]*args[0]["dv"],**config_standard)}\,d\py{var}
965
+ """, globals(), locals())
966
+ for i in range(len(args) - 1):
967
+ if args[i]["coeff"] == -1 and (args[i+1]["int"].could_extract_minus_sign() or latex(args[i+1]["int"], **config_standard).startswith('-')):
968
+ final_sol += myst(r"""
969
+ &= \py{latex(args[i]["uv"], **config_standard)}\py{latex(args[i+1]["int"], **config_standard)}
970
+ """, globals(), locals())
971
+ if a is None and b is None:
972
+ final_sol += myst(r""" +C """, globals(), locals())
973
+ if Add(args[i]["uv"], args[i+1]["int"], evaluate = False) != args[i]["uv"] + args[i+1]["int"]:
974
+ final_sol += myst(r"""
975
+ \\ &= \py{latex(integrate(args[0]["u"]*args[0]["dv"], (var, a, b)), **config_standard)}
976
+ """, globals(), locals())
977
+ if a is None and b is None:
978
+ final_sol += myst(r""" +C """, globals(), locals())
979
+ elif args[i]["coeff"] == -1:
980
+ final_sol += myst(r"""
981
+ &=\py{latex(args[i]["uv"], **config_standard)}+\py{latex(args[i+1]["int"], **config_standard)}
982
+ """, globals(), locals())
983
+ if a is None and b is None:
984
+ final_sol += myst(r""" + C """, globals(), locals())
985
+ if Add(args[i]["uv"], args[i+1]["int"], evaluate = False) != args[i]["uv"] + args[i+1]["int"]:
986
+ final_sol += myst(r"""
987
+ \\&= \py{latex(integrate(args[0]["u"]*args[0]["dv"], (var, a, b)), **config_standard)}
988
+ """, globals(), locals())
989
+ if a is None and b is None:
990
+ final_sol += myst(r""" + C """, globals(), locals())
991
+ else :
992
+ mult2 = mult if args[i]["coeff"] != 1 else myst(r""" """)
993
+ final_sol += myst(r"""
994
+ &= \py{latex(args[i]["uv"], **config_standard)}\py{pxsl_latex_coefficient(-args[i]["coeff"], sign = True)}\py{mult2}\py{pxsl_par(args[i+1]["int"], add = True, minus = True)}
995
+ """, globals(), locals())
996
+ if a is None and b is None:
997
+ final_sol += myst(r""" + C """, globals(), locals())
998
+ final_sol += myst(r"""
999
+ \\&= \py{latex(integrate(args[0]["u"]*args[0]["dv"], (var, a, b)), **config_standard)}
1000
+ """, globals(), locals())
1001
+ if a is None and b is None:
1002
+ final_sol += myst(r""" + C, \textrm{ \en{with}\fr{où} }C\textrm{ \en{a real constant}\fr{est une constante réelle}}. """, globals(), locals())
1003
+ final_sol += myst(r""" \end{equation*}""")
1004
+ sol["final_sentence"] = final_sol
1005
+ return final_sol
1006
+
1007
+ def pxsl_partial_decomp(
1008
+ num: list = [],
1009
+ den: list = [],
1010
+ var=Symbol('x'),
1011
+ mul_symbol=myst(r""" \cdot"""),
1012
+ method = "simple"
1013
+ ) -> dict:
1014
+ """
1015
+ Construct the symbolic structure of a partial fraction decomposition.
1016
+
1017
+ The function analyzes the denominator factors, generates the appropriate
1018
+ elementary fractions (including powers for repeated factors), assigns
1019
+ symbolic coefficients (A, B, C, ...), and builds the associated identity
1020
+ equation.
1021
+
1022
+ Parameters
1023
+ ----------
1024
+ num : list, optional
1025
+ List representing the numerator (kept for consistency, not expanded here).
1026
+ den : list, optional
1027
+ List of denominator factors (SymPy expressions).
1028
+ var : Symbol, optional
1029
+ Main symbolic variable (default is ``Symbol('x')``).
1030
+ mul_symbol : Any, optional
1031
+ Multiplication symbol used in LaTeX rendering.
1032
+ method : str, optional
1033
+ Decomposition method: "simple" or "advanced" (default is "simple").
1034
+ If "simple", one letter by term, if "advanced", linear terms for irreducible quadratics.
1035
+
1036
+ Returns
1037
+ -------
1038
+ dict
1039
+ A dictionary containing:
1040
+ - num : list
1041
+ - den : list
1042
+ - letters : list of str
1043
+ - elem_list : list of denominator elements
1044
+ - var : Symbol
1045
+ - expr : symbolic sum of elementary fractions
1046
+ - identity : simplified identity after clearing denominators
1047
+
1048
+ Examples
1049
+ --------
1050
+ Basic usage (distinct linear factors)
1051
+ >>> from sympy import Symbol
1052
+ >>> x = Symbol('x')
1053
+ >>> sol = pxsl_partial_decomp(den=[x, x - 1])
1054
+ >>> sol["letters"]
1055
+ ['A', 'B']
1056
+ >>> sol["expr"]
1057
+ A/x + B/(x - 1)
1058
+
1059
+ Repeated factor (powers are generated automatically)
1060
+ >>> sol = pxsl_partial_decomp(den=[x, (x - 1)**2])
1061
+ >>> sol["letters"]
1062
+ ['A', 'B', 'C']
1063
+ >>> sol["expr"]
1064
+ A/x + B/(x - 1) + C/(x - 1)**2
1065
+
1066
+ Mix of repeated and distinct factors
1067
+ >>> sol = pxsl_partial_decomp(den=[(x + 2)**3, (2*x - 1)])
1068
+ >>> sol["letters"]
1069
+ ['A', 'B', 'C', 'D']
1070
+ >>> sol["expr"]
1071
+ A/(x + 2) + B/(x + 2)**2 + C/(x + 2)**3 + D/(2*x - 1)
1072
+
1073
+ Advanced mode (irreducible quadratic gets a linear numerator)
1074
+ >>> sol = pxsl_partial_decomp(den=[x**2 + 1], method="advanced")
1075
+ >>> sol["letters"]
1076
+ ['A', 'B']
1077
+ >>> sol["expr"]
1078
+ (A*x + B)/(x**2 + 1)
1079
+
1080
+ Advanced mode with a mix (quadratic + repeated linear factor)
1081
+ >>> sol = pxsl_partial_decomp(den=[x**2 + 1, (x - 3)**2], method="advanced")
1082
+ >>> sol["letters"]
1083
+ ['A', 'B', 'C', 'D']
1084
+ >>> sol["expr"]
1085
+ (A*x + B)/(x**2 + 1) + C/(x - 3) + D/(x - 3)**2
1086
+
1087
+ Identity after clearing denominators (useful to solve for coefficients)
1088
+ >>> sol = pxsl_partial_decomp(den=[x, x - 1])
1089
+ >>> sol["identity"]
1090
+ A*(x - 1) + B*x
1091
+
1092
+ :pxs_trigger: décomposition en éléments simples, fraction rationnelle P(x)/Q(x), pôles simples et multiples, poser les coefficients A, B, C, trinôme irréductible au dénominateur (méthode "advanced"), identité polynomiale après multiplication
1093
+ :pxs_returns: |
1094
+ dictionnaire ``sol`` contenant :
1095
+ - ``letters`` : liste des coefficients symboliques générés ["A","B",...]
1096
+ - ``expr`` : somme symbolique ``A/den1 + B/den2 + ...`` (avec
1097
+ numérateur linéaire ``A*x+B`` pour les quadratiques irréductibles
1098
+ si ``method="advanced"``)
1099
+ - ``identity`` : polynôme obtenu en multipliant ``expr`` par le
1100
+ produit des dénominateurs (utile pour résoudre A, B, C)
1101
+ - ``num``, ``den``, ``var`` : ré-exposés pour les étapes suivantes.
1102
+ :pxs_example: |
1103
+ from sympy import Symbol
1104
+ x = Symbol('x')
1105
+ sol = pxsl_partial_decomp(den=[x, (x - 1)**2], method="simple")
1106
+ # sol["expr"] → A/x + B/(x-1) + C/(x-1)**2
1107
+ # sol["identity"] → A*(x-1)**2 + B*x*(x-1) + C*x
1108
+ :pxs_antipattern: Créer à la main ``Symbol('A')/d1 + Symbol('B')/d2 + ...`` et boucler soi-même sur les puissances et les trinômes irréductibles à chaque exercice.
1109
+ """
1110
+
1111
+ sol = {
1112
+ "num": num,
1113
+ "den": den,
1114
+ "letters": [],
1115
+ "expr": 0,
1116
+ "var": var,
1117
+ }
1118
+ for elem in sol["den"]:
1119
+ try:
1120
+ poly = Poly(elem, sol["var"])
1121
+ except:
1122
+ pass
1123
+ if isinstance(poly, Poly) and poly.degree() >= 2 and not pxs_is_factorable(poly) and method != "simple":
1124
+ _pxs_add_letter(sol)
1125
+ _pxs_add_letter(sol)
1126
+ sol["expr"] += (Symbol(sol["letters"][-2])*sol["var"] + Symbol(sol["letters"][-1])) / poly
1127
+ elif isinstance(elem, Pow) and elem.args[1] >= 2:
1128
+ for n in range(1, elem.exp + 1):
1129
+ _pxs_add_letter(sol)
1130
+ sol["expr"] += Symbol(sol["letters"][-1]) / elem.base**n
1131
+ else:
1132
+ _pxs_add_letter(sol)
1133
+ sol["expr"] += Symbol(sol["letters"][-1]) / elem
1134
+
1135
+ sol["identity"] = simplify(sol["expr"] * Mul(*sol["den"]))
1136
+
1137
+ return sol
1138
+
1139
+
1140
+ def pxsl_decomp_sol(sol: dict, x_0, mul_symbol: str = "", par: bool = False) -> None:
1141
+ """
1142
+ Generate and store the LaTeX representation of the decomposition identity
1143
+ evaluated at a specific value of the variable.
1144
+
1145
+ The result is stored directly in the solution dictionary under a dynamically
1146
+ generated key.
1147
+
1148
+ Parameters
1149
+ ----------
1150
+ sol : dict
1151
+ Dictionary produced by ``pxsl_partial_decomp``.
1152
+ x_0 : int or float
1153
+ Value substituted for the main variable.
1154
+ mul_symbol : str, optional
1155
+ Multiplication symbol used in LaTeX output.
1156
+ par : bool, optional
1157
+ If True, negative values of `x_0` are enclosed in parentheses.
1158
+
1159
+ Returns
1160
+ -------
1161
+ None
1162
+ The dictionary is modified in place by adding a LaTeX string.
1163
+
1164
+ Examples
1165
+ --------
1166
+ >>> pxsl_decomp_sol(sol, 2)
1167
+ >>> "expr_2" in sol
1168
+ True
1169
+
1170
+ :pxs_trigger: évaluation de l'identité de décomposition en éléments simples en un point x_0, méthode des valeurs particulières pour trouver A, B, C, substitution x = pôle ou x = 0/1 dans l'identité polynomiale
1171
+ :pxs_returns: |
1172
+ ``None``. Effet de bord : ajoute à ``sol`` une clé ``"expr" + str(x_0)``
1173
+ contenant la chaîne LaTeX de ``sol["identity"]`` avec la variable
1174
+ remplacée par ``x_0`` (entourée de parenthèses si ``x_0 < 0`` et
1175
+ ``par=True``), prête pour un ``\\py{...}`` dans le corrigé MyST.
1176
+ :pxs_example: |
1177
+ sol = pxsl_partial_decomp(den=[x, x - 1])
1178
+ pxsl_decomp_sol(sol, 0)
1179
+ pxsl_decomp_sol(sol, 1)
1180
+ # dans le .md : {sol["expr0"]} et {sol["expr1"]}
1181
+ :pxs_antipattern: Faire ``latex(sol["identity"].subs(var, x_0))`` à la main en oubliant de gérer les parenthèses pour les valeurs négatives et de stocker sous la bonne clé "expr<x_0>".
1182
+ """
1183
+ var_str = (
1184
+ myst(r"""\py{str(x_0)}""", globals(), locals())
1185
+ if x_0 >= 0 or par is False
1186
+ else myst(r"""\left(\py{str(x_0)}\right)""", globals(), locals())
1187
+ )
1188
+
1189
+ sol["expr" + str(x_0)] = latex(
1190
+ sol["identity"],
1191
+ symbol_names={sol["var"]: var_str},
1192
+ mul_symbol=mul_symbol,
1193
+ )
app/corpus/Mes_fctions_generalistes_bis.py ADDED
The diff for this file is too large to render. See raw diff
 
app/corpus/Mes_fctions_probabilistes_bis.py ADDED
@@ -0,0 +1,1162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ Created on Thu Apr 04 2025
5
+
6
+ @author: Delphine
7
+ """
8
+
9
+
10
+ from __future__ import division
11
+ import sys
12
+ from copy import deepcopy
13
+
14
+ import src.scripts.Mes_fctions.Mes_fctions_deterministes
15
+ from src.scripts.Mes_fctions.Mes_fctions_deterministes import *
16
+
17
+ import src.scripts.Mes_fctions.Mes_fctions_generalistes
18
+ from src.scripts.Mes_fctions.Mes_fctions_generalistes import *
19
+
20
+ import src.scripts.Mes_fctions.Mes_fctions_probabilistes
21
+ from src.scripts.Mes_fctions.Mes_fctions_probabilistes import *
22
+
23
+ import src.scripts.Mes_fctions.Mes_fctions_d_ecriture_Latex
24
+ from src.scripts.Mes_fctions.Mes_fctions_d_ecriture_Latex import *
25
+
26
+ import src.scripts.Mes_fctions.Mes_fctions_d_alg_lineaire_bis
27
+ from src.scripts.Mes_fctions.Mes_fctions_d_alg_lineaire_bis import *
28
+
29
+ from src.scripts.pxs_runtime import myst
30
+ from sympy import *
31
+ import sympy.stats as stats
32
+ import functools as fct
33
+ import math as m
34
+ import random as rd
35
+ import numpy as np
36
+
37
+ ####################### FONCTIONS COPIES A RETIRER DES QUE LE PROBLEME DE DOUBLE APPEL EST REGLE
38
+
39
+ def pxsl_pow(x, n=1, opt=0, displaystyle=True):
40
+ """
41
+ Fonction permettant d'écrire le nombre x entouré de parenthèses
42
+ lorsqu'il est négatif ou irrationnel avec deux termes (par ex : 1+sqrt(2) ou 3sqrt(2))
43
+ Ne fonctionne pas pour des valeurs numériques non simplifiées (par ex : 1+3 ou 3*3/2)
44
+
45
+ Version
46
+ -------
47
+ 13/02/25
48
+
49
+ Paramètres
50
+ ----------
51
+ x : nombre ou expression
52
+ La base à élever à la puissance n
53
+ n : int, optional
54
+ L'exposant (défaut: 1)
55
+ opt : int, optional
56
+ Option de formatage (défaut: 0)
57
+ 0: formatage standard
58
+ 1: simplifie l'affichage pour x=1, x=0 ou n=1
59
+ 2: simplifie davantage et renvoie une chaîne vide pour x=0
60
+ displaystyle : bool, optional
61
+ Si True, utilise \displaystyle pour les fractions (défaut: False)
62
+
63
+ Retour
64
+ ------
65
+ str
66
+ retourne l'expression en latex
67
+
68
+ :pxs_trigger: écriture LaTeX d'une puissance, base potentiellement négative, base fractionnaire Rational, expression composée (Add/Mul), parenthèses conditionnelles autour d'une base, affichage x^n dans un calcul, exposant entier appliqué à un coefficient
69
+ :pxs_returns: |
70
+ str LaTeX rendu via myst() (pour injection \\py{...}).
71
+ Ajoute automatiquement \\left(...\\right) autour de x si x est négatif, Rational non entier, Add ou Mul.
72
+ Sans parenthèses si x est Symbol ou positif. Si n==1, l'exposant n'est pas affiché.
73
+ :pxs_example: |
74
+ a = -3
75
+ expr = pxsl_pow(a, 2) # -> \\left(-3\\right)^{2}
76
+ expr2 = pxsl_pow(Rational(1,2), 3) # -> \\left(\\frac{1}{2}\\right)^{3}
77
+ # Injection : myst(r\"\"\"On a \\py{expr}\"\"\", globals(), locals())
78
+ :pxs_antipattern: écrire à la main f"({latex(x)})^{n}" if x < 0 else f"{latex(x)}^{n}" — manque les cas Rational, Add, Mul, Symbol et n==1.
79
+ """
80
+
81
+ # Préparation de l'expression LaTeX selon le mode displaystyle
82
+ if displaystyle:
83
+ latex_x = r"\displaystyle " + latex(x)
84
+ else:
85
+ latex_x = latex(x)
86
+
87
+ # Cas où x est une expression (Add ou Mul) ou nombre négatif:
88
+ if isinstance(x, Add) or isinstance(x, Mul) :
89
+ if n == 1 :
90
+ return myst(r"""\left(\py{latex_x}\right)""", globals(), locals())
91
+ else:
92
+ return myst(r"""\left(\py{latex_x}\right)^{\py{n}}""", globals(), locals())
93
+ # Cas où x est un Rational
94
+ elif isinstance(x,Rational) and x.q!=1:
95
+ if n == 1 : # Pas de parenthèses quand n=1
96
+ return myst(r"""\py{latex_x}""", globals(), locals())
97
+ else: # Parenthèses quand n différent de 1
98
+ return myst(r"""\left(\py{latex_x}\right)^{\py{n}}""", globals(), locals())
99
+ # Cas où x est un Symbol:
100
+ elif isinstance(x,Symbol):
101
+ if n == 1:
102
+ return myst(r"""\py{latex_x}""", globals(), locals())
103
+ else:
104
+ return myst(r"""\py{latex_x}^{\py{n}}""", globals(), locals())
105
+ # Cas où x est strictement négatif
106
+ elif x<0:
107
+ if n == 1:
108
+ return myst(r"""\left(\py{latex_x}\right)""", globals(), locals())
109
+ else:
110
+ return myst(r"""\left(\py{latex_x}\right)^{\py{n}}""", globals(), locals())
111
+ # Cas où x est un nombre positif ou nul
112
+ else:
113
+ # Option 0: formatage standard
114
+ if opt == 0:
115
+ if n == 1:
116
+ return myst(r"""\py{latex_x}""", globals(), locals())
117
+ else:
118
+ return myst(r"""\py{latex_x}^{\py{n}}""", globals(), locals())
119
+
120
+ # Option 1: simplifie pour x=0, x=1 ou n=1
121
+ elif opt == 1:
122
+ if x == 1 or x == 0 or n == 1:
123
+ return myst(r"""\py{latex_x}""", globals(), locals())
124
+ else:
125
+ return myst(r"""\py{latex_x}^{\py{n}}""", globals(), locals())
126
+
127
+ # Option 2: simplifie davantage, chaîne vide pour x=0
128
+ else: # opt == 2 ou autres valeurs
129
+ if x == 0:
130
+ return myst(r""" """, globals(), locals())
131
+ elif x == 1 or n == 1:
132
+ return myst(r"""\py{latex_x}""", globals(), locals())
133
+ else:
134
+ return myst(r"""\py{latex_x}^{\py{n}}""", globals(), locals())
135
+
136
+ #################################################################################
137
+
138
+ def pxs_nvirgzero(x):
139
+ """
140
+ Fr : Fonction qui supprime .0 si le nombre a une valeur entière en le convertissant en int.
141
+ En : Function that removes .0 if the number has an integer value by converting it to int.
142
+
143
+ Version 2
144
+ ---------
145
+ 13/03/25
146
+
147
+ Vérification
148
+ ------------
149
+ Auteur : Ronan
150
+ Vérificateurs : Delphine
151
+
152
+ Paramètres
153
+ ----------
154
+ x : nombre
155
+
156
+ Retour
157
+ ------
158
+ int ou float :
159
+ si le nombre a une valeur entière avec une précision de E-10, il est transformé en int, sinon il n'est pas modifié.
160
+
161
+ Fonction utilisée par
162
+ ---------------------
163
+ pxsl_res_num, pxs_simul_law, pxsl_sum_vector
164
+
165
+ :pxs_trigger: suppression du .0 terminal, conversion float→int si valeur entière, nettoyage d'affichage numérique avant LaTeX, éviter "3.0" au lieu de "3", tolérance numérique aux erreurs de flottant
166
+ :pxs_returns: |
167
+ int si abs(x - int(x)) < 1e-10 (tolérance), sinon float inchangé.
168
+ Utilisé principalement juste avant latex(...) pour éviter ".0" parasites.
169
+ :pxs_example: |
170
+ a = pxs_nvirgzero(3.0) # -> 3 (int)
171
+ b = pxs_nvirgzero(2.00000000000004) # -> 2 (int, tolérance)
172
+ c = pxs_nvirgzero(0.235) # -> 0.235 (float, inchangé)
173
+ # Usage typique : myst(r"\\py{latex(pxs_nvirgzero(round(v, 4)))}", ...)
174
+ :pxs_antipattern: `int(x) if x == int(x) else x` — échoue silencieusement sur 2.00000000000004 qui devrait être traité comme 2.
175
+ """
176
+
177
+ if m.isclose(x, int(x), abs_tol=1e-10)==True:
178
+ x=int(x)
179
+ return x
180
+
181
+ # # #############################################################################################################
182
+ # # #### Début des essais #######
183
+ # # #############################################################################################################
184
+
185
+ # a=0.23546
186
+ # pxs_nvirgzero(a)
187
+ # retourne 0.23546
188
+ # b=3.0
189
+ # pxs_nvirgzero(b)
190
+ # retourne 3
191
+ # c=2.00000000000004
192
+ # pxs_nvirgzero(c)
193
+ # retourne 2
194
+
195
+ # # #############################################################################################################
196
+ # # #### Fin des essais ########
197
+ # # #############################################################################################################
198
+
199
+ def pxsl_res_num(x, dec=4, pourc=False, text=False, egal=True, dot = True):
200
+ """
201
+ Fr : Formate un nombre pour l'affichage avec LaTeX, avec gestion d'approximation.
202
+ En : Formats a number for display with LaTeX, with approximation handling.
203
+
204
+ Version 2
205
+ ---------
206
+ 13/03/25
207
+
208
+ Vérification
209
+ ------------
210
+ Auteur : Ronan
211
+ Vérificateurs : Delphine
212
+
213
+ Arguments:
214
+ x (float/str): Nombre à formater
215
+ dec (int): Nombre de décimales pour l'arrondi (défaut: 4)
216
+ pourc (bool): Si True, affiche également le résultat en pourcentage (défaut: False)
217
+ text (bool): Si True, utilise un format texte plus descriptif (défaut: False)
218
+ egal (bool): Si False, affichera simplement le nombre sans = ou approx devant
219
+
220
+ Returns:
221
+ str: Formule LaTeX formatée
222
+
223
+ Fonction utilisée par
224
+ ---------------------
225
+ Aucune fonction pyxiscience
226
+
227
+ :pxs_trigger: affichage résultat final d'un calcul probabiliste ou numérique, choix automatique entre "=" et "\\approx" selon exactitude de l'arrondi, conversion en pourcentage avec texte bilingue FR/EN, "soit environ X %"
228
+ :pxs_returns: |
229
+ str LaTeX. Si egal=True : préfixé par " = " (exact) ou " \\approx " (arrondi).
230
+ Si pourc=True : ajoute la version en pourcentage. Si text=True : texte descriptif bilingue "\\fr{environ}\\en{approximately}".
231
+ :pxs_example: |
232
+ p = 7/30
233
+ resultat = pxsl_res_num(p, dec=4, pourc=True)
234
+ # -> " \\approx 0.2333 \\%" en fait " \\approx 23.33 \\%"
235
+ # myst(r"La probabilité vaut \\py{resultat}", globals(), locals())
236
+ :pxs_antipattern: f" = {round(x, 4)}" ou f" \\approx {round(x*100, 2)}\\%" — ne distingue pas exact/approché et ne gère ni le bilinguisme ni le point final.
237
+ """
238
+ # Conversion et arrondi du nombre
239
+ valeur_precise = round(float(x), 10) # Conversion en float et arrondi à 10 décimales pour précision interne
240
+ valeur_arrondie = round(valeur_precise, dec) # Arrondi au nombre de décimales demandé
241
+
242
+ # Vérification si l'arrondi modifie la valeur (pour décider d'utiliser ≈ ou =)
243
+ valeur_precise_int = int(valeur_precise * (10**10)) # Conversion en entier pour comparaison précise
244
+ valeur_arrondie_int = int(valeur_arrondie * (10**10)) # Conversion de la valeur arrondie
245
+
246
+ # Définition du symbole et format selon que la valeur est exacte ou approximative
247
+ est_exact = (valeur_precise_int == valeur_arrondie_int)
248
+ symbole = "" if egal == False else (" = " if est_exact else " \\approx ")
249
+
250
+ # Construction de la formule LaTeX selon les paramètres
251
+ if text:
252
+ # Version texte descriptive
253
+ prefixe = "" if est_exact else " \\fr{ environ }\\en{ approximately } "
254
+
255
+ if pourc:
256
+ # Format pourcentage avec texte explicatif
257
+ texte_pourcentage = ", \\fr{ soit " + ("" if est_exact else "environ ") + "}\\en{that is " + ("" if est_exact else "approximately ") + "} "
258
+ if dot:
259
+ resultat = myst(r"""{0}$\py{{latex(pxs_nvirgzero(round(valeur_precise,dec)))}}${1}$\py{{latex(pxs_nvirgzero(round(100*valeur_precise,dec-2)))}}$ $\%$.""".format(
260
+ prefixe, texte_pourcentage), globals(), locals())
261
+ else:
262
+ resultat = myst(r"""{0}$\py{{latex(pxs_nvirgzero(round(valeur_precise,dec)))}}${1}$\py{{latex(pxs_nvirgzero(round(100*valeur_precise,dec-2)))}}$ $\%$""".format(
263
+ prefixe, texte_pourcentage), globals(), locals())
264
+ else:
265
+ # Format décimal simple
266
+ if dot:
267
+ resultat = myst(r"""{0}$\py{{latex(pxs_nvirgzero(round(valeur_precise,dec)))}}$.""".format(prefixe), globals(), locals())
268
+ else:
269
+ resultat = myst(r"""{0}$\py{{latex(pxs_nvirgzero(round(valeur_precise,dec)))}}$""".format(prefixe), globals(), locals())
270
+ else:
271
+ # Version concise avec symbole mathématique
272
+ if pourc:
273
+ # Format pourcentage
274
+ resultat = myst(r"""{0}\py{{latex(pxs_nvirgzero(round(100*valeur_precise,dec-2)))}} \%""".format(symbole), globals(), locals())
275
+ else:
276
+ # Format décimal simple
277
+ resultat = myst(r"""{0}\py{{latex(pxs_nvirgzero(round(valeur_precise,dec)))}}""".format(symbole), globals(), locals())
278
+
279
+ return resultat
280
+
281
+ # # #############################################################################################################
282
+ # # #### Début des essais #######
283
+ # # #############################################################################################################
284
+
285
+ # a=0.2354
286
+ # b=pxsl_res_num(a,dec=4,pourc=False,text=False)
287
+ # retourne "=0.2354"
288
+ # c=pxsl_res_num(a,dec=4,pourc=True,text=False)
289
+ # retourne "=23.45%"
290
+ # d=pxsl_res_num(a,dec=4,pourc=False,text=True)
291
+ # retourne "0.2354." centré
292
+ # e=pxsl_res_num(a,dec=4,pourc=True,text=True)
293
+ # retourne "est 0.2354, soit 23.54%"
294
+ # f=0.2354278
295
+ # g=pxsl_res_num(f,dec=4,pourc=False,text=False)
296
+ # retourne "\approx 0.2354"
297
+ # h=pxsl_res_num(f,dec=4,pourc=True,text=False)
298
+ # retourne "\approx 23.54%"
299
+ # i=pxsl_res_num(f,dec=4,pourc=False,text=True)
300
+ # retourne "est environ 0.2354"
301
+ # j=pxsl_res_num(f,dec=4,pourc=True,text=True)
302
+ # retourne "est environ 0.2354, soit environ 23.54%"
303
+
304
+ # # #############################################################################################################
305
+ # # #### Fin des essais ########
306
+ # # #############################################################################################################
307
+
308
+ def pxsl_scalar_product(a, b, prod="times",displaystyle=True):
309
+ """
310
+ Fr : Fonction permettant d'écrire le calcul du produit scalaire entre les deux vecteurs a et b.
311
+ En : Function to calculate the dot product between two vectors a and b.
312
+
313
+ Version 1
314
+ ---------
315
+ 02/03/25
316
+
317
+ Vérification
318
+ ------------
319
+ Auteur : Ronan
320
+ Vérificateurs : Delphine
321
+
322
+ Paramètres
323
+ ----------
324
+ a : liste
325
+ Premier vecteur du produit
326
+ b : liste
327
+ Deuxième vecteur du produit
328
+ prod : str
329
+ times : le symbole produit est \times
330
+ dot : le symbole produit est \cdot
331
+
332
+ Retour
333
+ ------
334
+ str
335
+ retourne l'expression en latex
336
+
337
+ Fonction utilisée par
338
+ ---------------------
339
+ Aucune fonction pyxiscience
340
+
341
+ :pxs_trigger: produit scalaire de deux vecteurs, somme de produits terme à terme a1×b1+a2×b2+..., calcul détaillé en LaTeX avec \\times ou \\cdot, développement de <u,v> pour exercice de géométrie ou probabilités
342
+ :pxs_returns: |
343
+ str LaTeX de la forme "a1 \\times b1 + a2 \\times b2 + ... + an \\times bn".
344
+ Chaque terme passe par pxsl_pow donc parenthèses auto sur nombres négatifs/Rational.
345
+ Retourne un message d'erreur LaTeX si listes vides ou tailles différentes.
346
+ :pxs_example: |
347
+ u = [Rational(1,2), 2]
348
+ v = [3, 4]
349
+ calcul = pxsl_scalar_product(u, v, prod="times")
350
+ # -> "\\frac{1}{2}\\times 3 + 2\\times 4"
351
+ # myst(r"\\langle u,v\\rangle = \\py{calcul}", globals(), locals())
352
+ :pxs_antipattern: " + ".join(f"{ai}\\times {bi}" for ai, bi in zip(a, b)) — casse sur négatifs (signe perdu) et fractions (pas de displaystyle).
353
+ """
354
+ # Vérification si une des listes est vide
355
+ if len(a) == 0 or len(b) == 0:
356
+ return myst(r""" \textrm{Attention liste vide}""")
357
+
358
+ # Vérification si les listes sont de tailles différentes
359
+ if len(a) != len(b):
360
+ return myst(r"""\textrm{Attention les deux listes ne sont pas de la même taille}""")
361
+
362
+ # Détermination de la taille des vecteurs
363
+ taille_vecteur = len(a)
364
+ dernier_index = taille_vecteur - 1
365
+
366
+ # Initialisation de la chaîne résultat
367
+ resultat = myst(r""" """)
368
+
369
+ # Détermination du symbole de produit à utiliser
370
+ symbole_produit = r"""\times""" if prod == "times" else r"""\cdot"""
371
+
372
+ # Construction de l'expression du produit scalaire terme à terme
373
+ for i in range(dernier_index):
374
+ # Ajout de chaque terme sauf le dernier, suivi du symbole +
375
+ resultat = resultat + pxsl_pow(a[i],displaystyle=displaystyle) + myst(symbole_produit) + pxsl_pow(b[i],displaystyle=displaystyle) + myst(r"""+ """)
376
+
377
+ # Ajout du dernier terme (sans symbole + à la fin)
378
+ resultat = resultat + pxsl_pow(a[dernier_index],displaystyle=displaystyle) + myst(f" {symbole_produit}") + pxsl_pow(b[dernier_index],displaystyle=displaystyle)
379
+
380
+ return resultat
381
+
382
+ # # #############################################################################################################
383
+ # # #### Début des essais #######
384
+ # # #############################################################################################################
385
+
386
+ # pxsl_scalar_product([1, 2], [3, 4], prod="times")
387
+ # renvoie la forme latex de 1x3+2x4
388
+ # pxsl_scalar_product([5, 6, 7], [8, 9, 10], prod="dot")
389
+ # renvoie la forme latex de 5.8+6.9+7.10
390
+ # pxsl_scalar_product([Rational(1,2), 2], [3, 4])
391
+ # renvoie la forme latex de 1/2x3+2x4 avec displaystyle actif
392
+ # pxsl_scalar_product([Rational(1,2), 2], [3, 4],displaystyle=False)
393
+ # renvoie la forme latex de 1/2x3+2x4 avec displaystyle inactif
394
+ # pxsl_scalar_product([], [])
395
+ # renvoie un message indiquant qu'une des listes est vide
396
+ # pxsl_scalar_product([5], [10])
397
+ # renvoie la forme latex de 5x10
398
+ # pxsl_scalar_product([5,2], [10])
399
+ # renvoie un message indiquant que les listes ne sont pas de la même taille
400
+
401
+ # # #############################################################################################################
402
+ # # #### Fin des essais ########
403
+ # # #############################################################################################################
404
+
405
+ def pxsl_moment(X, n=1, prod="times",displaystyle=True):
406
+ """
407
+ Fr : Fonction permettant d'écrire le calcul du moment d'ordre n de la variable aléatoire finie X.
408
+ En : Function to calculate the nth order moment of the finite random variable X.
409
+
410
+ Version 1
411
+ ---------
412
+ 02/03/25
413
+
414
+ Vérification
415
+ ------------
416
+ Auteur : Ronan
417
+ Vérificateurs : Delphine
418
+
419
+ Paramètres
420
+ ----------
421
+ X : variable aléatoire finie
422
+
423
+ n : int
424
+ Ordre du moment
425
+
426
+ prod : str
427
+ times : le symbole produit est \times
428
+ dot : le symbole produit est \cdot
429
+
430
+ Retour
431
+ ------
432
+ str
433
+ retourne l'expression en latex
434
+
435
+ Fonction utilisée par
436
+ ---------------------
437
+ Aucune fonction pyxiscience
438
+
439
+ :pxs_trigger: calcul détaillé espérance E(X) ou E(X^n) d'une variable aléatoire finie sympy, moment d'ordre n, écriture développée Σ x_i^n × P(X=x_i), exercice "calculer E(X)" ou "calculer la variance" avec étape détaillée
440
+ :pxs_returns: |
441
+ str LaTeX de la forme "x1^n \\times p1 + x2^n \\times p2 + ... + xk^n \\times pk".
442
+ Valeurs triées par clé croissante. pxsl_pow gère les parenthèses autour de valeurs négatives et des Rational.
443
+ :pxs_example: |
444
+ X = stats.FiniteRV('X', {-1: Rational(1,4), 0: Rational(1,2), 1: Rational(1,4)})
445
+ calcul_esp = pxsl_moment(X, n=1) # pour E(X)
446
+ calcul_var = pxsl_moment(X, n=2) # pour E(X^2)
447
+ # myst(r"E(X) = \\py{calcul_esp}", globals(), locals())
448
+ :pxs_antipattern: boucler manuellement `density(X).dict.items()` et concaténer `f"{k}^{n} * {v} + "` — rate le tri, les parenthèses sur négatifs et le displaystyle des fractions.
449
+ """
450
+ # Récupération et tri des éléments de la variable aléatoire
451
+ loi_proba = stats.density(X).dict
452
+ loi_proba_triee = dict(sorted(loi_proba.items()))
453
+ valeurs = list(loi_proba_triee.keys())
454
+ probabilites = list(loi_proba_triee.values())
455
+
456
+ # Vérification si la distribution est vide
457
+ if len(valeurs) == 0:
458
+ return myst(r""" Attention distribution vide""")
459
+
460
+ # Détermination du symbole de produit à utiliser
461
+ symbole_produit = r"""\times""" if prod == "times" else r"""\cdot"""
462
+
463
+ # Initialisation du résultat
464
+ resultat = myst(r""" """)
465
+
466
+ # Construction de l'expression du moment terme à terme
467
+ dernier_index = len(valeurs) - 1
468
+
469
+ # Ajout de tous les termes sauf le dernier
470
+ for i in range(dernier_index):
471
+ resultat = resultat + pxsl_pow(valeurs[i], n,displaystyle=displaystyle) + myst(symbole_produit) + pxsl_pow(probabilites[i],displaystyle=displaystyle) + myst(r"""+ """)
472
+
473
+ # Ajout du dernier terme (sans symbole + à la fin)
474
+ resultat = resultat + pxsl_pow(valeurs[dernier_index], n,displaystyle=displaystyle) + myst(f" {symbole_produit}") + pxsl_pow(probabilites[dernier_index],displaystyle=displaystyle)
475
+
476
+ return resultat
477
+
478
+ # # #############################################################################################################
479
+ # # #### Début des essais #######
480
+ # # #############################################################################################################
481
+
482
+ # Calcul du moment d'ordre 1 d'une loi de Bernouilli
483
+ # X = stats.FiniteRV('X', {0: 0.3, 1: 0.7})
484
+ # pxsl_moment(X, n=1, prod="times")
485
+ # renvoie l'expression latex de 0 x 0.3 + 1 x 0.7
486
+
487
+ # Calcul du moment d'ordre 2 pour un dé à 6 faces displaystyle actif
488
+ # Y = stats.FiniteRV('Y', {1: Rational(1,6), 2: Rational(1,6), 3: Rational(1,6), 4: Rational(1,6), 5: Rational(1,6), 6: Rational(1,6)})
489
+ # pxsl_moment(Y, n=2, prod="dot")
490
+ # renvoie l'expression latex de 1^2.1/6+2^2.1/6+3^2.1/6+4^2.1/6+5^2.1/6+6^2.1/6 les fractions étant écrite en displaystyle
491
+
492
+ # Calcul du moment d'ordre 2 pour un dé à 6 faces, displaystyle inactif
493
+ # Z = stats.FiniteRV('Z', {1: Rational(1,6), 2: Rational(1,6), 3: Rational(1,6), 4: Rational(1,6), 5: Rational(1,6), 6: Rational(1,6)})
494
+ # pxsl_moment(Z, n=2, prod="dot",displaystyle=False)
495
+ # même résultat que pour Y mais sans le format displaystyle
496
+
497
+ # Loi simple - moment d'ordre 3
498
+ # W = stats.FiniteRV('W', {-1: 0.25, 0: 0.5, 1: 0.25})
499
+ # pxsl_moment(W, n=3, prod="times")
500
+ # renvoie l'expression latex de (-1)^3 x 0.25+0^3 x 0.5 + 1^3 x 0.25
501
+
502
+ # # #############################################################################################################
503
+ # # #### Fin des essais ########
504
+ # # #############################################################################################################
505
+
506
+ def pxsl_law(textx, textprob, X, frac="", nzero=True):
507
+ """
508
+ Fr : Fonction permettant d'écrire le tableau de loi d'une variable aléatoire X finie.
509
+ En : Function to write the probability distribution table of a finite random variable X.
510
+
511
+ Version 1
512
+ ---------
513
+ 02/03/25
514
+
515
+ Vérification
516
+ ------------
517
+ Auteur : Ronan
518
+ Vérificateurs : Delphine
519
+
520
+ Paramètres
521
+ ----------
522
+ textx : str
523
+ Entrée de la première ligne du tableau de loi (valeurs possibles)
524
+ Peut contenir du LaTeX directement (sans échappement)
525
+
526
+ textprob : str
527
+ Entrée de la deuxième ligne du tableau de loi (probabilités)
528
+ Peut contenir du LaTeX directement (sans échappement)
529
+
530
+ X : variable aléatoire finie
531
+ Variable aléatoire dont on veut afficher la loi
532
+
533
+ frac : str, optional
534
+ "/" : les fractions sont représentées avec / (notation simple)
535
+ "" : les fractions sont représentées avec la commande \frac{}{} (défaut)
536
+
537
+ nzero : boolean, optional
538
+ True : les probabilités nulles ne sont pas représentées (défaut)
539
+ False : les probabilités nulles sont représentées
540
+
541
+ Retour
542
+ ------
543
+ str
544
+ Retourne un tableau LaTeX contenant la loi de probabilité
545
+
546
+ Fonction utilisée par
547
+ ---------------------
548
+ Aucune fonction pyxiscience
549
+
550
+ :pxs_trigger: tableau de loi d'une variable aléatoire discrète finie, ligne x_i + ligne P(X=x_i), représenter la distribution d'une VA dans un énoncé ou une correction, table à 2 lignes valeurs/probabilités avec entêtes LaTeX personnalisées
551
+ :pxs_returns: |
552
+ str LaTeX d'un \\begin{array}{...} à 2 lignes (valeurs, probabilités) avec séparateurs verticaux.
553
+ Les fractions sont rendues en \\displaystyle par défaut. Les probabilités nulles sont masquées si nzero=True.
554
+ :pxs_example: |
555
+ X = stats.FiniteRV('X', {1: Rational(1,6), 2: Rational(1,6), 3: Rational(1,6),
556
+ 4: Rational(1,6), 5: Rational(1,6), 6: Rational(1,6)})
557
+ tableau = pxsl_law("x_i", "P(X=x_i)", X)
558
+ # myst(r"La loi de X est donnée par : \\py{tableau}", globals(), locals())
559
+ :pxs_antipattern: construire à la main `\\begin{array}{|c|c|c|}` avec une boucle sur `density(X).dict.items()` et `latex(v)` — duplique la logique de tri, de gestion des zéros et du displaystyle.
560
+ """
561
+ # Récupération et tri des éléments de la variable aléatoire
562
+ loi_proba = stats.density(X).dict
563
+ loi_proba_triee = dict(sorted(loi_proba.items()))
564
+
565
+ # Filtrage des probabilités nulles si demandé
566
+ if nzero:
567
+ loi_proba_triee = {k: v for k, v in loi_proba_triee.items() if v != 0}
568
+
569
+ # Extraction des valeurs et probabilités
570
+ valeurs = list(loi_proba_triee.keys())
571
+ probabilites = list(loi_proba_triee.values())
572
+ nb_valeurs = len(valeurs)
573
+
574
+ # Configuration du tableau LaTeX
575
+ largeur_colonnes = 'ccc|' * (nb_valeurs + 1)
576
+ ligne_vide = '&' * (nb_valeurs * 3 + 2)
577
+
578
+ # Début du tableau
579
+ resultat = myst(r""" \begin{array}{|\py{largeur_colonnes}} \hline """, globals(), locals())
580
+
581
+ # Construction de la première ligne (valeurs possibles) - Les en-têtes sont passés tels quels
582
+ resultat = resultat + myst(r""" \py{ligne_vide} \\""", globals(), locals())
583
+ resultat = resultat + myst(r""" & \py{textx} & """, globals(), locals())
584
+
585
+ for i in range(nb_valeurs):
586
+ if frac == "/":
587
+ # Affichage simple sans utiliser \frac
588
+ resultat = resultat + myst(r"""& & \py{valeurs[i]} & """, globals(), locals())
589
+ else:
590
+ # Affichage avec \displaystyle pour les fractions
591
+ resultat = resultat + myst(r"""& & \displaystyle \py{latex(valeurs[i])} & """, globals(), locals())
592
+
593
+ resultat = resultat + myst(r"""\\ """)
594
+ resultat = resultat + myst(r""" \py{ligne_vide} \\""", globals(), locals())
595
+ resultat = resultat + myst(r"""\hline """)
596
+
597
+ # Construction de la deuxième ligne (probabilités)
598
+ resultat = resultat + myst(r""" \py{ligne_vide} \\""", globals(), locals())
599
+ resultat = resultat + myst(r""" & \py{textprob} & """, globals(), locals())
600
+
601
+ for i in range(nb_valeurs):
602
+ if frac == "/":
603
+ # Affichage simple des probabilités
604
+ resultat = resultat + myst(r"""& & \py{probabilites[i]} &""", globals(), locals())
605
+ else:
606
+ # Affichage des probabilités avec \displaystyle pour les fractions
607
+ resultat = resultat + myst(r"""& & \displaystyle \py{latex(probabilites[i])} &""", globals(), locals())
608
+
609
+ resultat = resultat + myst(r"""\\ """)
610
+ resultat = resultat + myst(r""" \py{ligne_vide} \\""", globals(), locals())
611
+
612
+ # Fin du tableau
613
+ resultat = resultat + myst(r"""\hline """)
614
+ resultat = resultat + myst(r"""\end{array}""")
615
+
616
+ return resultat
617
+
618
+ # # #############################################################################################################
619
+ # # #### Début des essais #######
620
+ # # #############################################################################################################
621
+
622
+ # Affichage entête simple
623
+ # X = stats.FiniteRV('X', {0: 0.3, 1: 0.7})
624
+ # pxsl_law("x", "P(X=x)", X)
625
+ # renvoie un tableau 2 lignes, 3 colonnes
626
+ # | x | 0 | 1 |
627
+ # |P(X=x)|0.3|0.7|
628
+
629
+ # Affichage entête mathématique
630
+ # X2 = stats.FiniteRV('X2', {1: Rational(1,6), 2: Rational(1,6), 3: Rational(1,6), 4: Rational(1,6), 5: Rational(1,6), 6: Rational(1,6)})
631
+ # pxsl_law("y", "P(Y=y)", X2)
632
+ # renvoie un tableau 2 lignes, 7 colonnes (fractions écrites en displaystyle)
633
+ # | y | 1 | 2 | 3 | 4 | 5 | 6 |
634
+ # |P(Y=y)|1/6|1/6|1/6|1/6|1/6|1/6|
635
+
636
+ # Choix d'affichage des zéros
637
+ # Z = stats.FiniteRV('Z', {1: 0.2, 2: 0, 3: 0.5, 4: 0, 5: 0.3})
638
+ # Sans les zéros
639
+ # pxsl_law("z", "P(Z=z)", Z)
640
+ # renvoie un tableau 2 lignes, 4 colonnes
641
+ # | z | 1 | 3 | 5 |
642
+ # |P(Z=z)|0.2|0.5|0.3|
643
+ # Avec les zéros
644
+ # pxsl_law("z", "P(Z=z)", Z, nzero=False)
645
+ # renvoie un tableau 2 lignes, 6 colonnes
646
+ # | z | 1 | 2 | 3 | 4 | 5 |
647
+ # |P(Z=z)|0.2| 0 |0.5| 0 |0.3|
648
+
649
+ # Variable avec valeur fractionnaire
650
+ # W = stats.FiniteRV('W', {Rational(1, 3): 0.25, Rational(2, 3): 0.25, 1: 0.5})
651
+ # pxsl_law("z", "P(Z=z)", W)
652
+ # renvoie un tableau 2 lignes, 4 colonnes, les fractions sont en displaystyle
653
+ # | z |1/3 |2/3 | 1 |
654
+ # |P(Z=z)|0.25|0.25|0.5|
655
+
656
+ # Affichage entête personnalisée
657
+ # stats.FiniteRV('Z', {1: 0.4, 2: 0.6})
658
+ # pxsl_law(r"\text{Valeur} ~ z", r"\text{Probabilité} ~ P(Z=z)", Z)
659
+ # renvoie un tableau 2 lignes, 3 colonnes
660
+ # | Valeur z | 1 | 2 |
661
+ # |Probabilité P(Z=z)|0.4|0.6|
662
+ # stats.FiniteRV('W', {10: 0.25, 20: 0.25, 30: 0.5})
663
+ # pxsl_law("w", "P_W(w)", W)
664
+ # renvoie un tableau 2 lignes, 4 colonnes (le P_W(w) est interprêté en latex)
665
+ # | w | 10 | 20 | 30 |
666
+ # |P_W(w)|0.25|0.25|0.5 |
667
+
668
+ # # #############################################################################################################
669
+ # # #### Fin des essais ########
670
+ # # #############################################################################################################
671
+
672
+ def pxs_simul_law(n, type_proba="dec", prec=0.01, nzero=True):
673
+ """
674
+ Fr : Fonction permettant de simuler une loi de probabilité discrète de taille n.
675
+ En : Function to simulate a discrete probability distribution of size n.
676
+
677
+ Version 1
678
+ ---------
679
+ 02/03/25
680
+
681
+ Vérification
682
+ ------------
683
+ Auteur : Ronan
684
+ Vérificateurs : Delphine
685
+
686
+ Paramètres:
687
+ -----------
688
+ n : int
689
+ Nombre de valeurs possibles de la loi
690
+
691
+ type_proba : str
692
+ Format des probabilités générées
693
+ - "dec" : nombres décimaux (entre 0 et 1)
694
+ - "perc" : pourcentages (entre 0 et 100)
695
+ - "frac" : fractions
696
+
697
+ prec : float ou int
698
+ - Si type=="dec" ou "perc" : les probabilités seront des multiples de prec
699
+ - Si type=="frac" : prec est un entier, les probabilités seront des multiples de 1/prec
700
+
701
+ nzero : bool
702
+ - True : les probabilités seront non nulles si possible
703
+ - False : les probabilités peuvent être nulles
704
+
705
+ Retour:
706
+ -------
707
+ list
708
+ Liste des probabilités (la somme vaut 1 ou 100 selon le type)
709
+
710
+ Fonction utilisée par
711
+ ---------------------
712
+ Aucune fonction pyxiscience
713
+
714
+ :pxs_trigger: génération aléatoire des probabilités d'un énoncé probabiliste, simulation d'une loi discrète dont la somme vaut exactement 1 (ou 100%), création de données pour exercices variabilisés, choix décimal/pourcentage/fraction avec précision contrôlée
715
+ :pxs_returns: |
716
+ list de longueur n. Somme exacte = 1 (dec), 100 (perc) ou 1 (frac).
717
+ En mode "frac" : liste de sympy.Rational avec dénominateur prec. Ordre aléatoire (shuffle final).
718
+ Avec nzero=True : toutes les entrées sont > 0 si faisable.
719
+ :pxs_example: |
720
+ probas = pxs_simul_law(4, type_proba="frac", prec=12)
721
+ # ex: [Rational(1,2), Rational(1,3), Rational(1,12), Rational(1,12)]
722
+ X = pxs_finiterv('X', [5, 10, 15, 20], probas)
723
+ tableau = pxsl_law("x_i", "P(X=x_i)", X)
724
+ :pxs_antipattern: `probas = [random.random() for _ in range(n)]; probas = [p/sum(probas) for p in probas]` — pas de précision contrôlée, ne garantit pas la somme exacte après arrondi, pas de support Rational.
725
+ """
726
+
727
+ resultat = []
728
+
729
+ # Cas des pourcentages (entre 0 et 100)
730
+ if type_proba == "perc":
731
+ total_restant = 100
732
+ compteur = 1
733
+ probas_temp = []
734
+ precision_log = m.floor(m.log10(prec))
735
+ valeur = rd.randint(0, int(round(total_restant/(2*prec)))) * prec
736
+ if precision_log < 0:
737
+ valeur = round(valeur, -precision_log)
738
+ probas_temp.append(pxs_nvirgzero(valeur))
739
+
740
+ while compteur < (n-1):
741
+ total_restant = 100 - sum(probas_temp)
742
+ valeur = rd.randint(0, int(round(total_restant/(2*prec)))) * prec
743
+ if precision_log < 0:
744
+ valeur = round(valeur, -precision_log)
745
+ probas_temp.append(pxs_nvirgzero(valeur))
746
+ compteur += 1
747
+
748
+ valeur = 100 - sum(probas_temp)
749
+ if precision_log < 0:
750
+ valeur = round(valeur, -precision_log)
751
+ probas_temp.append(pxs_nvirgzero(valeur))
752
+
753
+ # Si on veut des valeurs non nulles et que c'est possible
754
+ if nzero == True and prec*(n-1) < 100:
755
+ produit = 1
756
+ taille = len(probas_temp)
757
+ for i in range(taille):
758
+ produit *= probas_temp[i]
759
+
760
+ while produit == 0: # S'il y a au moins un zéro
761
+ total_restant = 100
762
+ compteur = 1
763
+ probas_temp = []
764
+ precision_log = m.floor(m.log10(prec))
765
+ valeur = rd.randint(0, int(round(total_restant/(2*prec)))) * prec
766
+ if precision_log < 0:
767
+ valeur = round(valeur, -precision_log)
768
+ probas_temp.append(pxs_nvirgzero(valeur))
769
+
770
+ while compteur < (n-1):
771
+ total_restant = 100 - sum(probas_temp)
772
+ valeur = rd.randint(0, int(round(total_restant/(2*prec)))) * prec
773
+ if precision_log < 0:
774
+ valeur = round(valeur, -precision_log)
775
+ probas_temp.append(pxs_nvirgzero(valeur))
776
+ compteur += 1
777
+
778
+ valeur = 100 - sum(probas_temp)
779
+ if precision_log < 0:
780
+ valeur = round(valeur, -precision_log)
781
+ probas_temp.append(pxs_nvirgzero(valeur))
782
+
783
+ # Recalculer le produit
784
+ produit = 1
785
+ for i in range(taille):
786
+ produit *= probas_temp[i]
787
+
788
+ resultat = probas_temp
789
+
790
+ # Cas des décimaux (entre 0 et 1)
791
+ elif type_proba == "dec":
792
+ total_restant = 1
793
+ compteur = 1
794
+ probas_temp = []
795
+ precision_log = m.floor(m.log10(prec))
796
+ valeur = rd.randint(0, int(round(total_restant/(2*prec)))) * prec
797
+ if precision_log < 0:
798
+ valeur = round(valeur, -precision_log)
799
+ probas_temp.append(pxs_nvirgzero(valeur))
800
+
801
+ while compteur < (n-1):
802
+ total_restant = 1 - sum(probas_temp)
803
+ valeur = rd.randint(0, int(round(total_restant/(2*prec)))) * prec
804
+ if precision_log < 0:
805
+ valeur = round(valeur, -precision_log)
806
+ probas_temp.append(pxs_nvirgzero(valeur))
807
+ compteur += 1
808
+
809
+ valeur = 1 - sum(probas_temp)
810
+ if precision_log < 0:
811
+ valeur = round(valeur, -precision_log)
812
+ probas_temp.append(pxs_nvirgzero(valeur))
813
+
814
+ # Si on veut des valeurs non nulles et que c'est possible
815
+ if nzero == True and prec*(n-1) < 1:
816
+ produit = 1
817
+ taille = len(probas_temp)
818
+ for i in range(taille):
819
+ produit *= probas_temp[i]
820
+
821
+ while produit == 0: # S'il y a au moins un zéro
822
+ total_restant = 1
823
+ compteur = 1
824
+ probas_temp = []
825
+ precision_log = m.floor(m.log10(prec))
826
+ valeur = rd.randint(0, int(round(total_restant/(2*prec)))) * prec
827
+ if precision_log < 0:
828
+ valeur = round(valeur, -precision_log)
829
+ probas_temp.append(pxs_nvirgzero(valeur))
830
+
831
+ while compteur < (n-1):
832
+ total_restant = 1 - sum(probas_temp)
833
+ valeur = rd.randint(0, int(round(total_restant/(2*prec)))) * prec
834
+ if precision_log < 0:
835
+ valeur = round(valeur, -precision_log)
836
+ probas_temp.append(pxs_nvirgzero(valeur))
837
+ compteur += 1
838
+
839
+ valeur = 1 - sum(probas_temp)
840
+ if precision_log < 0:
841
+ valeur = round(valeur, -precision_log)
842
+ probas_temp.append(pxs_nvirgzero(valeur))
843
+
844
+ # Recalculer le produit
845
+ produit = 1
846
+ for i in range(len(probas_temp)):
847
+ produit *= probas_temp[i]
848
+
849
+ resultat = probas_temp
850
+
851
+ # Cas des fractions
852
+ elif type_proba == "frac":
853
+ total_restant = prec
854
+ compteur = 1
855
+ probas_temp = []
856
+ probas_temp.append(Rational(rd.randint(0, int(round(total_restant/2))), prec))
857
+
858
+ while compteur < (n-1):
859
+ total_restant = int(prec - sum(probas_temp)*prec)
860
+ probas_temp.append(Rational(rd.randint(0, int(round(total_restant/2))), prec))
861
+ compteur += 1
862
+
863
+ probas_temp.append(Rational(prec - sum(probas_temp*prec), prec))
864
+
865
+ # Si on veut des valeurs non nulles et que c'est possible
866
+ if nzero == True and n <= prec:
867
+ produit = 1
868
+ taille = len(probas_temp)
869
+ for i in range(taille):
870
+ produit *= probas_temp[i]
871
+
872
+ while produit == 0: # S'il y a au moins un zéro
873
+ total_restant = prec
874
+ compteur = 1
875
+ probas_temp = []
876
+ probas_temp.append(Rational(rd.randint(0, int(round(total_restant/2))), prec))
877
+
878
+ while compteur < (n-1):
879
+ total_restant = int(prec - sum(probas_temp)*prec)
880
+ probas_temp.append(Rational(rd.randint(0, int(round(total_restant/2))), prec))
881
+ compteur += 1
882
+
883
+ probas_temp.append(Rational(prec - sum(probas_temp*prec), prec))
884
+
885
+ # Recalculer le produit
886
+ produit = 1
887
+ for i in range(len(probas_temp)):
888
+ produit *= probas_temp[i]
889
+
890
+ resultat = probas_temp
891
+
892
+ # Mélange des probabilités pour avoir un ordre aléatoire
893
+ rd.shuffle(resultat)
894
+ return resultat
895
+
896
+ # # #############################################################################################################
897
+ # # #### Début des essais #######
898
+ # # #############################################################################################################
899
+
900
+ # 1. Test avec type "dec" (décimal, valeur par défaut)
901
+ # Test avec paramètres par défaut
902
+ # pxs_simul_law(n=5)
903
+ # renvoie par exemple la liste [0.2,0.04,0.47,0.23,0.06]
904
+
905
+ # Test avec une précision différente
906
+ # pxs_simul_law(n=4, prec=0.05)
907
+ # renvoie par exemple la liste [0.4,0.3,0.25,0.05]
908
+
909
+ # Test avec sans_zero=False
910
+ # pxs_simul_law(n=6, nzero=False)
911
+ # renvoie par exemple la liste [0.45,0.19,0.09,0.17,0.1,0]
912
+
913
+ # Test avec un grand nombre de valeurs
914
+ # pxs_simul_law(n=10, prec=0.001)
915
+ # renvoie par exemple la liste [0.012,0.191,0.134,0.187,0.05,0.046,0.078,0.043,0.024,0.235]
916
+
917
+ # 2. Test avec type "perc" (pourcentage)
918
+ # pxs_simul_law(n=4, type_proba="perc", prec=0.5)
919
+ # renvoie par exemple la liste [1.5,43.5,47,8]
920
+
921
+ # 3. Test avec type "frac" (fraction)
922
+ # pxs_simul_law(n=4, type_proba="frac", prec=12)
923
+ # renvoie par exemple la liste [1/2,1/3,1/12,1/12]
924
+
925
+ # # #############################################################################################################
926
+ # # #### Fin des essais ########
927
+ # # #############################################################################################################
928
+
929
+ def pxs_fct_finiterv(f, X):
930
+ """
931
+ Fr : Transforme une variable aléatoire finie X via une fonction f.
932
+ Cette fonction crée une nouvelle variable aléatoire Y = f(X) en appliquant
933
+ la fonction f à chaque valeur possible de X et en adaptant les probabilités.
934
+ En : Transforms a finite random variable X using a function f.
935
+ This function creates a new random variable Y = f(X) by applying
936
+ the function f to each possible value of X and adapting the probabilities accordingly.
937
+
938
+ Version 1
939
+ ---------
940
+ 02/03/25
941
+
942
+ Vérification
943
+ ------------
944
+ Auteur : Ronan
945
+ Vérificateurs : Delphine
946
+
947
+ Paramètres
948
+ ----------
949
+ f : function
950
+ Fonction à appliquer à la variable aléatoire X
951
+ X : RandomSymbol
952
+ Variable aléatoire finie source
953
+
954
+ Retour
955
+ ------
956
+ RandomSymbol
957
+ Variable aléatoire finie Y = f(X)
958
+
959
+ Fonction utilisée par
960
+ ---------------------
961
+ Aucune fonction pyxiscience
962
+
963
+ :pxs_trigger: création de Y=f(X) à partir d'une VA finie X (Y=X², Y=|X|, Y=floor(X), Y=1_{X>a}), calcul de la loi de image d'une VA, agrégation automatique des probabilités quand f n'est pas injective
964
+ :pxs_returns: |
965
+ stats.FiniteRV nommé "Y" : nouvelle variable aléatoire finie sympy avec pour support {f(x): sum_{k:f(k)=f(x)} P(X=k)}.
966
+ Prêt à être passé à pxsl_law, pxsl_moment, stats.E(), stats.variance()...
967
+ :pxs_example: |
968
+ X = stats.FiniteRV('X', {-2: 0.25, -1: 0.25, 1: 0.25, 2: 0.25})
969
+ Y = pxs_fct_finiterv(lambda x: x**2, X) # Y=X², support {1: 0.5, 4: 0.5}
970
+ tableau_Y = pxsl_law("y_i", "P(Y=y_i)", Y)
971
+ # myst(r"Loi de Y=X^2 : \\py{tableau_Y}", globals(), locals())
972
+ :pxs_antipattern: `{f(k): v for k, v in density(X).dict.items()}` — écrase les probabilités quand f non injective (ex : f(-1)=f(1)=1) au lieu de les sommer.
973
+ """
974
+
975
+ # Initialisation du nouveau dictionnaire de probabilités
976
+ dico = {}
977
+
978
+ # Pour chaque valeur possible de X et sa probabilité associée
979
+ for key, value in density(X).dict.items():
980
+ # Appliquer f à la valeur
981
+ newkey = f(key)
982
+
983
+ # Si la valeur transformée existe déjà, on ajoute la probabilité
984
+ # (cas où plusieurs valeurs de X donnent la même valeur après transformation)
985
+ if newkey in dico:
986
+ dico[newkey] = dico[newkey] + value
987
+ else:
988
+ dico[newkey] = value
989
+
990
+ # Création du nom de la nouvelle variable aléatoire
991
+ Name = "Y"
992
+
993
+ # Création de la nouvelle variable aléatoire
994
+ Y = stats.FiniteRV(Name, dico)
995
+
996
+ return Y
997
+
998
+ # # #############################################################################################################
999
+ # # #### Début des essais #######
1000
+ # # #############################################################################################################
1001
+
1002
+ # Définir une pièce biaisée (70% face, 30% pile)
1003
+ # piece_biaisee = stats.FiniteRV('piece_biaisee', {0: 0.3, 1: 0.7})
1004
+
1005
+ # Définir une variable discrète représentant le nombre d'enfants dans une famille
1006
+ # nb_enfants = stats.FiniteRV('nb_enfants', {0: 0.1, 1: 0.3, 2: 0.4, 3: 0.15, 4: 0.05})
1007
+
1008
+ # Cas 1: Fonction définie directement (lambda x: x**2)
1009
+ # pxs_fct_finiterv(lambda x: x**2, X2)
1010
+ # renvoie stats.FiniteRV('Y',{1: Rational(1,6), 4: Rational(1,6), 9: Rational(1,6), 16: Rational(1,6), 25: Rational(1,6), 36: Rational(1,6)})
1011
+
1012
+ # Cas 2: Fonctions mathématiques standard
1013
+ # pxs_fct_finiterv(exp, X2)
1014
+ # renvoie stats.FiniteRV('Y',{e: Rational(1,6), e^2: Rational(1,6), e^3: Rational(1,6), e^4: Rational(1,6), e^5: Rational(1,6), e^6: Rational(1,6)})
1015
+ # pxs_fct_finiterv(sqrt, X2)
1016
+ # renvoie stats.FiniteRV('Y',{1: Rational(1,6), sqrt(2): Rational(1,6), sqrt(3): Rational(1,6), 2: Rational(1,6), sqrt(5): Rational(1,6), sqrt(6): Rational(1,6)})
1017
+
1018
+ # Cas 3: Fonctions de partie entière
1019
+ # notes = stats.FiniteRV('notes', {8.5: 0.05, 8.7: 0.1, 11.3: 0.15, 11.6: 0.2,14.9: 0.15, 15.5: 0.2, 17.8: 0.15})
1020
+ # pxs_fct_finiterv(floor, notes)
1021
+ # renvoie stats.FiniteRV('Y',{8: 0.15, 11: 0.35, 14: 0.15, 15: 0.2, 17: 0.15})
1022
+ # pxs_fct_finiterv(ceiling, notes)
1023
+ # renvoie stats.FiniteRV('Y',{9: 0.15, 12: 0.35, 15: 0.15, 16: 0.2, 18: 0.15})
1024
+
1025
+ # Cas 4: Fonctions indicatrices
1026
+ # nb_enfants = stats.FiniteRV('nb_enfants', {0: 0.1, 1: 0.3, 2: 0.4, 3: 0.15, 4: 0.05})
1027
+ # Indicatrice (x > 2)
1028
+ # pxs_fct_finiterv(lambda x: 1 if x > 2 else 0, nb_enfants)
1029
+ # renvoie stats.FiniteRV('Y',{0: 0.8, 1: 0.2})
1030
+ # Indicatrice (x est pair)
1031
+ # pxs_fct_finiterv(lambda x: 1 if x % 2 == 0 else 0, nb_enfants)
1032
+ # renvoie stats.FiniteRV('Y',{0: 0.45, 1: 0.55})
1033
+
1034
+ # # #############################################################################################################
1035
+ # # #### Fin des essais ########
1036
+ # # #############################################################################################################
1037
+
1038
+ def pxsl_sum_vector(x):
1039
+ """
1040
+ Fr : Fonction permettant d'écrire la somme des éléments du vecteur x
1041
+ En: Function to calculate the sum of elements in vector x
1042
+
1043
+ Version
1044
+ -------
1045
+ 02/03/25
1046
+
1047
+ Vérification
1048
+ ------
1049
+ Auteur : Ronan
1050
+ Vérificateurs : Delphine
1051
+
1052
+ Paramètres
1053
+ ----------
1054
+ x : liste
1055
+
1056
+ Retour
1057
+ ------
1058
+ str
1059
+ retourne la somme de la liste de x
1060
+
1061
+ Fonction utilisée par
1062
+ ---------------------
1063
+ Aucune fonction pyxiscience
1064
+
1065
+ :pxs_trigger: affichage LaTeX d'une somme d'entiers/décimaux signés, écriture "a - b + c" avec gestion automatique des signes + et -, détail du calcul d'une somme algébrique d'une liste, linéarisation d'un résultat (ex : total d'une série)
1066
+ :pxs_returns: |
1067
+ str LaTeX. Premier terme : "-v" si négatif, "v" sinon (pas de "+" initial).
1068
+ Termes suivants : " -|v|" si négatif, " +v" si positif. Passe par pxs_nvirgzero pour nettoyer les .0.
1069
+ :pxs_example: |
1070
+ valeurs = [2, -1, 3, -4]
1071
+ somme_latex = pxsl_sum_vector(valeurs) # -> "2 -1 +3 -4"
1072
+ # myst(r"S = \\py{somme_latex} = \\py{sum(valeurs)}", globals(), locals())
1073
+ :pxs_antipattern: `" + ".join(str(v) for v in liste)` qui produit "2 + -1 + 3 + -4" (double opérateur laid) au lieu de "2 - 1 + 3 - 4".
1074
+ """
1075
+ s=len(x)
1076
+ if x[0]<0:
1077
+ d=myst(r""" -\py{latex(pxs_nvirgzero(abs(x[0])))}""",globals(),locals())
1078
+ else:
1079
+ d=myst(r"""\py{latex(pxs_nvirgzero(x[0]))}""",globals(),locals())
1080
+ for i in range(1,s):
1081
+ if x[i]<0:
1082
+ d=d+myst(r""" -\py{latex(pxs_nvirgzero(abs(x[i])))}""",globals(),locals())
1083
+ else:
1084
+ d=d+myst(r""" +\py{latex(pxs_nvirgzero(x[i]))}""",globals(),locals())
1085
+ return d
1086
+
1087
+ # # #############################################################################################################
1088
+ # # #### Début des essais #######
1089
+ # # #############################################################################################################
1090
+
1091
+ # a=[2,-1]
1092
+ # pxsl_sum_vector(a)
1093
+ # retourne l'écriture latex de la somme des éléments de a : 2 - 1
1094
+ # b=[-2,-1,3]
1095
+ # pxsl_sum_vector(b)
1096
+ # retourne l'écriture latex de la somme des éléments de b : - 2 - 1 + 3
1097
+
1098
+ # # #############################################################################################################
1099
+ # # #### Fin des essais ########
1100
+ # # #############################################################################################################
1101
+
1102
+ def pxs_finiterv(x,val,prob):
1103
+ """
1104
+ Fr : Fonction permettant de créer la variables aléatoire x dont les valeurs sont val et les probabilités associées sont prob.
1105
+ En: Function to create the random variable x whose values are val and the associated probabilities are prob.
1106
+
1107
+ Version
1108
+ -------
1109
+ 02/03/25
1110
+
1111
+ Vérification
1112
+ ------------
1113
+ Auteur : Ronan
1114
+ Vérificateurs : Delphine
1115
+
1116
+ Paramètres
1117
+ ----------
1118
+ x : liste
1119
+
1120
+ Retour
1121
+ ------
1122
+ variable aléatoire
1123
+
1124
+ Fonction utilisée par
1125
+ ---------------------
1126
+ Aucune fonction pyxiscience
1127
+
1128
+ :pxs_trigger: création d'une VA finie sympy à partir de deux listes parallèles valeurs/probabilités, raccourci de stats.FiniteRV quand on a déjà val et prob séparés (souvent issus de pxs_simul_law), instanciation rapide d'une loi discrète
1129
+ :pxs_returns: |
1130
+ stats.FiniteRV (RandomSymbol sympy) nommé x, de support dict(zip(val, prob)).
1131
+ Prêt à passer à pxsl_law, pxsl_moment, pxs_fct_finiterv, stats.E(), stats.variance()...
1132
+ :pxs_example: |
1133
+ val = [5, 10, 15]
1134
+ prob = [Rational(1,4), Rational(1,2), Rational(1,4)]
1135
+ X = pxs_finiterv('X', val, prob)
1136
+ tableau = pxsl_law("x_i", "P(X=x_i)", X)
1137
+ # myst(r"La loi de X : \\py{tableau}", globals(), locals())
1138
+ :pxs_antipattern: `stats.FiniteRV('X', {val[i]: prob[i] for i in range(len(val))})` — verbose, duplique la logique à chaque exercice.
1139
+ """
1140
+
1141
+ siz=len(val)
1142
+ dic={}
1143
+ for j in range(siz):
1144
+ dic[val[j]]=prob[j]
1145
+ return stats.FiniteRV(x,dic)
1146
+
1147
+ # # #############################################################################################################
1148
+ # # #### Début des essais #######
1149
+ # # #############################################################################################################
1150
+
1151
+ # x='X'
1152
+ # val = [5,10,15]
1153
+ # prob= [1/4,1/2,1/4]
1154
+ # pxsl_law("x", "P(X=x)",pxs_finiterv(x,val,prob) )
1155
+ # retourne la variable aléatoire X dont la loi est dict={5 : 0.25 , 10 : 0.5, 15 : 0.25}
1156
+ # prob= [Rational(1,4),Rational(1,2),Rational(1,4)]
1157
+ # pxsl_law("x", "P(X=x)",pxs_finiterv(x,val,prob) )
1158
+ # retourne la variable aléatoire X dont la loi est dict={5 : 1/4 , 10 : 1/2, 15 : 1/4}
1159
+
1160
+ # # #############################################################################################################
1161
+ # # #### Fin des essais ########
1162
+ # # #############################################################################################################
app/keys.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Centralised loader for API keys.
3
+
4
+ Loads variables from a `.env` file at the project root if present, then exposes
5
+ them as module-level constants. Never hardcode secrets here — put them in `.env`.
6
+ """
7
+
8
+ import os
9
+ from pathlib import Path
10
+
11
+ try:
12
+ from dotenv import load_dotenv
13
+ load_dotenv(Path(__file__).parent.parent / ".env") # pythonisation_app/.env
14
+ except ImportError:
15
+ # python-dotenv is optional; env vars can also be set directly in the shell
16
+ pass
17
+
18
+ OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY", "")
19
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "")
20
+
21
+ if not OPENROUTER_API_KEY:
22
+ print("[ld.py] WARNING: OPENROUTER_API_KEY is empty. Set it in .env or the shell environment.")
app/knowledge/__init__.py ADDED
File without changes
app/knowledge/fewshots/equations.md ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ `````{exercise}
2
+ :title: Tester si une valeur est solution
3
+ :modules:
4
+ :recommendedExecutionTime: 6
5
+ :level: Elementary
6
+ :chap: chap_equations_Inequalities_linearEquations_ESCP
7
+ :involvedConcepts:
8
+ :originalSource:
9
+ :visibility: All
10
+ :variations:
11
+ :comment: Échauffement. Tester une valeur par substitution dans les deux membres, puis résoudre l'équation linéaire et donner l'ensemble solution.
12
+
13
+ ````{python}
14
+ import random as rd
15
+ from pyxiscience.Mes_fctions_generalistes_bis import pxs_config, pxsl_latex_coefficient as lc
16
+
17
+ config_standard = pxs_config()
18
+
19
+ # Contraintes : a != 0, b != 0, solution entière non nulle (a | (c - b), c != b).
20
+ for _ in range(300):
21
+ a = rd.choice([i for i in range(-10, 11) if i not in (0, 1, -1)])
22
+ b = rd.choice([i for i in range(-15, 16) if i != 0])
23
+ c = rd.randint(-15, 15)
24
+ if c == b or (c - b) % a != 0:
25
+ continue
26
+ xSol = (c - b) // a
27
+ if xSol == 0:
28
+ continue
29
+ delta = rd.choice([i for i in range(-3, 4) if i != 0])
30
+ xTest1 = xSol
31
+ xTest2 = xSol + delta
32
+ break
33
+
34
+ bPrime = b - c
35
+ verifTest1 = a * xTest1 + b # == c (xTest1 est solution)
36
+ verifTest2 = a * xTest2 + b # != c (xTest2 n'est pas solution)
37
+ prodTest1 = a * xTest1
38
+ prodTest2 = a * xTest2
39
+
40
+ coefAAff = lc(a)
41
+ coefANumAff = lc(a, ones=True)
42
+ cstBAff = lc(b, ones=True, sign=True)
43
+ cstBPrimeAff = lc(bPrime, ones=True, sign=True)
44
+ prodTest1Aff = lc(prodTest1, ones=True)
45
+ prodTest2Aff = lc(prodTest2, ones=True)
46
+ xTest1ParenAff = str(xTest1) if xTest1 >= 0 else "(%d)" % xTest1
47
+ xTest2ParenAff = str(xTest2) if xTest2 >= 0 else "(%d)" % xTest2
48
+ repSolAff = str(xSol)
49
+ repSolParenAff = str(xSol) if xSol >= 0 else "(%d)" % xSol
50
+
51
+ globals()
52
+ ````
53
+
54
+ :::::{question}
55
+ :questionType: STQ
56
+ :questionId: 0
57
+ :questionIndex: 0
58
+
59
+ ::::{questionStatement}
60
+ On considère l'équation ${}{{coefAAff}}x {{cstBAff}} = {{c}}$. La valeur $x = {{xTest1}}$ est-elle solution ? Et la valeur $x = {{xTest2}}$ ? Justifier dans chaque cas en substituant la valeur dans les deux membres.
61
+ ::::
62
+
63
+ ::::{questionHint}
64
+ Pour tester une valeur, substitue-la dans les deux membres et vérifie si l'égalité est vraie.
65
+ ::::
66
+
67
+ ::::{detailedSolution}
68
+ Test de $x = {{xTest1}}$ :
69
+
70
+ \begin{equation*}
71
+ {{coefANumAff}} \times {{xTest1ParenAff}} {{cstBAff}} &= {{prodTest1Aff}} {{cstBAff}} \\
72
+ &= {{verifTest1}}.
73
+ \end{equation*}
74
+
75
+ Le membre de droite vaut ${}{{c}}$. Comme ${}{{verifTest1}} = {{c}}$, l'égalité est vraie : $x = {{xTest1}}$ est solution.
76
+
77
+ Test de $x = {{xTest2}}$ :
78
+
79
+ \begin{equation*}
80
+ {{coefANumAff}} \times {{xTest2ParenAff}} {{cstBAff}} &= {{prodTest2Aff}} {{cstBAff}} \\
81
+ &= {{verifTest2}}.
82
+ \end{equation*}
83
+
84
+ Le membre de droite vaut ${}{{c}}$. Comme ${}{{verifTest2}} \neq {{c}}$, l'égalité est fausse : $x = {{xTest2}}$ n'est pas solution.
85
+ ::::
86
+
87
+ ::::{weightDistribution}
88
+ :logic: 15
89
+ :abstraction: 15
90
+ :reasoning: 25
91
+ :calculation: 45
92
+ ::::
93
+ :::::
94
+
95
+ :::::{question}
96
+ :questionType: STQ
97
+ :questionId: 1
98
+ :questionIndex: 1
99
+
100
+ ::::{questionStatement}
101
+ Donner l'ensemble solution de l'équation ${}{{coefAAff}}x {{cstBAff}} = {{c}}$.
102
+ ::::
103
+
104
+ ::::{questionHint}
105
+ Mets l'équation sous la forme $ax + b = 0$, puis applique $x = -b/a$.
106
+ ::::
107
+
108
+ ::::{detailedSolution}
109
+ En soustrayant ${}{{c}}$ des deux membres, l'équation s'écrit ${}{{coefAAff}}x {{cstBPrimeAff}} = 0$, avec $a = {{a}} \neq 0$ et $b = {{bPrime}}$. Par le théorème d'unicité :
110
+
111
+ \begin{equation*}
112
+ x &= -\dfrac{b}{a} \\
113
+ &= -\dfrac{ {{bPrime}} }{ {{a}} } \\
114
+ &= {{repSolAff}}.
115
+ \end{equation*}
116
+
117
+ Vérification : ${}{{coefANumAff}} \times {{repSolParenAff}} {{cstBAff}} = {{c}}$. L'ensemble solution est $\{ {{repSolAff}} \}$.
118
+ ::::
119
+
120
+ ::::{weightDistribution}
121
+ :logic: 12
122
+ :abstraction: 18
123
+ :reasoning: 25
124
+ :calculation: 45
125
+ ::::
126
+ :::::
127
+
128
+ `````
app/knowledge/fewshots/figure.md ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ `````{exercise}
2
+ :title: Seuil de rentabilité d'une entreprise
3
+ :modules:
4
+ :recommendedExecutionTime: 18
5
+ :level: Advanced
6
+ :chap:
7
+ :involvedConcepts:
8
+ :originalSource:
9
+ :visibility: All
10
+ :variations:
11
+ :comment: Appliqué (économie & gestion) : profit comme différence recette − coût, seuil de rentabilité, interprétation des signes et lecture graphique.
12
+
13
+ ````{python}
14
+ import random as rd
15
+ import math
16
+ import matplotlib.pyplot as plt
17
+ from sympy import symbols, latex, Rational
18
+ from pyxiscience.Mes_fctions_generalistes_bis import pxs_config, pxsl_latex_coefficient as lc
19
+ from pyxiscience.Mes_fctions_probabilistes_bis import pxsl_res_num
20
+
21
+ config_standard = pxs_config()
22
+ q = symbols('q')
23
+
24
+ # Tirage avec contraintes
25
+ for _ in range(2000):
26
+ prix_unitaire = rd.choice(range(40, 105, 5))
27
+ cout_variable = rd.choice(range(10, 55, 5))
28
+ if prix_unitaire <= cout_variable:
29
+ continue
30
+ cout_fixe = rd.choice(range(500, 3100, 100))
31
+ coef_profit = prix_unitaire - cout_variable
32
+ q_seuil = Rational(cout_fixe, coef_profit)
33
+ q_test_1 = rd.choice([10, 15, 20, 25, 30, 35, 40])
34
+ q_test_2 = rd.choice([50, 55, 60, 65, 70, 75, 80])
35
+ if q_test_1 < q_seuil < q_test_2:
36
+ break
37
+
38
+ profit_expr = coef_profit * q - cout_fixe
39
+ q_seuil_entier = math.ceil(cout_fixe / coef_profit)
40
+ qSeuilExactAff = latex(q_seuil)
41
+ qSeuilDecimalAff = pxsl_res_num(q_seuil, dec=2, egal=False)
42
+
43
+ # Marges et profits aux points de test
44
+ marge_un = coef_profit * q_test_1
45
+ marge_deux = coef_profit * q_test_2
46
+ profit_un = marge_un - cout_fixe
47
+ profit_deux = marge_deux - cout_fixe
48
+
49
+ # Chaînes d'affichage
50
+ piMidUn = f"{prix_unitaire}q - ({cout_fixe} + {cout_variable}q)"
51
+ piMidDeux = f"{prix_unitaire}q - {cout_fixe} - {cout_variable}q"
52
+ piFinalAff = f"{coef_profit}q {lc(-cout_fixe, ones=True, sign=True)}"
53
+ line1Un = f"{coef_profit}\\times {q_test_1} - {cout_fixe}"
54
+ line2Un = f"{marge_un} - {cout_fixe}"
55
+ line1Deux = f"{coef_profit}\\times {q_test_2} - {cout_fixe}"
56
+ line2Deux = f"{marge_deux} - {cout_fixe}"
57
+
58
+ # Variables injectées (sans underscore)
59
+ prixUnit = prix_unitaire
60
+ coutVar = cout_variable
61
+ coutFixe = cout_fixe
62
+ coefProfit = coef_profit
63
+ qTestUn = q_test_1
64
+ qTestDeux = q_test_2
65
+ qSeuilEntier = q_seuil_entier
66
+ profitUn = profit_un
67
+ profitDeux = profit_deux
68
+
69
+ # Figure (construite une seule fois dans le bloc unique)
70
+ q_seuil_f = float(q_seuil)
71
+ fig, ax = plt.subplots(figsize=(6, 5))
72
+ q_vals = [0, 100]
73
+ R_vals = [prix_unitaire * v for v in q_vals]
74
+ C_vals = [cout_fixe + cout_variable * v for v in q_vals]
75
+ ax.plot(q_vals, R_vals, 'b-', linewidth=2, label=f'$R(q)={prix_unitaire}q$')
76
+ ax.plot(q_vals, C_vals, 'r-', linewidth=2, label=f'$C(q)={cout_fixe}+{cout_variable}q$')
77
+ y_seuil = prix_unitaire * q_seuil_f
78
+ ax.plot([q_seuil_f, q_seuil_f], [0, y_seuil], 'k--', linewidth=1)
79
+ ax.plot([0, q_seuil_f], [y_seuil, y_seuil], 'k--', linewidth=1)
80
+ ax.plot(q_seuil_f, y_seuil, 'ko', markersize=6)
81
+ ax.text(q_seuil_f, y_seuil + 200, '$q_0$', ha='center')
82
+ ax.set_xlabel('$q$ (unités)', fontsize=11)
83
+ ax.set_ylabel('Euros', fontsize=11)
84
+ ax.set_xlim(-5, 105)
85
+ ax.set_ylim(-200, max(R_vals[-1], C_vals[-1]) + 500)
86
+ ax.grid(True, alpha=0.3)
87
+ ax.legend(fontsize=10)
88
+ ax.axhline(y=0, color='k', linewidth=0.8)
89
+ ax.axvline(x=0, color='k', linewidth=0.8)
90
+ plt.tight_layout()
91
+ plt.show()
92
+
93
+ globals()
94
+ ````
95
+
96
+ :::::{question}
97
+ :questionType: STQ
98
+ :questionId: 0
99
+ :questionIndex: 0
100
+
101
+ ::::{questionStatement}
102
+ Une entreprise produit et vend $q\geq 0$ unités d'un bien. La recette est $R(q)={{ prixUnit }}q$ euros et le coût total est $C(q)={{ coutFixe }} + {{ coutVar }}q$ euros. Écrire la fonction profit $\Pi(q)=R(q)-C(q)$ et simplifier.
103
+ ::::
104
+
105
+ ::::{questionHint}
106
+ $\Pi(q)=R(q)-C(q)$ : penser à distribuer le signe moins sur les deux termes de $C(q)$.
107
+ ::::
108
+
109
+ ::::{detailedSolution}
110
+ Règle utilisée : différence de deux fonctions, puis regroupement des termes.
111
+
112
+ \begin{equation*}
113
+ \Pi(q) &= {{ piMidUn }} \\
114
+ &= {{ piMidDeux }} \\
115
+ &= {{ piFinalAff }}.
116
+ \end{equation*}
117
+ ::::
118
+
119
+ ::::{weightDistribution}
120
+ :logic: 15
121
+ :abstraction: 20
122
+ :reasoning: 30
123
+ :calculation: 35
124
+ ::::
125
+ :::::
126
+
127
+ :::::{question}
128
+ :questionType: STQ
129
+ :questionId: 1
130
+ :questionIndex: 1
131
+
132
+ ::::{questionStatement}
133
+ Déterminer le seuil de rentabilité $q_0$, c'est-à-dire la valeur de $q$ pour laquelle $\Pi(q)=0$.
134
+ ::::
135
+
136
+ ::::{questionHint}
137
+ Résoudre l'équation du premier degré ${}{{ piFinalAff }}=0$.
138
+ ::::
139
+
140
+ ::::{detailedSolution}
141
+ On résout $\Pi(q_0)=0$.
142
+
143
+ \begin{equation*}
144
+ {{ coefProfit }}q_0 - {{ coutFixe }} &= 0 \\
145
+ q_0 &= \frac{ {{ coutFixe }} }{ {{ coefProfit }} } \\
146
+ &= {{ qSeuilExactAff }} \approx {{ qSeuilDecimalAff }}.
147
+ \end{equation*}
148
+
149
+ L'entreprise atteint le seuil de rentabilité à partir de ${}{{ qSeuilEntier }}$ unités vendues (arrondi au nombre entier supérieur).
150
+ ::::
151
+
152
+ ::::{weightDistribution}
153
+ :logic: 20
154
+ :abstraction: 25
155
+ :reasoning: 30
156
+ :calculation: 25
157
+ ::::
158
+ :::::
159
+
160
+ :::::{question}
161
+ :questionType: STQ
162
+ :questionId: 2
163
+ :questionIndex: 2
164
+
165
+ ::::{questionStatement}
166
+ Calculer $\Pi({{ qTestUn }})$ et $\Pi({{ qTestDeux }})$, puis interpréter.
167
+ ::::
168
+
169
+ ::::{questionHint}
170
+ Substituer chaque valeur dans $\Pi(q)={{ piFinalAff }}$ et comparer avec le seuil $q_0$.
171
+ ::::
172
+
173
+ ::::{detailedSolution}
174
+ On évalue la fonction profit.
175
+
176
+ \begin{equation*}
177
+ \Pi({{ qTestUn }}) &= {{ line1Un }} \\
178
+ &= {{ line2Un }} \\
179
+ &= {{ profitUn }}.
180
+ \end{equation*}
181
+
182
+ \begin{equation*}
183
+ \Pi({{ qTestDeux }}) &= {{ line1Deux }} \\
184
+ &= {{ line2Deux }} \\
185
+ &= {{ profitDeux }}.
186
+ \end{equation*}
187
+
188
+ Pour $q={{ qTestUn }}<q_0$, l'entreprise est en perte (${}{{ profitUn }}$ euros) ; pour $q={{ qTestDeux }}>q_0$, elle réalise un bénéfice de ${}{{ profitDeux }}$ euros.
189
+ ::::
190
+
191
+ ::::{weightDistribution}
192
+ :logic: 15
193
+ :abstraction: 20
194
+ :reasoning: 30
195
+ :calculation: 35
196
+ ::::
197
+ :::::
198
+
199
+ :::::{question}
200
+ :questionType: STQ
201
+ :questionId: 3
202
+ :questionIndex: 3
203
+
204
+ ::::{questionStatement}
205
+ Sur la figure ci-dessus, identifier graphiquement le seuil de rentabilité comme l'intersection des courbes de $R$ et $C$.
206
+ ::::
207
+
208
+ ::::{questionHint}
209
+ Le seuil de rentabilité est le point où recette = coût, c'est-à-dire l'intersection des deux droites.
210
+ ::::
211
+
212
+ ::::{detailedSolution}
213
+ Au seuil de rentabilité, les courbes de la recette $R$ et du coût total $C$ se croisent : à gauche de $q_0$ le coût dépasse la recette (perte), à droite la recette dépasse le coût (bénéfice).
214
+
215
+ Sur le graphique, on observe que les deux droites se coupent en $q_0 \approx {{ qSeuilDecimalAff }}$, ce qui correspond au calcul algébrique effectué à la question précédente. Pour $q<q_0$, la droite rouge (coût) est au-dessus de la droite bleue (recette), indiquant une perte. Pour $q>q_0$, la situation s'inverse et l'entreprise réalise un profit.
216
+ ::::
217
+
218
+ ::::{weightDistribution}
219
+ :logic: 25
220
+ :abstraction: 30
221
+ :reasoning: 35
222
+ :calculation: 10
223
+ ::::
224
+ :::::
225
+
226
+ `````
app/knowledge/fewshots/integration.md ADDED
@@ -0,0 +1,465 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ `````{exercise}
2
+ :title: {fr}`Étude d'une fonction avec logarithme : limites, variations et intégration par parties`{en}`Study of a function involving a logarithm: limits, variations and integration by parts`
3
+ :modules: annale_bac
4
+ :recommendedExecutionTime: 30
5
+ :level: Intermediate
6
+ :chap:
7
+ :involvedConcepts: TYPE_BAC,Integration_by_Parts, Limits, Comparative_Growth
8
+ :originalSource: Exercice 4 du baccalauréat Amérique du Nord 21 mai 2026 (sujet 2)
9
+ :visibility: All
10
+ :variations:
11
+ :comment: Exercice d'analyse (fonction x(ln x)^2, deux IPP, théorème de la bijection) - non randomisé. Énoncé et solution officiels ; solution validée par Chabane.
12
+ :id: 4e6e2f22-5f5a-11f1-a8a1-0ed8d3b012a9
13
+
14
+ ````{python}
15
+ import math
16
+ import random as rd
17
+ from sympy import symbols, exp, ln, sqrt, latex, Rational, nsolve
18
+ from pyxiscience.Mes_fctions_generalistes_bis import pxs_config, pxsl_res_num
19
+
20
+ config_standard = pxs_config()
21
+ x = symbols('x', positive=True, real=True)
22
+
23
+ # Fonction et identités officielles : f(x) = x (ln x)^2.
24
+ # L'exposant 2 est VERROUILLÉ (l'identité f = 4 (g(sqrt x))^2 de la Q2a, l'expression de f',
25
+ # le tableau de variation et les deux IPP avec la limite 1/4 ne valent que pour le carré).
26
+ # Seul paramètre randomisable proprement : le second membre de l'équation f(x) = seuil.
27
+ f = x * (ln(x)) ** 2
28
+ xCrit = exp(-2)
29
+ fMax = 4 * exp(-2) # = e^{-2} * (-2)^2, maximum local sur ]0 ; 1] (~0,541)
30
+
31
+ # Second membre entier de l'équation f(x) = seuil : seuil > 4/e^2 (~0,541),
32
+ # donc aucune solution sur ]0 ; 1] et une unique solution sur [1 ; +inf[. (Officiel : seuil = 2.)
33
+ seuil = rd.randint(1, 6)
34
+ alphaApprox = float(nsolve(f - seuil, 3))
35
+ alphaInf = math.floor(alphaApprox * 10) / 10
36
+ alphaSup = round(alphaInf + 0.1, 1)
37
+ limInt = Rational(1, 4)
38
+
39
+ fMaxAff = latex(fMax, **config_standard)
40
+ fMaxDecAff = pxsl_res_num(fMax, dec=2, egal=False)
41
+ seuilAff = str(seuil)
42
+ alphaApproxAff = pxsl_res_num(alphaApprox, dec=2, egal=False)
43
+ alphaInfAff = pxsl_res_num(alphaInf, dec=1, egal=False)
44
+ alphaSupAff = pxsl_res_num(alphaSup, dec=1, egal=False)
45
+ limIntAff = latex(limInt, **config_standard)
46
+
47
+ globals()
48
+ ````
49
+
50
+ On considère la fonction $f$ définie sur l'intervalle $]0\,;\,+\infty[$ par
51
+ \begin{equation*}
52
+ f(x) = x(\ln x)^2.
53
+ \end{equation*}
54
+ On admet que la fonction $f$ est dérivable sur l'intervalle $]0\,;\,+\infty[$. On note $f'$ sa fonction dérivée.
55
+
56
+ :::::{question}
57
+ :questionType: STQ
58
+ :questionId: 0
59
+ :questionIndex: 0
60
+
61
+ ::::{questionStatement}
62
+ Déterminer la limite de la fonction $f$ en $+\infty$.
63
+ ::::
64
+
65
+ ::::{questionHint}
66
+ Écrire $f(x) = x \times (\ln x)^2$ et utiliser la limite de $\ln x$ en $+\infty$, puis un produit de limites.
67
+ ::::
68
+
69
+ ::::{detailedSolution}
70
+ Pour tout réel $x > 0$, on a $f(x) = x \times (\ln x)^2$.
71
+
72
+ Comme $\ds \lim_{x \to +\infty} \ln x = +\infty$ et $\ds \lim_{x \to +\infty} x = +\infty$, on obtient par produit :
73
+ \begin{equation*}
74
+ \boxed{\lim_{x \to +\infty} f(x) = +\infty.}
75
+ \end{equation*}
76
+ ::::
77
+
78
+ ::::{weightDistribution}
79
+ :reasoning: 30
80
+ :logic: 20
81
+ :abstraction: 15
82
+ :calculation: 35
83
+ ::::
84
+ :::::
85
+
86
+ Pour tout réel $x > 0$, on pose $g(x) = x \ln x$.
87
+
88
+ :::::{question}
89
+ :questionType: STQ
90
+ :questionId: 1
91
+ :questionIndex: 1
92
+
93
+ ::::{questionStatement}
94
+ Démontrer que, pour tout réel $x > 0$, on a $f(x) = 4\bigl(g(\sqrt{x})\bigr)^2$.
95
+ ::::
96
+
97
+ ::::{questionHint}
98
+ Utiliser que $\ln\sqrt{x} = \dfrac{1}{2}\ln x$, puis développer ${}4\bigl(g(\sqrt{x})\bigr)^2$.
99
+ ::::
100
+
101
+ ::::{detailedSolution}
102
+ Soit $x \in\, ]0\,;\,+\infty[$. En utilisant $\ln\sqrt{x} = \dfrac{1}{2}\ln x$ :
103
+ \begin{equation*}
104
+ 4\bigl(g(\sqrt{x})\bigr)^2 &= 4\bigl(\sqrt{x}\,\ln(\sqrt{x})\bigr)^2 \\
105
+ &= 4\left(\sqrt{x} \times \tfrac{1}{2}\ln x\right)^2 \\
106
+ &= 4 \times x \times \tfrac{1}{4}(\ln x)^2 \\
107
+ &= x(\ln x)^2 \\
108
+ &= f(x).
109
+ \end{equation*}
110
+ On a donc bien, pour tout réel $x > 0$ :
111
+ \begin{equation*}
112
+ \boxed{f(x) = 4\bigl(g(\sqrt{x})\bigr)^2.}
113
+ \end{equation*}
114
+ ::::
115
+
116
+ ::::{weightDistribution}
117
+ :reasoning: 20
118
+ :logic: 20
119
+ :abstraction: 15
120
+ :calculation: 45
121
+ ::::
122
+ :::::
123
+
124
+ :::::{question}
125
+ :questionType: STQ
126
+ :questionId: 2
127
+ :questionIndex: 2
128
+
129
+ ::::{questionStatement}
130
+ En déduire $\ds \lim_{x\to 0}f(x)$.
131
+ ::::
132
+
133
+ ::::{questionHint}
134
+ Par croissances comparées, $\ds\lim_{X\to 0}X\ln X=0$. Composer avec $X=\sqrt{x}$.
135
+ ::::
136
+
137
+ ::::{detailedSolution}
138
+ On sait que $\ds\lim_{x\to 0}\sqrt{x}=0$ et, par croissances comparées, $\ds\lim_{X\to 0}X\ln X=0$.
139
+
140
+ Par composition, $\ds\lim_{x\to 0}g(\sqrt{x})=\lim_{x\to 0}\sqrt{x}\,\ln(\sqrt{x})=0$.
141
+
142
+ D'après la question précédente, $f(x)=4\bigl(g(\sqrt{x})\bigr)^2$, donc par produit :
143
+ \begin{equation*}
144
+ \boxed{\lim_{x\to 0}f(x)=0.}
145
+ \end{equation*}
146
+ ::::
147
+
148
+ ::::{weightDistribution}
149
+ :reasoning: 35
150
+ :logic: 25
151
+ :abstraction: 25
152
+ :calculation: 15
153
+ ::::
154
+ :::::
155
+
156
+ Dans cette question, on étudie les variations de la fonction $f$ sur l'intervalle $]0\,;\,+\infty[$.
157
+
158
+ :::::{question}
159
+ :questionType: STQ
160
+ :questionId: 3
161
+ :questionIndex: 3
162
+
163
+ ::::{questionStatement}
164
+ Démontrer que, sur l'intervalle $]0\,;\,+\infty[$, $f'(x)=(\ln x)(2+\ln x)$.
165
+ ::::
166
+
167
+ ::::{questionHint}
168
+ $f$ est un produit : poser $u(x)=x$ et $v(x)=(\ln x)^2$, puis appliquer $f'=u'v+uv'$.
169
+ ::::
170
+
171
+ ::::{detailedSolution}
172
+ La fonction $f$ est de la forme $uv$ avec, pour tout $x\in\,]0\,;\,+\infty[$, $u(x)=x$ et $v(x)=(\ln x)^2$, d'où $u'(x)=1$ et $v'(x)=2\times\dfrac{1}{x}\times\ln x=\dfrac{2\ln x}{x}$.
173
+
174
+ Comme $f'=u'v+uv'$, on obtient pour tout $x\in\,]0\,;\,+\infty[$ :
175
+ \begin{equation*}
176
+ f'(x)&=1\times(\ln x)^2+x\times\dfrac{2\ln x}{x}\\
177
+ &=(\ln x)^2+2\ln x\\
178
+ &=(\ln x)(\ln x+2).
179
+ \end{equation*}
180
+ Donc, sur l'intervalle $]0\,;\,+\infty[$ :
181
+ \begin{equation*}
182
+ \boxed{f'(x)=(\ln x)(2+\ln x).}
183
+ \end{equation*}
184
+ ::::
185
+
186
+ ::::{weightDistribution}
187
+ :reasoning: 20
188
+ :logic: 15
189
+ :abstraction: 10
190
+ :calculation: 55
191
+ ::::
192
+ :::::
193
+
194
+ :::::{question}
195
+ :questionType: STQ
196
+ :questionId: 4
197
+ :questionIndex: 4
198
+
199
+ ::::{questionStatement}
200
+ En déduire les variations de la fonction $f$ sur l'intervalle $]0\,;\,+\infty[$.
201
+ ::::
202
+
203
+ ::::{questionHint}
204
+ Étudier séparément le signe de $\ln x$ et celui de ${}2+\ln x$, puis en déduire le signe du produit $f'(x)$.
205
+ ::::
206
+
207
+ ::::{detailedSolution}
208
+ On étudie le signe de $f'(x)=(\ln x)(2+\ln x)$.
209
+
210
+ $\bullet$ ${}2+\ln x>0\iff \ln x>-2\iff x>\mathrm{e}^{-2}$ ;
211
+
212
+ $\bullet$ $\ln x>0\iff x>1$.
213
+
214
+ On en déduit le signe de $f'$ sur $]0\,;\,+\infty[$ :
215
+
216
+ $\bullet$ sur $]0\,;\,\mathrm{e}^{-2}]$ : $\ln x<0$ et ${}2+\ln x<0$, donc $f'(x)>0$ ;
217
+
218
+ $\bullet$ sur $[\mathrm{e}^{-2}\,;\,1]$ : $\ln x<0$ et ${}2+\ln x>0$, donc $f'(x)<0$ ;
219
+
220
+ $\bullet$ sur $[1\,;\,+\infty[$ : $\ln x>0$ et ${}2+\ln x>0$, donc $f'(x)>0$.
221
+
222
+ Par conséquent, $f$ est strictement croissante sur $]0\,;\,\mathrm{e}^{-2}]$, strictement décroissante sur $[\mathrm{e}^{-2}\,;\,1]$, puis strictement croissante sur $[1\,;\,+\infty[$.
223
+ ::::
224
+
225
+ ::::{weightDistribution}
226
+ :reasoning: 25
227
+ :logic: 35
228
+ :abstraction: 15
229
+ :calculation: 25
230
+ ::::
231
+ :::::
232
+
233
+ :::::{question}
234
+ :questionType: STQ
235
+ :questionId: 5
236
+ :questionIndex: 5
237
+
238
+ ::::{questionStatement}
239
+ Donner la valeur exacte du maximum de la fonction $f$ sur l'intervalle $]0\,;\,1]$.
240
+ ::::
241
+
242
+ ::::{questionHint}
243
+ Sur $]0\,;\,1]$, $f$ croît jusqu'en $\mathrm{e}^{-2}$ puis décroît : le maximum est $f(\mathrm{e}^{-2})$. Calculer cette valeur.
244
+ ::::
245
+
246
+ ::::{detailedSolution}
247
+ Sur l'intervalle $]0\,;\,1]$, la fonction $f$ est croissante sur $]0\,;\,\mathrm{e}^{-2}]$ puis décroissante sur $[\mathrm{e}^{-2}\,;\,1]$ : son maximum est donc atteint en $x=\mathrm{e}^{-2}$.
248
+ \begin{equation*}
249
+ f(\mathrm{e}^{-2})&=\mathrm{e}^{-2}\bigl(\ln(\mathrm{e}^{-2})\bigr)^2\\
250
+ &=\mathrm{e}^{-2}\times(-2)^2\\
251
+ &={{fMaxAff}}.
252
+ \end{equation*}
253
+ Le maximum de $f$ sur $]0\,;\,1]$ vaut donc :
254
+ \begin{equation*}
255
+ \boxed{ {{fMaxAff}} \approx {{fMaxDecAff}}. }
256
+ \end{equation*}
257
+ ::::
258
+
259
+ ::::{weightDistribution}
260
+ :reasoning: 25
261
+ :logic: 20
262
+ :abstraction: 15
263
+ :calculation: 40
264
+ ::::
265
+ :::::
266
+
267
+ On considère l'équation $f(x)={{seuilAff}}$.
268
+
269
+ :::::{question}
270
+ :questionType: STQ
271
+ :questionId: 6
272
+ :questionIndex: 6
273
+
274
+ ::::{questionStatement}
275
+ Justifier que, sur l'intervalle $]0\,;\,+\infty[$, cette équation admet une unique solution. On note $\alpha$ cette solution.
276
+ ::::
277
+
278
+ ::::{questionHint}
279
+ Distinguer $]0\,;\,1]$ (comparer le maximum à ${}{{seuilAff}}$) et $[1\,;\,+\infty[$ (appliquer le théorème de la bijection).
280
+ ::::
281
+
282
+ ::::{detailedSolution}
283
+ $\bullet$ Sur l'intervalle $]0\,;\,1]$, le maximum de $f$ vaut ${}{{fMaxAff}} \approx {{fMaxDecAff}} < {{seuilAff}}$ : l'équation $f(x)={{seuilAff}}$ n'y admet donc aucune solution.
284
+
285
+ $\bullet$ Sur l'intervalle $[1\,;\,+\infty[$, la fonction $f$ est continue (car dérivable) et strictement croissante. De plus $f(1)=0<{{seuilAff}}$ et $\ds\lim_{x\to+\infty}f(x)=+\infty>{{seuilAff}}$.
286
+
287
+ D'après le théorème de la bijection (corollaire du théorème des valeurs intermédiaires), l'équation $f(x)={{seuilAff}}$ admet une unique solution sur $[1\,;\,+\infty[$.
288
+
289
+ En réunissant les deux intervalles, l'équation $f(x)={{seuilAff}}$ admet une unique solution $\alpha$ sur $]0\,;\,+\infty[$.
290
+ ::::
291
+
292
+ ::::{weightDistribution}
293
+ :reasoning: 35
294
+ :logic: 30
295
+ :abstraction: 20
296
+ :calculation: 15
297
+ ::::
298
+ :::::
299
+
300
+ :::::{question}
301
+ :questionType: STQ
302
+ :questionId: 7
303
+ :questionIndex: 7
304
+
305
+ ::::{questionStatement}
306
+ Donner un encadrement de $\alpha$ d'amplitude ${}0{,}1$.
307
+ ::::
308
+
309
+ ::::{questionHint}
310
+ Utiliser la calculatrice (ou un tableau de valeurs) pour localiser $\alpha$ entre deux décimaux distants de ${}0{,}1$.
311
+ ::::
312
+
313
+ ::::{detailedSolution}
314
+ À l'aide de la calculatrice, $\alpha\approx{{alphaApproxAff}}$. On en déduit l'encadrement d'amplitude ${}0{,}1$ :
315
+ \begin{equation*}
316
+ \boxed{ {{alphaInfAff}} \leqslant \alpha \leqslant {{alphaSupAff}}. }
317
+ \end{equation*}
318
+ ::::
319
+
320
+ ::::{weightDistribution}
321
+ :reasoning: 15
322
+ :logic: 15
323
+ :abstraction: 10
324
+ :calculation: 60
325
+ ::::
326
+ :::::
327
+
328
+ Soit $a$ un nombre réel appartenant à l'intervalle $]0\,;\,1]$.
329
+
330
+ :::::{question}
331
+ :questionType: STQ
332
+ :questionId: 8
333
+ :questionIndex: 8
334
+
335
+ ::::{questionStatement}
336
+ Donner une interprétation géométrique de $\ds\int_a^1 f(x)\,\mathrm{d}x$.
337
+ ::::
338
+
339
+ ::::{questionHint}
340
+ Déterminer le signe de $f$ sur $[a\,;\,1]$, puis relier l'intégrale à une aire.
341
+ ::::
342
+
343
+ ::::{detailedSolution}
344
+ Sur l'intervalle $[a\,;\,1]$, la fonction $f$ est positive. L'intégrale $\ds\int_a^1 f(x)\,\mathrm{d}x$ représente donc l'aire, exprimée en unités d'aire, du domaine délimité par la courbe représentative de $f$, l'axe des abscisses et les droites d'équations $x=a$ et $x=1$.
345
+ ::::
346
+
347
+ ::::{weightDistribution}
348
+ :reasoning: 30
349
+ :logic: 20
350
+ :abstraction: 40
351
+ :calculation: 10
352
+ ::::
353
+ :::::
354
+
355
+ :::::{question}
356
+ :questionType: STQ
357
+ :questionId: 9
358
+ :questionIndex: 9
359
+
360
+ ::::{questionStatement}
361
+ À l'aide d'une intégration par parties, justifier que :
362
+ \begin{equation*}
363
+ \int_a^1 f(x)\,\mathrm{d}x=-\dfrac{a^2}{2}(\ln a)^2-\int_a^1 x\ln x\,\mathrm{d}x.
364
+ \end{equation*}
365
+ ::::
366
+
367
+ ::::{questionHint}
368
+ Poser $u'(x)=x$ et $v(x)=(\ln x)^2$, d'où $u(x)=\dfrac{x^2}{2}$ et $v'(x)=\dfrac{2\ln x}{x}$.
369
+ ::::
370
+
371
+ ::::{detailedSolution}
372
+ On pose $u'(x)=x$ et $v(x)=(\ln x)^2$, d'où $u(x)=\dfrac{x^2}{2}$ et $v'(x)=\dfrac{2\ln x}{x}$. Ces fonctions sont continûment dérivables sur $[a\,;\,1]$, donc par intégration par parties :
373
+ \begin{equation*}
374
+ \int_a^1 f(x)\,\mathrm{d}x&=\left[\dfrac{x^2}{2}(\ln x)^2\right]_a^1-\int_a^1 \dfrac{x^2}{2}\times\dfrac{2\ln x}{x}\,\mathrm{d}x\\
375
+ &=\left(\dfrac{1}{2}(\ln 1)^2-\dfrac{a^2}{2}(\ln a)^2\right)-\int_a^1 x\ln x\,\mathrm{d}x\\
376
+ &=-\dfrac{a^2}{2}(\ln a)^2-\int_a^1 x\ln x\,\mathrm{d}x,
377
+ \end{equation*}
378
+ ce qui est le résultat demandé.
379
+ ::::
380
+
381
+ ::::{weightDistribution}
382
+ :reasoning: 25
383
+ :logic: 20
384
+ :abstraction: 15
385
+ :calculation: 40
386
+ ::::
387
+ :::::
388
+
389
+ :::::{question}
390
+ :questionType: STQ
391
+ :questionId: 10
392
+ :questionIndex: 10
393
+
394
+ ::::{questionStatement}
395
+ En utilisant à nouveau une intégration par parties, démontrer que :
396
+ \begin{equation*}
397
+ \int_a^1 f(x)\,\mathrm{d}x=-\dfrac{a^2}{2}(\ln a)^2+\dfrac{a^2}{2}\ln a+\dfrac{1}{4}-\dfrac{a^2}{4}.
398
+ \end{equation*}
399
+ ::::
400
+
401
+ ::::{questionHint}
402
+ Calculer $\ds\int_a^1 x\ln x\,\mathrm{d}x$ par IPP avec $u'(x)=x$ et $v(x)=\ln x$, puis reporter dans la question précédente.
403
+ ::::
404
+
405
+ ::::{detailedSolution}
406
+ On calcule d'abord $\ds\int_a^1 x\ln x\,\mathrm{d}x$ par intégration par parties, avec $u'(x)=x$ et $v(x)=\ln x$, d'où $u(x)=\dfrac{x^2}{2}$ et $v'(x)=\dfrac{1}{x}$ :
407
+ \begin{equation*}
408
+ \int_a^1 x\ln x\,\mathrm{d}x&=\left[\dfrac{x^2}{2}\ln x\right]_a^1-\int_a^1 \dfrac{x^2}{2}\times\dfrac{1}{x}\,\mathrm{d}x\\
409
+ &=-\dfrac{a^2}{2}\ln a-\int_a^1 \dfrac{x}{2}\,\mathrm{d}x\\
410
+ &=-\dfrac{a^2}{2}\ln a-\left[\dfrac{x^2}{4}\right]_a^1\\
411
+ &=-\dfrac{a^2}{2}\ln a-\dfrac{1}{4}+\dfrac{a^2}{4}.
412
+ \end{equation*}
413
+ En reportant dans le résultat de la question précédente :
414
+ \begin{equation*}
415
+ \int_a^1 f(x)\,\mathrm{d}x&=-\dfrac{a^2}{2}(\ln a)^2-\left(-\dfrac{a^2}{2}\ln a-\dfrac{1}{4}+\dfrac{a^2}{4}\right)\\
416
+ &=-\dfrac{a^2}{2}(\ln a)^2+\dfrac{a^2}{2}\ln a+\dfrac{1}{4}-\dfrac{a^2}{4},
417
+ \end{equation*}
418
+ ce qui est le résultat demandé.
419
+ ::::
420
+
421
+ ::::{weightDistribution}
422
+ :reasoning: 20
423
+ :logic: 20
424
+ :abstraction: 10
425
+ :calculation: 50
426
+ ::::
427
+ :::::
428
+
429
+ :::::{question}
430
+ :questionType: STQ
431
+ :questionId: 11
432
+ :questionIndex: 11
433
+
434
+ ::::{questionStatement}
435
+ Déterminer la limite de $\ds\int_a^1 f(x)\,\mathrm{d}x$ quand $a$ tend vers ${}0$.
436
+ ::::
437
+
438
+ ::::{questionHint}
439
+ Faire apparaître $a\ln a$ : $a^2(\ln a)^2=(a\ln a)^2$. Par croissances comparées, $\ds\lim_{a\to 0}a\ln a=0$.
440
+ ::::
441
+
442
+ ::::{detailedSolution}
443
+ On part de l'expression obtenue à la question précédente. Par croissances comparées, $\ds\lim_{a\to 0}a\ln a=0$, donc :
444
+
445
+ $\bullet$ $\ds\lim_{a\to 0}\dfrac{a^2}{2}(\ln a)^2=\lim_{a\to 0}\dfrac{1}{2}(a\ln a)^2=0$ ;
446
+
447
+ $\bullet$ $\ds\lim_{a\to 0}\dfrac{a^2}{2}\ln a=\lim_{a\to 0}\dfrac{a}{2}\times a\ln a=0$ ;
448
+
449
+ $\bullet$ $\ds\lim_{a\to 0}\left(\dfrac{1}{4}-\dfrac{a^2}{4}\right)=\dfrac{1}{4}$.
450
+
451
+ Par somme :
452
+ \begin{equation*}
453
+ \boxed{\lim_{a\to 0}\int_a^1 f(x)\,\mathrm{d}x={{limIntAff}}.}
454
+ \end{equation*}
455
+ ::::
456
+
457
+ ::::{weightDistribution}
458
+ :reasoning: 30
459
+ :logic: 25
460
+ :abstraction: 20
461
+ :calculation: 25
462
+ ::::
463
+ :::::
464
+
465
+ `````
app/knowledge/fewshots/logexp.md ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ `````{exercise}
2
+ :title: Évaluation d'une fonction exponentielle et monotonie
3
+ :modules:
4
+ :recommendedExecutionTime: 7
5
+ :level: Elementary
6
+ :chap:
7
+ :involvedConcepts:
8
+ :originalSource:
9
+ :visibility: All
10
+ :variations:
11
+ :comment: Échauffement (thème pur) : évaluation de x↦3^x en des entiers (dont les exposants négatifs), passage par (0,1), et monotonie déduite de la base.
12
+
13
+ ````{python}
14
+ import random as rd
15
+
16
+ # Construction déterministe : base entière > 1 (donc f croissante), valeurs exactes.
17
+ b = rd.choice([2, 3, 4, 5])
18
+
19
+ f1 = b
20
+ f2 = b**2
21
+ f3 = b**3
22
+
23
+ fm1Aff = r'\dfrac{1}{' + str(b) + '}'
24
+ fm2Aff = r'\dfrac{1}{' + str(b**2) + '}'
25
+ monotonie = 'croissante' if b > 1 else 'décroissante'
26
+
27
+ globals()
28
+ ````
29
+
30
+ Soit $f(x)={{ b }}^{x}$. Calculer $f(0)$, $f(1)$, $f(2)$, $f(3)$, puis $f(-1)$ et $f(-2)$.
31
+
32
+ :::::{question}
33
+ :questionType: STQ
34
+ :questionId: 0
35
+ :questionIndex: 0
36
+
37
+ ::::{questionStatement}
38
+ Soit $f(x)={{ b }}^{x}$. Calculer $f(0)$, $f(1)$, $f(2)$, $f(3)$, puis $f(-1)$ et $f(-2)$.
39
+ ::::
40
+
41
+ ::::{questionHint}
42
+ Rappel : $b^{x}=1$ lorsque $x=0$ pour toute base $b>0$, et $b^{-n}=\dfrac{1}{b^{n}}$.
43
+ ::::
44
+
45
+ ::::{detailedSolution}
46
+ Pour les exposants positifs ou nuls : $f(0)=1$, $f(1)={{ f1 }}$, $f(2)={{ f2 }}$, $f(3)={{ f3 }}$.
47
+
48
+ En particulier $f(0)=1$ : le graphe d'une fonction exponentielle passe toujours par le point $(0,1)$.
49
+
50
+ Pour les exposants négatifs : $f(-1)={{ fm1Aff }}$ et $f(-2)={{ fm2Aff }}$.
51
+ ::::
52
+
53
+ ::::{weightDistribution}
54
+ :logic: 10
55
+ :abstraction: 15
56
+ :reasoning: 25
57
+ :calculation: 50
58
+ ::::
59
+ :::::
60
+
61
+ :::::{question}
62
+ :questionType: STQ
63
+ :questionId: 1
64
+ :questionIndex: 1
65
+
66
+ ::::{questionStatement}
67
+ En déduire si $f$ est croissante ou décroissante, et justifier à partir de la base.
68
+ ::::
69
+
70
+ ::::{questionHint}
71
+ Si $b>1$, la fonction $x\mapsto b^{x}$ est strictement croissante.
72
+ ::::
73
+
74
+ ::::{detailedSolution}
75
+ La base est $b={{ b }}>1$, donc $f$ est strictement {{ monotonie }} sur $\mathbb{R}$. On le vérifie sur les valeurs : ${{ fm2Aff }}<{{ fm1Aff }}<1<{{ f1 }}<{{ f2 }}<{{ f3 }}$, soit $f(-2)<f(-1)<f(0)<f(1)<f(2)<f(3)$.
76
+ ::::
77
+
78
+ ::::{weightDistribution}
79
+ :logic: 25
80
+ :abstraction: 35
81
+ :reasoning: 30
82
+ :calculation: 10
83
+ ::::
84
+ :::::
85
+
86
+ `````
app/knowledge/fewshots/quadratique.md ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ `````{exercise}
2
+ :title: Racine double et produit nul
3
+ :modules:
4
+ :recommendedExecutionTime: 6
5
+ :level: Elementary
6
+ :chap: chap_equations_Inequalities_radicalQuadraticEquations_ESCP
7
+ :involvedConcepts:
8
+ :originalSource:
9
+ :visibility: All
10
+ :variations:
11
+ :comment: Échauffement. Cas Delta nul (racine double) et règle du produit nul.
12
+
13
+ ````{python}
14
+ import random as rd
15
+ from sympy import symbols, latex, Rational
16
+ from pyxiscience.Mes_fctions_generalistes_bis import pxs_config
17
+
18
+ config_standard = pxs_config()
19
+ x = symbols('x')
20
+
21
+ # Carré parfait (m x - n)^2 = m^2 x^2 - 2 m n x + n^2 : discriminant nul.
22
+ m = rd.randint(2, 4)
23
+ n = rd.randint(1, 6)
24
+ a = m * m
25
+ b = -2 * m * n
26
+ c = n * n
27
+
28
+ bSquared = b * b
29
+ fourAC = 4 * a * c
30
+ negB = -b
31
+ twoA = 2 * a
32
+ doubleRoot = Rational(n, m)
33
+
34
+ eqAff = latex(a * x ** 2 + b * x + c, **config_standard)
35
+ factoredAff = latex((m * x - n) ** 2, **config_standard)
36
+ aAff = str(a)
37
+ bAff = str(b)
38
+ cAff = str(c)
39
+ bSquaredAff = str(bSquared)
40
+ fourACAff = str(fourAC)
41
+ negBAff = str(negB)
42
+ twoAAff = str(twoA)
43
+ doubleRootAff = latex(doubleRoot, **config_standard)
44
+
45
+ # Question 2 : produit nul x(alpha x - gamma) = 0, racines 0 et r = gamma/alpha.
46
+ alpha = rd.randint(2, 4)
47
+ r = rd.randint(2, 6)
48
+ gamma = alpha * r
49
+ alphaAff = str(alpha)
50
+ gammaAff = str(gamma)
51
+ rAff = str(r)
52
+
53
+ globals()
54
+ ````
55
+
56
+ :::::{question}
57
+ :questionType: STQ
58
+ :questionId: 0
59
+ :questionIndex: 0
60
+
61
+ ::::{questionStatement}
62
+ {fr}`Résoudre l'équation $\ds {{eqAff}} = 0$.`{en}`Solve the equation $\ds {{eqAff}} = 0$.`
63
+ ::::
64
+
65
+ ::::{questionHint}
66
+ {fr}`Calculer le discriminant : s'il est nul, il y a une racine double $\ds x_0 = \dfrac{-b}{2a}$.`{en}`Compute the discriminant: if it is zero, there is a double root $\ds x_0 = \dfrac{-b}{2a}$.`
67
+ ::::
68
+
69
+ ::::{detailedSolution}
70
+ {fr}`Avec $\ds a = {{aAff}}$, $\ds b = {{bAff}}$, $\ds c = {{cAff}}$, le discriminant vaut :`{en}`With $\ds a = {{aAff}}$, $\ds b = {{bAff}}$, $\ds c = {{cAff}}$, the discriminant is:`
71
+
72
+ \begin{equation*}
73
+ \ds \Delta &= ({{bAff}})^2 - 4 \times {{aAff}} \times {{cAff}} \\
74
+ &= {{bSquaredAff}} - {{fourACAff}} \\
75
+ &= 0.
76
+ \end{equation*}
77
+
78
+ {fr}`Comme $\ds \Delta = 0$, il existe une unique solution réelle (racine double) :`{en}`Since $\ds \Delta = 0$, there is a single real solution (double root):`
79
+
80
+ \begin{equation*}
81
+ \ds x_0 &= \frac{-b}{2a} \\
82
+ &= \frac{ {{negBAff}} }{ {{twoAAff}} } \\
83
+ &= {{doubleRootAff}}.
84
+ \end{equation*}
85
+
86
+ {fr}`On retrouve la forme factorisée $\ds {{factoredAff}} = 0$, qui s'annule en $\ds x = {{doubleRootAff}}$. L'ensemble solution est $\ds \left\{ {{doubleRootAff}} \right\}$.`{en}`This matches the factored form $\ds {{factoredAff}} = 0$, which vanishes at $\ds x = {{doubleRootAff}}$. The solution set is $\ds \left\{ {{doubleRootAff}} \right\}$.`
87
+ ::::
88
+
89
+ ::::{weightDistribution}
90
+ :logic: 15
91
+ :abstraction: 20
92
+ :reasoning: 25
93
+ :calculation: 40
94
+ ::::
95
+ :::::
96
+
97
+ :::::{question}
98
+ :questionType: STQ
99
+ :questionId: 1
100
+ :questionIndex: 1
101
+
102
+ ::::{questionStatement}
103
+ {fr}`Résoudre l'équation $\ds x({{alphaAff}}x - {{gammaAff}}) = 0$.`{en}`Solve the equation $\ds x({{alphaAff}}x - {{gammaAff}}) = 0$.`
104
+ ::::
105
+
106
+ ::::{questionHint}
107
+ {fr}`Le membre gauche est un produit : appliquer la règle du produit nul.`{en}`The left-hand side is a product: apply the zero-product rule.`
108
+ ::::
109
+
110
+ ::::{detailedSolution}
111
+ {fr}`Par la règle du produit nul, un produit est nul si et seulement si l'un de ses facteurs est nul :`{en}`By the zero-product rule, a product is zero if and only if one of its factors is zero:`
112
+
113
+ \begin{equation*}
114
+ \ds x({{alphaAff}}x - {{gammaAff}}) = 0 \quad\Longleftrightarrow\quad x = 0 \quad\text{ou}\quad x = {{rAff}}.
115
+ \end{equation*}
116
+
117
+ {fr}`Le second facteur donne $\ds {{alphaAff}}x - {{gammaAff}} = 0$, soit $\ds x = {{rAff}}$. L'ensemble solution est $\ds \{0\,;\,{{rAff}}\}$.`{en}`The second factor gives $\ds {{alphaAff}}x - {{gammaAff}} = 0$, i.e. $\ds x = {{rAff}}$. The solution set is $\ds \{0\,;\,{{rAff}}\}$.`
118
+ ::::
119
+
120
+ ::::{weightDistribution}
121
+ :logic: 18
122
+ :abstraction: 18
123
+ :reasoning: 24
124
+ :calculation: 40
125
+ ::::
126
+ :::::
127
+
128
+ `````
app/knowledge/fewshots/systemes.md ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ `````{exercise}
2
+ :title: Assortiment : solution unique mais non réalisable
3
+ :modules:
4
+ :recommendedExecutionTime: 14
5
+ :level: Elementary
6
+ :chap:
7
+ :involvedConcepts:
8
+ :originalSource:
9
+ :visibility: All
10
+ :variations:
11
+ :comment: Appliqué (économie & gestion) : système 2×2 à solution unique mais non réalisable (quantité négative). Distinction « système soluble » vs « plan réalisable ».
12
+
13
+ ````{python}
14
+ import random as rd
15
+ import numpy as np
16
+ import matplotlib.pyplot as plt
17
+ from sympy import Rational, latex
18
+ from pyxiscience.Mes_fctions_generalistes_bis import pxs_config, pxsl_latex_coefficient as lc
19
+
20
+ config_standard = pxs_config()
21
+
22
+ # solution entière, non réalisable (solR < 0) : (prix_A-prix_R) divise extra
23
+ for _ in range(2000):
24
+ prix_A = rd.choice([10, 12, 14, 16, 18, 20])
25
+ prix_R = rd.choice([4, 5, 6, 7, 8, 9, 10])
26
+ quantite_totale = rd.choice([15, 20, 25, 30])
27
+ if prix_A <= prix_R:
28
+ continue
29
+ extra = rd.randint(20, 80)
30
+ if extra % (prix_A - prix_R) != 0:
31
+ continue
32
+ cout_total = quantite_totale * prix_A + extra
33
+ solA = quantite_totale + extra // (prix_A - prix_R)
34
+ solR = quantite_totale - solA
35
+ if solR < 0 and solA > quantite_totale:
36
+ break
37
+
38
+ # Rendus
39
+ prixA = prix_A
40
+ prixR = prix_R
41
+ quantiteTotale = quantite_totale
42
+ coutTotal = cout_total
43
+ prixRSignAff = lc(prix_R, sign=True)
44
+ prixRQtSignAff = lc(prix_R * quantite_totale, sign=True)
45
+ negPrixRSignAff = lc(-prix_R, sign=True)
46
+ prixMoins = prix_A - prix_R
47
+ coutMoins = cout_total - prix_R * quantite_totale
48
+ coutMoyenAff = latex(Rational(cout_total, quantite_totale))
49
+ rapportUnAff = latex(Rational(1, prix_A))
50
+ rapportDeuxAff = latex(Rational(1, prix_R))
51
+
52
+ # Figure (une seule fois) : droites D1 et D2 dans le plan (a, r)
53
+ amax = solA + 4
54
+ xs = np.linspace(-1, amax, 200)
55
+ r_d1 = quantite_totale - xs
56
+ r_d2 = (cout_total - prix_A * xs) / prix_R
57
+ fig, ax = plt.subplots(figsize=(6, 5.5))
58
+ ax.plot(xs, r_d1, color="tab:blue", linewidth=2, label="$D_1:a+r=%d$" % quantite_totale)
59
+ ax.plot(xs, r_d2, color="tab:red", linewidth=2, label="$D_2$ (coût total)")
60
+ ax.fill([0, quantite_totale, 0], [0, 0, quantite_totale], color="gray", alpha=0.15)
61
+ ax.text(quantite_totale * 0.18, quantite_totale * 0.18, "zone réalisable", color="gray", fontsize=9)
62
+ ax.plot([solA], [solR], "o", color="black", markersize=7)
63
+ ax.text(solA, solR, " $(%d;%d)$" % (solA, solR), fontsize=10, va="top")
64
+ ax.axhline(y=0, color="k", linewidth=0.8)
65
+ ax.axvline(x=0, color="k", linewidth=0.8)
66
+ ax.set_xlabel("$a$ (kg Arabica)", fontsize=11)
67
+ ax.set_ylabel("$r$ (kg Robusta)", fontsize=11)
68
+ ax.set_title("Intersection hors du domaine réalisable", fontsize=11)
69
+ ax.grid(True, alpha=0.3)
70
+ ax.legend(fontsize=9, loc="upper right")
71
+ plt.tight_layout()
72
+ plt.show()
73
+
74
+ globals()
75
+ ````
76
+
77
+ :::::{question}
78
+ :questionType: STQ
79
+ :questionId: 0
80
+ :questionIndex: 0
81
+
82
+ ::::{questionStatement}
83
+ Un responsable logistique veut constituer un assortiment de deux cafés en grains : Arabica à ${}{{ prixA }}$ €/kg et Robusta à ${}{{ prixR }}$ €/kg. Il vise exactement ${}{{ quantiteTotale }}$ kg d'assortiment pour un coût total de ${}{{ coutTotal }}$ €. On note $a$ la quantité d'Arabica (kg) et $r$ celle de Robusta (kg). Modéliser la situation par un système de deux équations à deux inconnues.
84
+ ::::
85
+
86
+ ::::{questionHint}
87
+ Une équation pour la quantité totale, une équation pour le coût total.
88
+ ::::
89
+
90
+ ::::{detailedSolution}
91
+ Les contraintes de quantité totale et de coût total donnent :
92
+
93
+ \begin{equation*}
94
+ \begin{cases}
95
+ a + r &= {{ quantiteTotale }} & (1) \\
96
+ {{ prixA }}a {{ prixRSignAff }}r &= {{ coutTotal }} & (2)
97
+ \end{cases}
98
+ \end{equation*}
99
+ ::::
100
+
101
+ ::::{weightDistribution}
102
+ :logic: 20
103
+ :abstraction: 35
104
+ :reasoning: 30
105
+ :calculation: 15
106
+ ::::
107
+ :::::
108
+
109
+ :::::{question}
110
+ :questionType: STQ
111
+ :questionId: 1
112
+ :questionIndex: 1
113
+
114
+ ::::{questionStatement}
115
+ Résoudre le système, puis examiner le signe des quantités obtenues afin de déterminer si le plan d'assortiment est réalisable.
116
+ ::::
117
+
118
+ ::::{questionHint}
119
+ Les coefficients ne sont pas proportionnels (${}{{ rapportUnAff }}\neq {{ rapportDeuxAff }}$) : le système a une solution unique. Vérifier ensuite que $a\geq 0$ et $r\geq 0$.
120
+ ::::
121
+
122
+ ::::{detailedSolution}
123
+ Les rapports des coefficients diffèrent (${}{{ rapportUnAff }}\neq {{ rapportDeuxAff }}$) : droites sécantes, solution unique. De $(1)$ : $r={{ quantiteTotale }}-a$. On substitue dans $(2)$ :
124
+
125
+ \begin{equation*}
126
+ {{ prixA }}a + {{ prixR }}({{ quantiteTotale }} - a) &= {{ coutTotal }} \\
127
+ {{ prixA }}a {{ prixRQtSignAff }} {{ negPrixRSignAff }}a &= {{ coutTotal }} \\
128
+ {{ prixMoins }}a &= {{ coutMoins }} \\
129
+ a &= {{ solA }}.
130
+ \end{equation*}
131
+
132
+ \begin{equation*}
133
+ r &= {{ quantiteTotale }} - {{ solA }} \\
134
+ &= {{ solR }}.
135
+ \end{equation*}
136
+
137
+ La solution mathématique est $(a,r)=({{ solA }},{{ solR }})$. Comme $r={{ solR }}<0$, une quantité négative de Robusta n'a pas de sens : le système a bien une solution unique, mais le plan d'assortiment n'est pas réalisable.
138
+ ::::
139
+
140
+ ::::{weightDistribution}
141
+ :logic: 25
142
+ :abstraction: 30
143
+ :reasoning: 30
144
+ :calculation: 15
145
+ ::::
146
+ :::::
147
+
148
+ :::::{question}
149
+ :questionType: STQ
150
+ :questionId: 2
151
+ :questionIndex: 2
152
+
153
+ ::::{questionStatement}
154
+ Interpréter économiquement ce résultat : pourquoi ce plan d'assortiment est-il irréalisable ? La situation est représentée graphiquement en tête d'exercice.
155
+ ::::
156
+
157
+ ::::{questionHint}
158
+ Comparer le coût moyen visé au prix du café le plus cher.
159
+ ::::
160
+
161
+ ::::{detailedSolution}
162
+ Le coût moyen visé serait ${}{{ coutTotal }}/{{ quantiteTotale }}={{ coutMoyenAff }}$ €/kg. Or le café le plus cher (Arabica) ne coûte que ${}{{ prixA }}$ €/kg : aucun mélange de deux cafés à ${}{{ prixA }}$ et ${}{{ prixR }}$ €/kg ne peut atteindre une moyenne de ${}{{ coutMoyenAff }}$ €/kg. Le budget de ${}{{ coutTotal }}$ € est trop élevé pour ${}{{ quantiteTotale }}$ kg. Aucun plan réalisable ($a\geq 0$, $r\geq 0$) ne satisfait les deux contraintes : les droites se coupent en $({{ solA }},{{ solR }})$, hors du domaine de faisabilité (voir la figure en tête d'exercice).
163
+ ::::
164
+
165
+ ::::{weightDistribution}
166
+ :logic: 25
167
+ :abstraction: 35
168
+ :reasoning: 30
169
+ :calculation: 10
170
+ ::::
171
+ :::::
172
+
173
+ `````
app/knowledge/functions_catalogue.md ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--
2
+ VÉRIFICATION (2026-06-12, contre app/corpus/*.py + 222 exemples livrés) :
3
+ • Les 41 fonctions _bis de ce catalogue sont TOUTES présentes dans le corpus
4
+ embarqué (généralistes / analyse / alg. lin. / proba) ✅.
5
+ • pxs_Interval (Classes_Extensions.py), pxs_construct_RREF, pxs_gauss_jordan
6
+ sont présents (le catalogue en doutait) ✅.
7
+ • NON présents dans le corpus embarqué (runtime plateforme uniquement —
8
+ à n'utiliser que si la plateforme les charge) : myst, pxsl_mat (alias),
9
+ indi_l_r_symb, pxs_round, Poly_with_random_coef.
10
+ • ⚠️ DIVERGENCE catalogue ↔ corpus livré : le §0 recommande `pxsl_latex` et
11
+ « jamais latex() brut ». Or les 222 exemples LIVRÉS de la plateforme
12
+ utilisent `latex(expr, **config_standard)` 126 fois et `pxsl_latex(` 0 fois.
13
+ → L'app garde `latex(expr, **config_standard)` comme voie PAR DÉFAUT pour
14
+ toute sortie scalaire/expression (c'est la forme prouvée VERTE au harnais et
15
+ celle que produit l'auto-lift). `pxsl_latex` reste disponible mais n'est PAS
16
+ le défaut. Pour les MATRICES / SYSTÈMES / PROBA / IBP : utiliser les helpers
17
+ dédiés ci-dessous (le corpus livré ne contient aucun exemple de ces domaines,
18
+ donc le LLM doit s'appuyer sur ces signatures plutôt que coder à la main).
19
+ • Doc en ligne : https://scripts.doc.pyxiscience.com/
20
+ -->
21
+
22
+ # PyxiScience — Catalogue des fonctions (helpers à utiliser DANS le bloc Python)
23
+
24
+ > Workflow : scanner l'exercice → identifier le domaine (analyse / algèbre
25
+ > linéaire / proba / formatage) → récupérer ici les fonctions utiles et leur
26
+ > signature exacte AVANT d'écrire du code. **Tout affichage passe par un helper
27
+ > du catalogue appelé dans le bloc Python, résultat rangé dans une variable
28
+ > `…Aff` injectée nue.** Ne jamais réimplémenter une fonction qui existe ici.
29
+
30
+ ## 0. Conventions critiques
31
+
32
+ - **Expression/scalaire → `latex(expr, **config_standard)`** (voie par défaut,
33
+ prouvée sur le corpus livré). `pxsl_latex(expr)` existe (convention maison,
34
+ réordonne si `reverse=True`) mais n'est pas le défaut. **Matrice →
35
+ `pxsl_matrix(...)`. Résultat numérique → `pxsl_res_num(...)`.**
36
+ - **`config_standard = pxs_config()`** en tête de bloc, puis `**config_standard`
37
+ passé à `latex(...)` (notation `ln`, séparateur FR `,`, ordre des termes).
38
+ `**config_standard` est réservé à `latex()` — **jamais** sur un helper `pxsl_*`.
39
+ - **Nom Python réservé** : `total` interdit → `nb_total`.
40
+ - **Ne jamais concaténer un signe** : construire la chaîne complète
41
+ (`pxsl_latex_coefficient(c, sign=True)`) puis injecter la variable seule.
42
+
43
+ ## 2. Briques quasi toujours utiles
44
+
45
+ 1. `pxs_config()` → `config_standard`.
46
+ 2. `latex(expr, **config_standard)` → toute sortie scalaire/expression.
47
+ 3. `pxsl_latex_coefficient(c, sign=, ones=)` → coefficients signés sans `1·x`/`+0`.
48
+ 4. `pxsl_res_num(x, dec=, egal=)` → résultat numérique formaté (`= 0,2354`, `23,54 %`).
49
+ 5. `pxsl_pow(x, n)` → puissance avec parenthèses si base négative/irrationnelle.
50
+
51
+ ## 4. Généralistes — formatage & LaTeX (`Mes_fctions_generalistes_bis.py`)
52
+
53
+ - **`pxs_config()`** → dict d'options LaTeX (ln, virgule FR, ordre). `**config_standard`.
54
+ - **`latex(expr, **config_standard)`** — voie par défaut. `pxsl_latex(expr, reverse=False)`
55
+ = variante maison (réordonne du degré faible au fort si `reverse=True`).
56
+ - **`pxsl_sign(expr)`** → `'+'` / `'-'` / `''`. Construire un signe à part AVANT injection.
57
+ - **`pxsl_format_number(n)`** → milliers en espaces fines, gère `±∞`. (Aucun kwarg — pas d'arrondi, arrondir avant.) `pxsl_format_number(1234)`→`'1\ 234'`.
58
+ - **`pxsl_latex_with_formatting(expr, sign=False, display=True)`** → `latex()` + milliers (≥1000), y compris dans les fractions.
59
+ - **`pxsl_latex_coefficient(coeff, variable=None, sign=False, zeros=True, ones=False, display=True)`** → gère `1`→`''`, `-1`→`'-'` (ou `'-1'` si `ones=True`), signe explicite. Alias `lc`.
60
+ - **`pxsl_to_rational_or_symbol(value)`** → `Rational` SymPy précis (via Fraction) ; laisse un Symbol.
61
+ - **`pxsl_solve_general_inequality(a=1, b=0, c=0, variable='x', inequality='>=', domain='R', power=1, sign_a=None)`** → résout `a·x^p+b ⋛ c` (p=1 ou 2) + rédaction LaTeX complète. Retour `(solution_set, latex_reasoning)`.
62
+ - **`pxsl_Rational(num, den, orientation='v', display=True)`** → fraction « propre » `π/2`, `x/2` (simplifie le numérique, garde le symbolique). ⚠️ ZeroDivisionError si den=0.
63
+ - **`pxs_is_reductible_sqrt(x)`** → bool (carré parfait sous la racine).
64
+ - **`pxs_separate_factors(expr, var)`** → `(indépendants de var, dépendants de var)`.
65
+
66
+ ## 5. Analyse — intégration par parties (`Mes_fctions_d_analyse_bis.py`)
67
+
68
+ - **`pxs_explain_IBP(var=Symbol('x'), f1=None, f2=None, type_int='udv', a=None, b=None, nb_IBP=1, intro=True, conclude=True)`** → **rédaction LaTeX complète** d'un calcul par IPP (intégrale définie `a,b` ou primitive ; une ou deux IPP). Pour « calculer ∫ u·v′ par IPP ». `type_int='udv'`/`'vdu'`. Retour `str` LaTeX prêt à injecter.
69
+ Ex. `ipp = pxs_explain_IBP(f1=x, f2=exp(x), type_int='udv', a=0, b=1)` → `{{ipp}}`.
70
+ - **`pxsl_par(expr, minus=False, add=False)`** → parenthèses si l'expression commence par `-` ou est une somme (`Add`). Sécurise un facteur.
71
+ - **`pxsl_final_sentence(sol, a, b, var, mult, *args)`** → phrase finale d'une IPP multi-étapes.
72
+
73
+ ## 6. Algèbre linéaire — matrices & systèmes (`Mes_fctions_d_alg_lineaire_bis.py`)
74
+
75
+ > `pxsl_*` AFFICHENT (LaTeX) ; `pxs_*` GÉNÈRENT/CALCULENT. `sepG`/`sepD` =
76
+ > délimiteurs (`'('`/`')'` défaut ; `'|'`/`'|'` pour un déterminant).
77
+
78
+ - **`pxsl_pow(x, n=1, opt=0, displaystyle=True)`** → `x^n` avec parenthèses si base négative/irrationnelle. `pxsl_pow(-3,2)`→`'\left(-3\right)^{2}'`.
79
+ - **`pxsl_matrix(A, sepG='(', sepD=')', display=False)`** → matrice LaTeX (nombres alignés à droite) ; `'|','|'` → déterminant.
80
+ - **`pxsl_sum_matrix(A, B, s='+')`** → détail case par case de `A±B`.
81
+ - **`pxsl_prod_scalar_matrix(lamb, A, mult='times')`** → détail de `λ·A`.
82
+ - **`pxsl_prod_matrix(A, B, mult='times')`** → détail du produit `A·B`.
83
+ - **`pxsl_ax(a, x=Symbol('x'), sign=' ', frac=True)`** → `ax` en gérant `a=0/1/−1` ; `x` symbole quelconque (`L_{1}`).
84
+ - **`pxsl_system_lin(A, B, x='x')`** → système `Ax=B` en forme accolade.
85
+ - **`pxsl_double_matrix(A, B, opt='sep')`** → `A` et `B` côte à côte (`'sep'`) ou matrice augmentée (`'ext'`).
86
+ - **`pxsl_lines_op(n, listOp, opt='sys')`** → opération `L_{i} ← a·L_{i}+b·L_{j}` depuis `listOp=[a,i,b,j]`.
87
+ - **`pxsl_resol_system(listA, listB=[], listOp=[], x='x', method='sys', view='sep')`** → chaque étape d'une élimination (`method` : `'sys'`/`'mat'`/`'ech'`).
88
+ - **`pxs_steps_invert_matrix(A, B, method='sys')`** → résolution de système (`B`) ou **inversion** (`B=eye(n)`, `method='mat'`), rédaction LaTeX complète.
89
+ - **`pxs_compute_ech(A)` / `pxs_compute_ech_reduite(A)`** → forme échelonnée / **RREF** avec étapes en LaTeX. (Équivalents de `pxs_construct_RREF`.)
90
+ - **`pxs_system_simpl(n=3, opt='sys', max_coef=2, limit_sum=15)`** → génère `(A, B)` d'un système `Ax=B` à solution entière simple.
91
+ - **`pxs_commute_matrix(n, opt='')`** → `(A,B)` qui commutent et `(A,C)` qui non.
92
+ - **`pxsl_pow_matrix(A, k)`** → chaque coefficient élevé à la puissance `k`.
93
+ - **`pxs_invertible_matrix(n)`** / **`pxs_diag_matrix(p, a, b)`** / **`randmatrixrect(p, q, a, b)`** → matrice inversible / diagonale / rectangulaire aléatoire (coeffs entiers).
94
+
95
+ ## 7. Probabilités — variables aléatoires finies (`Mes_fctions_probabilistes_bis.py`)
96
+
97
+ > v.a. finies SymPy (`stats.FiniteRV`). `pxsl_*` affichent ; `pxs_*` construisent.
98
+
99
+ - **`pxs_finiterv(x, val, prob)`** → v.a. `x` de valeurs `val` et probas `prob`. Ex. `X = pxs_finiterv('X', [0,1,2], [Rational(1,4),Rational(1,2),Rational(1,4)])`.
100
+ - **`pxsl_law(textx, textprob, X, frac='', nzero=True)`** → tableau de loi (valeurs / probas) en LaTeX. `textx`/`textprob` = en-têtes.
101
+ - **`pxsl_moment(X, n=1, prod='times')`** → calcul détaillé de `E[Xⁿ]` (espérance/variance).
102
+ - **`pxsl_scalar_product(a, b, prod='times')`** → calcul de `a·b = Σ aᵢbᵢ`.
103
+ - **`pxs_simul_law(n, type_proba='dec', prec=0.01)`** → simule une loi discrète de taille n.
104
+ - **`pxs_fct_finiterv(f, X)`** → v.a. `Y = f(X)`. Ex. `Y = pxs_fct_finiterv(lambda t: t**2, X)`.
105
+ - **`pxsl_res_num(x, dec=4, pourc=False, text=False, egal=True, dot=True)`** → résultat numérique (`= 0,2354`, `23,54 %`). `egal=False` retire le préfixe.
106
+ - **`pxsl_sum_vector(x)`** → `Σ xᵢ` en LaTeX.
107
+ - **`pxs_nvirgzero(x)`** → supprime `.0` d'un float entier (tolérance 1e-10).
108
+ - **`pxsl_pow(...)`** aussi présent ici (identique à §6).
109
+
110
+ ## 8. Utilitaires complémentaires (présence runtime à vérifier)
111
+
112
+ ⚠️ NON présents dans le corpus embarqué — ne les utiliser que si la plateforme
113
+ les charge au runtime (sinon coder l'équivalent à la main) :
114
+ - **`indi_l_r_symb(l, alpha, beta, r)`** → fonction indicatrice symbolique `1_{[α,β]}`. `f = indi_l_r_symb('[',0,1,']'); f(x)`.
115
+ - **`pxs_round(x, ndigits=0)`** → arrondi « calculatrice » (half-up, pas banker's). `pxs_round(0.125,2)`→`0.13`.
116
+ - **`Poly_with_random_coef(symbol, deg, constant_coef)`** → polynôme aléatoire (coeffs `[-9,9]`) + LaTeX croissant/décroissant.
117
+
118
+ ## 3. Primitives plateforme (référencées, non dans ces modules)
119
+
120
+ - **`{{ var }}`** — interpolation MyST (un nom de variable nu, voir règles).
121
+ - **`myst(...)`** — rendu plateforme (stubbé en local). Les `\fr{}\en{}` legacy ne
122
+ rendent pas → utiliser `` {fr}`…`{en}`…` ``.
123
+ - **`pxsl_mat(...)`** — alias plateforme ; équivalent présent = **`pxsl_matrix`**.
124
+ - **`pxs_Interval(...)`** — affichage d'intervalle (présent dans Classes_Extensions.py).
app/knowledge/prompts_v1_archive.md ADDED
@@ -0,0 +1,1047 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Archive v1 des prompts LLM (extraits verbatim de routes/pythonise_routes_v2.py avant refonte 2026-06-12)
2
+
3
+ ## STEP1_PROMPT (v1)
4
+ # ─────────────────────────────────────────────────────────────────────────────
5
+ # v1 → version antérieure conservée dans l'historique git (commit avant 2026-05-13).
6
+ # Cette version étend la sortie JSON avec target_rules / property_constraints /
7
+ # has_validated_solution_in_input afin que STEP_PAIR_PROMPT puisse injecter
8
+ # un digest ciblé des règles de pythonisation_rules.md à risque pour cet exo.
9
+ STEP1_PROMPT = """\
10
+ Tu es un expert en analyse d'exercices mathématiques & detection des variables pythons pour PyxiScience.
11
+ Permettant de passer d'un exercice avec des valeurs statiques à un exercice avec des valeurs aléatoires **correctes**.
12
+
13
+ EXERCICE :
14
+ {content}
15
+
16
+ ─────────────────────────────────────────────────────
17
+ MISSION : Analyse cet exercice et identifie **TOUTES** les entités mathématiques
18
+ qui devront être générées aléatoirement en Python pour produire des variables aléatoires python valides.
19
+
20
+ Couvre TOUS les types possibles :
21
+ • Scalaires entiers (ex: coefficients, dimensions, scores)
22
+ • Scalaires réels (ex: probabilités, longueurs)
23
+ • Fractions (ex: 3/4, -2/5)
24
+ • Listes / tableaux (ex: liste de notes, de mesures)
25
+ • Vecteurs (ex: (3, -2, 1))
26
+ • Matrices (ex: matrice 2×2, 3×3)
27
+ • Ensembles (ex: Ω = {{1,2,3,4,5,6}})
28
+ • Polynômes (ex: ax² + bx + c → coefficients a,b,c)
29
+ • Fonctions (ex: f(x) = x·e^(ax))
30
+ • Pourcentages (ex: 25%, 50%)
31
+ • Autres entités (ex: angles, intervalles)
32
+
33
+ Pour chaque variable :
34
+ • nom : nom Python valide court (ex: a, b, n, mat_A, liste_notes),
35
+ cette variable peut être partagée entre plusieurs questions
36
+ • type_python : "int"|"float"|"Fraction"|"list"|"matrix"|"set"|"vector"|"other"
37
+ • description : rôle dans l'énoncé (1 phrase)
38
+ • contraintes : contraintes mathématiques (ex: a ≠ 0, n ∈ [2,10])
39
+ • plage_python : expression Python exacte de génération aléatoire
40
+ • location : "énoncé"|"inter-question"|"question"|"solution 1"|"solution 2"|"solution 3"|"solution 4"|"solution 5"
41
+ les emplacements de l'apparition de la variable dans les differentes parties de l'exercice.
42
+ "énoncé" = texte d'introduction avant la 1ère question.
43
+ "inter-question" = texte entre deux blocs question (transitions, hypothèses partagées).
44
+ • valeur_exemple: valeur typique
45
+
46
+ ─────────────────────────────────────────────────────
47
+ RÈGLES DE PYTHONISATION (catalogue) — choisis dans "target_rules" celles qui
48
+ sont LE PLUS À RISQUE pour CET exercice spécifique (5 à 12 IDs maximum).
49
+ Une règle est "à risque" si l'énoncé contient un piège typique (tirages flottants,
50
+ matplotlib, coefficients signés, paragraphes contextuels, bilingue long, etc.).
51
+
52
+ {available_rules_menu}
53
+
54
+ ─────────────────────────────────────────────────────
55
+ Réponds UNIQUEMENT en JSON valide :
56
+ {{
57
+ "exercise_type": "...",
58
+ "exercise_title": "...",
59
+ "exercise_summary": "...",
60
+ "suggested_concepts": ["..."],
61
+ "nb_questions": 1,
62
+ "variables": [
63
+ {{
64
+ "nom": "...",
65
+ "type_python": "...",
66
+ "description": "...",
67
+ "contraintes": "...",
68
+ "location": "énoncé|question|solution 1 ",
69
+ "plage_python": "...",
70
+ "valeur_exemple": "..."
71
+ }}
72
+ ],
73
+ "needs_fraction": false,
74
+ "needs_sympy": false,
75
+ "needs_numpy": false,
76
+ "needs_matplolib": false,
77
+ "mathematical_structure": "...",
78
+ "target_rules": ["3.1", "4.1", "6.1"],
79
+ "property_constraints": [
80
+ "<invariant mathématique en français — ex: w_n ≥ n pour tout n>",
81
+ "<peut être vide si aucun invariant non-trivial>"
82
+ ],
83
+ "has_validated_solution_in_input": false
84
+ }}
85
+
86
+ Notes :
87
+ • "target_rules" : uniquement des IDs présents dans le catalogue ci-dessus.
88
+ Sélectionne celles qui CET exercice risque de violer (top 5-12).
89
+ • "property_constraints" : invariants à préserver lors du tirage aléatoire
90
+ (cf. règle 4.3). Liste vide si aucun.
91
+ • "has_validated_solution_in_input" : true SI l'énoncé contient déjà des
92
+ blocs `::::{{detailedSolution}}` rédigés (cf. règles 8.1–8.3).
93
+ """
94
+
95
+ ## STEP_PAIR_PROMPT (v1)
96
+ # STEP 2+ – Per-pair generation (python block + énoncé/inter-text + questions)
97
+ # ─────────────────────────────────────────────────────────────────────────────
98
+
99
+ """
100
+ STEP_PAIR_PROMPT — Restructuré pour forcer l'usage du catalogue PyxiScience
101
+ ET pour pythoniser l'énoncé + les textes inter-question.
102
+
103
+ Changements majeurs vs version précédente :
104
+ • La SECTION À PYTHONISER peut désormais contenir, en plus des blocs
105
+ :::::{question}, du texte d'énoncé (1ère paire) et du texte
106
+ inter-question (avant chaque question d'une paire), à réécrire avec
107
+ injections de variables.
108
+ • Catalogue et règles de compliance déplacés au TOUT DÉBUT du prompt
109
+ (exploit du biais primacy : les LLMs retiennent mieux ce qui arrive
110
+ en tête).
111
+ • Imports PyxiScience NE SONT PLUS hardcodés — le modèle doit les
112
+ recopier depuis le catalogue pour les fonctions qu'il utilise.
113
+ • Exemples concrets ❌/✅ de violation au lieu de règles abstraites.
114
+ • Suppression des phrases "ne pas sur-optimiser / ne pas complexifier"
115
+ qui poussaient le modèle à faire l'inverse du souhaité.
116
+ • Règles MyST et structure de question conservées intactes.
117
+ """
118
+
119
+ STEP_PAIR_PROMPT = """\
120
+ Tu es un expert en pythonisation d'exercices PyxiScience MyST, niveau {niveau}.
121
+ Mission : transformer un exercice statique (paramètres fixes) en version pythonisée
122
+ (paramètres randomisés + injectés dans le MyST).
123
+
124
+ ═══════════════════════════════════════════════════════════════════════════
125
+ PRINCIPE FONDAMENTAL — PYTHON = VALEURS, MyST = TEXTE
126
+ ═══════════════════════════════════════════════════════════════════════════
127
+
128
+ Bloc Python = imports + tirages aléatoires + calculs sympy + `globals()` final.
129
+ Variables = VALEURS brutes (nombres, expressions sympy, intervalles).
130
+ **Aucun texte pédagogique en chaîne Python.**
131
+
132
+ Texte (énoncés, hypothèses, démonstrations) = directement dans le MyST des
133
+ `questionStatement` / `detailedSolution`. Valeurs injectées via :
134
+ • `{{{{var}}}}` — nom de variable simple
135
+ • `{{{{latex(expr)}}}}` — expression sympy (config_standard est injecté automatiquement par post-process)
136
+ • `{{{{pxsl_res_num(val, egal=False)}}}}` — résultat numérique
137
+ • `{{{{pxsl_format_number(n)}}}}` — nombre formaté
138
+ • `{{{{lc(c, sign=True)}}}}` — coefficient (alias `pxsl_latex_coefficient`)
139
+ • `{{{{obj.print()}}}}` — intervalle, polynôme
140
+
141
+ ⚠️ **JAMAIS de `**kwargs` dans `{{{{...}}}}`** (cf. règle 6.1). MyST parse `**` comme bold
142
+ markdown avant l'interpolation Python — le rendu casse. Si tu as besoin d'arguments,
143
+ pré-calcule la string dans le bloc python : `coef_disp = pxsl_format_number(float(coef), **config_standard)`
144
+ puis injecte `{{{{coef_disp}}}}`.
145
+
146
+ ❌ ANTI-PATTERN — pré-construire la solution pédagogique en variable Python :
147
+ ```{{python}}
148
+ calcul_q2 = myst(r'''\begin{{equation*}} P(A_n) &= ... \end{{equation*}}''', globals(), locals())
149
+ ```
150
+ Puis `{{{{calcul_q2}}}}` dans le MyST → toute la pédagogie quitte le fichier.
151
+ **REJETÉ.** Idem pour `*_latex`, `*_display` qui pré-stockent un rendu.
152
+
153
+ ✅ EXCEPTION — `myst(r'''...''', globals(), locals())` est légitime UNIQUEMENT
154
+ quand le TEXTE varie selon une condition Python (ex: signe d'un coefficient,
155
+ `pxs_variation_number == N`). Pattern : variables `xxx_fr` / `xxx_en` SANS
156
+ directives bilingues internes, injectées dans des parents `:::{{fr}}/:::{{en}}`.
157
+
158
+ ═══════════════════════════════════════════════════════════════════════════
159
+ EXEMPLE MINIMAL — Signe d'un trinôme (branchement conditionnel + intervalles)
160
+ ═══════════════════════════════════════════════════════════════════════════
161
+
162
+ ```{{python}}
163
+ import random as rd
164
+ from sympy import symbols, sqrt, latex, simplify, oo
165
+ from pyxiscience.Mes_fctions_generalistes_bis import pxs_config, pxsl_latex_coefficient as lc
166
+ from pyxiscience.Classes_Extensions import pxs_Interval
167
+
168
+ config_standard = pxs_config()
169
+ x = symbols('x')
170
+
171
+ # Contrainte : a > 0 et c < 0 garantit delta > 0 (deux racines réelles)
172
+ a = rd.randint(1, 3)
173
+ b = rd.randint(2, 6)
174
+ c = rd.randint(-4, -1)
175
+
176
+ T = a*x**2 + b*x + c
177
+ delta = b**2 - 4*a*c
178
+ x1 = (-b - sqrt(delta)) / (2*a)
179
+ x2 = (-b + sqrt(delta)) / (2*a)
180
+
181
+ intervalle_entre = pxs_Interval(x1, x2, True, True)
182
+ intervalle_avant = pxs_Interval(-oo, x1, True, True)
183
+ intervalle_apres = pxs_Interval(x2, oo, True, True)
184
+
185
+ globals()
186
+ ```
187
+
188
+ :::{{fr}}
189
+ On considère le trinôme défini pour tout réel $x$ par
190
+ \begin{{equation*}}
191
+ T(x) = {{{{latex(T)}}}}.
192
+ \end{{equation*}}
193
+ :::
194
+ :::{{en}}
195
+ We consider the quadratic polynomial defined for every real $x$ by
196
+ \begin{{equation*}}
197
+ T(x) = {{{{latex(T)}}}}.
198
+ \end{{equation*}}
199
+ :::
200
+
201
+ :::::{{question}}
202
+ :questionType: STQ
203
+ :questionId: 0
204
+ :questionIndex: 0
205
+
206
+ ::::{{questionStatement}}
207
+ {{fr}}`Calculer le discriminant $\Delta$ et en déduire le nombre de racines.`{{en}}`Compute $\Delta$ and deduce the number of real roots.`
208
+ ::::
209
+
210
+ ::::{{questionHint}}
211
+ {{fr}}`$\Delta = b^2 - 4ac$.`{{en}}`$\Delta = b^2 - 4ac$.`
212
+ ::::
213
+
214
+ ::::{{detailedSolution}}
215
+ {{fr}}`Application numérique :`{{en}}`Numerical application:`
216
+ \begin{{equation*}}
217
+ \Delta &= {{{{b}}}}^2 - 4 \times {{{{a}}}} \times ({{{{c}}}}) \\
218
+ &= {{{{latex(delta)}}}}.
219
+ \end{{equation*}}
220
+ {{fr}}`Comme $\Delta = {{{{latex(delta)}}}} > 0$, deux racines réelles distinctes.`{{en}}`Since $\Delta > 0$, two distinct real roots.`
221
+ ::::
222
+
223
+ ::::{{weightDistribution}}
224
+ :reasoning: 25
225
+ :logic: 20
226
+ :abstraction: 15
227
+ :calculation: 40
228
+ ::::
229
+ :::::
230
+
231
+ ```{{python}}
232
+ # Bloc intermédiaire : phrase qui dépend du signe de a
233
+ if a > 0:
234
+ text = myst(r""{{fr}}`Comme $a = {{{{a}}}} > 0$, $T$ est négatif entre les racines, positif à l'extérieur :`{{en}}`Since $a = {{{{a}}}} > 0$, $T$ is negative between the roots and positive outside:`"", globals(), locals())
235
+ else:
236
+ text = myst(r""{{fr}}`Comme $a = {{{{a}}}} < 0$, $T$ est positif entre les racines, négatif à l'extérieur :`{{en}}`Since $a = {{{{a}}}} < 0$, $T$ is positive between the roots and negative outside:`"", globals(), locals())
237
+ ```
238
+
239
+ :::::{{question}}
240
+ :questionType: STQ
241
+ :questionId: 1
242
+ :questionIndex: 1
243
+
244
+ ::::{{questionStatement}}
245
+ {{fr}}`Étudier le signe de $T(x)$.`{{en}}`Study the sign of $T(x)$.`
246
+ ::::
247
+
248
+ ::::{{questionHint}}
249
+ ::::
250
+
251
+ ::::{{detailedSolution}}
252
+ {{{{text}}}}
253
+
254
+ {{fr}}` - $T(x) < 0$ sur $\ds {{{{intervalle_entre.print()}}}}$ ;`
255
+ {{en}}` - $T(x) < 0$ on $\ds {{{{intervalle_entre.print()}}}}$ ;`
256
+
257
+ {{fr}}` - $T(x) > 0$ sur $\ds {{{{intervalle_avant.print()}}}} \cup {{{{intervalle_apres.print()}}}}$.`
258
+ {{en}}` - $T(x) > 0$ on $\ds {{{{intervalle_avant.print()}}}} \cup {{{{intervalle_apres.print()}}}}$.`
259
+ ::::
260
+
261
+ ::::{{weightDistribution}}
262
+ :reasoning: 30
263
+ :logic: 30
264
+ :abstraction: 20
265
+ :calculation: 20
266
+ ::::
267
+ :::::
268
+ ```
269
+
270
+ ═══════════════════════════════════════════════════════════════════════════
271
+ EXEMPLE CORPUS — extrait Bac Amérique du Nord (style authentique)
272
+ ═══════════════════════════════════════════════════════════════════════════
273
+
274
+ ```{{python}}
275
+ import random as rd
276
+ from sympy import *
277
+ from pyxiscience.Mes_fctions_generalistes_bis import pxs_config, pxsl_latex_coefficient as lc
278
+ from pyxiscience.Classes_Extensions import pxs_Interval
279
+
280
+ config_standard = pxs_config()
281
+ x = symbols('x')
282
+
283
+ # 4 entiers DISTINCTS dans [1,5]
284
+ a, b, c, d = rd.sample(range(1, 6), 4)
285
+
286
+ f1 = exp(b*x); f2 = sin(b*x)
287
+ f = f1 * f2
288
+ df1 = diff(f1, x); df2 = diff(f2, x)
289
+
290
+ dom = pxs_Interval(0, pi/b, False, False)
291
+
292
+ globals()
293
+ ```
294
+
295
+ {{fr}}`Soit $f$ définie sur `{{en}}`Let $f$ be defined on `$\ds {{{{dom.print()}}}}$ {{fr}}`par`{{en}}`by`
296
+ \begin{{equation*}}
297
+ f(x) = {{{{latex(f)}}}}.
298
+ \end{{equation*}}
299
+
300
+ :::::{{question}}
301
+ :questionType: STQ
302
+ :questionId: 0
303
+ :questionIndex: 0
304
+
305
+ ::::{{questionStatement}}
306
+ {{fr}}`Démontrer que pour tout $x$ de `{{en}}`Prove that for all $x$ in `$\ds {{{{dom.print()}}}}$,
307
+ \begin{{equation*}}
308
+ f'(x) = {{{{b}}}}e^{{{{{{lc(b)}}}}x}}[\sin({{{{lc(b)}}}}x) + \cos({{{{lc(b)}}}}x)].
309
+ \end{{equation*}}
310
+ ::::
311
+
312
+ ::::{{questionHint}}
313
+ {{fr}}`Règle du produit avec $u = {{{{latex(f1)}}}}$, $v = {{{{latex(f2)}}}}$.`{{en}}`Product rule with $u = {{{{latex(f1)}}}}$, $v = {{{{latex(f2)}}}}$.`
314
+ ::::
315
+
316
+ ::::{{detailedSolution}}
317
+ {{fr}}`$f = u \times v$ avec $u = {{{{latex(f1)}}}}$, $v = {{{{latex(f2)}}}}$. Alors $u' = {{{{latex(df1)}}}}$, $v' = {{{{latex(df2)}}}}$. Donc :`{{en}}`$f = u \times v$ with $u = {{{{latex(f1)}}}}$, $v = {{{{latex(f2)}}}}$. Then $u' = {{{{latex(df1)}}}}$, $v' = {{{{latex(df2)}}}}$. Therefore:`
318
+ \begin{{equation*}}
319
+ f'(x) &= {{{{latex(df1)}}}} \times {{{{latex(f2)}}}} + {{{{latex(f1)}}}} \times {{{{latex(df2)}}}} \\[6pt]
320
+ &= {{{{b}}}}e^{{{{{{lc(b)}}}}x}}[\sin({{{{lc(b)}}}}x) + \cos({{{{lc(b)}}}}x)].
321
+ \end{{equation*}}
322
+ ::::
323
+
324
+ ::::{{weightDistribution}}
325
+ :reasoning: 20
326
+ :logic: 20
327
+ :abstraction: 20
328
+ :calculation: 40
329
+ ::::
330
+ :::::
331
+ ```
332
+
333
+ ═══════════════════════════════════════════════════════════════════════════
334
+ EXEMPLE CATALOGUE — usage dense des helpers pxsl_*
335
+ (Add evaluate=False, lc avec ones=/sign=, pxsl_par avec minus=)
336
+ ═══════════════════════════════════════════════════════════════════════════
337
+
338
+ ```{{python}}
339
+ import random as rd
340
+ from sympy import *
341
+ from pyxiscience.Mes_fctions_generalistes_bis import pxs_config, pxsl_latex_coefficient as lc
342
+ from pyxiscience.Mes_fctions_d_analyse_bis import pxs_explain_IBP, pxsl_par, pxsl_mult
343
+
344
+ config_standard = pxs_config()
345
+ x = symbols('x')
346
+ n = Symbol('n')
347
+
348
+ a = rd.randint(1, 5)
349
+ b = rd.randint(2, 5)
350
+ c = rd.randint(a + 1, 9)
351
+ d = rd.choice([-1, 1]) * rd.randint(1, 10)
352
+
353
+ # Add(..., evaluate=False) préserve la forme non simplifiée pour l'affichage
354
+ fx = Add(a*x * exp(-b*x), c*x + d, evaluate=False)
355
+
356
+ # Intégration par parties auto-explicative : retourne le LaTeX complet du calcul
357
+ # type_int='vdu' = ∫u dv ; bornes [a, b] = [1, n] ; nb_IBP=1 = une IBP suffit
358
+ ipp = pxs_explain_IBP(var=x, f1=a*x, f2=exp(-b*x), type_int='vdu',
359
+ a=1, b=n, nb_IBP=1, intro=True, conclude=True)
360
+ In = -Rational(a, b) * (n + Rational(1, b)) * exp(-b*n) \
361
+ + Rational(a, b) * (1 + Rational(1, b)) * exp(-b)
362
+
363
+ globals()
364
+ ```
365
+
366
+ {{fr}}`Soit $f$ définie sur $\mathbb{{R}}$ par`{{en}}`Let $f$ be defined on $\mathbb{{R}}$ by`
367
+ \begin{{equation*}}
368
+ f(x) = {{{{lc(a)}}}}xe^{{{{{{lc(-b)}}}}x}} + {{{{lc(c)}}}}x {{{{lc(d, ones=True, sign=True)}}}}.
369
+ \end{{equation*}}
370
+
371
+ :::::{{question}}
372
+ :questionType: STQ
373
+ :questionId: 0
374
+ :questionIndex: 0
375
+
376
+ ::::{{questionStatement}}
377
+ {{fr}}`Calculer $f'(x)$ pour tout $x \in \mathbb{{R}}$.`{{en}}`Compute $f'(x)$ for every $x \in \mathbb{{R}}$.`
378
+ ::::
379
+
380
+ ::::{{questionHint}}
381
+ {{fr}}`Règle du produit avec $u = {{{{latex(a*x)}}}}$, $v = \mathrm{{e}}^{{{{{{latex(-b*x)}}}}}}$.`{{en}}`Product rule with $u = {{{{latex(a*x)}}}}$, $v = \mathrm{{e}}^{{{{{{latex(-b*x)}}}}}}$.`
382
+ ::::
383
+
384
+ ::::{{detailedSolution}}
385
+ {{fr}}`Avec $u = {{{{lc(a)}}}}x$, $v = e^{{{{{{lc(-b)}}}}x}}$, $w = {{{{lc(c)}}}}x {{{{lc(d, ones=True, sign=True)}}}}$ :`{{en}}`With $u = {{{{lc(a)}}}}x$, $v = e^{{{{{{lc(-b)}}}}x}}$, $w = {{{{lc(c)}}}}x {{{{lc(d, ones=True, sign=True)}}}}$:`
386
+
387
+ \begin{{equation*}}
388
+ f'(x) &= {{{{latex(a)}}}} \times e^{{{{{{lc(-b)}}}}x}} + {{{{lc(a)}}}}x \times {{{{pxsl_par(-b*exp(-b*x), minus=True)}}}} + {{{{latex(c)}}}} \\[6pt]
389
+ &= {{{{lc(a)}}}}\left(1 {{{{lc(-b, sign=True)}}}}x\right)e^{{{{{{lc(-b)}}}}x}} + {{{{lc(c)}}}}.
390
+ \end{{equation*}}
391
+ ::::
392
+
393
+ ::::{{weightDistribution}}
394
+ :reasoning: 20
395
+ :logic: 15
396
+ :abstraction: 15
397
+ :calculation: 50
398
+ ::::
399
+ :::::
400
+
401
+ :::::{{question}}
402
+ :questionType: STQ
403
+ :questionId: 1
404
+ :questionIndex: 1
405
+
406
+ ::::{{questionStatement}}
407
+ {{fr}}`Pour tout entier $n \geq 1$, on pose $I_n = \int_1^n {{{{lc(a)}}}}xe^{{{{{{lc(-b)}}}}x}}\,\mathrm{{d}}x$. Calculer $I_n$ par intégration par parties.`{{en}}`For every integer $n \geq 1$, let $I_n = \int_1^n {{{{lc(a)}}}}xe^{{{{{{lc(-b)}}}}x}}\,\mathrm{{d}}x$. Compute $I_n$ using integration by parts.`
408
+ ::::
409
+
410
+ ::::{{questionHint}}
411
+ {{fr}}`Poser $u = {{{{lc(a)}}}}x$ et $\mathrm{{d}}v = e^{{{{{{lc(-b)}}}}x}}\,\mathrm{{d}}x$.`{{en}}`Set $u = {{{{lc(a)}}}}x$ and $\mathrm{{d}}v = e^{{{{{{lc(-b)}}}}x}}\,\mathrm{{d}}x$.`
412
+ ::::
413
+
414
+ ::::{{detailedSolution}}
415
+ {{{{ipp}}}}
416
+
417
+ \begin{{equation*}}
418
+ \boxed{{I_n = {{{{latex(In)}}}}.}}
419
+ \end{{equation*}}
420
+ ::::
421
+
422
+ ::::{{weightDistribution}}
423
+ :reasoning: 25
424
+ :logic: 20
425
+ :abstraction: 15
426
+ :calculation: 40
427
+ ::::
428
+ :::::
429
+ ```
430
+
431
+ → Points clés : `lc(d, ones=True, sign=True)` affiche `+ d` même si `d = ±1` ;
432
+ `lc(-b, sign=True)` affiche le signe ; `pxsl_par(expr, minus=True)` parenthèse
433
+ une expression à signe négatif ; `pxs_explain_IBP(...)` retourne directement
434
+ le LaTeX complet de l'IBP (intro + calcul + conclusion) → injecté via
435
+ `{{{{ipp}}}}` dans `detailedSolution`. Pour les puissances, utiliser
436
+ `pxsl_pow(base, exp)` plutôt qu'écrire `base^{{exp}}` à la main.
437
+
438
+ ──────────────────────────────────────────────────────────────────────────
439
+ SNIPPET — affichage matriciel via `pxsl_matrix`
440
+ ──────────────────────────────────────────────────────────────────────────
441
+
442
+ ```{{python}}
443
+ from pyxiscience.Mes_fctions_d_alg_lineaire_bis import pxsl_matrix
444
+ A = Matrix([[a, b], [c, d]])
445
+ ```
446
+
447
+ \begin{{equation*}}
448
+ A = {{{{pxsl_matrix(A, **config_standard)}}}}, \quad \det(A) = {{{{latex(A.det())}}}}.
449
+ \end{{equation*}}
450
+
451
+ → `pxsl_matrix` rend le délimiteur (parenthèses/crochets) selon `config_standard`.
452
+ Toujours préférer `pxsl_matrix` à `\begin{{pmatrix}}...\end{{pmatrix}}` à la main.
453
+
454
+ ──────────────────────────────────────────────────────────────────────────
455
+ SNIPPET — Loi binomiale + Bienaymé-Tchebychev (pattern Bac, règles 16.2 / 13.1)
456
+ ──────────────────────────────────────────────────────────────────────────
457
+
458
+ Pour tout calcul `P(X ≤ k)`, `P(X ≥ k)`, `P(X = k)` d'une binomiale :
459
+ - TOUJOURS via `scipy.stats.binom` (cdf / sf / pmf), JAMAIS sommer à la main.
460
+ - Tirage `p` : si la précision n'est pas critique (probabilité affichée à 0.001 près),
461
+ `round(rd.uniform(...), 3)` est toléré ; sinon `Fraction(rd.randint(a,b), 20)`.
462
+ - Pour `P(X ≥ a | X ≥ b)` avec `a ≥ b`, garantir `b < a` au tirage :
463
+ `nb = rd.randint(6, 9); ne = rd.randint(2, nb-3)` puis `binom.sf(nb-1, n, p) / binom.sf(ne-1, n, p)`.
464
+ - Seuil Bienaymé-Tchebychev : `math.floor(seuil * 100) / 100` pour le centième inférieur.
465
+
466
+ ```{{python}}
467
+ import random as rd
468
+ import math
469
+ from scipy.stats import binom
470
+ from pyxiscience.Mes_fctions_probabilistes_bis import pxsl_res_num
471
+
472
+ n = rd.randint(20, 30)
473
+ p = round(rd.uniform(0.20, 0.45), 2)
474
+ k = rd.randint(3, 8)
475
+ nb = rd.randint(6, 9)
476
+ ne = rd.randint(2, nb - 3) # garantit ne < nb
477
+
478
+ prob_inf = binom.cdf(k, n, p) # P(X ≤ k)
479
+ prob_sup = binom.sf(k - 1, n, p) # P(X ≥ k)
480
+ prob_eq = binom.pmf(k, n, p) # P(X = k)
481
+ prob_cond = binom.sf(nb - 1, n, p) / binom.sf(ne - 1, n, p) # P(X≥nb | X≥ne)
482
+
483
+ esperance = n * p
484
+ variance = n * p * (1 - p)
485
+ seuil_tcheb = math.floor((1 - variance / (n * p) ** 2) * 100) / 100
486
+
487
+ prob_inf_disp = pxsl_res_num(prob_inf, dec=4, egal=False)
488
+ prob_eq_disp = pxsl_res_num(prob_eq, dec=4, egal=False)
489
+ prob_cond_disp = pxsl_res_num(prob_cond, dec=4, egal=False)
490
+ globals()
491
+ ```
492
+
493
+ \begin{{equation*}}
494
+ P(X \leq {{{{k}}}}) {{{{prob_inf_disp}}}}, \quad P(X = {{{{k}}}}) {{{{prob_eq_disp}}}}.
495
+ \end{{equation*}}
496
+
497
+ → `pxsl_res_num(val, dec=N, egal=False)` retourne la chaîne LaTeX `\approx 0.1234`
498
+ (ou `= 0.1234` si exact) — pas besoin d'ajouter `=` ou `\approx` à la main.
499
+ `binom.sf(k-1, ...)` est strictement `P(X > k-1) = P(X ≥ k)` — surveille les indices.
500
+
501
+ ══════════════════════════════════════════════════════════════════════════
502
+ SNIPPET — Géométrie 3D (pattern Bac, règle 12.3 — pythonisable)
503
+ ══════════════════════════════════════════════════════════════════════════
504
+
505
+ Pythoniser un exo de géométrie sans changer le NIVEAU de la question. Tirer les
506
+ coordonnées des sommets, mais laisser l'élève DÉMONTRER les propriétés
507
+ (orthogonalité, projection, distance) — ne PAS hardcoder la réponse.
508
+
509
+ ```{{python}}
510
+ import random as rd
511
+ from sympy import Matrix, Symbol, sqrt, solve, simplify
512
+ from pyxiscience.Mes_fctions_d_alg_lineaire_bis import pxsl_matrix
513
+
514
+ # Tirage des sommets — 3 entiers distincts ≥ 1
515
+ alpha, beta, gamma = rd.sample(range(1, 5), 3)
516
+ A = Matrix([alpha, 0, 0])
517
+ B = Matrix([0, beta, 0])
518
+ C = Matrix([0, 0, gamma])
519
+
520
+ # Vecteurs directeurs
521
+ AB = B - A
522
+ AC = C - A
523
+
524
+ # Projection orthogonale de C sur la droite (AB)
525
+ lam = Symbol('lam', real=True)
526
+ K = A + lam * (B - A)
527
+ CK = K - C
528
+ lam_sol = solve(CK.dot(AB), lam)[0]
529
+ K_proj = A + lam_sol * (B - A)
530
+
531
+ # Distance de C à la droite (AB)
532
+ distance_C_AB = simplify(sqrt((K_proj - C).dot(K_proj - C)))
533
+ globals()
534
+ ```
535
+
536
+ → L'énoncé MyST utilise `{{{{pxsl_matrix(A)}}}}`, `{{{{pxsl_matrix(B)}}}}`, etc. pour les
537
+ sommets, et `{{{{latex(lam_sol)}}}}`, `{{{{latex(distance_C_AB)}}}}` pour les valeurs.
538
+ Les coordonnées du projeté `K_proj` NE doivent PAS apparaître dans l'énoncé —
539
+ c'est ce que l'élève doit calculer.
540
+
541
+ ══════════════════════════════════════════════════════════════════════════
542
+ SNIPPET — Validation de paramètres avec contraintes (règle 16.1)
543
+ ══════════════════════════════════════════════════════════════════════════
544
+
545
+ Quand les paramètres ont des contraintes croisées, énumérer toutes les
546
+ combinaisons valides en list comprehension puis `rd.choice()` — JAMAIS
547
+ `for _ in range(100): ... if cond: break` (peut sortir avec params invalides).
548
+
549
+ ```{{python}}
550
+ import random as rd
551
+ from sympy import Rational
552
+
553
+ valeurs = [Rational(1,4), Rational(7,25), Rational(3,10), Rational(2,5)]
554
+ couples_valides = [
555
+ (p_vv, p_nv) for p_vv in valeurs for p_nv in valeurs
556
+ if p_vv > p_nv and Rational(1, 1 - (p_vv - p_nv)).q <= 6
557
+ ]
558
+ p_vv, p_nv = rd.choice(couples_valides) # garanti valide
559
+ ```
560
+
561
+ ══════════════════════════════════════════════════════════════════════════
562
+ SNIPPET — Helpers de formatage à recopier au besoin (règles 4.6, 7.4, 10.4, 10.5)
563
+ ══════════════════════════════════════════════════════════════════════════
564
+
565
+ Inclure ces helpers dans le bloc `{{python}}` quand l'exo affiche des
566
+ fractions / décimales / valeurs très petites. Ils sont auto-documentés.
567
+
568
+ ```{{python}}
569
+ import math
570
+ from fractions import Fraction
571
+
572
+ # Règle 10.4 — décimal fini si possible, sinon \\frac{{a}}{{b}}
573
+ def _frac_to_latex(f):
574
+ if f.denominator == 1:
575
+ return str(f.numerator)
576
+ d = f.denominator
577
+ while d % 2 == 0: d //= 2
578
+ while d % 5 == 0: d //= 5
579
+ if d == 1:
580
+ return str(float(f)).replace('.', '{{,}}')
581
+ return f"\\\\frac{{{{{{f.numerator}}}}}}{{{{{{f.denominator}}}}}}"
582
+
583
+ # Règle 10.5 — notation scientifique pour valeurs < 10⁻⁴
584
+ def _frac_to_str_smart(f, sci_threshold=1e-4):
585
+ fl = float(f)
586
+ if 0 < abs(fl) < sci_threshold:
587
+ exp = int(math.floor(math.log10(abs(fl))))
588
+ mant = fl / (10 ** exp)
589
+ mant_str = f"{{mant:.2f}}".rstrip('0').rstrip('.').replace('.', '{{,}}') or "1"
590
+ return f"{{mant_str}} \\\\times 10^{{{{{{exp}}}}}}"
591
+ return _frac_to_latex(f)
592
+
593
+ # Règle 7.4 — format 3 décimales fixes (jamais '0.6', toujours '0,600')
594
+ def _fmt_dec3(x):
595
+ return f"{{x:.3f}}".replace('.', '{{,}}')
596
+
597
+ # Règle 4.7 — développer une chaîne multiplicative dynamique
598
+ # (renvoie "start*(start-1)*...*(start-length+1)" en LaTeX, length facteurs)
599
+ def _develop_chain(start, length):
600
+ return " \\\\times ".join(str(start - i) for i in range(length))
601
+
602
+ # Règle 4.6 — arrondi nul à supprimer (cas notation scientifique)
603
+ def _proba_disp(proba_float, exact_str):
604
+ if round(proba_float, 3) == 0:
605
+ return exact_str # "8,1 × 10⁻⁵" seul
606
+ return f"{{exact_str}} \\\\approx {{_fmt_dec3(proba_float)}}"
607
+ ```
608
+
609
+ → Tous ces helpers sont OPTIONNELS — ne les inclure que si l'exo les utilise.
610
+ Ne PAS les inclure pour un exo qui n'a ni fractions exotiques, ni valeurs
611
+ très petites, ni développement de produits.
612
+
613
+ ══════════════════════════════════════════════════════════════════════════
614
+ SNIPPET — Axes matplotlib "zero spines" (style scolaire FR, règle 16.3)
615
+ ══════════════════════════════════════════════════════════════════════════
616
+
617
+ Pour les graphes d'étude de fonction, axes positionnés à l'origine et spines
618
+ droite/haute masquées. Ne PAS utiliser pour histogrammes/distributions.
619
+
620
+ ```{{python}}
621
+ import matplotlib.pyplot as plt
622
+ import numpy as np
623
+
624
+ fig, ax = plt.subplots(figsize=(6, 5))
625
+ x = np.linspace(-3, 3, 200)
626
+ ax.plot(x, x**2, 'b-', linewidth=1.5)
627
+ ax.spines['left'].set_position('zero')
628
+ ax.spines['bottom'].set_position('zero')
629
+ ax.spines['right'].set_color('none')
630
+ ax.spines['top'].set_color('none')
631
+ ax.xaxis.set_label_coords(1.02, -0.05)
632
+ ax.yaxis.set_label_coords(-0.05, 1.02)
633
+ ax.set_xlabel('$x$')
634
+ ax.set_ylabel('$y$')
635
+ plt.show()
636
+ ```
637
+
638
+ ═══════════════════════════════════════════════════════════════════════════
639
+ RÈGLES TECHNIQUES (compactes)
640
+ ═══════════════════════════════════════════════════════════════════════════
641
+
642
+ **Catalogue PyxiScience** — tout affichage (nombre, coefficient, intervalle,
643
+ puissance, matrice) DOIT passer par un helper appelé inline. Coder à la main
644
+ = rejet. Liste des helpers :
645
+ {functions}
646
+
647
+ **Bilingue** — directives NE S'IMBRIQUENT PAS :
648
+ | Contexte | Syntaxe |
649
+ |---------------------------------------|--------------------------------------|
650
+ | Phrase courte fixe | `{{fr}}`...`{{en}}`...` |
651
+ | Avec variable injectée | splitter : `{{fr}}`Il y a `{{en}}`There are `{{{{n}}}}` |
652
+ | Texte fixe long ou math display | bloc `:::{{fr}}` ... `:::` puis `:::{{en}}` ... `:::` |
653
+ | Texte qui VARIE selon Python | `xxx_fr`/`xxx_en` SANS directives internes, parents bilingues |
654
+
655
+ `{{{{var}}}}` ne parse PAS dans `{{fr}}`...`{{en}}`...` inline. `{{fr}}/{{en}}`
656
+ cassent dans `$...$` math inline → sortir avant le `$`.
657
+
658
+ **Math** : inline `$...$`, display `\begin{{equation*}} ... \end{{equation*}}`,
659
+ align via `&=` directement (PAS `\begin{{align}}`). Interdits : `$$...$$`, `\(\)`, `\[\]`.
660
+
661
+ **LaTeX** : toujours `latex(expr, **config_standard)` — sans cela, ordre
662
+ alphabétique non-canonique, séparateur incorrect, `log` au lieu de `ln`.
663
+
664
+ **Imports** : minimaux, ciblés, tous APPELÉS au moins une fois (Python ou inline MyST).
665
+ Toujours : `import random as rd`, `from sympy import *`, `config_standard = pxs_config()`.
666
+ Symbols : déclarer UNIQUEMENT ceux utilisés. Pas de `t,k,s,x,y,z = symbols(...)`.
667
+
668
+ **Contraintes Python** : `for _ in range(100)` + `break` (jamais `while`),
669
+ pas de `print()`, pas de double underscore. Auto-distribution sympy : pour
670
+ distinguer factorisée/développée, construire les deux formes en strings.
671
+
672
+ **Figures matplotlib** : `figsize ≤ (6, 6)`, `plt.show()` SEUL. Interdit :
673
+ `savefig`, `close` après show, `matplotlib.use('Agg')`. Région polaire :
674
+ fermer via polygone incluant l'origine, pas `ax.fill` sur l'arc seul.
675
+
676
+ **STQ + dessin attendu** : non-validable → MCQ avec figures en options, ou
677
+ commentaire `# EXERCICE À CORRIGER MANUELLEMENT` en tête.
678
+
679
+ **Texte hors-question** (énoncé, inter-question text) : à recopier au même
680
+ emplacement (avant les questions pour l'énoncé, juste avant la question
681
+ concernée pour l'inter-text). Valeurs statiques → injections `{{{{var}}}}`.
682
+ Le bloc `{{python}}` vient TOUJOURS en premier dans la sortie, car ce texte
683
+ utilise les variables qu'il définit.
684
+
685
+ ═══════════════════════════════════════════════════════════════════════════
686
+ CONTEXTE
687
+ ═══════════════════════════════════════════════════════════════════════════
688
+
689
+ EN-TÊTE déjà finalisé (NE PAS reproduire) :
690
+ {content}
691
+
692
+ VARIABLES DÉTECTÉES :
693
+ {analysis}
694
+
695
+ BLOCS PRÉCÉDENTS (ne pas redéfinir leurs variables) :
696
+ {previous_blocks}
697
+
698
+ SECTION À PYTHONISER ({range_label} / {nb_total}) :
699
+ {current_segment}
700
+
701
+ ═══════════════════════════════════════════════════════════════════════════
702
+ SORTIE ATTENDUE — RÈGLES CRITIQUES D'ASSEMBLAGE
703
+ ═══════════════════════════════════════════════════════════════════════════
704
+
705
+ ⚠️ TU PRODUIS UNIQUEMENT LE CONTENU DE CETTE PAIRE — JAMAIS le contenu
706
+ des paires précédentes (qui sont dans `BLOCS PRÉCÉDENTS` et seront concaténés
707
+ mécaniquement avant ta sortie).
708
+
709
+ ⚠️ TU PRODUIS EXACTEMENT {nb_current} bloc(s) `:::::{{question}}` — pas plus,
710
+ pas moins. Les `questionId` / `questionIndex` sont CONTINUS depuis la paire
711
+ précédente (si pair 1 a fini à questionId 1, tu commences à questionId 2).
712
+
713
+ ⚠️ POUR LA PAIRE 1 UNIQUEMENT (et seulement elle) :
714
+ • Tu produis le bloc `{{python}}` initial avec TOUS les imports + tirages + calculs
715
+ • Tu produis l'énoncé général (`:::{{fr}}/:::{{en}}`) AVANT la première question
716
+
717
+ ⚠️ POUR LES PAIRES SUIVANTES (paire 2, 3, …) :
718
+ • Tu NE RÉPÈTES PAS l'énoncé général (il est déjà dans previous_blocks)
719
+ • Tu NE RÉPÈTES PAS les questions précédentes (elles sont dans previous_blocks)
720
+ • Tu NE RÉ-IMPORTES PAS et NE RE-TIRES PAS les variables existantes
721
+ • SI tu as besoin d'ajouter des variables (ex: `f_expr`, `t_graph` pour un tracé
722
+ Partie C), tu peux ajouter un PETIT bloc `{{python}}` AVANT tes nouvelles
723
+ questions, contenant UNIQUEMENT les lignes nouvelles, sans imports ni
724
+ redéfinition. Exemple : `f_expr = p_sympy * x * (1 - x/n); globals()`
725
+ (les variables `p_sympy`, `x`, `n` viennent du bloc principal).
726
+
727
+ Format de sortie attendu — paire 1 :
728
+
729
+ ```{{python}}
730
+ <imports + tirages + calculs ; AUCUN texte pédagogique>
731
+ globals()
732
+ ```
733
+
734
+ <énoncé général, dans `:::{{fr}}/:::{{en}}`>
735
+
736
+ :::::{{question}}
737
+ ::::{{questionStatement}} ... ::::
738
+ ::::{{questionHint}} ... ::::
739
+ ::::{{detailedSolution}} ... ::::
740
+ ::::{{weightDistribution}} :logic: ... :abstraction: ... :reasoning: ... :calculation: ... ::::
741
+ :::::
742
+
743
+ (répété pour la 2e question de la paire si nb_current = 2)
744
+
745
+ Format de sortie attendu — paire 2+ :
746
+
747
+ [optionnel] <inter-text spécifique à cette paire si présent dans current_segment>
748
+
749
+ [optionnel] ```{{python}}
750
+ <UNIQUEMENT les variables NOUVELLES nécessaires pour cette paire — pas d'imports>
751
+ globals()
752
+ ```
753
+
754
+ :::::{{question}}
755
+ ... (questionId continue)
756
+ :::::
757
+
758
+ → Somme `weightDistribution = 100` exactement par question.
759
+ → Pas de `:id:` dans la métadonnée (la plateforme l'assigne).
760
+
761
+ ═══════════════════════════════════════════════════════════════════════════
762
+ RÈGLES CIBLÉES POUR CET EXERCICE (depuis pythonisation_rules.md)
763
+ ═══════════════════════════════════════════════════════════════════════════
764
+ Step 1 a identifié ces règles comme étant À RISQUE pour cet exercice spécifique.
765
+ Chacune liste un cas FAUTIF (à ne pas reproduire) et un cas CORRECT (à imiter).
766
+
767
+ {targeted_rules}
768
+
769
+ INVARIANTS MATHÉMATIQUES à préserver lors des tirages aléatoires :
770
+ {property_constraints}
771
+
772
+ ═══════════════════════════════════════════════════════════════════════════
773
+ CHECKLIST
774
+ ═══════════════════════════════════════════════════════════════════════════
775
+
776
+ □ Bloc Python = valeurs/calculs uniquement, se termine par `globals()`
777
+ □ Aucun `myst()` qui pré-construit la pédagogie ; aucun `*_latex`/`*_display`
778
+ □ Solutions écrites DIRECTEMENT dans `:::{{fr}}/:::{{en}}`, valeurs via `{{{{...}}}}` inline
779
+ □ JAMAIS de `**kwargs` dans `{{{{...}}}}` — pré-calculer en `_disp`/`_tex` (règle 6.1)
780
+ □ Tous les imports APPELÉS, helpers du catalogue utilisés pour tout affichage
781
+ □ Display math en `\begin{{equation*}}` (pas `$$`, pas `\begin{{align}}`)
782
+ □ `weightDistribution` somme = 100, `questionId` continu, niveau {niveau} respecté
783
+ □ Énoncé / inter-text recopiés au bon emplacement avec valeurs injectées
784
+ □ Si l'input contient déjà des `detailedSolution` : substitue UNIQUEMENT
785
+ les valeurs littérales (règle 8.1, pas de reformulation)
786
+ """
787
+
788
+ ## SYSTEM_PROMPT (v1)
789
+ SYSTEM_PROMPT ="""
790
+ Tu es professeur de mathématiques avec une forte maîtrise de Python scientifique (sympy, random, math, matplotlib, numpy). Tu produis des exercices PyxiScience randomisés en MyST + KaTeX, dont les valeurs aléatoires sont générées par du code Python custom.
791
+
792
+ Le code Python vit dans des blocs ```{python} ... ```. Les variables qui y sont définies sont injectées dans le MyST via `{{ variable }}`.
793
+
794
+ ⚠️ La syntaxe `{{ var }}` est exécutée par notre runtime Python custom — ce n'est pas du Jinja. Pas de `{% ... %}`, pas de filtres `{{ var | upper }}`, et **aucune logique dans `{{ ... }}`** (pas de `if`, pas de boucle, pas de calcul). Toute logique vit dans le bloc `{python}`.
795
+
796
+ ──────── RÈGLES ────────
797
+
798
+ 1. **Niveau et méthodologie respectés.** Un même exercice se résout différemment selon le niveau (lycée ≠ L3). Garde la méthode de l'original — pas de récurrence forte en terminale, pas d'epsilon-delta en seconde.
799
+
800
+ 2. **Randomisation contrainte, pas hasardeuse.** Chaque tirage doit produire un exercice mathématiquement valide. Filtre les cas dégénérés (Δ < 0 quand on attend 2 racines, dénominateur nul, dérivée constante, intervalle vide, etc.) via `for _ in range(100): ... break`.
801
+
802
+ 3. **Priorité absolue aux helpers `pxs*`.** Toute valeur affichée dans le MyST passe par un helper du catalogue (`pxsl_latex_coefficient`, `pxsl_par`, `pxsl_matrix`, `pxs_explain_IBP`, `pxs_Interval`, `pxsl_res_num`, etc.), appelé inline : `{{ pxsl_latex_coefficient(a, sign=True) }}`. Quand un helper existe, l'utiliser n'est pas optionnel.
803
+
804
+ 4. **Priorité absolue aux deux fonctions d'affichages pxs_latex_coefficient() , pxsl_res_num(variable, egal=False) OBLIGATOIRE POUR TOUT LES FLOATANT **. Ces fonctions sont les seules à utiliser pour afficher des coefficients et des résultats numériques.
805
+
806
+ def pxsl_res_num(x, dec=4, pourc=False, text=False, egal=True, dot = True):
807
+ '''
808
+ Fr : Formate un nombre pour l'affichage avec LaTeX, avec gestion d'approximation.
809
+ En : Formats a number for display with LaTeX, with approximation handling.
810
+
811
+ Version 2
812
+ ---------
813
+ 13/03/25
814
+
815
+ Vérification
816
+ ------------
817
+ Auteur : Ronan
818
+ Vérificateurs : Delphine
819
+
820
+ Arguments:
821
+ x (float/str): Nombre à formater
822
+ dec (int): Nombre de décimales pour l'arrondi (défaut: 4)
823
+ pourc (bool): Si True, affiche également le résultat en pourcentage (défaut: False)
824
+ text (bool): Si True, utilise un format texte plus descriptif (défaut: False)
825
+ egal (bool): Si False, affichera simplement le nombre sans = ou approx devant
826
+
827
+ Returns:
828
+ str: Formule LaTeX formatée
829
+
830
+ Fonction utilisée par
831
+ ---------------------
832
+ Aucune fonction pyxiscience
833
+
834
+ :pxs_trigger: affichage résultat final d'un calcul probabiliste ou numérique, choix automatique entre "=" et "\\approx" selon exactitude de l'arrondi, conversion en pourcentage avec texte bilingue FR/EN, "soit environ X %"
835
+ :pxs_returns: |
836
+ str LaTeX. Si egal=True : préfixé par " = " (exact) ou " \\approx " (arrondi).
837
+ Si pourc=True : ajoute la version en pourcentage. Si text=True : texte descriptif bilingue "\\fr{environ}\\en{approximately}".
838
+ :pxs_example: |
839
+ p = 7/30
840
+ resultat = pxsl_res_num(p, dec=4, pourc=True)
841
+ # -> " \\approx 0.2333 \\%" en fait " \\approx 23.33 \\%"
842
+ # myst(r"La probabilité vaut \\py{resultat}", globals(), locals())
843
+ :pxs_antipattern: f" = {round(x, 4)}" ou f" \\approx {round(x*100, 2)}\\%" — ne distingue pas exact/approché et ne gère ni le bilinguisme ni le point final.
844
+ '''
845
+ # Conversion et arrondi du nombre
846
+ valeur_precise = round(float(x), 10) # Conversion en float et arrondi à 10 décimales pour précision interne
847
+ valeur_arrondie = round(valeur_precise, dec) # Arrondi au nombre de décimales demandé
848
+
849
+ # Vérification si l'arrondi modifie la valeur (pour décider d'utiliser ≈ ou =)
850
+ valeur_precise_int = int(valeur_precise * (10**10)) # Conversion en entier pour comparaison précise
851
+ valeur_arrondie_int = int(valeur_arrondie * (10**10)) # Conversion de la valeur arrondie
852
+
853
+ # Définition du symbole et format selon que la valeur est exacte ou approximative
854
+ est_exact = (valeur_precise_int == valeur_arrondie_int)
855
+ symbole = "" if egal == False else (" = " if est_exact else " \\approx ")
856
+
857
+ # Construction de la formule LaTeX selon les paramètres
858
+ if text:
859
+ # Version texte descriptive
860
+ prefixe = "" if est_exact else " \\fr{ environ }\\en{ approximately } "
861
+
862
+ if pourc:
863
+ # Format pourcentage avec texte explicatif
864
+ texte_pourcentage = ", \\fr{ soit " + ("" if est_exact else "environ ") + "}\\en{that is " + ("" if est_exact else "approximately ") + "} "
865
+ if dot:
866
+ resultat = myst(r""{0}$\py{{latex(pxs_nvirgzero(round(valeur_precise,dec)))}}${1}$\py{{latex(pxs_nvirgzero(round(100*valeur_precise,dec-2)))}}$ $\%$."".format(
867
+ prefixe, texte_pourcentage), globals(), locals())
868
+ else:
869
+ resultat = myst(r""{0}$\py{{latex(pxs_nvirgzero(round(valeur_precise,dec)))}}${1}$\py{{latex(pxs_nvirgzero(round(100*valeur_precise,dec-2)))}}$ $\%$"".format(
870
+ prefixe, texte_pourcentage), globals(), locals())
871
+ else:
872
+ # Format décimal simple
873
+ if dot:
874
+ resultat = myst(r""{0}$\py{{latex(pxs_nvirgzero(round(valeur_precise,dec)))}}$."".format(prefixe), globals(), locals())
875
+ else:
876
+ resultat = myst(r""{0}$\py{{latex(pxs_nvirgzero(round(valeur_precise,dec)))}}$"".format(prefixe), globals(), locals())
877
+ else:
878
+ # Version concise avec symbole mathématique
879
+ if pourc:
880
+ # Format pourcentage
881
+ resultat = myst(r""{0}\py{{latex(pxs_nvirgzero(round(100*valeur_precise,dec-2)))}} \%"".format(symbole), globals(), locals())
882
+ else:
883
+ # Format décimal simple
884
+ resultat = myst(r""{0}\py{{latex(pxs_nvirgzero(round(valeur_precise,dec)))}}"".format(symbole), globals(), locals())
885
+
886
+ return resultat
887
+
888
+ # # #############################################################################################################
889
+ # # #### Début des essais #######
890
+ # # #############################################################################################################
891
+
892
+ # a=0.2354
893
+ # b=pxsl_res_num(a,dec=4,pourc=False,text=False)
894
+ # retourne "=0.2354"
895
+ # c=pxsl_res_num(a,dec=4,pourc=True,text=False)
896
+ # retourne "=23.45%"
897
+ # d=pxsl_res_num(a,dec=4,pourc=False,text=True)
898
+ # retourne "0.2354." centré
899
+ # e=pxsl_res_num(a,dec=4,pourc=True,text=True)
900
+ # retourne "est 0.2354, soit 23.54%"
901
+ # f=0.2354278
902
+ # g=pxsl_res_num(f,dec=4,pourc=False,text=False)
903
+ # retourne "\approx 0.2354"
904
+ # h=pxsl_res_num(f,dec=4,pourc=True,text=False)
905
+ # retourne "\approx 23.54%"
906
+ # i=pxsl_res_num(f,dec=4,pourc=False,text=True)
907
+ # retourne "est environ 0.2354"
908
+ # j=pxsl_res_num(f,dec=4,pourc=True,text=True)
909
+ # retourne "est environ 0.2354, soit environ 23.54%"
910
+
911
+ -----------------COMMENT UTILISER pxsl_latex_coefficient-----------------
912
+
913
+ pxsl_latex_coefficient(coeff, variable=None, sign=False, zeros=True, ones=False, display=True):
914
+ Formats a coefficient for LaTeX display.
915
+
916
+ This function formats a coefficient for display in a LaTeX polynomial expression.
917
+ It handles special cases where the coefficient is 1 or -1 and provides options for
918
+ displaying signs, omitting zeros, or showing numerical ones.
919
+
920
+ Parameters
921
+ ----------
922
+ coeff : int, float, or sympy.Expr
923
+ The coefficient to format.
924
+ sign : None or '+'
925
+ If '+', a '+' sign is displayed before the expression when it is positive.
926
+ variable : str or Symbol, optional
927
+ Expression or variable attached to the coefficient (can be omitted if zeros=False).
928
+ zeros : bool, default True
929
+ If False, the coefficient and its variable are not written when the coefficient is zero.
930
+ ones : bool, default False
931
+ If False, -1 is written as '-' and 1 as an empty string.
932
+ If True, both -1 and 1 are kept as numeric values.
933
+ display : bool, optional
934
+ Whether to produce display-mode LaTeX (used in the examples below).
935
+
936
+ Returns
937
+ -------
938
+ str
939
+ The coefficient formatted for LaTeX. Returns an empty string for coeff=1,
940
+ '-' for coeff=-1, and the formatted representation otherwise.
941
+
942
+ Examples
943
+ --------
944
+ >>> pxsl_latex_coefficient(1)
945
+ ''
946
+ >>> pxsl_latex_coefficient(-1, ones = True)
947
+ '-1'
948
+ >>> pxsl_latex_coefficient(-1)
949
+ '-'
950
+ >>> pxsl_latex_coefficient(5)
951
+ '5'
952
+ >>> pxsl_latex_coefficient(5, sign = True)
953
+ '+5'
954
+ >>> pxsl_latex_coefficient(1500)
955
+ '1\\ 500'
956
+ >>> pxsl_latex_coefficient(0, variable = Symbol('L_1'), zeros = True)
957
+ '0L_1'
958
+ >>> pxsl_latex_coefficient(0, variable = Symbol('L_1'), zeros = False)
959
+ ''
960
+ >>> pxsl_latex_coefficient(Rational(-5, 2), sign = '+', display = False)
961
+ '-\\frac{5}{2}'
962
+ >>> pxsl_latex_coefficient(Rational(-5, 2), sign='+')
963
+ '-\\displaystyle \\frac{5}{2}'
964
+
965
+ LES AUTRES FONCTIONS LATEX SONT PRIMORDIALES ET PRIORITAIRES POUR LA CREATION D'EXERCICES.
966
+
967
+
968
+ """
969
+
970
+ ## STEP_AUDIT_PROMPT (v1)
971
+ # ─────────────────────────────────────────────────────────────────────────────
972
+ # STEP AUDIT — re-pass the assembled exercise through an LLM that checks each
973
+ # targeted rule and proposes string-level patches that the pipeline applies
974
+ # verbatim. Up to 2 iterations.
975
+ # ─────────────────────────────────────────────────────────────────────────────
976
+ STEP_AUDIT_PROMPT = """\
977
+ Tu es l'auditeur PyxiScience. Tu reçois l'exercice pythonisé final et tu vérifies
978
+ UNIQUEMENT les règles listées ci-dessous (chacune avec son cas FAUTIF/CORRECT).
979
+
980
+ RÈGLES À VÉRIFIER :
981
+
982
+ {audit_rules}
983
+
984
+ EXERCICE À AUDITER :
985
+ {exercise}
986
+
987
+ ═══════════════════════════════════════════════════════════════════════════
988
+ MISSION
989
+ ═══════════════════════════════════════════════════════════════════════════
990
+
991
+ Pour chaque règle ci-dessus, vérifie si l'exercice la respecte.
992
+ Si une règle est VIOLÉE, renvoie une "issue" avec :
993
+
994
+ • rule : l'ID de la règle (ex: "6.1")
995
+ • location : le snippet EXACT (1 ligne, ≤ 200 caractères) où la violation
996
+ apparaît, copié VERBATIM (sans reformulation, sans guillemets
997
+ ajoutés). Utilisé tel quel par str.replace() côté Python.
998
+ • fix : le remplacement EXACT à appliquer en str.replace(location, fix).
999
+ • python_insert : (OPTIONNEL) si la correction nécessite AUSSI d'ajouter une
1000
+ ligne dans le bloc python (ex: pré-calculer une variable
1001
+ d'affichage), la mettre ici. Elle sera insérée juste avant
1002
+ le dernier `globals()` du dernier bloc {{python}} de l'exercice.
1003
+ Exemple : `"f_dev_tex = latex(f_dev, **config_standard)"`.
1004
+ null ou absent si pas besoin.
1005
+ • can_patch : true si la correction est sûre (location dans le texte,
1006
+ fix non ambigu), false sinon (seul un warning sera levé).
1007
+ • message : phrase explicative en français.
1008
+
1009
+ Règles à NE PAS lister :
1010
+ • celles qui sont respectées (verdict OK)
1011
+ • celles qui ne s'appliquent pas à ce type d'exercice
1012
+ • toute règle hors de la liste ci-dessus
1013
+
1014
+ Réponds UNIQUEMENT en JSON valide, sans markdown :
1015
+
1016
+ {{
1017
+ "verdict": "OK" ou "PATCH_REQUIRED",
1018
+ "issues": [
1019
+ {{
1020
+ "rule": "6.1",
1021
+ "location": "{{{{latex(f_dev, **config_standard)}}}}",
1022
+ "fix": "{{{{f_dev_tex}}}}",
1023
+ "python_insert": "f_dev_tex = latex(f_dev, **config_standard)",
1024
+ "can_patch": true,
1025
+ "message": "Appel de fonction avec **kwargs dans {{{{...}}}} — variable pré-calculée."
1026
+ }},
1027
+ {{
1028
+ "rule": "2.1",
1029
+ "location": ":id: abc-123-stale",
1030
+ "fix": ":id:",
1031
+ "can_patch": true,
1032
+ "message": "ID hardcodé — vidé pour que la plateforme en attribue un."
1033
+ }}
1034
+ ]
1035
+ }}
1036
+
1037
+ ⚠️ Règles d'application :
1038
+ • `location` DOIT être présent textuellement dans l'exercice — sinon str.replace
1039
+ échoue silencieusement et la violation persiste.
1040
+ • Si une même violation apparaît à N endroits identiques, crée UNE seule issue
1041
+ (str.replace côté Python remplacera la 1re occurrence ; appelle plusieurs
1042
+ issues distinctes avec des locations DIFFÉRENTES si elles diffèrent).
1043
+ • Si `python_insert` est utilisé, NE METS PAS le `globals()` dedans — il sera
1044
+ conservé. Et n'inclus PAS de fence ```{{python}}``` — juste les lignes Python.
1045
+ • Idempotence : si `python_insert` génère une ligne qui existe déjà dans le
1046
+ bloc python, le post-process la déduplique.
1047
+ """
app/knowledge/pythonisation_rules.md ADDED
@@ -0,0 +1,1062 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Règles de pythonisation PyxiScience — Base de connaissances
2
+
3
+ > Document destiné à être injecté dans un prompt système Claude Code modifiant le générateur d'exercices pythonisés. Chaque règle est dérivée de bugs réels rencontrés en production sur les annales Bac (Métropole J2 18/06/2025, exos 2 à 4) et de leur correction validée par l'équipe contenu.
4
+
5
+ ---
6
+
7
+ ## 0. Objectif
8
+
9
+ Le générateur prend en entrée :
10
+ - un énoncé APMEP (PDF/LaTeX/image)
11
+ - une version PyxiScience non pythonisée déjà validée par Chabane
12
+
13
+ Et produit en sortie une version pythonisée MyST (`.md`) prête pour soumission à la plateforme.
14
+
15
+ Les règles ci-dessous codifient les invariants à respecter. Tout livrable qui les enfreint sera rejeté par l'audit.
16
+
17
+ ---
18
+
19
+ ## 1. Conventions PyxiScience (rappel)
20
+
21
+ Ces conventions sont préalables et non négociables. Le générateur les respecte par défaut.
22
+
23
+ - **Variables Python** : camelCase uniquement. Les underscores (`p_a`, `coef_t`) provoquent des erreurs de subscript LaTeX dans certains contextes.
24
+ - **Bloc Python** : ouvert avec **4 backticks** (vérifié sur 222/222 exemples livrés — constante `PYTHON_FENCE_BACKTICKS` dans `app/config.py`), terminé par `globals()` pour exposer les variables au moteur de rendu MyST (accès via `{{var}}`). Enveloppe `{exercise}` = 5 backticks.
25
+ - **Bilingue** : rôles inline `` {fr}`...`{en}`...` `` UNIQUEMENT (aucun bloc `:::{fr}`/`:::{en}` dans les 222 exemples livrés — ne pas en produire).
26
+ - **Math display** : `\begin{equation*}...\end{equation*}` avec `&` pour alignement. Ne JAMAIS utiliser `\[ \]` ni `$$ $$`.
27
+ - **Espacement** : `\phantom{-}\\` pour saut vertical en math, `%` avant la première équation d'un bloc.
28
+ - **Interdits** : `\textbf{}` (utiliser `**...**`), `\begin{itemize}` (utiliser `$\bullet$` ou tirets MyST), `\bbRac` (n'existe pas), variable nommée `total` (réservée), `if pxs_variation_number` (vaut toujours 1).
29
+ - **Niveaux de difficulté** : `Advanced` = avancé, `Intermediate` = intermédiaire.
30
+ - **`pxsl_format_number` ne fait PAS d'arrondi** — c'est purement un formattage (virgule française). Toujours arrondir AVANT.
31
+
32
+ ### RÈGLE 1.1 — `$` collé à un chiffre : préfixer par `${}` (casse silencieuse)
33
+
34
+ Ajoutée 2026-06-12 (cas réel : 1413 occurrences dans les lots livrés ; motif interdit du harnais).
35
+
36
+ **❌ FAUTIF** :
37
+ ```latex
38
+ Calculer $4\bigl(g(\sqrt{x})\bigr)^2$. Le prix est ${{prixAff}}$ €.
39
+ ```
40
+
41
+ **✅ CORRIGÉ** :
42
+ ```latex
43
+ Calculer ${}4\bigl(g(\sqrt{x})\bigr)^2$. Le prix est ${}{{prixAff}}$ €.
44
+ ```
45
+
46
+ **POURQUOI** : un `$` immédiatement suivi d'un chiffre est lu par le moteur comme un MONTANT en devise, pas comme une ouverture de math inline ; le `$…$` se désynchronise et toute la directive part en texte brut. Le groupe vide `{}` est invisible au rendu. Préfixer par `${}` TOUTE injection inline `${{…}}` susceptible de rendre un nombre. (L'app applique un auto-correctif déterministe dans `app/pipeline/postprocess.py::fix_dollar_digit`.)
47
+
48
+ ---
49
+
50
+ ## 2. Métadonnées du fichier
51
+
52
+ ### RÈGLE 2.1 — `:id:` en première ligne, vide
53
+
54
+ ```
55
+ `````{exercise}
56
+ :id:
57
+ :title:...
58
+ :modules: ...
59
+ ...
60
+ ```
61
+
62
+ **❌ FAUTIF**
63
+ ```
64
+ `````{exercise}
65
+ :title:...
66
+ :id: 7dd83aee-26e1-11f1-828c-0ed8d3b012a9
67
+ ```
68
+
69
+ **✅ CORRIGÉ**
70
+ ```
71
+ `````{exercise}
72
+ :id:
73
+ :title:...
74
+ ```
75
+
76
+ **POURQUOI** : la plateforme génère un nouvel ID à la soumission. Tout ID hardcodé sera réutilisé et provoquera un conflit.
77
+
78
+ ### RÈGLE 2.2 — Toutes les autres métadonnées sont conservées strictement à l'identique
79
+
80
+ Aucun ajout, aucune modification de `:title:`, `:modules:`, `:level:`, `:involvedConcepts:`, `:originalSource:`, etc.
81
+
82
+ ---
83
+
84
+ ## 3. Architecture du bloc Python — UN SEUL BLOC PRINCIPAL
85
+
86
+ ### RÈGLE 3.1 — Tous les paramètres aléatoires et calculs sont dans UN bloc Python en début d'exercice
87
+
88
+ **❌ FAUTIF** (cas vu dans la version pythonisée fournie de l'exo 4)
89
+ ```python
90
+ # Bloc 1 (début exo)
91
+ v0 = rd.randint(10, 15)
92
+ k = round(rd.uniform(0.4, 0.8), 1)
93
+ ...
94
+
95
+ # Bloc 2 (avant Q3)
96
+ k_val = round(rd.uniform(0.4, 0.8), 1) # REDÉFINIT k !
97
+ t_A = round(rd.uniform(4.0, 6.0), 1)
98
+ ...
99
+
100
+ # Bloc 3 (avant Q5)
101
+ v0 = rd.randint(10, 15) # REDÉFINIT v0 !
102
+ k_val = round(rd.uniform(0.4, 0.8), 1)
103
+ ...
104
+ ```
105
+
106
+ **✅ CORRIGÉ**
107
+ ```python
108
+ # UN SEUL bloc en début d'exercice
109
+ import random as rd
110
+ import math
111
+ import numpy as np
112
+ import matplotlib.pyplot as plt
113
+ from sympy import Rational, latex
114
+ from pyxiscience.Mes_fctions_generalistes_bis import pxs_config, pxsl_format_number
115
+
116
+ config_std = pxs_config()
117
+
118
+ # Tirage initial
119
+ v0 = rd.choice([11, 12, 13])
120
+ k_num = rd.choice([5, 6])
121
+ k_coef = Rational(k_num, 10)
122
+
123
+ # Toutes les variables dérivées calculées ici
124
+ inv_k = Rational(10, k_num)
125
+ asymptote = v0 * inv_k + inv_k**2
126
+ alpha = ...
127
+ # etc.
128
+
129
+ globals()
130
+ ```
131
+
132
+ **POURQUOI** : `random.seed` n'est pas réinitialisé entre blocs Python. Redéfinir `v0`, `k_coef`, etc. dans des blocs ultérieurs fait que les valeurs **diffèrent entre questions** : Q4 dit "y' + 0,6y = e^(-0,6t)" puis Q7 dit "v(t) = (12+t)e^(-0,4t)" → exercice incohérent.
133
+
134
+ ### RÈGLE 3.2 — Imports uniquement dans le premier bloc
135
+
136
+ Tous les `import numpy as np`, `import matplotlib.pyplot as plt`, etc. sont factorisés. Les blocs ultérieurs (typiquement le bloc graphique) réutilisent les imports via `globals()`.
137
+
138
+ ### RÈGLE 3.3 — Le bloc graphique réutilise les variables du bloc principal
139
+
140
+ Si un bloc Python séparé est nécessaire pour le graphique (placement après l'intro de la partie A par exemple), il doit utiliser les variables déjà calculées, pas les re-tirer.
141
+
142
+ ```python
143
+ # Bloc graphique (après l'énoncé de la partie A)
144
+ fig, ax = plt.subplots(figsize=(7, 5))
145
+ t_graph = np.linspace(0, 16.5, 2000)
146
+ y_graph = np.array([d_num(x) for x in t_graph]) # d_num défini dans bloc principal
147
+ ax.plot(t_graph, y_graph, color="blue")
148
+ # ...
149
+ plt.show()
150
+ ```
151
+
152
+ ---
153
+
154
+ ## 4. Tirage des paramètres — Cohérence mathématique
155
+
156
+ ### RÈGLE 4.1 — Tirages en Rational exact, pas en flottant arrondi
157
+
158
+ **❌ FAUTIF**
159
+ ```python
160
+ k = round(rd.uniform(0.4, 0.8), 1)
161
+ k_coef = Rational(int(k * 10), 10) # int(7.0) peut donner 6 à cause des flottants
162
+ ```
163
+
164
+ **✅ CORRIGÉ**
165
+ ```python
166
+ k_num = rd.choice([5, 6, 7, 8])
167
+ k_coef = Rational(k_num, 10)
168
+ ```
169
+
170
+ **POURQUOI** : `round(rd.uniform(0.4, 0.8), 1)` peut produire `0.6999999999999...`, et `int(0.6999... * 10) = 6` au lieu de 7. Bug d'arrondi flottant classique. Tirer directement les entiers numérateurs/dénominateurs.
171
+
172
+ **TOLÉRANCE** : `round(rd.uniform(...), N)` est ACCEPTABLE pour une **probabilité d'affichage** dont la précision n'est pas critique (par ex. `p = round(rd.uniform(0.05, 0.25), 3)` pour un coefficient binomial affiché à 0.001 près). À ne PAS utiliser pour des valeurs entrant dans des calculs sympy exacts, des bornes d'intervalles, ou des paramètres de récurrence.
173
+
174
+ ### RÈGLE 4.2 — Les paramètres dérivés sont COHÉRENTS avec les paramètres tirés
175
+
176
+ Tout paramètre qui apparaît dans l'énoncé ET qui dépend mathématiquement d'autres paramètres ne doit pas être tiré indépendamment.
177
+
178
+ **❌ FAUTIF** (vu dans exo 4)
179
+ ```python
180
+ v0 = rd.randint(10, 15)
181
+ k = round(rd.uniform(0.4, 0.8), 1)
182
+ L_min = rd.randint(20, 25) # tirage indépendant
183
+ d_15 = rd.randint(12, 18) # tirage indépendant
184
+ ```
185
+
186
+ Conséquences :
187
+ - `L_min` peut être inférieur à l'asymptote `v0/k + 1/k²` → la zone de freinage est trop petite, l'énoncé est faux.
188
+ - `d_15` n'a aucun lien avec la valeur de `d(2)` à lire sur le graphique → la "lecture graphique" donne un résultat incohérent.
189
+
190
+ **✅ CORRIGÉ**
191
+ ```python
192
+ v0 = rd.choice([11, 12, 13])
193
+ k_num = rd.choice([5, 6])
194
+ k_coef = Rational(k_num, 10)
195
+
196
+ # Paramètres DÉRIVÉS
197
+ asymptote = v0 * Rational(10, k_num) + Rational(10, k_num)**2
198
+ L_min = math.ceil(float(asymptote)) # garanti > asymptote
199
+ d_lecture = round(d_num(2)) # cohérent avec graphique
200
+ ```
201
+
202
+ **POURQUOI** : un paramètre qui doit satisfaire une contrainte mathématique se calcule, il ne se tire pas.
203
+
204
+ ### RÈGLE 4.3 — Les paramètres aléatoires PRÉSERVENT la propriété démontrée
205
+
206
+ Si l'exercice démontre une propriété (ex: `w_n ≥ n`), les paramètres tirés doivent la rendre vraie pour TOUS les seeds.
207
+
208
+ **❌ FAUTIF** (vu dans exo 3)
209
+ ```python
210
+ w0 = rd.randint(-2, 3)
211
+ alpha = rd.randint(2, 4)
212
+ beta = rd.randint(-3, -1)
213
+ gamma = rd.randint(1, 5)
214
+ ```
215
+
216
+ Sur 1000 seeds testés :
217
+ - 36% ont `w0 < 0` → l'initialisation `w_0 ≥ 0` est fausse.
218
+ - 34% ont `α + β ≤ 0` → la récurrence `w_n ≥ n` est mathématiquement fausse (testé : `α=2, β=-3, γ=1, w_0=1` donne `w_4 = -2 < 4`).
219
+
220
+ **✅ CORRIGÉ**
221
+ ```python
222
+ # Contrainte : w_0 >= 0, alpha + beta = 1, gamma >= 1
223
+ w0 = rd.randint(0, 3)
224
+ ab_pairs = [(2, -1), (3, -2), (4, -3)] # alpha + beta = 1 garanti
225
+ alpha, beta = rd.choice(ab_pairs)
226
+ gamma = rd.randint(1, 5)
227
+ ```
228
+
229
+ **POURQUOI** : pythoniser ne signifie pas randomiser sans contrainte. La propriété démontrée doit rester vraie sur 100% des variantes. Si nécessaire, restreindre la plage ou utiliser une boucle `while` pour rejeter les tirages invalides.
230
+
231
+ **EXTENSION — calculs intermédiaires dans `detailedSolution`** : si une variable aléatoire change (ex. `p ∈ {0.7, 0.8, 0.9}`), TOUS les calculs intermédiaires affichés dans les `detailedSolution` doivent être recalculés à partir de cette variable. **Aucune valeur dérivée ne peut être hardcodée en littéral.**
232
+
233
+ ```
234
+ ❌ FAUTIF : `= 0{,}81 + 0{,}01 = 0{,}82` (vrai uniquement pour p=0.9)
235
+ ✅ CORRIGÉ : `= {{p_fidele_carre_str}} + {{p_contraire_carre_str}} = {{p_V3_str}}`
236
+ ```
237
+
238
+ L'audit doit lister TOUS les nombres décimaux apparaissant dans les `detailedSolution` et vérifier qu'ils proviennent d'une variable Python, pas d'une chaîne littérale.
239
+
240
+ ### RÈGLE 4.5 — Détection des invariants Vrai/Faux dépendants des paramètres
241
+
242
+ Pour les exercices "Vrai ou Faux", la réponse V/F dépend souvent de valeurs numériques précises. **Avant de tirer aléatoirement un paramètre**, vérifier algébriquement pour quelles valeurs la réponse V/F annoncée par la solution reste correcte.
243
+
244
+ Exemples typiques :
245
+ - `∫₀^a x² dx = a²` (aire d'un carré) ⟺ `a = 3`
246
+ - `f(x) = e^x + e^(cx)` solution de `y' = cy - e^x` ⟺ `c = 2`
247
+ - `A(n, k) = C(m, p)` ⟺ couples (n, k, m, p) précis
248
+
249
+ **Deux stratégies acceptables** :
250
+ 1. **Fixer les paramètres** sur la valeur source (pas de variation aléatoire)
251
+ 2. **Adapter dynamiquement la conclusion V/F** selon le tirage (cf. règle 8.4)
252
+
253
+ ### RÈGLE 4.6 — Arrondi nul à supprimer
254
+
255
+ Quand une probabilité ou un résultat est exprimé en notation scientifique (valeur `< 10⁻³`), ne pas afficher l'arrondi `≈ 0,000` qui n'apporte aucune information.
256
+
257
+ **✅ PATTERN**
258
+ ```python
259
+ if round(float(proba), 3) == 0:
260
+ proba_final = proba_exact_str # ex: "8,1 × 10⁻⁵"
261
+ else:
262
+ proba_final = f"{proba_exact_str} \\approx {proba_str}"
263
+ ```
264
+
265
+ ### RÈGLE 4.7 — Cohérence des formules développées avec les paramètres
266
+
267
+ Si une solution développe une formule pas à pas (ex. `n × (n-1) × (n-2)` pour un arrangement à `k=3`), le paramètre `k` DOIT être fixé OU le développement DOIT être généré dynamiquement.
268
+
269
+ **✅ PATTERN — helpers à inclure dans le bloc `{python}`**
270
+ ```python
271
+ def develop_chain(start, length):
272
+ """start × (start-1) × ... (length facteurs)"""
273
+ return " \\times ".join(str(start - i) for i in range(length))
274
+
275
+ def develop_chain_to(start, end_inclusive):
276
+ """start × (start-1) × ... × end_inclusive"""
277
+ return " \\times ".join(str(i) for i in range(start, end_inclusive - 1, -1))
278
+ ```
279
+
280
+ ### RÈGLE 4.8 — Pas d'assertion sur les distances numériques
281
+
282
+ Quand on tire une variable "presque égale" à une valeur cible (typiquement pour créer un piège dans un Vrai/Faux), NE PAS imposer un seuil de distance strict — l'inégalité mathématique structurelle (ex: rationnel vs irrationnel) suffit.
283
+
284
+ ```
285
+ ❌ FAUTIF : assert abs(float(frac) - J_approx) > 1e-4
286
+ # plante pour 7/11 (différence ≈ 7×10⁻⁵) qui est pourtant
287
+ # le piège le plus crédible
288
+
289
+ ✅ CORRIGÉ : pas d'assertion sur la distance — la distinction structurelle
290
+ (rationnel vs irrationnel) garantit l'inégalité.
291
+ ```
292
+
293
+ ### RÈGLE 4.4 — Identifier les contraintes mathématiques avant de pythoniser
294
+
295
+ Avant de transformer une constante en variable aléatoire, vérifier qu'elle peut varier sans casser :
296
+ - l'initialisation d'une récurrence
297
+ - les conditions d'une inégalité
298
+ - les hypothèses d'un théorème invoqué dans la solution
299
+ - le sens d'une asymptote / limite
300
+
301
+ Si une contrainte existe, soit borner le tirage, soit ne pas pythoniser ce paramètre.
302
+
303
+ ---
304
+
305
+ ## 5. Calculs — Rational exact, pas de double approximation
306
+
307
+ ### RÈGLE 5.1 — Tous les calculs intermédiaires en Rational/Fraction exacte
308
+
309
+ **❌ FAUTIF**
310
+ ```python
311
+ p_A = round(rd.uniform(0.4, 0.8) / 0.05) * 0.05 # produit 0.35000000000000003
312
+ ```
313
+
314
+ **✅ CORRIGÉ**
315
+ ```python
316
+ num_pA = rd.randint(8, 16) # 0,40 à 0,80 par pas de 0,05
317
+ p_A = Fraction(num_pA, 20)
318
+ ```
319
+
320
+ ### RÈGLE 5.2 — Conversion `float()` UNIQUEMENT au moment de l'affichage
321
+
322
+ ```python
323
+ # Calculs : tout en Rational
324
+ asymptote = v0 * inv_k + inv_k**2
325
+
326
+ # Affichage : convertir avec arrondi explicite
327
+ asymptote_disp = pxsl_format_number(round(float(asymptote), 2), **config_std)
328
+ ```
329
+
330
+ ### RÈGLE 5.3 — Pas de fractions reconstruites par double `limit_denominator`
331
+
332
+ **❌ FAUTIF**
333
+ ```python
334
+ frac = Fraction(p_float).limit_denominator(1000) / Fraction(q_float).limit_denominator(1000)
335
+ frac = frac.limit_denominator(100)
336
+ ```
337
+
338
+ **✅ CORRIGÉ**
339
+ ```python
340
+ # Calculer la fraction exacte directement à partir des Rational initiaux
341
+ frac_exact = p_inter_q / p_total
342
+ ```
343
+
344
+ ### RÈGLE 5.4 — Centième inférieur via `math.floor`, pas via formule arithmétique
345
+
346
+ **❌ FAUTIF**
347
+ ```python
348
+ seuil_arrondi = round(seuil * 100 - 5) / 100 # donne 0,73 au lieu de 0,77
349
+ ```
350
+
351
+ **✅ CORRIGÉ**
352
+ ```python
353
+ seuil_arrondi = math.floor(seuil * 100) / 100
354
+ ```
355
+
356
+ ### RÈGLE 5.5 — Vérifier les opérations sur les coefficients
357
+
358
+ Si la solution simplifie `αn + βn`, le coefficient résultant est `α + β`, pas `α - β`.
359
+
360
+ **❌ FAUTIF** (vu dans exo 3)
361
+ ```python
362
+ # Dans la solution :
363
+ {{alpha}} w_n {{beta}} n + {{gamma}} &\geqslant {{alpha - beta}} n + {{gamma}}
364
+ ```
365
+
366
+ Avec `α=3, β=-2`, le code calcule `α - β = 5` au lieu de `α + β = 1`. Bug critique de simplification.
367
+
368
+ **✅ CORRIGÉ**
369
+ ```python
370
+ {{alpha}} w_n {{beta_n_str}} + {{gamma}} &\geqslant n + {{gamma}} # car alpha + beta = 1
371
+ ```
372
+
373
+ ---
374
+
375
+ ## 6. Interpolation MyST `{{...}}` — Pièges critiques
376
+
377
+ ### RÈGLE 6.1 — INTERDIT : appels de fonction avec `**kwargs` dans `{{...}}`
378
+
379
+ **❌ FAUTIF**
380
+ ```
381
+ La suite converge vers ${{latex(limite_proposee, **config_standard)}}$.
382
+ ```
383
+
384
+ **Le rendu produit `latex(limite_proposee, **config_standard)` en clair**, pas la valeur. Cause : MyST parse `**config_standard` comme du gras markdown, ce qui casse l'expression.
385
+
386
+ **✅ CORRIGÉ**
387
+ ```python
388
+ # Dans le bloc Python
389
+ limite_proposee_tex = latex(limite_proposee, **config_standard)
390
+ ```
391
+ ```
392
+ La suite converge vers ${{limite_proposee_tex}}$.
393
+ ```
394
+
395
+ **POURQUOI** : tout appel `f(x, **kwargs)` dans `{{...}}` est interprété par MyST comme markdown avant interpolation Python. Toujours stocker le résultat dans une variable string en amont.
396
+
397
+ ### RÈGLE 6.2 — `pxsl_format_number(...)` dans `{{...}}` : créer la string en amont
398
+
399
+ **❌ FAUTIF**
400
+ ```
401
+ Le coefficient vaut ${{pxsl_format_number(round(float(coef), 2), **config_standard)}}$.
402
+ ```
403
+
404
+ **✅ CORRIGÉ**
405
+ ```python
406
+ coef_disp = pxsl_format_number(round(float(coef), 2), **config_std)
407
+ ```
408
+ ```
409
+ Le coefficient vaut ${{coef_disp}}$.
410
+ ```
411
+
412
+ ### RÈGLE 6.3 — Pré-calculer toutes les variables d'affichage dans le bloc Python
413
+
414
+ À la fin du bloc Python principal, créer un bloc dédié au formattage. Seul `sympy.latex(...)` accepte `**config_standard` — les helpers PyxiScience (`pxsl_format_number`, `pxsl_res_num`, etc.) ont leurs propres kwargs spécifiques (cf. règle 6.4).
415
+
416
+ ```python
417
+ # === Variables d'affichage prêtes ===
418
+ k_disp = pxsl_format_number(float(k_coef)) # PAS de **config_std
419
+ coef_const_disp = pxsl_format_number(float(coef_const))
420
+ inv_k_tex = latex(inv_k, **config_standard) # OK ici
421
+ asymptote_tex = latex(asymptote, **config_standard) # OK ici
422
+ alpha_disp = pxsl_format_number(alpha)
423
+ # etc.
424
+
425
+ globals()
426
+ ```
427
+
428
+ Le markdown ne contient alors plus que `{{var}}` simples, sans appel de fonction.
429
+
430
+ ### RÈGLE 6.4 — `**config_standard` réservé à `sympy.latex`
431
+
432
+ Le résultat de `pxs_config()` contient des clés (`ln_notation`, `mat_str`, etc.) destinées **uniquement à `sympy.latex()`**. Les helpers PyxiScience (`pxsl_format_number`, `pxsl_res_num`, `pxsl_matrix`, etc.) ont leurs propres kwargs et **plantent** si on leur passe `**config_standard`.
433
+
434
+ ```
435
+ ❌ FAUTIF : pxsl_format_number(aire_carre, **config_standard)
436
+ → TypeError: got an unexpected keyword argument 'ln_notation'
437
+
438
+ ✅ CORRECT : pxsl_format_number(aire_carre) ← pas de splat
439
+ ✅ CORRECT : pxsl_res_num(proba, dec=4, egal=False) ← kwargs explicites
440
+ ✅ CORRECT : latex(p_fidele, **config_standard) ← seul sympy.latex
441
+ ```
442
+
443
+ Liste explicite : **NE PAS** splat `**config_standard` sur `pxsl_format_number`, `pxsl_res_num`, `pxsl_matrix`, `pxsl_pow`, `pxsl_latex_coefficient` (alias `lc`), `pxsl_par`, `pxsl_mult`, `pxsl_choose_udv`, `pxs_Interval(...).print()`. **TOUJOURS** splat sur `sympy.latex(...)`.
444
+
445
+ ### RÈGLE 6.5 — `{{ }}` ne contient QU'UN nom de variable nu (camelCase, suffixe `Aff`)
446
+
447
+ Ajoutée 2026-06-12 (convention vérifiée sur 222/222 exemples livrés : 0 appel de fonction, 0 underscore, 2563 injections `…Aff` ; contrôle STATIQUE du harnais).
448
+
449
+ **❌ FAUTIF** :
450
+ ```latex
451
+ $T(x) = {{latex(T)}}$, coefficient {{lc(a, sign=True)}}, sur {{dom.print()}}, p = {{p_str}}
452
+ ```
453
+
454
+ **✅ CORRIGÉ** :
455
+ ```python
456
+ # Dans le bloc Python :
457
+ tTex = latex(T, **config_standard)
458
+ coefAAff = lc(a, sign=True)
459
+ domAff = dom.print()
460
+ pStr = str(p)
461
+ ```
462
+ ```latex
463
+ $T(x) = {{tTex}}$, coefficient {{coefAAff}}, sur {{domAff}}, p = {{pStr}}
464
+ ```
465
+
466
+ **POURQUOI** : le runtime de la plateforme ne substitue de façon fiable que des identifiants nus ; un appel/calcul dans `{{ }}` peut fuir tel quel dans le rendu, et un underscore crée des indices LaTeX parasites. Tout s'évalue dans le bloc Python, dans des variables d'affichage camelCase suffixées `Aff`. (Auto-lift déterministe : `app/pipeline/postprocess.py::auto_lift_injections` + `rename_underscore_injections`.)
467
+
468
+ ---
469
+
470
+ ## 7. Affichage des coefficients signés — Anti-concaténation
471
+
472
+ ### RÈGLE 7.1 — NE JAMAIS concaténer un signe à une valeur dans le markdown
473
+
474
+ **❌ FAUTIF**
475
+ ```
476
+ w_{n+1} = {{alpha}} w_n {{beta}} n + {{gamma}}
477
+ ```
478
+
479
+ Avec `β = -1`, le rendu donne `2 w_n -1 n + 3` (moche : `-1n` au lieu de `-n`).
480
+
481
+ **✅ CORRIGÉ**
482
+ ```python
483
+ # Dans le bloc Python
484
+ if beta == -1:
485
+ beta_n_str = "- n"
486
+ elif beta < 0:
487
+ beta_n_str = f"- {-beta}n"
488
+ else:
489
+ beta_n_str = f"+ {beta}n"
490
+ ```
491
+ ```
492
+ w_{n+1} = {{alpha}} w_n {{beta_n_str}} + {{gamma}}
493
+ ```
494
+
495
+ ### RÈGLE 7.2 — Pour tout coefficient pouvant être ±, générer une string complète avec signe intégré
496
+
497
+ ```python
498
+ # Pour v'(t) = (coef_const + coef_t * t) e^(-kt)
499
+ # coef_const < 0 toujours → latex(coef_const) commence par "-"
500
+ # coef_t < 0 toujours → on construit explicitement
501
+ coef_t_signed = f"- {pxsl_format_number(float(-coef_t), **config_std)}"
502
+ # Affichage : ({{coef_const_disp}} {{coef_t_signed}} t)
503
+ # → "(-6,2 - 0,6 t)"
504
+ ```
505
+
506
+ ### RÈGLE 7.3 — Cas typiques de coefficients à traiter explicitement
507
+
508
+ - Coefficient devant `t`, `n`, `x` (terme variable d'un polynôme)
509
+ - Constante d'intégration ajoutée
510
+ - Reste d'une factorisation
511
+ - Termes dans une somme avec signes alternés
512
+
513
+ ### RÈGLE 7.4 — Format des décimales à 3 chiffres fixes
514
+
515
+ Pour les arrondis à 10⁻³ près (consigne fréquente en Bac), utiliser un format à **3 décimales fixes** plutôt que `str(round(...))` qui tronque les zéros.
516
+
517
+ ```
518
+ ❌ FAUTIF : str(round(0.6561, 3)) → '0.656' (OK)
519
+ str(round(0.6, 3)) → '0.6' (manque "00" final attendu)
520
+
521
+ ✅ CORRECT : f"{x:.3f}".replace('.', '{,}')
522
+ # 0.6561 → '0{,}656'
523
+ # 0.6 → '0{,}600'
524
+ ```
525
+
526
+ ---
527
+
528
+ ## 8. Solutions validées — Directive Chabane
529
+
530
+ ### RÈGLE 8.1 — INTERDICTION ABSOLUE de modifier les solutions validées
531
+
532
+ Le générateur ne doit pas :
533
+ - ajouter des listes à puces qui n'existaient pas
534
+ - ajouter des préambules redondants en début de solution
535
+ - ajouter des étapes intermédiaires de calcul non validées
536
+ - reformuler des phrases (changer "factoriser" en "diviser", etc.)
537
+ - ajouter de la pédagogie ("Les quatre conditions de la loi binomiale sont vérifiées...")
538
+
539
+ **❌ FAUTIF** (vu dans exo 3)
540
+ ```
541
+ {fr}`On divise le numérateur et le dénominateur par {{b1}}^n :`
542
+ ```
543
+
544
+ Alors que la version validée disait :
545
+ ```
546
+ {fr}`On factorise le numérateur par 5^n et le dénominateur par 3^n :`
547
+ ```
548
+
549
+ (La manipulation est en réalité une **factorisation séparée** au numérateur et au dénominateur, pas une division commune.)
550
+
551
+ **✅ CORRIGÉ**
552
+ ```
553
+ {fr}`On factorise le numérateur par {{b1}}^n et le dénominateur par {{d1}}^n :`
554
+ ```
555
+
556
+ ### RÈGLE 8.2 — En cas de doute, copier-coller la solution validée
557
+
558
+ Le générateur ne doit jamais "améliorer" ou "compléter" une solution validée. Si la pythonisation impose une adaptation (variable au lieu de constante), substituer mécaniquement et rien d'autre.
559
+
560
+ ### RÈGLE 8.3 — Si la pythonisation a touché à une solution validée, signaler avant correction
561
+
562
+ L'audit doit demander confirmation explicite avant de restaurer. Le générateur ne doit pas le faire silencieusement.
563
+
564
+ ### RÈGLE 8.4 — Conclusions Vrai/Faux adaptatives
565
+
566
+ Pour les exos "Vrai ou Faux" où on veut faire varier des paramètres qui peuvent changer la réponse, préparer la conclusion en Python comme variable conditionnelle :
567
+
568
+ ```python
569
+ if condition_vraie:
570
+ conclusion_fr = "... L'affirmation est vraie."
571
+ conclusion_en = "... Statement is true."
572
+ else:
573
+ conclusion_fr = f"... (détail spécifique). L'affirmation est fausse."
574
+ conclusion_en = f"... (specific detail). Statement is false."
575
+ ```
576
+
577
+ Puis injecter via `{{conclusion_fr}}` / `{{conclusion_en}}` dans la `detailedSolution`. La structure du raisonnement reste identique, seul le verdict final s'adapte au tirage.
578
+
579
+ ---
580
+
581
+ ## 9. Structure MyST — Paragraphes contextuels
582
+
583
+ ### RÈGLE 9.1 — Les paragraphes contextuels (intro de partie, intro de question groupée) sont HORS `questionStatement`
584
+
585
+ **❌ FAUTIF**
586
+ ```
587
+ :::::{question}
588
+ :questionType: STQ
589
+
590
+ ::::{questionStatement}
591
+ $\underline{\textbf{Partie A}}$
592
+
593
+ {fr}`Le centre propose aux personnes...`{en}`...`
594
+
595
+ {fr}`Question 1...`{en}`...`
596
+ ::::
597
+ ```
598
+
599
+ **✅ CORRIGÉ**
600
+ ```
601
+ $\underline{\textbf{Partie A}}$
602
+
603
+ {fr}`Le centre propose aux personnes...`{en}`...`
604
+
605
+ (exo1-q1)=
606
+
607
+ :::::{question}
608
+ :questionType: STQ
609
+
610
+ ::::{questionStatement}
611
+ {fr}`Question 1...`{en}`...`
612
+ ::::
613
+ ```
614
+
615
+ **POURQUOI** : `questionStatement` doit contenir UNIQUEMENT la consigne de la question. Tout contexte commun à plusieurs questions est un paragraphe libre entre les blocs `:::::{question}`.
616
+
617
+ ### RÈGLE 9.2 — Les paragraphes contextuels qui utilisent des variables `{{var}}` viennent APRÈS le bloc Python qui les définit
618
+
619
+ ```
620
+ ```{python}
621
+ v0 = ...
622
+ k_coef = ...
623
+ globals()
624
+ ```
625
+
626
+ {fr}`On considère la fonction $v$ avec $v(0) = {{v0}}$.`{en}`...`
627
+ ```
628
+
629
+ ### RÈGLE 9.3 — Phrase "Dans cette question, on étudie..." (regroupement APMEP)
630
+
631
+ L'APMEP utilise parfois "Dans cette question, on étudie X" pour introduire un groupe de sous-questions (2.a, 2.b, 2.c, 2.d). En PyxiScience, les sous-questions sont éclatées en questions distinctes.
632
+
633
+ **RÈGLE** : reformuler en précisant le périmètre exact pour ne pas inclure les questions hors groupe.
634
+
635
+ ```
636
+ {fr}`Dans les quatre questions qui suivent, on étudie la fonction $v$ sur $[0~;~+\infty[$.`
637
+ ```
638
+
639
+ Le **nombre est explicite** (`les quatre questions`) pour éviter d'englober la question suivante (numérotée séparément en APMEP).
640
+
641
+ ### RÈGLE 9.4 — Pas de doublons d'énoncés
642
+
643
+ L'énoncé de chaque question apparaît UNE SEULE FOIS, dans son `questionStatement`. Ne pas le répéter en paragraphe libre avant le bloc question.
644
+
645
+ **❌ FAUTIF** (vu dans exo 4)
646
+ ```
647
+ {fr}`Que vaut $d'(t_A)$ ? Interpréter ce résultat.`
648
+
649
+ :::::{question}
650
+ ::::{questionStatement}
651
+ {fr}`Que vaut $d'(t_A)$ ? Interpréter ce résultat.` # DOUBLON
652
+ ::::
653
+ ```
654
+
655
+ ### RÈGLE 9.5 — Variables Python dans les blocs matplotlib
656
+
657
+ Les substitutions `{{...}}` ne fonctionnent que dans le **texte MyST**, **PAS** à l'intérieur des blocs ```` ```{python} ```` . Dans un bloc Python, utiliser les vraies variables Python (f-string ou concaténation).
658
+
659
+ ```
660
+ ❌ FAUTIF : probs = r"${{p_fidele_str}}$"
661
+ # matplotlib reçoit littéralement "${{p_fidele_str}}$"
662
+ # mathtext rend "p_fidele_str" en italique math (incompréhensible)
663
+
664
+ ✅ CORRECT : probs = f"${p_fidele_str}$"
665
+ # Python interpole d'abord → matplotlib reçoit "$0{,}9$"
666
+ ```
667
+
668
+ Pareil pour les `ax.set_title(...)`, `ax.text(...)`, `ax.legend(...)` : utiliser des f-strings Python, jamais `{{...}}`.
669
+
670
+ ---
671
+
672
+ ## 10. Bilinguisme FR/EN — Symétrie
673
+
674
+ ### RÈGLE 10.1 — FR et EN doivent être équivalents en niveau de détail
675
+
676
+ **❌ FAUTIF** (vu dans exo 2 Q6, exo 4 Q9)
677
+ - FR détaille le changement de variable `X = 0,6t` puis applique les croissances comparées (5 lignes)
678
+ - EN saute directement à "by comparison of growth rates" puis le boxed (2 lignes)
679
+
680
+ **✅ CORRIGÉ** : les deux versions ont le même squelette de raisonnement, mêmes étapes, mêmes formules.
681
+
682
+ ### RÈGLE 10.2 — Notation math identique en FR et EN
683
+
684
+ **❌ FAUTIF**
685
+ ```
686
+ {fr}`...l'intervalle $[0\,;\,1]$.`{en}`...the interval [0\,;\,1].`
687
+ ^^^^^^^^^^^ pas en mode math
688
+ ```
689
+
690
+ **✅ CORRIGÉ**
691
+ ```
692
+ {fr}`...l'intervalle $[0\,;\,1]$.`{en}`...the interval $[0\,;\,1]$.`
693
+ ```
694
+
695
+ ### RÈGLE 10.3 — Si l'utilisateur a modifié l'énoncé, effacer la version EN
696
+
697
+ Si la version pythonisée modifie le contenu de l'énoncé (pas seulement réagencement structurel), le générateur efface tous les blocs `{en}` pour permettre passage en retraduction par l'app dédiée. Le réagencement (séparation a/b/c en questions distinctes) n'est PAS une modification.
698
+
699
+ ### RÈGLE 10.4 — Format auto fraction / décimal selon la nature
700
+
701
+ Pour les valeurs qui peuvent être rationnelles non-décimales (ex. `0,5 / 0,6 = 5/6`), créer un helper qui choisit automatiquement entre forme décimale finie et fraction LaTeX :
702
+
703
+ ```python
704
+ def _frac_to_latex(f):
705
+ """Fraction Python → décimal LaTeX si fini, sinon \\frac{a}{b}."""
706
+ if f.denominator == 1:
707
+ return str(f.numerator)
708
+ d = f.denominator
709
+ while d % 2 == 0: d //= 2
710
+ while d % 5 == 0: d //= 5
711
+ if d == 1:
712
+ return str(float(f)).replace('.', '{,}')
713
+ return f"\\frac{{{f.numerator}}}{{{f.denominator}}}"
714
+ ```
715
+
716
+ Exemples :
717
+ - `_frac_to_latex(Fraction(5, 8))` → `'0{,}625'` (décimal fini)
718
+ - `_frac_to_latex(Fraction(5, 6))` → `'\\frac{5}{6}'` (décimal infini)
719
+ - `_frac_to_latex(Fraction(5, 4))` → `'1{,}25'` (décimal fini)
720
+
721
+ ### RÈGLE 10.5 — Notation scientifique française pour valeurs très petites
722
+
723
+ Pour les valeurs `< 10⁻⁴`, basculer en notation scientifique LaTeX plutôt qu'afficher `0{,}000081`.
724
+
725
+ ```python
726
+ import math
727
+
728
+ def _frac_to_str_smart(f, sci_threshold=1e-4):
729
+ """Décimal pour valeurs raisonnables, sinon notation scientifique."""
730
+ fl = float(f)
731
+ if 0 < abs(fl) < sci_threshold:
732
+ exp = int(math.floor(math.log10(abs(fl))))
733
+ mant = fl / (10 ** exp)
734
+ mant_str = f"{mant:.2f}".rstrip('0').rstrip('.').replace('.', '{,}') or "1"
735
+ return f"{mant_str} \\times 10^{{{exp}}}"
736
+ return _frac_to_latex(f)
737
+ ```
738
+
739
+ ---
740
+
741
+ ## 11. Rendu graphique matplotlib
742
+
743
+ ### RÈGLE 11.1 — Toute variable utilisée dans l'énoncé DOIT être utilisée dans le tracé
744
+
745
+ **❌ FAUTIF** (vu dans exo 3)
746
+ ```python
747
+ x_tangente_horiz = rd.randint(1, 3) # tirée
748
+
749
+ # Énoncé : "tangente horizontale en x = {{x_tangente_horiz}}"
750
+
751
+ # Mais le code matplotlib trace une fonction f(x) = K * (x^c - 1) * ln(x)
752
+ # qui a SA tangente horizontale FIGÉE en x=1 (par construction f(1)=0, f'(1)=0).
753
+ ```
754
+
755
+ Le graphique montre la tangente horizontale en x=1 alors que l'énoncé annonce x=2 ou x=3. Incohérent dans 66% des seeds.
756
+
757
+ **✅ CORRIGÉ**
758
+ - Soit fixer `x_tangente_horiz = 1` (constante), soit modifier la fonction tracée pour que sa tangente horizontale soit effectivement en `x_tangente_horiz`.
759
+
760
+ ### RÈGLE 11.2 — La tangente tracée DOIT être la vraie tangente analytique
761
+
762
+ **❌ FAUTIF**
763
+ ```python
764
+ slope = f(x_A) / (x_A + 0.3) # heuristique arbitraire
765
+ ```
766
+
767
+ **✅ CORRIGÉ**
768
+ ```python
769
+ def f_prime(x):
770
+ c = coeff_puissance
771
+ return facteur * (c * x**(c-1) * np.log(x) + (x**c - 1)/x)
772
+
773
+ slope = f_prime(x_A)
774
+ b_intercept = f(x_A) - slope * x_A
775
+ ```
776
+
777
+ ### RÈGLE 11.3 — Les labels (Cf, T, Δ, A) doivent rester DANS la fenêtre du graphique
778
+
779
+ **Symptôme** : si un label est positionné à `(x, y)` avec `y > ylim_max`, matplotlib étend automatiquement la zone d'affichage pour l'inclure, ce qui **compresse** le graphique.
780
+
781
+ **❌ FAUTIF**
782
+ ```python
783
+ ax.set_ylim(-1.2, 8)
784
+ ax.text(11, f(11) - 0.4, r"$\mathcal{C}_f$", ...) # f(11) peut être > 8
785
+ ax.text(11, slope*11 + b_intercept + 0.15, "T", ...) # idem
786
+ ```
787
+
788
+ **✅ CORRIGÉ**
789
+ ```python
790
+ # Borner les paramètres pour que f(x_max_visible) reste sous le plafond
791
+ y_label_target = 6.5
792
+ denom_y_max = (x_max**coeff_puissance - 1) * np.log(x_max)
793
+ facteur_max = min(70, int(y_label_target / denom_y_max))
794
+ facteur_echelle = rd.randint(30, max(30, facteur_max))
795
+
796
+ # Placer les labels dans une zone garantie sûre
797
+ x_label = max(x_A + 1, x_max - 1.5)
798
+ x_label = min(x_label, x_max)
799
+ y_lab_cf = f(x_label) - 0.3
800
+ y_lab_t = min(slope * x_label + b_intercept + 0.5, ylim_max - 0.5)
801
+ ```
802
+
803
+ ### RÈGLE 11.4 — Pas de mélange Rational sympy + numpy array
804
+
805
+ **❌ FAUTIF**
806
+ ```python
807
+ d_vals = Rational(5, 3) * t_graph + asymptote # Rational * np.array casse
808
+ ```
809
+
810
+ **✅ CORRIGÉ**
811
+ ```python
812
+ d_vals = float(Rational(5, 3)) * t_graph + float(asymptote)
813
+ # ou
814
+ inv_k_float = 1.0 / float(k_coef)
815
+ d_vals = -(v0 + t_graph) * inv_k_float * np.exp(-float(k_coef) * t_graph) + ...
816
+ ```
817
+
818
+ ### RÈGLE 11.5 — `plt.show()`, jamais `plt.savefig`
819
+
820
+ ```python
821
+ # ❌ Le chemin local n'est pas résolu côté plateforme
822
+ plt.savefig('arbre.png')
823
+ # puis dans le markdown : ![](arbre.png)
824
+
825
+ # ✅
826
+ plt.show()
827
+ ```
828
+
829
+ ### RÈGLE 11.6 — Pas d'éléments parasites dans le graphique
830
+
831
+ - Pas de `ax.text(8.5, 22.2, "Fig. 2", ...)` à l'intérieur du graphique. La référence "Fig. 2" est une légende externe APMEP, pas un élément du tracé.
832
+ - Pas de doubles labels "1" sur les axes si les ticks par défaut sont déjà annotés.
833
+ - Pas de titre auto matplotlib.
834
+
835
+ ---
836
+
837
+ ## 12. Fidélité APMEP
838
+
839
+ ### RÈGLE 12.1 — L'énoncé pythonisé est strictement conforme à l'APMEP, modulo paramètres
840
+
841
+ - Toutes les phrases-clés de l'énoncé original sont présentes textuellement.
842
+ - Toutes les valeurs numériques sont identiques (modulo pythonisation).
843
+ - L'ordre des questions est respecté.
844
+
845
+ ### RÈGLE 12.2 — Sous-questions APMEP a/b/c → questions PyxiScience distinctes
846
+
847
+ Convention PyxiScience : chaque sous-question APMEP devient une question distincte (`q1`, `q2`, ...) avec son propre `questionStatement` / `questionHint` / `detailedSolution`. Ce réagencement n'est PAS une modification d'énoncé au sens de la directive 2.
848
+
849
+ ### RÈGLE 12.3 — Géométrie : pythonisation autorisée à condition de préserver le niveau
850
+
851
+ La pythonisation des exercices de géométrie dans l'espace (vecteurs, droites, plans, projections, orthocentres) est **autorisée** (cf. exos validés Amérique du Sud 13 novembre 2025, Amérique du Nord 22 mai 2025). Convention observée :
852
+
853
+ - **Représenter les points/vecteurs en `sympy.Matrix([x, y, z])`** pour calculs symboliques.
854
+ - **Vérifier l'orthogonalité via `.dot()` = 0** au lieu de calculer par projection.
855
+ - **Pour une projection orthogonale**, paramétrer la droite (`K = A + lam*(B-A)`), construire `CK.dot(AB) = 0`, résoudre via `solve(...)`.
856
+ - **Distances via `sqrt(vec.dot(vec))`** (norme).
857
+
858
+ ⚠️ **NE PAS changer le niveau pédagogique** : si l'APMEP demande une démonstration géométrique (collinéarité, coplanarité, équation cartésienne d'un plan), la version pythonisée doit conserver cette difficulté — on randomise les coefficients, pas la nature du raisonnement.
859
+
860
+ **❌ FAUTIF** (mauvaise pythonisation)
861
+ ```python
862
+ # Donner les coordonnées du point projeté directement
863
+ A = Matrix([1, 0, 0]); B = Matrix([0, 1, 0]); C = Matrix([0, 0, 1])
864
+ K = Matrix([0.5, 0.5, 0]) # hardcodé — élève n'a plus à calculer
865
+ ```
866
+
867
+ **✅ CORRIGÉ**
868
+ ```python
869
+ # Le tirage des sommets randomise les valeurs, mais l'élève DOIT calculer la projection
870
+ alpha, beta, gamma = rd.sample(range(1, 4), 3)
871
+ A = Matrix([alpha, 0, 0]); B = Matrix([0, beta, 0]); C = Matrix([0, 0, gamma])
872
+ lam = Symbol('lam', real=True)
873
+ K = A + lam*(B - A)
874
+ sol = solve((K - C).dot(B - A), lam)[0]
875
+ # K_proj = A + sol*(B - A) # ← l'élève le démontre dans sa solution
876
+ ```
877
+
878
+ ### RÈGLE 12.4 — Coquilles APMEP corrigées silencieusement
879
+
880
+ Si l'APMEP contient une coquille (ex: "au activités" sans "x"), la version PyxiScience peut la corriger silencieusement. Ce n'est pas une modification d'énoncé.
881
+
882
+ ---
883
+
884
+ ## 13. Pièges spécifiques par type d'exercice
885
+
886
+ ### 13.1 — Probabilités
887
+
888
+ - Tirages de probabilités : `rd.randint(a, b) / 20` + `Fraction`, jamais `round(uniform/0.05)*0.05`.
889
+ - Variables conditionnelles : ne pas écraser `p_non_B_sachant_non_A` (P_{Ā}(B̄)) par `p_non_A_sachant_non_B` (P_{B̄}(Ā)). Ce sont des conditionnelles inversées (Bayes), pas la même quantité.
890
+ - Loi binomiale : `scipy.stats.binom.cdf(k, n, p)` pour `P(X ≤ k)`.
891
+ - Bienaymé-Tchebychev : `math.floor(seuil*100)/100` pour le centième inférieur.
892
+
893
+ ### 13.2 — Suites
894
+
895
+ - Variation `\case1`/`\case2` : à mettre INSIDE `\right{}`/`\wrong{}`, jamais autour.
896
+ - `pxs_variation_number` toujours = 1 dans le code Python — calculer toutes les variations en parallèle.
897
+ - Récurrence : voir RÈGLE 4.3 (préserver la propriété par contraintes sur les paramètres).
898
+
899
+ ### 13.3 — Analyse / Intégration
900
+
901
+ - Constante d'intégration : ajouter `\py{C_new}` ou demander explicitement à l'utilisateur.
902
+ - Pas de concaténation `\py{sg(x)}` : créer une variable complète `signe_coeff_x = "+ val"` ou `"- val"` (RÈGLE 7.1).
903
+
904
+ ### 13.4 — Tracés matplotlib
905
+
906
+ - Voir section 11 complète.
907
+
908
+ ---
909
+
910
+ ## 16bis. Patterns récurrents observés en production
911
+
912
+ (Section issue de l'analyse des exos validés de mai/novembre 2025. À ne pas confondre avec la section 16 (Anti-patterns), qui liste les BUGS — ici on liste des CONVENTIONS positives à reproduire.)
913
+
914
+ ### RÈGLE 16.1 — Tirage de paramètres avec contraintes : préférer la list comprehension
915
+
916
+ Quand plusieurs paramètres doivent satisfaire une contrainte couplée (ex: `p_vv > p_nv` et `denominator(1/(1-(p_vv-p_nv))) <= 6`), ne PAS faire de `for _ in range(100): ... if cond: break` qui peut échouer silencieusement. Préférer une **list comprehension qui énumère toutes les combinaisons valides**, puis `rd.choice()`.
917
+
918
+ **❌ FAUTIF**
919
+ ```python
920
+ for _ in range(100):
921
+ p_vv = rd.choice(valeurs)
922
+ p_nv = rd.choice(valeurs)
923
+ if p_vv > p_nv and Rational(1, 1-(p_vv-p_nv)).denominator <= 6:
924
+ break # peut sortir sans break, valeurs invalides en silence
925
+ ```
926
+
927
+ **✅ CORRIGÉ**
928
+ ```python
929
+ couples_valides = [
930
+ (p_vv, p_nv) for p_vv in valeurs for p_nv in valeurs
931
+ if p_vv > p_nv and Rational(1, 1 - (p_vv - p_nv)).denominator <= 6
932
+ ]
933
+ p_vv, p_nv = rd.choice(couples_valides) # garanti valide
934
+ ```
935
+
936
+ **POURQUOI** : la list comprehension échoue de manière visible (IndexError si liste vide), au lieu de laisser passer des paramètres invalides. Pattern observé dans les exos validés Amérique du Sud 13 novembre 2025.
937
+
938
+ ### RÈGLE 16.2 — Loi binomiale : utiliser scipy.stats.binom (sf / cdf / pmf)
939
+
940
+ Pour les calculs `P(X ≥ k)`, `P(X ≤ k)`, `P(X = k)` d'une binomiale, **toujours** utiliser `scipy.stats.binom`.
941
+
942
+ **❌ FAUTIF** (calcul à la main, lent et fragile)
943
+ ```python
944
+ prob_inf = sum(binomial(n, i) * p**i * (1-p)**(n-i) for i in range(k+1))
945
+ ```
946
+
947
+ **✅ CORRIGÉ**
948
+ ```python
949
+ from scipy.stats import binom
950
+ prob_inf = binom.cdf(k, n, p) # P(X ≤ k)
951
+ prob_sup_strict = binom.sf(k - 1, n, p) # P(X ≥ k) (sf = 1 - cdf(k-1))
952
+ prob_egal = binom.pmf(k, n, p) # P(X = k)
953
+ ```
954
+
955
+ **Astuce conditionnelle** : si `(X ≥ nb) ⊂ (X ≥ ne)` (donc `nb ≥ ne`), alors `P(X ≥ nb | X ≥ ne) = binom.sf(nb-1, n, p) / binom.sf(ne-1, n, p)`. Garantir `ne < nb` au tirage pour que le quotient soit ≤ 1.
956
+
957
+ **POURQUOI** : `binom.sf` (survival function) évite les sommes manuelles de coefficients binomiaux qui sont coûteuses en sympy et peuvent dériver numériquement. Pattern dans Exo 2 Amérique du Sud, exo binomiale randomisée.
958
+
959
+ ### RÈGLE 16.3 — Matplotlib : axes "zero spines" pour la convention math française
960
+
961
+ Pour les graphes de fonction (style scolaire FR), positionner les axes sur l'origine et masquer les spines droite/haute. C'est la convention attendue par les enseignants.
962
+
963
+ **✅ PATTERN STANDARD**
964
+ ```python
965
+ fig, ax = plt.subplots(figsize=(6, 5))
966
+ # ... ax.plot(...) ...
967
+ ax.spines['left'].set_position('zero')
968
+ ax.spines['bottom'].set_position('zero')
969
+ ax.spines['right'].set_color('none')
970
+ ax.spines['top'].set_color('none')
971
+ ax.xaxis.set_label_coords(1.02, -0.05) # label "x" en bout d'axe
972
+ ax.yaxis.set_label_coords(-0.05, 1.02) # label "y" en haut d'axe
973
+ plt.show()
974
+ ```
975
+
976
+ À utiliser pour **toute étude de fonction** (Bac, terminale). Ne PAS utiliser pour les graphes de distribution / histogrammes (cadre classique avec spines complètes mieux adapté). Pattern observé dans Exos 3 + 4 Amérique du Sud.
977
+
978
+ ---
979
+
980
+ ## 14. Checklist pre-flight avant livraison
981
+
982
+ Le générateur n'envoie pas le fichier tant que les points suivants ne sont pas cochés :
983
+
984
+ ### Métadonnées
985
+ - [ ] `:id:` est en première ligne et vide
986
+ - [ ] Toutes les autres métadonnées sont identiques à la version non pythonisée
987
+
988
+ ### Architecture Python
989
+ - [ ] UN SEUL bloc Python principal en début d'exercice
990
+ - [ ] Imports uniquement dans le premier bloc
991
+ - [ ] Tous les blocs Python se terminent par `globals()`
992
+ - [ ] Aucune redéfinition de variable entre blocs
993
+ - [ ] Bloc graphique (s'il existe) réutilise les variables du bloc principal
994
+
995
+ ### Tirages aléatoires
996
+ - [ ] Calculs en `Rational` exact, conversion `float()` uniquement à l'affichage
997
+ - [ ] Pas de `int(x * 10)` sur des flottants
998
+ - [ ] Tous les paramètres dérivés sont **calculés**, pas tirés indépendamment
999
+ - [ ] La propriété démontrée par l'exercice est vraie sur 100% des seeds (testée sur ≥ 200 seeds)
1000
+ - [ ] Pas de valeurs négatives quand l'énoncé exige des entiers naturels (ex: `w_0 ≥ 0`)
1001
+
1002
+ ### Affichage / interpolation
1003
+ - [ ] Aucun `{{f(x, **kwargs)}}` dans le markdown — toutes les strings d'affichage pré-calculées dans le bloc Python
1004
+ - [ ] Coefficients signés générés explicitement (pas de `{{a}}{{b}}t` avec `b` négatif)
1005
+ - [ ] `pxsl_format_number` reçoit toujours des valeurs déjà arrondies (`round(float(x), n)` en amont)
1006
+
1007
+ ### Solutions
1008
+ - [ ] Toutes les solutions validées Chabane sont conformes textuellement (modulo paramètres)
1009
+ - [ ] Aucun ajout pédagogique non sollicité (listes à puces, préambules, étapes intermédiaires)
1010
+ - [ ] Pas de reformulation ("factoriser" reste "factoriser", pas "diviser")
1011
+
1012
+ ### Structure MyST
1013
+ - [ ] Paragraphes contextuels HORS `questionStatement`
1014
+ - [ ] Pas de doublons d'énoncés (chaque énoncé apparaît une seule fois)
1015
+ - [ ] Phrases "Dans cette question, on étudie..." reformulées avec périmètre explicite
1016
+ - [ ] Ancres `(exoN-qK)=` présentes avant chaque bloc question
1017
+
1018
+ ### Bilinguisme
1019
+ - [ ] FR et EN équivalents en niveau de détail
1020
+ - [ ] Notation math identique (`$[0\,;\,1]$` dans les deux versions)
1021
+ - [ ] Si l'énoncé est modifié → blocs `{en}` effacés (sinon conservés intacts)
1022
+
1023
+ ### Rendu graphique
1024
+ - [ ] Toutes les variables aléatoires utilisées dans l'énoncé sont effectivement utilisées dans le tracé
1025
+ - [ ] Tangentes calculées analytiquement (`f'(x_A)`), pas par heuristique
1026
+ - [ ] Tous les labels (Cf, T, Δ, A) restent dans la fenêtre `[xlim, ylim]`
1027
+ - [ ] Paramètres bornés pour que les courbes ne sortent pas du cadre
1028
+ - [ ] `plt.show()` (pas `plt.savefig`)
1029
+ - [ ] Pas de Rational sympy mélangé à des array numpy
1030
+
1031
+ ### Tests automatiques
1032
+ - [ ] Simulation sur ≥ 100 seeds : aucune erreur de rendu
1033
+ - [ ] Simulation sur ≥ 100 seeds : aucun artefact flottant (`0.35000000000000003`, `0.44999999999999996`)
1034
+ - [ ] Simulation sur ≥ 100 seeds : toutes les contraintes mathématiques de l'exercice sont respectées
1035
+ - [ ] Aucune valeur affichée hors plage attendue (probabilité > 1, distance négative, etc.)
1036
+
1037
+ ---
1038
+
1039
+ ## 15. Convention de nommage des fichiers
1040
+
1041
+ - Version non pythonisée corrigée : `exoN_corrige.md`
1042
+ - Version pythonisée corrigée : `exoN_pythonise_corrige.md`
1043
+ - Version FR-only (après modif d'énoncé) : `*_FR_only.md`
1044
+ - Toujours dans `/mnt/user-data/outputs/`
1045
+ - Pas de longues chaînes descriptives dans le nom
1046
+
1047
+ ---
1048
+
1049
+ ## 16. Anti-patterns récurrents — résumé
1050
+
1051
+ Les 10 erreurs les plus fréquentes vues sur les pythonisations livrées :
1052
+
1053
+ 1. **`{{latex(x, **config_standard)}}`** dans le markdown → casse à cause des `**`. Stocker en variable.
1054
+ 2. **Variables redéfinies entre blocs Python** → valeurs incohérentes entre questions.
1055
+ 3. **Tirages indépendants de paramètres mathématiquement liés** → énoncé faux (ex: `L_min < asymptote`).
1056
+ 4. **Paramètres aléatoires qui invalident la propriété démontrée** → solution dit "vrai" alors que c'est faux.
1057
+ 5. **`int(x * 10)` sur flottant** → bugs d'arrondi (ex: `int(4.7 * 10) = 46`).
1058
+ 6. **Heuristique de tangente** au lieu de `f'(x_A)` analytique.
1059
+ 7. **`x_paramètre` aléatoire mais ignoré dans le tracé matplotlib** → graphique incohérent avec l'énoncé.
1060
+ 8. **Labels matplotlib qui sortent de la fenêtre** → graphique compressé.
1061
+ 9. **Solutions validées modifiées** (listes à puces ajoutées, reformulations, étapes ajoutées) → directive Chabane violée.
1062
+ 10. **Doublons d'énoncés** (même phrase en paragraphe libre + dans `questionStatement`).
app/knowledge/rules_digest.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ rules_digest.py (ex utils/rules_digest.py)
3
+ ──────────────────────────────────────────
4
+ Parser de `pythonisation_rules.md` + construction de digests ciblés injectés
5
+ dans les prompts. Parsé une fois à l'import, caché en module.
6
+
7
+ API publique :
8
+ RULES_BY_ID dict[str, Rule]
9
+ ALL_RULE_IDS list[str]
10
+ build_rules_digest(rule_ids) → markdown compact
11
+ AUDIT_RULES_ALWAYS list[str]
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import re
17
+ from typing import Optional, TypedDict
18
+
19
+ from app.config import RULES_MD
20
+
21
+
22
+ class Rule(TypedDict, total=False):
23
+ id: str
24
+ title: str
25
+ section: str
26
+ bad: Optional[str]
27
+ good: Optional[str]
28
+ why: Optional[str]
29
+
30
+
31
+ _RULE_HEADING = re.compile(
32
+ r"^### RÈGLE (?P<id>\d+\.\d+(?:\.\d+)?)\s*—\s*(?P<title>.+?)\s*$",
33
+ re.MULTILINE,
34
+ )
35
+ _SECTION_HEADING = re.compile(
36
+ r"^## (?P<num>\d+)\.\s*(?P<title>.+?)\s*$",
37
+ re.MULTILINE,
38
+ )
39
+ _BAD_BLOCK = re.compile(
40
+ r"\*\*❌\s*FAUTIF\*\*[^\n]*\n```(?:[a-zA-Z]*)\n(.+?)\n```",
41
+ re.DOTALL,
42
+ )
43
+ _GOOD_BLOCK = re.compile(
44
+ r"\*\*✅\s*CORRIG(?:É|EE?|É?)\*\*[^\n]*\n```(?:[a-zA-Z]*)\n(.+?)\n```",
45
+ re.DOTALL,
46
+ )
47
+ _WHY = re.compile(
48
+ r"\*\*POURQUOI\*\*\s*:\s*(.+?)(?=\n{2,}|\n#{2,3}\s|\Z)",
49
+ re.DOTALL,
50
+ )
51
+
52
+
53
+ def _parse_rules(content: str) -> dict[str, Rule]:
54
+ sections: list[tuple[int, str]] = []
55
+ for m in _SECTION_HEADING.finditer(content):
56
+ sections.append((m.start(), f"{m.group('num')}. {m.group('title').strip()}"))
57
+
58
+ rule_matches = list(_RULE_HEADING.finditer(content))
59
+ rules: dict[str, Rule] = {}
60
+
61
+ for i, m in enumerate(rule_matches):
62
+ rule_id = m.group("id")
63
+ title = m.group("title").strip()
64
+ body_start = m.end()
65
+ body_end = rule_matches[i + 1].start() if i + 1 < len(rule_matches) else len(content)
66
+ body = content[body_start:body_end].strip()
67
+
68
+ section_title = ""
69
+ for off, label in sections:
70
+ if off < m.start():
71
+ section_title = label
72
+
73
+ bad_m = _BAD_BLOCK.search(body)
74
+ good_m = _GOOD_BLOCK.search(body)
75
+ why_m = _WHY.search(body)
76
+
77
+ rules[rule_id] = Rule(
78
+ id=rule_id,
79
+ title=title,
80
+ section=section_title,
81
+ bad=bad_m.group(1).rstrip() if bad_m else None,
82
+ good=good_m.group(1).rstrip() if good_m else None,
83
+ why=why_m.group(1).strip() if why_m else None,
84
+ )
85
+ return rules
86
+
87
+
88
+ _RULES_CACHE: Optional[dict[str, Rule]] = None
89
+
90
+
91
+ def _load_rules() -> dict[str, Rule]:
92
+ global _RULES_CACHE
93
+ if _RULES_CACHE is None:
94
+ _RULES_CACHE = _parse_rules(RULES_MD.read_text(encoding="utf-8"))
95
+ return _RULES_CACHE
96
+
97
+
98
+ RULES_BY_ID: dict[str, Rule] = _load_rules()
99
+ ALL_RULE_IDS: list[str] = sorted(
100
+ RULES_BY_ID.keys(),
101
+ key=lambda s: tuple(int(p) for p in s.split(".")),
102
+ )
103
+
104
+
105
+ def build_rules_digest(rule_ids: list[str]) -> str:
106
+ """Digest markdown compact des règles demandées (IDs inconnus ignorés)."""
107
+ if not rule_ids:
108
+ return ""
109
+ parts: list[str] = []
110
+ for rid in rule_ids:
111
+ rule = RULES_BY_ID.get(rid)
112
+ if rule is None:
113
+ continue
114
+ parts.append(f"### Règle {rule['id']} — {rule['title']}")
115
+ if rule.get("bad"):
116
+ parts.append("❌ FAUTIF :")
117
+ parts.append(f"```\n{rule['bad']}\n```")
118
+ if rule.get("good"):
119
+ parts.append("✅ CORRECT :")
120
+ parts.append(f"```\n{rule['good']}\n```")
121
+ if rule.get("why"):
122
+ parts.append(f"→ {' '.join(rule['why'].split())}")
123
+ parts.append("")
124
+ return "\n".join(parts).rstrip() + "\n"
125
+
126
+
127
+ # Règles vérifiables sur le texte assemblé seul (pas d'exec) — passe d'audit.
128
+ AUDIT_RULES_ALWAYS: list[str] = [
129
+ "2.1", # :id: vide en première ligne
130
+ "3.1", # un seul bloc Python principal
131
+ "6.1", # pas d'appels **kwargs dans {{...}}
132
+ "6.2", # pas de pxsl_format_number(**kwargs) dans {{...}}
133
+ "6.3", # variables d'affichage pré-calculées
134
+ "7.1", # pas de concaténation signe + valeur
135
+ "9.1", # paragraphes contextuels hors questionStatement
136
+ "9.4", # pas de doublons d'énoncés
137
+ "11.5", # plt.show() (pas savefig)
138
+ ]
app/llm/__init__.py ADDED
File without changes
app/llm/client.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Client LLM OpenRouter — appels texte (+ multimodal) avec retries et tracking
3
+ des coûts. Fusion de l'ancien utils/llm_client.py et de la variante
4
+ « reasoning » (utils/llm_client_with_reasoning.py, jamais branchée) : le
5
+ raisonnement est désormais un simple paramètre `reasoning=` contrôlé par
6
+ config.USE_REASONING.
7
+ """
8
+
9
+ import logging
10
+ import os
11
+ import random
12
+ import time
13
+ from typing import Optional, Tuple
14
+
15
+ import requests
16
+
17
+ from app.config import AVAILABLE_MODELS, REASONING_CONFIG
18
+ from app.llm.cost import get_cost_tracker, CostTracker
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+ SYSTEM_MSG = "Vous êtes un assistant pour la génération d'exercices MystMarkdown dynamiques."
23
+
24
+
25
+ class LLMClient:
26
+ """Client pour les appels LLM via OpenRouter avec tracking des coûts."""
27
+
28
+ def __init__(self, track_costs: bool = True):
29
+ self.api_key = os.getenv("OPENROUTER_API_KEY", "")
30
+ if not self.api_key:
31
+ raise ValueError("OPENROUTER_API_KEY not found in environment variables")
32
+
33
+ self.base_url = "https://openrouter.ai/api/v1/chat/completions"
34
+ self.headers = {
35
+ "Authorization": f"Bearer {self.api_key}",
36
+ "HTTP-Referer": "http://localhost:5000",
37
+ "Content-Type": "application/json",
38
+ }
39
+ self.max_retries = 3
40
+ self.retry_delay = 2
41
+ self.track_costs = track_costs
42
+ self._cost_tracker: Optional[CostTracker] = None
43
+
44
+ @property
45
+ def cost_tracker(self) -> CostTracker:
46
+ if self._cost_tracker is None:
47
+ self._cost_tracker = get_cost_tracker()
48
+ return self._cost_tracker
49
+
50
+ def call_llm(self, prompt: str, model_idx: int, temperature: float = 0.0,
51
+ max_tokens: int = 4096, system_prompt: str = SYSTEM_MSG,
52
+ reasoning: bool = False) -> str:
53
+ """Appel LLM standard avec gestion des erreurs et retry."""
54
+ model = AVAILABLE_MODELS.get(model_idx)
55
+ if model is None:
56
+ raise ValueError(f"model_idx {model_idx} inexistant dans AVAILABLE_MODELS")
57
+
58
+ payload = {
59
+ "model": model,
60
+ "temperature": temperature,
61
+ "max_tokens": max_tokens,
62
+ "messages": [
63
+ {"role": "system", "content": system_prompt},
64
+ {"role": "user", "content": prompt},
65
+ ],
66
+ }
67
+ if reasoning:
68
+ payload["reasoning"] = dict(REASONING_CONFIG)
69
+
70
+ content, generation_id = self._make_request(payload)
71
+
72
+ if self.track_costs and generation_id:
73
+ self.cost_tracker.track_cost(
74
+ generation_id=generation_id,
75
+ model=model,
76
+ is_image=False,
77
+ prompt=prompt,
78
+ response=content,
79
+ )
80
+ return content
81
+
82
+ def call_llm_multimodal(self, image_b64: str, prompt: str, model_idx: int,
83
+ temperature: float = 0.0, max_tokens: int = 4096,
84
+ system_prompt: str = SYSTEM_MSG) -> str:
85
+ """Appel LLM multimodal avec image."""
86
+ model = AVAILABLE_MODELS.get(model_idx)
87
+ if model is None:
88
+ raise ValueError(f"model_idx {model_idx} inexistant dans AVAILABLE_MODELS")
89
+
90
+ payload = {
91
+ "model": model,
92
+ "temperature": temperature,
93
+ "max_tokens": max_tokens,
94
+ "messages": [
95
+ {"role": "system", "content": system_prompt},
96
+ {"role": "user", "content": [
97
+ {"type": "text", "text": prompt},
98
+ {"type": "image_url", "image_url": f"data:image/png;base64,{image_b64}"},
99
+ ]},
100
+ ],
101
+ }
102
+ content, generation_id = self._make_request(payload, is_multimodal=True)
103
+
104
+ if self.track_costs and generation_id:
105
+ self.cost_tracker.track_cost(
106
+ generation_id=generation_id,
107
+ model=model,
108
+ is_image=True,
109
+ prompt=prompt,
110
+ response=content,
111
+ )
112
+ return content
113
+
114
+ def _make_request(self, payload: dict, is_multimodal: bool = False) -> Tuple[str, Optional[str]]:
115
+ """Requête POST avec retries (backoff exponentiel + jitter, gestion 429)."""
116
+ for attempt in range(self.max_retries):
117
+ try:
118
+ resp = requests.post(self.base_url, json=payload, headers=self.headers, timeout=180)
119
+
120
+ if resp.status_code == 429:
121
+ wait = self.retry_delay * (2 ** attempt) + random.uniform(0, 5)
122
+ logger.warning("Rate-limited (%s) ; attente %.1fs (retry %d/%d)",
123
+ "multimodal" if is_multimodal else "standard",
124
+ wait, attempt + 1, self.max_retries)
125
+ time.sleep(wait)
126
+ continue
127
+
128
+ resp.raise_for_status()
129
+ data = resp.json()
130
+
131
+ if "error" in data:
132
+ raise RuntimeError(f"API error : {data['error']}")
133
+
134
+ content = data["choices"][0]["message"]["content"]
135
+ generation_id = data.get("id")
136
+ return content, generation_id
137
+
138
+ except (requests.RequestException, RuntimeError) as e:
139
+ if attempt == self.max_retries - 1:
140
+ raise
141
+ wait = self.retry_delay * (2 ** attempt) + random.uniform(0, 5)
142
+ logger.warning("Erreur LLM : %s — retry dans %.1fs", e, wait)
143
+ time.sleep(wait)
144
+
145
+ raise RuntimeError("Échec après plusieurs tentatives")
146
+
147
+
148
+ _llm_client: Optional[LLMClient] = None
149
+
150
+
151
+ def get_llm_client() -> LLMClient:
152
+ global _llm_client
153
+ if _llm_client is None:
154
+ _llm_client = LLMClient()
155
+ return _llm_client
156
+
157
+
158
+ def process_with_openrouter(prompt: str, model_idx: int, temperature: float = 0.0,
159
+ max_tokens: int = 4096, image_b64: str = None,
160
+ system_prompt: str = SYSTEM_MSG, reasoning: bool = False) -> str:
161
+ """Point d'entrée unique du pipeline pour tous les appels LLM."""
162
+ if image_b64:
163
+ return get_llm_client().call_llm_multimodal(
164
+ image_b64, prompt, model_idx, temperature, max_tokens, system_prompt)
165
+ return get_llm_client().call_llm(
166
+ prompt, model_idx, temperature, max_tokens, system_prompt, reasoning=reasoning)
app/llm/cost.py ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Suivi des coûts des appels OpenRouter (ex utils/cost_estimator.py).
3
+ Coûts RÉELS récupérés via GET /api/v1/generation?id=… (tokens + coût exacts) ;
4
+ estimation len//4 utilisée uniquement en fallback temporaire, remplacée dès
5
+ que la réponse de l'API arrive.
6
+ """
7
+
8
+ import logging
9
+ import os
10
+ import threading
11
+ import time
12
+ from dataclasses import dataclass, field
13
+ from datetime import datetime
14
+ from typing import Any, Dict, Optional
15
+
16
+ import requests
17
+
18
+ from app.config import MODEL_PRICING
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+ IMAGE_COST_PER_IMAGE = 0.002 # ~$0.002 par image pour la plupart des modèles
23
+
24
+
25
+ @dataclass
26
+ class CostRecord:
27
+ """Enregistrement d'un coût pour une génération."""
28
+ generation_id: str
29
+ model: str
30
+ timestamp: datetime
31
+ input_tokens: int = 0
32
+ output_tokens: int = 0
33
+ total_cost: float = 0.0
34
+ is_estimated: bool = True
35
+ is_image: bool = False
36
+ raw_stats: Dict = field(default_factory=dict)
37
+
38
+
39
+ class CostEstimator:
40
+ """Estime et enregistre les coûts des appels LLM."""
41
+
42
+ def __init__(self):
43
+ self.actual_costs: Dict[str, CostRecord] = {}
44
+ self.estimated_costs: Dict[str, CostRecord] = {}
45
+ self.session_total: float = 0.0
46
+ self.session_start: datetime = datetime.now()
47
+ self._lock = threading.Lock()
48
+
49
+ def estimate_tokens(self, text: str) -> int:
50
+ """Approximation ~4 caractères/token (fallback uniquement)."""
51
+ if not text:
52
+ return 0
53
+ return max(1, len(text) // 4)
54
+
55
+ def get_model_pricing(self, model: str) -> Dict[str, float]:
56
+ return MODEL_PRICING.get(model, {"input": 1.0, "output": 3.0})
57
+
58
+ def estimate_cost(self, model: str, prompt: str, response: str,
59
+ is_image: bool = False) -> CostRecord:
60
+ input_tokens = self.estimate_tokens(prompt)
61
+ output_tokens = self.estimate_tokens(response)
62
+ pricing = self.get_model_pricing(model)
63
+ total_cost = (
64
+ (input_tokens / 1_000_000) * pricing["input"]
65
+ + (output_tokens / 1_000_000) * pricing["output"]
66
+ )
67
+ if is_image:
68
+ total_cost += IMAGE_COST_PER_IMAGE
69
+
70
+ record = CostRecord(
71
+ generation_id=f"est_{int(time.time() * 1000)}",
72
+ model=model,
73
+ timestamp=datetime.now(),
74
+ input_tokens=input_tokens,
75
+ output_tokens=output_tokens,
76
+ total_cost=total_cost,
77
+ is_estimated=True,
78
+ is_image=is_image,
79
+ )
80
+ with self._lock:
81
+ self.estimated_costs[record.generation_id] = record
82
+ self.session_total += total_cost
83
+ return record
84
+
85
+ def record_actual_cost(self, model: str, generation_id: str,
86
+ stats: Dict, is_image: bool = False) -> bool:
87
+ try:
88
+ usage = stats.get("usage", stats.get("data", {}))
89
+ input_tokens = usage.get("prompt_tokens", 0) or usage.get("tokens_prompt", 0)
90
+ output_tokens = usage.get("completion_tokens", 0) or usage.get("tokens_completion", 0)
91
+ total_cost = (
92
+ stats.get("total_cost")
93
+ or stats.get("cost")
94
+ or usage.get("total_cost")
95
+ or 0.0
96
+ )
97
+ if total_cost == 0 and (input_tokens > 0 or output_tokens > 0):
98
+ pricing = self.get_model_pricing(model)
99
+ total_cost = (
100
+ (input_tokens / 1_000_000) * pricing["input"]
101
+ + (output_tokens / 1_000_000) * pricing["output"]
102
+ )
103
+ if is_image:
104
+ total_cost += IMAGE_COST_PER_IMAGE
105
+
106
+ record = CostRecord(
107
+ generation_id=generation_id,
108
+ model=model,
109
+ timestamp=datetime.now(),
110
+ input_tokens=input_tokens,
111
+ output_tokens=output_tokens,
112
+ total_cost=total_cost,
113
+ is_estimated=False,
114
+ is_image=is_image,
115
+ raw_stats=stats,
116
+ )
117
+ with self._lock:
118
+ # Remplacer l'estimation provisoire la plus proche dans le temps.
119
+ for est_id, est_record in list(self.estimated_costs.items()):
120
+ if est_record.model == model and abs(
121
+ (est_record.timestamp - record.timestamp).total_seconds()
122
+ ) < 60:
123
+ del self.estimated_costs[est_id]
124
+ self.session_total -= est_record.total_cost
125
+ break
126
+ self.actual_costs[generation_id] = record
127
+ self.session_total += total_cost
128
+ return True
129
+
130
+ except (KeyError, TypeError, ValueError) as e:
131
+ logger.warning("Enregistrement du coût réel impossible : %s", e)
132
+ return False
133
+
134
+ def get_session_summary(self) -> Dict[str, Any]:
135
+ with self._lock:
136
+ costs_by_model: Dict[str, Dict] = {}
137
+ for record in list(self.actual_costs.values()) + list(self.estimated_costs.values()):
138
+ entry = costs_by_model.setdefault(record.model, {
139
+ "requests": 0, "input_tokens": 0, "output_tokens": 0, "total_cost": 0.0,
140
+ })
141
+ entry["requests"] += 1
142
+ entry["input_tokens"] += record.input_tokens
143
+ entry["output_tokens"] += record.output_tokens
144
+ entry["total_cost"] += record.total_cost
145
+
146
+ return {
147
+ "session_start": self.session_start.isoformat(),
148
+ "total_requests": len(self.actual_costs) + len(self.estimated_costs),
149
+ "actual_costs_count": len(self.actual_costs),
150
+ "estimated_costs_count": len(self.estimated_costs),
151
+ "total_cost_usd": round(self.session_total, 6),
152
+ "total_cost_eur": round(self.session_total * 0.92, 6),
153
+ "costs_by_model": costs_by_model,
154
+ }
155
+
156
+ def reset_session(self):
157
+ with self._lock:
158
+ self.actual_costs.clear()
159
+ self.estimated_costs.clear()
160
+ self.session_total = 0.0
161
+ self.session_start = datetime.now()
162
+
163
+
164
+ class CostTracker:
165
+ """Tracker de coûts avec récupération asynchrone des stats réelles."""
166
+
167
+ def __init__(self, api_key: str = None):
168
+ self.api_key = api_key or os.getenv("OPENROUTER_API_KEY")
169
+ self.cost_estimator = CostEstimator()
170
+ self.base_url = "https://openrouter.ai/api/v1"
171
+ self._pending_fetches: Dict[str, threading.Thread] = {}
172
+
173
+ def fetch_generation_stats(self, generation_id: str) -> Optional[Dict]:
174
+ """Stats réelles (tokens + coût) d'une génération via l'API OpenRouter."""
175
+ if not generation_id:
176
+ return None
177
+ try:
178
+ headers = {
179
+ "Authorization": f"Bearer {self.api_key}",
180
+ "Content-Type": "application/json",
181
+ }
182
+ url = f"{self.base_url}/generation?id={generation_id}"
183
+ response = requests.get(url, headers=headers, timeout=10)
184
+ if response.status_code == 200:
185
+ return response.json()
186
+ logger.debug("API stats %s : %s", response.status_code, response.text[:200])
187
+ return None
188
+ except requests.RequestException as e:
189
+ logger.debug("Récupération des stats impossible : %s", e)
190
+ return None
191
+
192
+ def _schedule_generation_stats_fetch(self, generation_id: str, model: str, is_image: bool):
193
+ """Récupération asynchrone différée (les stats arrivent avec ~2 s de retard)."""
194
+ def fetch_delayed():
195
+ time.sleep(2)
196
+ try:
197
+ stats = self.fetch_generation_stats(generation_id)
198
+ if stats:
199
+ self.cost_estimator.record_actual_cost(
200
+ model=model, generation_id=generation_id,
201
+ stats=stats, is_image=is_image,
202
+ )
203
+ finally:
204
+ self._pending_fetches.pop(generation_id, None)
205
+
206
+ thread = threading.Thread(target=fetch_delayed, daemon=True)
207
+ self._pending_fetches[generation_id] = thread
208
+ thread.start()
209
+
210
+ def track_cost(self, generation_id: str, model: str, is_image: bool,
211
+ prompt: str = "", response: str = "") -> bool:
212
+ """Coût réel si dispo immédiatement, sinon estimation + fetch async."""
213
+ try:
214
+ stats = self.fetch_generation_stats(generation_id)
215
+ if stats and ("data" in stats or "cost" in stats
216
+ or "total_cost" in stats or "usage" in stats):
217
+ if self.cost_estimator.record_actual_cost(
218
+ model=model, generation_id=generation_id,
219
+ stats=stats, is_image=is_image,
220
+ ):
221
+ return True
222
+ except Exception as e:
223
+ logger.debug("Fetch immédiat du coût raté : %s", e)
224
+
225
+ self._schedule_generation_stats_fetch(generation_id, model, is_image)
226
+ if generation_id not in self.cost_estimator.actual_costs:
227
+ self.cost_estimator.estimate_cost(
228
+ model=model, prompt=prompt, response=response, is_image=is_image)
229
+ return False
230
+
231
+ def get_summary(self) -> Dict[str, Any]:
232
+ return self.cost_estimator.get_session_summary()
233
+
234
+ def reset(self):
235
+ self.cost_estimator.reset_session()
236
+
237
+
238
+ _cost_tracker: Optional[CostTracker] = None
239
+
240
+
241
+ def get_cost_tracker() -> CostTracker:
242
+ global _cost_tracker
243
+ if _cost_tracker is None:
244
+ _cost_tracker = CostTracker()
245
+ return _cost_tracker
246
+
247
+
248
+ def cost_snapshot() -> dict:
249
+ """Photo des totaux de session — l'orchestrateur fait before/after pour
250
+ attribuer un coût par job (mono-poste : pas de jobs LLM concurrents)."""
251
+ s = get_cost_tracker().get_summary()
252
+ return {"usd": s["total_cost_usd"], "requests": s["total_requests"]}
253
+
254
+
255
+ def cost_delta(before: dict) -> dict:
256
+ """Coût (USD/EUR) et nb de requêtes depuis `before` (cf. cost_snapshot)."""
257
+ after = cost_snapshot()
258
+ usd = max(0.0, round(after["usd"] - before["usd"], 6))
259
+ return {
260
+ "usd": usd,
261
+ "eur": round(usd * 0.92, 6),
262
+ "requests": after["requests"] - before["requests"],
263
+ }
app/pipeline/__init__.py ADDED
File without changes
app/pipeline/analyze.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ analyze.py
3
+ ──────────
4
+ Étape 0 du pipeline : analyse LLM (variables/règles/invariants), retriever de
5
+ notions, RAG fonctions — les trois sont INDÉPENDANTS et lancés en parallèle
6
+ (gain de latence sans aucun impact sur la correction).
7
+
8
+ Corrige au passage (vs v1) :
9
+ • model_idx=2 codé en dur → ANALYSIS_MODEL_IDX (None = modèle utilisateur) ;
10
+ • typo needs_matplolib → needs_matplotlib (les deux lues en transition,
11
+ une seule orthographe en sortie) ;
12
+ • top_k=3 → RAG_TOP_K (10).
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import logging
19
+ from concurrent.futures import ThreadPoolExecutor
20
+
21
+ from app.config import ANALYSIS_MODEL_IDX, NOTIONS_XLSX, RAG_EMBEDDING_MODEL, RAG_TOP_K
22
+ from app.knowledge.rules_digest import ALL_RULE_IDS, RULES_BY_ID
23
+ from app.llm.client import process_with_openrouter
24
+ from app.pipeline.postprocess import strip_fences
25
+ from app.pipeline.prompts import STEP1_PROMPT
26
+ from app.rag.functions import retrieve_functions_context
27
+ from app.rag.notions import enrich_exercise_with_notions
28
+
29
+ logger = logging.getLogger(__name__)
30
+
31
+
32
+ def _rules_menu() -> str:
33
+ return "\n".join(f" - {rid} — {RULES_BY_ID[rid]['title']}" for rid in ALL_RULE_IDS)
34
+
35
+
36
+ _ANALYSIS_FALLBACK = {
37
+ "exercise_type": "Général",
38
+ "exercise_title": "Exercice",
39
+ "suggested_concepts": [],
40
+ "nb_questions": 2,
41
+ "variables": [],
42
+ "needs_fraction": False,
43
+ "needs_sympy": False,
44
+ "needs_numpy": False,
45
+ "needs_matplotlib": False,
46
+ "mathematical_structure": "Non déterminé",
47
+ "target_rules": [],
48
+ "property_constraints": [],
49
+ "has_validated_solution_in_input": False,
50
+ }
51
+
52
+
53
+ def _parse_analysis(raw: str, content: str) -> dict:
54
+ try:
55
+ analysis = json.loads(strip_fences(raw))
56
+ if not isinstance(analysis, dict):
57
+ raise json.JSONDecodeError("not a dict", raw, 0)
58
+ except json.JSONDecodeError:
59
+ logger.warning("Analyse LLM : JSON invalide — fallback générique utilisé.")
60
+ analysis = dict(_ANALYSIS_FALLBACK)
61
+ analysis["exercise_summary"] = content[:300]
62
+ # Transition typo v1 : accepter needs_matplolib, ne sortir QUE needs_matplotlib.
63
+ if "needs_matplolib" in analysis:
64
+ analysis["needs_matplotlib"] = bool(
65
+ analysis.get("needs_matplotlib") or analysis.pop("needs_matplolib")
66
+ )
67
+ analysis.setdefault("needs_matplotlib", False)
68
+ return analysis
69
+
70
+
71
+ def run_analysis_phase(content: str, model_idx: int) -> tuple[dict, str, str, str]:
72
+ """
73
+ Lance EN PARALLÈLE : analyse LLM, notions, RAG fonctions.
74
+
75
+ Retourne (analysis, notions_ctx, lists_of_notions, functions_ctx).
76
+ Une erreur sur notions/RAG est dégradée en contexte vide (warning loggé) ;
77
+ une erreur sur l'analyse LLM est propagée (le pipeline n'a pas de sens sans).
78
+ """
79
+ analysis_model = ANALYSIS_MODEL_IDX if ANALYSIS_MODEL_IDX is not None else model_idx
80
+
81
+ with ThreadPoolExecutor(max_workers=3, thread_name_prefix="analyse") as pool:
82
+ f_analysis = pool.submit(
83
+ process_with_openrouter,
84
+ prompt=STEP1_PROMPT.format(content=content, available_rules_menu=_rules_menu()),
85
+ model_idx=analysis_model,
86
+ max_tokens=6096,
87
+ )
88
+ f_notions = pool.submit(enrich_exercise_with_notions, content, xlsx_path=NOTIONS_XLSX)
89
+ f_functions = pool.submit(
90
+ retrieve_functions_context,
91
+ exercise=content,
92
+ embedding_model=RAG_EMBEDDING_MODEL,
93
+ top_k=RAG_TOP_K,
94
+ force_rebuild=False,
95
+ )
96
+
97
+ raw_analysis = f_analysis.result()
98
+
99
+ try:
100
+ notions_ctx, lists_of_notions = f_notions.result()
101
+ except Exception as e:
102
+ logger.warning("Retriever de notions en échec (%s) — contexte vide.", e)
103
+ notions_ctx, lists_of_notions = "", ""
104
+
105
+ try:
106
+ functions_ctx = f_functions.result()["catalogue"]
107
+ except Exception as e:
108
+ logger.warning("RAG fonctions en échec (%s) — catalogue vide.", e)
109
+ functions_ctx = ""
110
+
111
+ analysis = _parse_analysis(raw_analysis, content)
112
+ logger.info("Analyse : type=%s, %d variables, %d règles ciblées",
113
+ analysis.get("exercise_type"), len(analysis.get("variables") or []),
114
+ len(analysis.get("target_rules") or []))
115
+ return analysis, notions_ctx, lists_of_notions, functions_ctx
app/pipeline/audit.py ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ audit.py
3
+ ────────
4
+ Passe d'audit LLM (≤ MAX_AUDIT_ITERATIONS) + filet de sécurité des patches.
5
+ Code déplacé depuis routes/pythonise_routes_v2.py avec deux corrections :
6
+ • un patch sûr est appliqué à TOUTES les occurrences identiques de
7
+ `location` (la v1 ne corrigeait que la première — un problème répété
8
+ subsistait N-1 fois) ;
9
+ • gestion d'erreurs ciblée (plus d'`except (json.JSONDecodeError, Exception)`).
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import logging
16
+ import re
17
+ from typing import Callable, Optional
18
+
19
+ from app.config import MAX_AUDIT_ITERATIONS
20
+ from app.knowledge.rules_digest import AUDIT_RULES_ALWAYS, build_rules_digest
21
+ from app.llm.client import process_with_openrouter
22
+ from app.pipeline.postprocess import insert_python_lines, strip_fences
23
+ from app.pipeline.prompts import STEP_AUDIT_PROMPT, SYSTEM_PROMPT
24
+
25
+ logger = logging.getLogger(__name__)
26
+
27
+
28
+ # ─────────────────────────────────────────────────────────────────────────────
29
+ # Filet de sécurité des patches (déplacé tel quel, noms inchangés)
30
+ # ─────────────────────────────────────────────────────────────────────────────
31
+
32
+ _KNOWN_FREE_NAMES = frozenset({
33
+ "True", "False", "None", "and", "or", "not", "in", "is", "if", "else",
34
+ "elif", "for", "while", "def", "class", "return", "lambda", "yield",
35
+ "with", "as", "from", "import", "pass", "break", "continue", "try",
36
+ "except", "finally", "raise", "global", "nonlocal", "assert", "del",
37
+ "self", "cls",
38
+ "pi", "e", "oo", "abs", "min", "max", "sum", "range", "len", "int",
39
+ "float", "str", "bool", "list", "tuple", "dict", "set", "round", "pow",
40
+ "all", "any", "map", "filter", "zip", "enumerate", "sorted", "reversed",
41
+ "print", "isinstance", "type", "repr", "hash",
42
+ "x", "y", "z", "t", "n", "config_standard",
43
+ })
44
+
45
+
46
+ def _patch_introduces_unbound_name(
47
+ myst_exercise: str,
48
+ location: str,
49
+ fix: str,
50
+ python_insert: Optional[str],
51
+ ) -> Optional[str]:
52
+ """Nom INJECTÉ ({{var}}) introduit par `fix` qui ne serait lié nulle part
53
+ après patch (NameError au rendu). None = sûr sur ce critère.
54
+ Volontairement limité aux placeholders : les autres mots d'un patch
55
+ markdown sont de la prose/du LaTeX, pas des variables Python (la v2 du
56
+ filet flaguait à tort `id`, `f`, `align`… dans des patches purement texte)."""
57
+ fix_names = set(re.findall(r"\{\{\s*([a-zA-Z_]\w*)\s*\}\}", fix))
58
+ loc_names = set(re.findall(r"\{\{\s*([a-zA-Z_]\w*)\s*\}\}", location))
59
+ new_names = (fix_names - loc_names) - _KNOWN_FREE_NAMES
60
+ if not new_names:
61
+ return None
62
+
63
+ after_patch = myst_exercise.replace(location, fix)
64
+ if python_insert:
65
+ after_patch += "\n" + python_insert
66
+
67
+ for name in new_names:
68
+ patterns = (
69
+ rf"\b{re.escape(name)}\s*=(?!=)",
70
+ rf"\bdef\s+{re.escape(name)}\b",
71
+ rf"\bclass\s+{re.escape(name)}\b",
72
+ rf"\bfor\s+{re.escape(name)}\b",
73
+ rf"\bas\s+{re.escape(name)}\b",
74
+ rf"\bimport\s+(?:\w+\s*,\s*)*{re.escape(name)}\b",
75
+ rf"\bfrom\s+[\w.]+\s+import\s+(?:[^,\n]*,\s*)*{re.escape(name)}\b",
76
+ rf"\bdef\s+\w+\([^)]*\b{re.escape(name)}\b[^)]*\)",
77
+ )
78
+ if not any(re.search(p, after_patch) for p in patterns):
79
+ return name
80
+ return None
81
+
82
+
83
+ def _is_patch_safe(
84
+ myst_exercise: str,
85
+ location: str,
86
+ fix: str,
87
+ python_insert: Optional[str] = None,
88
+ ) -> tuple[bool, str]:
89
+ """Validation défensive avant application d'un patch d'audit."""
90
+ # 1) Alias d'import supprimé mais encore utilisé.
91
+ alias_re = re.compile(r"\bimport\b[^\n]*?\bas\s+(\w+)")
92
+ dropped = set(alias_re.findall(location)) - set(alias_re.findall(fix))
93
+ if dropped:
94
+ rest = myst_exercise.replace(location, "", 1)
95
+ for alias in dropped:
96
+ if re.search(rf"\b{re.escape(alias)}\s*\(", rest):
97
+ return False, f"Alias `{alias}` est utilisé ailleurs dans le code — patch refusé."
98
+
99
+ # 1bis) Import supprimé mais encore référencé.
100
+ def _extract_imported_names(text: str) -> set[str]:
101
+ names: set[str] = set()
102
+ for m in re.finditer(r"^\s*import\s+([\w.]+)(?:\s+as\s+(\w+))?", text, re.MULTILINE):
103
+ names.add(m.group(2) or m.group(1).split(".")[0])
104
+ for m in re.finditer(r"^\s*from\s+[\w.]+\s+import\s+(.+?)\s*$", text, re.MULTILINE):
105
+ for piece in m.group(1).split(","):
106
+ am = re.match(r"^(\w+)(?:\s+as\s+(\w+))?$", piece.strip())
107
+ if am:
108
+ names.add(am.group(2) or am.group(1))
109
+ return names
110
+
111
+ dropped_imports = _extract_imported_names(location) - _extract_imported_names(fix)
112
+ if dropped_imports:
113
+ rest = myst_exercise.replace(location, fix, 1)
114
+ for name in dropped_imports:
115
+ if re.search(rf"\b{re.escape(name)}\b(?:\s*[(.])", rest):
116
+ return False, (f"L'import `{name}` est encore utilisé ailleurs après le patch "
117
+ "— refus pour éviter une NameError au runtime.")
118
+
119
+ # 2) Suppression de globals().
120
+ if "globals()" in location and "globals()" not in fix:
121
+ return False, "Le patch supprimerait `globals()` (requis en fin de bloc python)."
122
+
123
+ # 2bis) Règle 6.4 — **config_standard sur un helper PyxiScience (réservé à
124
+ # sympy.latex). Liste alignée sur le catalogue curé app/knowledge.
125
+ _PYXISCIENCE_HELPERS = (
126
+ "pxsl_format_number", "pxsl_res_num", "pxsl_matrix", "pxsl_pow",
127
+ "pxsl_latex_coefficient", "pxsl_par", "pxsl_mult", "pxsl_choose_udv", "lc",
128
+ "pxsl_latex", "pxsl_sign", "pxsl_latex_with_formatting", "pxsl_Rational",
129
+ "pxsl_sum_matrix", "pxsl_prod_matrix", "pxsl_prod_scalar_matrix",
130
+ "pxsl_ax", "pxsl_system_lin", "pxsl_double_matrix", "pxsl_lines_op",
131
+ "pxsl_resol_system", "pxsl_pow_matrix", "pxsl_law", "pxsl_moment",
132
+ "pxsl_scalar_product", "pxsl_sum_vector", "pxs_explain_IBP",
133
+ )
134
+
135
+ def _splat_pattern(name: str) -> str:
136
+ return (rf"\b{re.escape(name)}\s*\("
137
+ r"(?:[^()]|\([^()]*\))*"
138
+ r"\*\*\s*config_standard"
139
+ r"(?:[^()]|\([^()]*\))*\)")
140
+
141
+ for helper in _PYXISCIENCE_HELPERS:
142
+ pat = _splat_pattern(helper)
143
+ if re.search(pat, fix) and not re.search(pat, location):
144
+ return False, (f"Le patch ajoute `**config_standard` à `{helper}(...)` — "
145
+ "ce helper PyxiScience ne l'accepte pas et plante (règle 6.4). "
146
+ "Réserve `**config_standard` à `sympy.latex(...)` uniquement.")
147
+
148
+ # 3) Variable jamais définie.
149
+ unbound = _patch_introduces_unbound_name(myst_exercise, location, fix, python_insert)
150
+ if unbound:
151
+ return False, (f"Le patch introduit la variable `{unbound}` qui n'est définie nulle part "
152
+ "(NameError à l'exécution). Si une définition Python est nécessaire, "
153
+ "utilise `python_insert` dans l'audit.")
154
+ return True, ""
155
+
156
+
157
+ def _replace_everywhere(text: str, location: str, fix: str) -> tuple[str, int]:
158
+ """Remplace TOUTES les occurrences de location (1 seule si fix ⊇ location,
159
+ pour éviter la ré-expansion infinie)."""
160
+ if location in fix:
161
+ return text.replace(location, fix, 1), 1
162
+ n = text.count(location)
163
+ return text.replace(location, fix), n
164
+
165
+
166
+ # ─────────────────────────────────────────────────────────────────────────────
167
+ # Boucle d'audit
168
+ # ─────────────────────────────────────────────────────────────────────────────
169
+
170
+ def run_audit(
171
+ myst_exercise: str,
172
+ step1_targets: list[str],
173
+ model_idx: int,
174
+ set_step: Optional[Callable[[str], None]] = None,
175
+ ) -> tuple[str, list[dict], list[dict]]:
176
+ """Audit LLM en boucle (≤ MAX_AUDIT_ITERATIONS). Retourne
177
+ (exercice patché, patches appliqués, warnings)."""
178
+ audit_rule_ids = list(dict.fromkeys(AUDIT_RULES_ALWAYS + step1_targets))
179
+ audit_digest = build_rules_digest(audit_rule_ids)
180
+
181
+ patches: list[dict] = []
182
+ warnings: list[dict] = []
183
+
184
+ for audit_iter in range(MAX_AUDIT_ITERATIONS):
185
+ if set_step:
186
+ set_step(f"Audit {audit_iter + 1}/{MAX_AUDIT_ITERATIONS}…")
187
+ try:
188
+ audit_raw = process_with_openrouter(
189
+ prompt=STEP_AUDIT_PROMPT.format(
190
+ audit_rules=audit_digest,
191
+ exercise=myst_exercise,
192
+ ),
193
+ model_idx=model_idx,
194
+ temperature=0.0,
195
+ max_tokens=8192,
196
+ system_prompt=SYSTEM_PROMPT,
197
+ )
198
+ except (RuntimeError, ValueError, OSError) as audit_err:
199
+ logger.warning("Appel d'audit en échec : %s", audit_err)
200
+ warnings.append({"rule": "?", "message": f"Audit pass failed: {audit_err}"})
201
+ break
202
+
203
+ try:
204
+ audit_data = json.loads(strip_fences(audit_raw))
205
+ except json.JSONDecodeError:
206
+ warnings.append({
207
+ "rule": "?",
208
+ "message": "Audit LLM did not return valid JSON; skipping further iterations.",
209
+ })
210
+ break
211
+
212
+ if audit_data.get("verdict") == "OK":
213
+ break
214
+
215
+ applied_this_iter = 0
216
+ for issue in audit_data.get("issues") or []:
217
+ if not isinstance(issue, dict):
218
+ continue
219
+ rule = str(issue.get("rule", "?"))
220
+ location = issue.get("location") or ""
221
+ fix = issue.get("fix")
222
+ python_insert = issue.get("python_insert")
223
+ can_patch = bool(issue.get("can_patch", True))
224
+ message = issue.get("message") or ""
225
+ applied = False
226
+
227
+ if (can_patch and isinstance(location, str) and isinstance(fix, str)
228
+ and location and location in myst_exercise):
229
+ safe, reason = _is_patch_safe(myst_exercise, location, fix, python_insert)
230
+ if safe:
231
+ myst_exercise, n_occ = _replace_everywhere(myst_exercise, location, fix)
232
+ applied = True
233
+ if n_occ > 1:
234
+ message += f" ({n_occ} occurrences corrigées)"
235
+ else:
236
+ warnings.append({
237
+ "rule": rule,
238
+ "location": location,
239
+ "message": f"Patch refusé par filet de sécurité : {reason} (suggestion: {message})",
240
+ })
241
+ continue
242
+
243
+ if applied and isinstance(python_insert, str) and python_insert.strip():
244
+ myst_exercise = insert_python_lines(myst_exercise, [python_insert.strip()])
245
+
246
+ if applied:
247
+ patches.append({
248
+ "rule": rule,
249
+ "location": location,
250
+ "fix": fix,
251
+ "python_insert": python_insert or None,
252
+ "message": message,
253
+ "iteration": audit_iter + 1,
254
+ })
255
+ applied_this_iter += 1
256
+ else:
257
+ warnings.append({
258
+ "rule": rule,
259
+ "location": location if isinstance(location, str) else "",
260
+ "message": message,
261
+ })
262
+
263
+ if applied_this_iter == 0:
264
+ break
265
+
266
+ return myst_exercise, patches, warnings
app/pipeline/fewshots.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ fewshots.py
3
+ ───────────
4
+ Banque de few-shots par type d'exercice, tirée des exemples pythonisés LIVRÉS
5
+ de la plateforme (Exemples d'exercices/master_all → app/knowledge/fewshots/).
6
+ Seuls des exemples VERTS au harnais sont admis comme modèles positifs.
7
+
8
+ Sélection : mots-clés sur (exercise_type + title + concepts) de l'analyse.
9
+ Injection : version ÉLAGUÉE (bloc python + énoncé + 1re question) pour
10
+ limiter le coût en contexte.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import logging
16
+ import re
17
+ from functools import lru_cache
18
+
19
+ from app.config import FEWSHOTS_DIR
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+ # Ordre = priorité (premier motif qui matche gagne).
24
+ _TYPE_KEYWORDS: list[tuple[str, str]] = [
25
+ ("figure", r"figure|graph|matplotlib|trac[ée]|courbe|repr[ée]sent|parabole.*dessin"),
26
+ ("integration", r"int[ée]gra|primitive|\bipp\b|parties"),
27
+ ("systemes", r"syst[èe]me"),
28
+ ("logexp", r"\blog\b|logarithm|exponentiel|exposant|puissance"),
29
+ ("quadratique", r"trin[ôo]me|quadrat|second degr[ée]|discriminant|racine|factoris"),
30
+ ("equations", r"[ée]quation|in[ée]quation|lin[ée]aire|affine|int[ée]r[êe]t|seuil|finance|proportion"),
31
+ ]
32
+ _DEFAULT_KEY = "equations"
33
+
34
+ _Q_BLOCK_RE = re.compile(r":::::\{question\}.*?:::::", re.DOTALL)
35
+ _PY_BLOCK_RE = re.compile(r"(?ms)^(`{3,4})\{python\}[ \t]*\n.*?\n\1[ \t]*$")
36
+
37
+
38
+ def pick_fewshot_key(analysis: dict) -> str:
39
+ """Choisit la clé de few-shot selon le type détecté par l'analyse."""
40
+ haystack = " ".join([
41
+ str(analysis.get("exercise_type", "")),
42
+ str(analysis.get("exercise_title", "")),
43
+ " ".join(str(c) for c in (analysis.get("suggested_concepts") or [])),
44
+ ]).lower()
45
+ if analysis.get("needs_matplotlib"):
46
+ return "figure"
47
+ for key, pattern in _TYPE_KEYWORDS:
48
+ if re.search(pattern, haystack):
49
+ return key
50
+ return _DEFAULT_KEY
51
+
52
+
53
+ @lru_cache(maxsize=None)
54
+ def load_fewshot(key: str) -> str:
55
+ """Few-shot élagué : bloc python + énoncé + 1re question de l'exemple
56
+ canonique. Chaîne vide si le fichier manque (le prompt reste valable)."""
57
+ path = FEWSHOTS_DIR / f"{key}.md"
58
+ if not path.exists():
59
+ logger.warning("Few-shot absent : %s", path)
60
+ return ""
61
+ text = path.read_text(encoding="utf-8")
62
+
63
+ py = _PY_BLOCK_RE.search(text)
64
+ first_q = _Q_BLOCK_RE.search(text)
65
+ if not py or not first_q:
66
+ return ""
67
+
68
+ # Énoncé = texte entre la fin du bloc python et la 1re question.
69
+ enonce = text[py.end():first_q.start()].strip()
70
+ parts = [py.group(0)]
71
+ if enonce:
72
+ parts.append(enonce)
73
+ parts.append(first_q.group(0))
74
+ return "\n\n".join(parts)
75
+
76
+
77
+ def fewshot_for(analysis: dict) -> str:
78
+ key = pick_fewshot_key(analysis)
79
+ shot = load_fewshot(key)
80
+ logger.info("Few-shot sélectionné : %s (%d caractères)", key, len(shot))
81
+ return shot or "(aucun exemple canonique disponible pour ce type)"
app/pipeline/generate.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ generate.py
3
+ ───────────
4
+ Découpage de l'exercice source (métadonnées / énoncé / segments de questions)
5
+ et génération par paires de questions (LLM). Code déplacé par blocs depuis
6
+ routes/pythonise_routes_v2.py ; les paires restent SÉQUENTIELLES (contexte
7
+ partagé : chaque appel reçoit les blocs déjà générés).
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import logging
14
+ import re
15
+ from typing import Callable, Optional
16
+
17
+ from app.config import USE_REASONING
18
+ from app.llm.client import process_with_openrouter
19
+ from app.pipeline.postprocess import (
20
+ PYTHON_FENCE_RE,
21
+ normalize_python_fences,
22
+ strip_fences,
23
+ )
24
+ from app.pipeline.prompts import STEP_PAIR_PROMPT, SYSTEM_PROMPT
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+
29
+ # ─────────────────────────────────────────────────────────────────────────────
30
+ # Découpage du source MyST
31
+ # ─────────────────────────────────────────────────────────────────────────────
32
+
33
+ def strip_python_block_from_text(text: str) -> str:
34
+ """Retire les blocs {python} d'un texte (le Python est régénéré par paire)."""
35
+ cleaned = PYTHON_FENCE_RE.sub("", text)
36
+ cleaned = re.sub(r"\n{3,}", "\n\n", cleaned)
37
+ return cleaned.strip()
38
+
39
+
40
+ def split_metadata_and_enonce(header: str) -> tuple[str, str]:
41
+ """Sépare l'en-tête en (métadonnées directives, énoncé libre)."""
42
+ lines = header.splitlines()
43
+ OPTION_RE = re.compile(r"^\s*:[A-Za-z_][\w-]*:")
44
+ DIRECTIVE_OPEN_RE = re.compile(r"^\s*(?:`{3,}|:{3,}|\\begin)")
45
+
46
+ metadata_end = 0
47
+ found_enonce = False
48
+ for i, line in enumerate(lines):
49
+ stripped = line.strip()
50
+ if not stripped:
51
+ metadata_end = i + 1
52
+ continue
53
+ if (OPTION_RE.match(line) or DIRECTIVE_OPEN_RE.match(line)
54
+ or stripped in ("}", "{")):
55
+ metadata_end = i + 1
56
+ continue
57
+ found_enonce = True
58
+ break
59
+
60
+ if not found_enonce:
61
+ return header.rstrip(), ""
62
+
63
+ while metadata_end > 0 and not lines[metadata_end - 1].strip():
64
+ metadata_end -= 1
65
+ return "\n".join(lines[:metadata_end]), "\n".join(lines[metadata_end:]).strip()
66
+
67
+
68
+ def split_original_questions(content: str) -> tuple[str, str, list[str]]:
69
+ """
70
+ Découpe l'exercice en (métadonnées, énoncé, segments de questions).
71
+ Chaque segment = [texte inter-question éventuel] + bloc :::::{question}.
72
+ Entrée non-MyST (pas de :::::{question}) → ("", content, []).
73
+ """
74
+ if ":::::{question}" not in content:
75
+ return "", content, []
76
+
77
+ first_q = content.index(":::::{question}")
78
+ metadata, enonce = split_metadata_and_enonce(content[:first_q])
79
+ enonce = strip_python_block_from_text(enonce)
80
+ body_part = content[first_q:]
81
+
82
+ pattern = re.compile(r":::::\{question\}.*?:::::", re.DOTALL)
83
+ segments: list[str] = []
84
+ last_end = 0
85
+ for m in pattern.finditer(body_part):
86
+ inter_text = strip_python_block_from_text(body_part[last_end:m.start()].strip())
87
+ segments.append(f"{inter_text}\n\n{m.group(0)}" if inter_text else m.group(0))
88
+ last_end = m.end()
89
+ return metadata, enonce, segments
90
+
91
+
92
+ def build_exercise_metadata(metadata: str, lists_of_notions: str) -> str:
93
+ """En-tête déterministe (aucun LLM) — injecte les notions à côté de
94
+ :involvedConcepts: TYPE_BAC."""
95
+ cleaned = strip_python_block_from_text(metadata)
96
+ if lists_of_notions and lists_of_notions not in cleaned:
97
+ cleaned = re.sub(
98
+ r":involvedConcepts:\s*TYPE_BAC(?![\w,])",
99
+ f":involvedConcepts: TYPE_BAC,{lists_of_notions}",
100
+ cleaned,
101
+ count=1,
102
+ )
103
+ return cleaned.rstrip()
104
+
105
+
106
+ def assemble_exercise(metadata_header: str, pair_blocks: list[str]) -> str:
107
+ """Header + blocs de paires + fence finale 5 backticks. Les fences {python}
108
+ sont normalisées à la convention plateforme (4 backticks)."""
109
+ parts = [metadata_header.rstrip()]
110
+ parts.extend(block.strip() for block in pair_blocks)
111
+ parts.append("`````")
112
+ assembled = "\n\n".join(parts)
113
+ assembled = assembled.replace("{align*}", "{equation*}")
114
+ return normalize_python_fences(assembled)
115
+
116
+
117
+ # ─────────────────────────────────────────────────────────────────────────────
118
+ # Génération par paires
119
+ # ─────────────────────────────────────────────────────────────────────────────
120
+
121
+ _LANG_DIRECTIVES = {
122
+ "fr": "Langue cible de CETTE sortie : FRANÇAIS uniquement (décimales à virgule).",
123
+ "en": "Langue cible de CETTE sortie : ANGLAIS uniquement (décimales à point).",
124
+ "both": ("Langue cible de CETTE sortie : BILINGUE — chaque prose en rôles "
125
+ "{fr}`…`{en}`…` symétriques (cf. règle bilingue ci-dessus)."),
126
+ "auto": "Langue cible : MÊME langue(s) que la source (ne traduis rien).",
127
+ }
128
+
129
+
130
+ def generate_pair_blocks(
131
+ content: str,
132
+ exercise_header: str,
133
+ enonce: str,
134
+ question_segments: list[str],
135
+ analysis: dict,
136
+ functions_ctx: str,
137
+ fewshot: str,
138
+ targeted_rules_digest: str,
139
+ property_constraints_text: str,
140
+ level: str,
141
+ model_idx: int,
142
+ lang: str = "auto",
143
+ set_step: Optional[Callable[[str], None]] = None,
144
+ ) -> list[str]:
145
+ """Boucle de génération par paires (séquentielle). Retourne les blocs."""
146
+ nb_questions = analysis.get("nb_questions", max(1, len(question_segments)))
147
+ lang_directive = _LANG_DIRECTIVES.get(lang, _LANG_DIRECTIVES["auto"])
148
+ common = dict(
149
+ analysis=json.dumps(analysis, ensure_ascii=False, indent=2),
150
+ functions=functions_ctx or "Aucune fonction spécifique détectée.",
151
+ niveau=level or "non précisé",
152
+ targeted_rules=targeted_rules_digest,
153
+ property_constraints=property_constraints_text,
154
+ fewshot=fewshot,
155
+ lang_directive=lang_directive,
156
+ nb_total=nb_questions,
157
+ )
158
+
159
+ generated: list[str] = []
160
+
161
+ if not question_segments:
162
+ # Entrée texte brut → une seule génération.
163
+ if set_step:
164
+ set_step("Génération (bloc Python + toutes les questions)…")
165
+ raw = process_with_openrouter(
166
+ prompt=STEP_PAIR_PROMPT.format(
167
+ content=content,
168
+ previous_blocks="(aucun — première génération)",
169
+ nb_current=nb_questions,
170
+ range_label=f"1–{nb_questions}",
171
+ current_segment=content,
172
+ **common,
173
+ ),
174
+ model_idx=model_idx,
175
+ max_tokens=30000,
176
+ system_prompt=SYSTEM_PROMPT,
177
+ reasoning=USE_REASONING,
178
+ )
179
+ return [strip_fences(raw)]
180
+
181
+ pairs = [question_segments[i: i + 2] for i in range(0, len(question_segments), 2)]
182
+ for pair_idx, pair in enumerate(pairs):
183
+ q_start = pair_idx * 2 + 1
184
+ q_end = min(pair_idx * 2 + len(pair), nb_questions)
185
+ range_label = str(q_start) if q_start == q_end else f"{q_start}–{q_end}"
186
+ if set_step:
187
+ set_step(f"Génération questions {range_label} / {nb_questions}…")
188
+
189
+ current_segment = "\n\n".join(pair)
190
+ if pair_idx == 0 and enonce:
191
+ current_segment = enonce + "\n\n" + current_segment
192
+
193
+ raw_pair = process_with_openrouter(
194
+ prompt=STEP_PAIR_PROMPT.format(
195
+ content=exercise_header,
196
+ previous_blocks=("\n\n".join(generated) if generated
197
+ else "(aucun — première paire)"),
198
+ nb_current=len(pair),
199
+ range_label=range_label,
200
+ current_segment=current_segment,
201
+ **common,
202
+ ),
203
+ model_idx=model_idx,
204
+ temperature=0.4,
205
+ max_tokens=16384,
206
+ system_prompt=SYSTEM_PROMPT,
207
+ reasoning=USE_REASONING,
208
+ )
209
+ generated.append(strip_fences(raw_pair))
210
+
211
+ return generated
app/pipeline/orchestrator.py ADDED
@@ -0,0 +1,406 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ orchestrator.py
3
+ ───────────────
4
+ Chef d'orchestre du pipeline pour UN exercice. (Le job/threading vit dans
5
+ server.py ; le mode batch boucle simplement sur run_exercise.)
6
+
7
+ Ordre des étapes :
8
+ 1. Analyse + notions + RAG fonctions (PARALLÈLE — indépendants)
9
+ 2. Génération par paires (séquentielle, contexte partagé)
10
+ 3. Post-traitements déterministes (config_standard, assemblage 4-backticks,
11
+ dédoublonnage)
12
+ 4. Substitution des solutions validées (si présentes dans la source)
13
+ 5. Audit LLM (≤ 2 itérations, patches toutes-occurrences sécurisés)
14
+ 6. Post-traitements déterministes finaux : auto-lift GÉNÉRALISÉ des
15
+ injections non nues, renommage underscores, auto-correctif $+chiffre,
16
+ :id: vide, diff solutions, décimales (langue), invariants multi-seed,
17
+ contrôles matplotlib
18
+ 7. Langue cible (déterministe ou LLM masqué)
19
+ 8. PORTE HARNAIS (HARNESS_GATE_SEEDS graines) + 1 boucle de réparation LLM
20
+ max ; verdict exposé dans le résultat.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import json
26
+ import logging
27
+ import time
28
+ from typing import Callable, Optional
29
+
30
+ from app.config import (
31
+ HARNESS_GATE_SEEDS,
32
+ HARNESS_REPAIR_MAX,
33
+ MULTI_SEED_NUM,
34
+ )
35
+ from app.knowledge.rules_digest import build_rules_digest
36
+ from app.llm.client import process_with_openrouter
37
+ from app.llm.cost import cost_delta, cost_snapshot
38
+ from app.rag.catalogue import catalogue_for
39
+ from app.pipeline import postprocess as pp
40
+ from app.pipeline.analyze import run_analysis_phase
41
+ from app.pipeline.audit import run_audit
42
+ from app.pipeline.fewshots import fewshot_for
43
+ from app.pipeline.generate import (
44
+ assemble_exercise,
45
+ build_exercise_metadata,
46
+ generate_pair_blocks,
47
+ split_original_questions,
48
+ )
49
+ from app.pipeline.prompts import REPAIR_PROMPT, SYSTEM_PROMPT, TRANSLATE_CONSTRAINTS_PROMPT
50
+ from app.pipeline.solutions import replace_gen_solutions_with_source
51
+ from app.pipeline.translate import ensure_language
52
+ from app.validation import harness
53
+ from app.validation.sandbox import (
54
+ dynamic_check_matplotlib,
55
+ extract_all_python_blocks,
56
+ extract_main_python_block,
57
+ multi_seed_validate,
58
+ static_check_rational_numpy_mix,
59
+ static_check_unused_random_vars,
60
+ )
61
+
62
+ logger = logging.getLogger(__name__)
63
+
64
+ TRUNK_RULES = ["2.1", "3.1", "3.2", "6.1", "6.3", "8.1"]
65
+
66
+
67
+ def _translate_constraints_to_assertions(code: str, constraints: list[str],
68
+ model_idx: int) -> list[dict]:
69
+ """Mini appel LLM : contrainte FR → expression booléenne Python."""
70
+ if not constraints or not code.strip():
71
+ return []
72
+ try:
73
+ raw = process_with_openrouter(
74
+ prompt=TRANSLATE_CONSTRAINTS_PROMPT.format(
75
+ code=code,
76
+ constraints="\n".join(f" • {c}" for c in constraints
77
+ if isinstance(c, str) and c.strip()),
78
+ ),
79
+ model_idx=model_idx,
80
+ temperature=0.0,
81
+ max_tokens=2048,
82
+ system_prompt=SYSTEM_PROMPT,
83
+ )
84
+ except (RuntimeError, ValueError, OSError) as e:
85
+ logger.warning("Traduction des contraintes en échec : %s", e)
86
+ return []
87
+ try:
88
+ data = json.loads(pp.strip_fences(raw))
89
+ except json.JSONDecodeError:
90
+ logger.warning("Traduction des contraintes : JSON invalide.")
91
+ return []
92
+ if not isinstance(data, list):
93
+ return []
94
+ return [
95
+ {"description": str(d.get("description", "")), "assertion": d.get("assertion")}
96
+ for d in data
97
+ if isinstance(d, dict) and d.get("assertion")
98
+ ]
99
+
100
+
101
+ def run_exercise(
102
+ content: str,
103
+ filename: str = "exercise.md",
104
+ level: str = "",
105
+ model_idx: int = 1,
106
+ lang: str = "fr",
107
+ set_step: Optional[Callable[[str], None]] = None,
108
+ ) -> dict:
109
+ """
110
+ Pythonise UN exercice. Retourne le dict résultat (contrat UI) :
111
+ exercise, pair_blocks, analysis, functions, notions, audit_patches,
112
+ warnings, harness {ok, summary, seeds}, lang {source, target, action},
113
+ cost {usd, eur, requests}, duration_s
114
+ """
115
+ t0 = time.time()
116
+ cost_before = cost_snapshot()
117
+ _step = set_step or (lambda label: None)
118
+
119
+ # ── 1. Analyse + notions + RAG (parallèle) ───────────────────────────────
120
+ _step("Analyse + notions + catalogue RAG (en parallèle)…")
121
+ analysis, notions_ctx, lists_of_notions, functions_ctx = run_analysis_phase(
122
+ content, model_idx)
123
+
124
+ step1_targets = [r for r in (analysis.get("target_rules") or []) if isinstance(r, str)]
125
+ target_rules = list(dict.fromkeys(TRUNK_RULES + step1_targets))
126
+ targeted_rules_digest = build_rules_digest(target_rules) or "(aucune règle spécifique ciblée)"
127
+
128
+ constraints = [c for c in (analysis.get("property_constraints") or [])
129
+ if isinstance(c, str) and c.strip()]
130
+ property_constraints_text = ("\n".join(f" • {c}" for c in constraints)
131
+ if constraints
132
+ else " (aucun invariant explicite — tirages libres)")
133
+
134
+ # ── 2. Génération par paires ─────────────────────────────────────────────
135
+ metadata, enonce, question_segments = split_original_questions(content)
136
+ exercise_header = build_exercise_metadata(metadata, lists_of_notions)
137
+
138
+ # Contexte fonctions = catalogue CURÉ (domaine détecté) + hits RAG FAISS.
139
+ # Le catalogue curé donne « quel helper pour quel besoin » + couvre les
140
+ # domaines absents du corpus livré (matrices, proba, IBP).
141
+ catalogue_ctx = catalogue_for(analysis)
142
+ functions_combined = "\n\n".join(filter(None, [
143
+ catalogue_ctx,
144
+ ("CATALOGUE RAG (hits spécifiques sur le code réel) :\n" + functions_ctx)
145
+ if functions_ctx else "",
146
+ ])) or "Aucune fonction spécifique détectée."
147
+
148
+ pair_blocks = generate_pair_blocks(
149
+ content=content,
150
+ exercise_header=exercise_header,
151
+ enonce=enonce,
152
+ question_segments=question_segments,
153
+ analysis=analysis,
154
+ functions_ctx=functions_combined,
155
+ fewshot=fewshot_for(analysis),
156
+ targeted_rules_digest=targeted_rules_digest,
157
+ property_constraints_text=property_constraints_text,
158
+ level=level,
159
+ model_idx=model_idx,
160
+ lang=lang,
161
+ set_step=_step,
162
+ )
163
+
164
+ # ── 3. Post-traitements déterministes ────────────────────────────────────
165
+ _step("Post-traitements déterministes…")
166
+ pair_blocks = [pp.inject_config_standard_in_pair_block(b) for b in pair_blocks]
167
+ myst_exercise = assemble_exercise(exercise_header, pair_blocks)
168
+
169
+ audit_patches: list[dict] = []
170
+ audit_warnings: list[dict] = []
171
+
172
+ myst_exercise, orphan_py = pp.fix_orphan_python_openers(myst_exercise)
173
+ if orphan_py:
174
+ audit_patches.append({
175
+ "rule": "3.1", "location": "(orphan python opener)",
176
+ "fix": f"{orphan_py} opener(s) orphelin(s) supprimé(s)",
177
+ "message": f"{orphan_py} fence(s) {{python}} orpheline(s) supprimée(s) (opener doublé).",
178
+ "iteration": 0,
179
+ })
180
+ myst_exercise, dup_q = pp.dedupe_question_blocks(myst_exercise)
181
+ myst_exercise, dup_py = pp.dedupe_python_blocks(myst_exercise)
182
+ myst_exercise, empty_py = pp.drop_empty_python_blocks(myst_exercise)
183
+ if empty_py:
184
+ audit_patches.append({
185
+ "rule": "3.1", "location": "(empty python blocks)",
186
+ "fix": f"{empty_py} bloc(s) vide(s) supprimé(s)",
187
+ "message": f"{empty_py} bloc(s) {{python}} vide(s) (globals() seul) supprimé(s).",
188
+ "iteration": 0,
189
+ })
190
+ if dup_q:
191
+ audit_patches.append({
192
+ "rule": "9.4", "location": "(duplicate question blocks)",
193
+ "fix": f"{dup_q} bloc(s) dédupliqué(s)",
194
+ "message": f"{dup_q} `:::::{{question}}` redondant(s) supprimé(s).",
195
+ "iteration": 0,
196
+ })
197
+ if dup_py:
198
+ audit_patches.append({
199
+ "rule": "3.1", "location": "(duplicate python blocks)",
200
+ "fix": f"{dup_py} bloc(s) dédupliqué(s)",
201
+ "message": f"{dup_py} bloc(s) {{python}} redondant(s) supprimé(s).",
202
+ "iteration": 0,
203
+ })
204
+
205
+ # ── 4. Solutions validées (règle 8.1) ────────────────────────────────────
206
+ if analysis.get("has_validated_solution_in_input"):
207
+ _step("Substitution déterministe des solutions validées…")
208
+ myst_exercise, sol_patches = replace_gen_solutions_with_source(
209
+ myst_exercise, content, analysis, model_idx)
210
+ audit_patches.extend(sol_patches)
211
+
212
+ # ── 5. Audit LLM ─────────────────────────────────────────────────────────
213
+ myst_exercise, llm_patches, llm_warnings = run_audit(
214
+ myst_exercise, step1_targets, model_idx, set_step=_step)
215
+ audit_patches.extend(llm_patches)
216
+ audit_warnings.extend(llm_warnings)
217
+
218
+ # ── 6. Filets déterministes finaux ───────────────────────────────────────
219
+ _step("Filets déterministes (injections, $, id, décimales)…")
220
+ myst_exercise, brace_patches = pp.fix_triple_braces(myst_exercise)
221
+ audit_patches.extend(brace_patches)
222
+
223
+ myst_exercise, sup_fixed = pp.fix_superscript_double_brace(myst_exercise)
224
+ if sup_fixed:
225
+ audit_patches.append({
226
+ "rule": "6.1", "location": "^{{\\latex / _{{\\latex",
227
+ "fix": "^{ {\\latex / _{ {\\latex",
228
+ "message": f"{sup_fixed} double-accolade de superscript/indice désambiguïsée(s) (espace inséré).",
229
+ "iteration": 0,
230
+ })
231
+
232
+ myst_exercise, unwrapped = pp.unwrap_latex_injections(myst_exercise)
233
+ if unwrapped:
234
+ audit_patches.append({
235
+ "rule": "6.1", "location": "{{ \\latex … }}",
236
+ "fix": f"{unwrapped} enveloppe(s) {{{{ }}}} externe(s) retirée(s)",
237
+ "message": f"{unwrapped} injection(s) enveloppant du LaTeX déballée(s) (l'injection interne est la vraie).",
238
+ "iteration": 0,
239
+ })
240
+
241
+ myst_exercise, lift_patches = pp.auto_lift_injections(myst_exercise)
242
+ audit_patches.extend(lift_patches)
243
+
244
+ myst_exercise, rename_patches = pp.rename_underscore_injections(myst_exercise)
245
+ audit_patches.extend(rename_patches)
246
+
247
+ myst_exercise, dollar_patches = pp.fix_dollar_digit(myst_exercise)
248
+ audit_patches.extend(dollar_patches)
249
+
250
+ # Les warnings 6.1 du LLM deviennent du bruit une fois l'auto-lift passé.
251
+ if not pp.INJECTION_RE.search(myst_exercise) or not any(
252
+ "(" in tok or "**" in tok for tok in pp.INJECTION_RE.findall(myst_exercise)
253
+ ):
254
+ audit_warnings = [w for w in audit_warnings
255
+ if not (isinstance(w, dict) and w.get("rule") == "6.1")]
256
+
257
+ myst_exercise, id_patched = pp.force_empty_id(myst_exercise)
258
+ if id_patched and not any(p.get("rule") == "2.1" for p in audit_patches):
259
+ audit_patches.append({
260
+ "rule": "2.1", "location": "(metadata header)", "fix": ":id:",
261
+ "message": "ID vidé par post-process déterministe.", "iteration": 0,
262
+ })
263
+
264
+ audit_warnings.extend(pp.diff_solutions(content, myst_exercise))
265
+ audit_warnings.extend(pp.check_hardcoded_decimals_in_solutions(myst_exercise))
266
+
267
+ # Invariants multi-seed (règle 4.3).
268
+ main_code = extract_main_python_block(myst_exercise)
269
+ if constraints and main_code:
270
+ _step("Validation multi-seed des invariants…")
271
+ assertions = _translate_constraints_to_assertions(main_code, constraints, model_idx)
272
+ if assertions:
273
+ seed_report = multi_seed_validate(
274
+ main_code, assertions, num_seeds=MULTI_SEED_NUM, timeout_per_seed=3.0)
275
+ if seed_report["num_exec_errors"] > 0:
276
+ audit_warnings.append({
277
+ "rule": "4.3",
278
+ "message": (f"Bloc Python : {seed_report['num_exec_errors']}/{MULTI_SEED_NUM} "
279
+ f"exécutions ont échoué. Première erreur : "
280
+ f"{seed_report.get('first_exec_error') or '?'}."),
281
+ })
282
+ for a in assertions:
283
+ summary = seed_report["summary_per_assertion"].get(a["assertion"], {})
284
+ viol = summary.get("violations", 0) + summary.get("errors", 0)
285
+ if viol:
286
+ audit_warnings.append({
287
+ "rule": "4.3",
288
+ "message": (f"Invariant « {a['description']} » violé sur "
289
+ f"{viol}/{MULTI_SEED_NUM} seeds. "
290
+ f"Assertion : `{a['assertion']}`."),
291
+ })
292
+
293
+ # Contrôles matplotlib (règles 11.x).
294
+ if main_code:
295
+ all_python_code = "\n".join(extract_all_python_blocks(myst_exercise))
296
+ audit_warnings.extend(static_check_rational_numpy_mix(all_python_code))
297
+ if "matplotlib" in all_python_code or analysis.get("needs_matplotlib"):
298
+ random_var_names = [v.get("nom") for v in (analysis.get("variables") or [])
299
+ if isinstance(v, dict) and isinstance(v.get("nom"), str)]
300
+ unused = static_check_unused_random_vars(
301
+ all_python_code, random_var_names, markdown_text=myst_exercise)
302
+ if unused:
303
+ audit_warnings.append({
304
+ "rule": "11.1",
305
+ "message": ("Variables aléatoires non utilisées dans le tracé : "
306
+ f"{', '.join(unused)}."),
307
+ })
308
+ _step("Validation matplotlib (labels in-bounds)…")
309
+ try:
310
+ audit_warnings.extend(dynamic_check_matplotlib(all_python_code, timeout=8.0))
311
+ except Exception as e:
312
+ audit_warnings.append({
313
+ "rule": "11.3",
314
+ "message": f"Audit matplotlib impossible : {type(e).__name__}: {e}.",
315
+ })
316
+
317
+ # ── 7. Langue cible ──────────────────────────────────────────────────────
318
+ _step("Langue cible…")
319
+ myst_exercise, lang_warnings, lang_info = ensure_language(myst_exercise, lang, model_idx)
320
+ audit_warnings.extend(lang_warnings)
321
+ effective_lang = lang if lang_info["action"] != "aucune" else lang_info["source"]
322
+ audit_warnings.extend(pp.check_decimals_for_lang(myst_exercise, effective_lang))
323
+
324
+ # ── 8. Porte harnais + réparation ────────────────────────────────────────
325
+ myst_exercise, renum = pp.renumber_question_ids(myst_exercise)
326
+ if renum:
327
+ audit_patches.append({
328
+ "rule": "2.x", "location": ":questionId:/:questionIndex:",
329
+ "fix": "renumérotation 0..N-1",
330
+ "message": f"{renum} questionId/questionIndex renuméroté(s) (contiguïté plateforme).",
331
+ "iteration": 0,
332
+ })
333
+ _step(f"Porte harnais ({HARNESS_GATE_SEEDS} graines)…")
334
+ report = harness.validate_text(myst_exercise, seeds=HARNESS_GATE_SEEDS)
335
+
336
+ for attempt in range(HARNESS_REPAIR_MAX):
337
+ if report["ok"]:
338
+ break
339
+ _step(f"Harnais ROUGE — réparation LLM {attempt + 1}/{HARNESS_REPAIR_MAX}…")
340
+ try:
341
+ repaired = process_with_openrouter(
342
+ prompt=REPAIR_PROMPT.format(
343
+ failures=harness.format_report(report),
344
+ exercise=myst_exercise,
345
+ ),
346
+ model_idx=model_idx,
347
+ temperature=0.0,
348
+ max_tokens=30000,
349
+ system_prompt=SYSTEM_PROMPT,
350
+ )
351
+ except (RuntimeError, ValueError, OSError) as e:
352
+ audit_warnings.append({"rule": "harnais",
353
+ "message": f"Réparation LLM en échec : {e}."})
354
+ break
355
+ candidate = pp.strip_fences(repaired)
356
+ # Re-passe des filets déterministes sur le candidat réparé.
357
+ candidate, _ = pp.fix_orphan_python_openers(candidate)
358
+ candidate = pp.normalize_python_fences(candidate)
359
+ candidate, _ = pp.drop_empty_python_blocks(candidate)
360
+ candidate, _ = pp.fix_triple_braces(candidate)
361
+ candidate, _ = pp.fix_superscript_double_brace(candidate)
362
+ candidate, _ = pp.unwrap_latex_injections(candidate)
363
+ candidate, _ = pp.auto_lift_injections(candidate)
364
+ candidate, _ = pp.rename_underscore_injections(candidate)
365
+ candidate, _ = pp.fix_dollar_digit(candidate)
366
+ candidate, _ = pp.renumber_question_ids(candidate)
367
+ candidate_report = harness.validate_text(candidate, seeds=HARNESS_GATE_SEEDS)
368
+
369
+ def _badness(r: dict) -> int:
370
+ return (len(r["static_errors"]) + r["n_exec_errors"]
371
+ + r["n_unresolved"] + r["n_forbidden"])
372
+
373
+ if candidate_report["ok"] or _badness(candidate_report) < _badness(report):
374
+ myst_exercise, report = candidate, candidate_report
375
+ audit_patches.append({
376
+ "rule": "harnais", "location": "(exercice complet)",
377
+ "fix": "réparation LLM post-harnais",
378
+ "message": "Sortie réparée suite au verdict rouge du harnais.",
379
+ "iteration": attempt + 1,
380
+ })
381
+
382
+ if not report["ok"]:
383
+ audit_warnings.append({
384
+ "rule": "harnais",
385
+ "message": ("⚠️ SORTIE NON VERTE AU HARNAIS — à corriger avant soumission. "
386
+ + harness.format_report(report)[:600]),
387
+ })
388
+
389
+ # ── Résultat ─────────────────────────────────────────────────────────────
390
+ return {
391
+ "exercise": myst_exercise,
392
+ "pair_blocks": pair_blocks,
393
+ "analysis": analysis,
394
+ "functions": functions_ctx,
395
+ "notions": (notions_ctx + "\n" + lists_of_notions).strip(),
396
+ "audit_patches": audit_patches,
397
+ "warnings": audit_warnings,
398
+ "harness": {
399
+ "ok": report["ok"],
400
+ "seeds": report["seeds"],
401
+ "summary": harness.format_report(report),
402
+ },
403
+ "lang": lang_info,
404
+ "cost": cost_delta(cost_before),
405
+ "duration_s": round(time.time() - t0, 1),
406
+ }
app/pipeline/postprocess.py ADDED
@@ -0,0 +1,676 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ postprocess.py
3
+ ──────────────
4
+ Tous les traitements DÉTERMINISTES (sans LLM) appliqués à l'exercice assemblé.
5
+
6
+ Déplacés depuis routes/pythonise_routes_v2.py :
7
+ • inject_config_standard_in_pair_block (AST : **config_standard sur latex())
8
+ • dedupe questions / blocs python, force_empty_id
9
+ • diff des solutions validées, décimales hardcodées
10
+
11
+ Nouveaux (alignement sur les conventions réelles de la plateforme,
12
+ vérifiées sur 222 exemples : fences {python} à 4 backticks, injections
13
+ = variables nues camelCase suffixe Aff, préfixe ${} anti-devise) :
14
+ • normalize_python_fences — fences {python} → PYTHON_FENCE_BACKTICKS
15
+ • fix_dollar_digit — `$`+chiffre / `${{` → `${}` (auto-correctif)
16
+ • auto_lift_injections — TOUTE injection non nue ({{latex(x)}},
17
+ {{lc(a)}}, {{obj.print()}}, {{a*b}}) remontée
18
+ en variable pré-calculée du bloc principal
19
+ • rename_underscore_injections — variables injectées avec `_` → camelCase
20
+ • detect_languages / strip_language / check_decimals_for_lang
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import ast
26
+ import difflib
27
+ import logging
28
+ import re
29
+ from typing import Optional
30
+
31
+ from app.config import PYTHON_FENCE_BACKTICKS
32
+
33
+ logger = logging.getLogger(__name__)
34
+
35
+ PY_FENCE = "`" * PYTHON_FENCE_BACKTICKS
36
+
37
+ # Fence {python} à 3 OU 4 backticks (lecture tolérante ; l'écriture est
38
+ # toujours normalisée à PYTHON_FENCE_BACKTICKS via normalize_python_fences).
39
+ PYTHON_FENCE_RE = re.compile(
40
+ r"(?ms)^(?P<open>`{3,4})\{python\}[ \t]*\n(?P<code>.*?)\n(?P=open)[ \t]*$"
41
+ )
42
+
43
+ INJECTION_RE = re.compile(r"\{\{(.*?)\}\}", re.DOTALL)
44
+ BARE_IDENT_RE = re.compile(r"^[A-Za-z][A-Za-z0-9]*$")
45
+
46
+
47
+ # ─────────────────────────────────────────────────────────────────────────────
48
+ # Utilitaires génériques
49
+ # ─────────────────────────────────────────────────────────────────────────────
50
+
51
+ def strip_fences(text: str) -> str:
52
+ """Retire un wrapper markdown EXTERNE (``` ou ```lang) d'une sortie LLM,
53
+ sans toucher aux fences qui font partie du contenu (```{python}, `````)."""
54
+ text = text.strip()
55
+ if text.startswith("`````"):
56
+ return text
57
+ text = re.sub(r"^```\w*\s*\n", "", text)
58
+ text = re.sub(r"\n```\s*$", "", text)
59
+ return text.strip()
60
+
61
+
62
+ def extract_python_blocks(text: str) -> list[str]:
63
+ """Tous les corps de blocs {python}, dans l'ordre du document."""
64
+ return [m.group("code") for m in PYTHON_FENCE_RE.finditer(text)]
65
+
66
+
67
+ def mask_python_blocks(text: str) -> tuple[str, list[str]]:
68
+ """Remplace chaque bloc {python} par un sentinel ; retourne (masqué, blocs)."""
69
+ blocks: list[str] = []
70
+
71
+ def _sub(m: re.Match) -> str:
72
+ blocks.append(m.group(0))
73
+ return f"\x00PYBLOCK{len(blocks) - 1}\x00"
74
+
75
+ return PYTHON_FENCE_RE.sub(_sub, text), blocks
76
+
77
+
78
+ def unmask_python_blocks(text: str, blocks: list[str]) -> str:
79
+ for i, b in enumerate(blocks):
80
+ text = text.replace(f"\x00PYBLOCK{i}\x00", b)
81
+ return text
82
+
83
+
84
+ def normalize_python_fences(text: str) -> str:
85
+ """Réécrit toute fence {python} (3 ou 4 backticks) avec exactement
86
+ PYTHON_FENCE_BACKTICKS backticks — convention plateforme (4)."""
87
+ def _sub(m: re.Match) -> str:
88
+ return f"{PY_FENCE}{{python}}\n{m.group('code')}\n{PY_FENCE}"
89
+ return PYTHON_FENCE_RE.sub(_sub, text)
90
+
91
+
92
+ def insert_python_lines(exercise: str, lines: list[str]) -> str:
93
+ """Insère des lignes juste avant le `globals()` du PREMIER bloc {python}
94
+ (bloc principal — les expressions injectées référencent ses variables).
95
+ Les lignes déjà présentes dans l'exercice ne sont pas dupliquées."""
96
+ todo = [l for l in lines if l and l not in exercise]
97
+ if not todo:
98
+ return exercise
99
+ m = PYTHON_FENCE_RE.search(exercise)
100
+ if not m:
101
+ return exercise
102
+ code = m.group("code")
103
+ idx = code.rfind("globals()")
104
+ if idx == -1:
105
+ new_code = code + "\n" + "\n".join(todo)
106
+ else:
107
+ new_code = code[:idx] + "\n".join(todo) + "\n" + code[idx:]
108
+ start, end = m.span()
109
+ return exercise[:start] + f"{m.group('open')}{{python}}\n{new_code}\n{m.group('open')}" + exercise[end:]
110
+
111
+
112
+ # ─────────────────────────────────────────────────────────────────────────────
113
+ # **config_standard automatique sur latex(...) — AST, idempotent
114
+ # ───────────────────────────────────────────────────��─────────────────────────
115
+
116
+ class LatexTransformer(ast.NodeTransformer):
117
+ def visit_Call(self, node):
118
+ self.generic_visit(node)
119
+ if isinstance(node.func, ast.Name) and node.func.id == "latex":
120
+ has_config = any(
121
+ isinstance(kw, ast.keyword) and kw.arg is None
122
+ and isinstance(kw.value, ast.Name) and kw.value.id == "config_standard"
123
+ for kw in node.keywords
124
+ )
125
+ if not has_config:
126
+ node.keywords.append(
127
+ ast.keyword(arg=None, value=ast.Name(id="config_standard", ctx=ast.Load()))
128
+ )
129
+ return node
130
+
131
+
132
+ def add_config_standard(code: str) -> str:
133
+ tree = ast.parse(code)
134
+ tree = LatexTransformer().visit(tree)
135
+ ast.fix_missing_locations(tree)
136
+ return ast.unparse(tree)
137
+
138
+
139
+ def inject_config_standard_in_pair_block(block: str) -> str:
140
+ """Applique add_config_standard à chaque bloc {python} d'un bloc de paire.
141
+ Un bloc non parsable (rare) est laissé intact plutôt que de planter."""
142
+ def _sub(m: re.Match) -> str:
143
+ try:
144
+ transformed = add_config_standard(m.group("code"))
145
+ except SyntaxError:
146
+ return m.group(0)
147
+ return f"{m.group('open')}{{python}}\n{transformed}\n{m.group('open')}"
148
+ return PYTHON_FENCE_RE.sub(_sub, block)
149
+
150
+
151
+ # ─────────────────────────────────────────────────────────────────────────────
152
+ # Dédoublonnage questions / blocs python
153
+ # ─────────────────────────────────────────────────────────────────────────────
154
+
155
+ _QUESTION_BLOCK_RE = re.compile(r"(:::::\{question\}.*?:::::)", re.DOTALL)
156
+
157
+
158
+ def dedupe_question_blocks(exercise: str) -> tuple[str, int]:
159
+ """Supprime les blocs :::::{question} dont le questionStatement est
160
+ identique (la paire N+1 régénère parfois une question de la paire N)."""
161
+ blocks = list(_QUESTION_BLOCK_RE.finditer(exercise))
162
+ if len(blocks) < 2:
163
+ return exercise, 0
164
+
165
+ qstmt_re = re.compile(r"::::\{questionStatement\}\s*\n?(.*?)\n?::::", re.DOTALL)
166
+ seen: set[str] = set()
167
+ to_remove: list[tuple[int, int]] = []
168
+ for m in blocks:
169
+ qm = qstmt_re.search(m.group(1))
170
+ if not qm:
171
+ continue
172
+ key = re.sub(r"\s+", " ", qm.group(1)).strip().lower()
173
+ if key in seen:
174
+ to_remove.append((m.start(), m.end()))
175
+ else:
176
+ seen.add(key)
177
+
178
+ if not to_remove:
179
+ return exercise, 0
180
+ new_exercise = exercise
181
+ for start, end in reversed(to_remove):
182
+ new_exercise = new_exercise[:start] + new_exercise[end:]
183
+ return re.sub(r"\n{3,}", "\n\n", new_exercise), len(to_remove)
184
+
185
+
186
+ def dedupe_python_blocks(exercise: str) -> tuple[str, int]:
187
+ """Supprime les blocs {python} identiques (modulo espaces)."""
188
+ blocks = list(PYTHON_FENCE_RE.finditer(exercise))
189
+ if len(blocks) < 2:
190
+ return exercise, 0
191
+ seen: set[str] = set()
192
+ to_remove: list[tuple[int, int]] = []
193
+ for m in blocks:
194
+ key = re.sub(r"\s+", " ", m.group("code")).strip()
195
+ if key in seen:
196
+ to_remove.append((m.start(), m.end()))
197
+ else:
198
+ seen.add(key)
199
+ if not to_remove:
200
+ return exercise, 0
201
+ new_exercise = exercise
202
+ for start, end in reversed(to_remove):
203
+ new_exercise = new_exercise[:start] + new_exercise[end:]
204
+ return re.sub(r"\n{3,}", "\n\n", new_exercise), len(to_remove)
205
+
206
+
207
+ def fix_orphan_python_openers(exercise: str) -> tuple[str, int]:
208
+ """Supprime un opener {python} immédiatement suivi (à blanc près) d'un
209
+ autre opener — malformation LLM observée qui fait avaler un bloc entier
210
+ par la regex de fence et casse l'extraction du code."""
211
+ new, n = re.subn(
212
+ r"(?m)^`{3,4}\{python\}[ \t]*\n\s*(?=`{3,4}\{python\}[ \t]*$)",
213
+ "",
214
+ exercise,
215
+ )
216
+ return new, n
217
+
218
+
219
+ def renumber_question_ids(exercise: str) -> tuple[str, int]:
220
+ """Renumérote :questionId: et :questionIndex: en séquence 0..N-1 dans
221
+ l'ordre du document (invariant plateforme : uniques et contigus). Le LLM
222
+ se trompe parfois sur les exercices longs — la renumérotation d'office
223
+ est toujours correcte."""
224
+ changed = {"n": 0}
225
+
226
+ def _renum(field: str, text: str) -> str:
227
+ counter = {"i": -1}
228
+
229
+ def _sub(m: re.Match) -> str:
230
+ counter["i"] += 1
231
+ if m.group(1) != str(counter["i"]):
232
+ changed["n"] += 1
233
+ return f":{field}: {counter['i']}"
234
+
235
+ return re.sub(rf":{field}:\s*(\d+)", _sub, text)
236
+
237
+ new = _renum("questionId", exercise)
238
+ new = _renum("questionIndex", new)
239
+ return new, changed["n"]
240
+
241
+
242
+ def fix_superscript_double_brace(exercise: str) -> tuple[str, int]:
243
+ """`^{{\\frac…}}` / `_{{\\sqrt…}}` : le `{` LaTeX collé au `{` du
244
+ superscript simule une ouverture d'injection `{{`. On insère un espace
245
+ (`^{ {\\frac…} }`) UNIQUEMENT quand le contenu commence par une commande
246
+ LaTeX — jamais quand c'est une vraie injection `^{{var}}`."""
247
+ masked, blocks = mask_python_blocks(exercise)
248
+ new, n = re.subn(r"([\^_])\{\{(?=\s*\\)", r"\1{ {", masked)
249
+ if not n:
250
+ return exercise, 0
251
+ return unmask_python_blocks(new, blocks), n
252
+
253
+
254
+ def unwrap_latex_injections(exercise: str) -> tuple[str, int]:
255
+ """`{{ \\frac{\\pi}{ {{xAff}} } }}` → `\\frac{\\pi}{ {{xAff}} }` :
256
+ quand le LLM enveloppe du LaTeX (ou une injection imbriquée) dans des
257
+ `{{ }}`, on retire la paire EXTERNE (scan à accolades équilibrées) —
258
+ l'injection interne reste la vraie."""
259
+ masked, blocks = mask_python_blocks(exercise)
260
+ out: list[str] = []
261
+ i, n, removed = 0, len(masked), 0
262
+ while i < n:
263
+ if masked.startswith("{{", i):
264
+ # contenu commence-t-il par du LaTeX (\) ou une injection imbriquée ?
265
+ j = i + 2
266
+ while j < n and masked[j] in " \t":
267
+ j += 1
268
+ if j < n and (masked[j] == "\\" or masked.startswith("{{", j)):
269
+ # scan équilibré depuis i+2 (profondeur 2)
270
+ depth, k = 2, i + 2
271
+ while k < n and depth > 0:
272
+ if masked[k] == "{":
273
+ depth += 1
274
+ elif masked[k] == "}":
275
+ depth -= 1
276
+ k += 1
277
+ if depth == 0 and k - 2 >= i + 2 and masked[k - 2:k] == "}}":
278
+ inner = masked[i + 2:k - 2]
279
+ out.append(inner)
280
+ removed += 1
281
+ i = k
282
+ continue
283
+ out.append(masked[i])
284
+ i += 1
285
+ if not removed:
286
+ return exercise, 0
287
+ return unmask_python_blocks("".join(out), blocks), removed
288
+
289
+
290
+ def drop_empty_python_blocks(exercise: str) -> tuple[str, int]:
291
+ """Supprime les blocs {python} VIDES (rien, ou seulement `globals()` /
292
+ commentaires) — la génération par paires en insère parfois un entre deux
293
+ questions ; le skill exige UN SEUL bloc utile (relecture 2026-06-12)."""
294
+ removed = {"n": 0}
295
+
296
+ def _sub(m: re.Match) -> str:
297
+ body = "\n".join(
298
+ l for l in m.group("code").splitlines()
299
+ if l.strip() and not l.strip().startswith("#") and l.strip() != "globals()"
300
+ )
301
+ if body.strip():
302
+ return m.group(0)
303
+ removed["n"] += 1
304
+ return ""
305
+
306
+ new = PYTHON_FENCE_RE.sub(_sub, exercise)
307
+ if removed["n"]:
308
+ new = re.sub(r"\n{3,}", "\n\n", new)
309
+ return new, removed["n"]
310
+
311
+
312
+ def force_empty_id(exercise: str) -> tuple[str, bool]:
313
+ """Règle 2.1 — vide la valeur de `:id:` si elle est renseignée."""
314
+ new = re.sub(r"^(\s*:id:)[ \t]+[^\n]+$", r"\1", exercise, flags=re.MULTILINE)
315
+ return new, (new != exercise)
316
+
317
+
318
+ # ─────────────────────────────────────────────────────────────────────────────
319
+ # Auto-correctif `$` collé à un chiffre (règle du skill §1) — casse silencieuse
320
+ # ─────────────────────────────────────────────────────────────────────────────
321
+
322
+ def fix_dollar_digit(exercise: str) -> tuple[str, list[dict]]:
323
+ """Hors blocs {python} :
324
+ • `$` non échappé immédiatement suivi d'un chiffre → `${}` + chiffre
325
+ • `$` non échappé immédiatement suivi de `{{` → `${}{{`
326
+ Le groupe vide {} est invisible au rendu mais empêche la lecture
327
+ « montant en devise » qui désynchronise tout le `$…$`."""
328
+ masked, blocks = mask_python_blocks(exercise)
329
+ patches: list[dict] = []
330
+
331
+ def _digit(m: re.Match) -> str:
332
+ patches.append({
333
+ "rule": "$+chiffre",
334
+ "location": m.group(0),
335
+ "fix": "${}" + m.group(1),
336
+ "message": "Auto-correctif : `$` collé à un chiffre préfixé par un groupe vide {} (anti-devise).",
337
+ "iteration": 0,
338
+ })
339
+ return "${}" + m.group(1)
340
+
341
+ def _inj(m: re.Match) -> str:
342
+ patches.append({
343
+ "rule": "$+chiffre",
344
+ "location": "${{",
345
+ "fix": "${}{{",
346
+ "message": "Auto-correctif : injection inline `${{…}}` préfixée par {} (le rendu peut commencer par un chiffre).",
347
+ "iteration": 0,
348
+ })
349
+ return "${}{{"
350
+
351
+ masked = re.sub(r"(?<!\\)\$(?!\{)(\d)", _digit, masked)
352
+ masked = re.sub(r"(?<!\\)\$\{\{", _inj, masked)
353
+ return unmask_python_blocks(masked, blocks), patches
354
+
355
+
356
+ def fix_triple_braces(exercise: str) -> tuple[str, list[dict]]:
357
+ """`x^{{{exp}}}` (triple accolade, motif interdit) → `x^{ {{exp}} }`.
358
+ Sans cette normalisation, le découpage des injections est ambigu et
359
+ l'auto-lift peut produire du Python invalide."""
360
+ masked, blocks = mask_python_blocks(exercise)
361
+ patches: list[dict] = []
362
+ n = 0
363
+ while "{{{" in masked or "}}}" in masked:
364
+ masked = masked.replace("{{{", "{ {{", 1) if "{{{" in masked else masked
365
+ masked = masked.replace("}}}", "}} }", 1) if "}}}" in masked else masked
366
+ n += 1
367
+ if n > 500: # garde-fou anti-boucle
368
+ break
369
+ if n:
370
+ patches.append({
371
+ "rule": "6.1",
372
+ "location": "{{{ / }}}",
373
+ "fix": "{ {{ / }} }",
374
+ "message": f"Triple-accolade normalisée avec espaces ({n} remplacement(s)) — motif interdit qui casse la substitution.",
375
+ "iteration": 0,
376
+ })
377
+ return unmask_python_blocks(masked, blocks), patches
378
+
379
+
380
+ # ─────────────────────────────────────────────────────────────────────────────
381
+ # Auto-lift GÉNÉRALISÉ : toute injection non nue → variable pré-calculée
382
+ # (les 222 exemples plateforme n'ont AUCUN appel/expr dans {{ }} — uniquement
383
+ # des noms nus camelCase ; le harnais le vérifie en statique)
384
+ # ─────────────────────────────────────────────────────────────────────────────
385
+
386
+ _LIFT_SUFFIX = {"latex": "Tex"}
387
+
388
+
389
+ def _camel(name: str) -> str:
390
+ parts = [p for p in name.split("_") if p]
391
+ if not parts:
392
+ return name
393
+ return parts[0] + "".join(p[:1].upper() + p[1:] for p in parts[1:])
394
+
395
+
396
+ def auto_lift_injections(exercise: str) -> tuple[str, list[dict]]:
397
+ """Remplace chaque `{{ <expr non nue> }}` par `{{ <varAff> }}` et insère
398
+ `<varAff> = <expr>` avant le globals() du bloc principal.
399
+
400
+ Couvre : appels ({{latex(f)}}, {{lc(a, sign=True)}}, y compris avec
401
+ **config_standard), attributs ({{dom.print()}}), opérations ({{a*b}}).
402
+ Idempotent : expressions identiques → même variable ; lignes déjà
403
+ présentes non dupliquées."""
404
+ masked, blocks = mask_python_blocks(exercise)
405
+ patches: list[dict] = []
406
+ lifted: dict[str, str] = {} # expr normalisée → nom de variable
407
+ used_names: set[str] = set(re.findall(r"\b([A-Za-z_]\w*)\s*=", exercise))
408
+ counter = {"n": 0}
409
+
410
+ def _make_name(expr: str) -> str:
411
+ m = re.match(r"^([A-Za-z_]\w*)\s*\(\s*([A-Za-z_]\w*)\s*(?:,\s*\*\*\s*config_standard\s*)?\)$", expr)
412
+ if m:
413
+ func, arg = m.group(1), m.group(2)
414
+ base = _camel(arg) + _LIFT_SUFFIX.get(func, "Aff")
415
+ else:
416
+ counter["n"] += 1
417
+ base = f"injAff{counter['n']}"
418
+ name, i = base, 2
419
+ while name in used_names:
420
+ name = f"{base}{i}"
421
+ i += 1
422
+ used_names.add(name)
423
+ return name
424
+
425
+ def _sub(m: re.Match) -> str:
426
+ expr = m.group(1).strip()
427
+ if not expr or BARE_IDENT_RE.match(expr):
428
+ return m.group(0) # déjà nu (ou vide → harnais)
429
+ if re.match(r"^[A-Za-z][A-Za-z0-9_]*$", expr):
430
+ return m.group(0) # identifiant avec _ → renommage dédié
431
+ if "{" in expr or "}" in expr or "\n" in expr:
432
+ return m.group(0) # découpage ambigu → on ne lifte pas
433
+ try: # l'insert DOIT être du Python valide
434
+ compile(f"_x = {expr}", "<lift>", "exec")
435
+ except SyntaxError:
436
+ logger.warning("Auto-lift refusé (expression non compilable) : %r", expr[:80])
437
+ return m.group(0)
438
+ key = re.sub(r"\s+", " ", expr)
439
+ if key in lifted:
440
+ name = lifted[key]
441
+ insert = None
442
+ else:
443
+ name = _make_name(expr)
444
+ lifted[key] = name
445
+ insert = f"{name} = {expr}"
446
+ patches.append({
447
+ "rule": "6.1",
448
+ "location": m.group(0),
449
+ "fix": "{{" + name + "}}",
450
+ "python_insert": insert,
451
+ "message": "Auto-lift déterministe : expression dans {{…}} pré-calculée en variable d'affichage.",
452
+ "iteration": 0,
453
+ })
454
+ return "{{" + name + "}}"
455
+
456
+ new_masked = INJECTION_RE.sub(_sub, masked)
457
+ if not patches:
458
+ return exercise, []
459
+ new_exercise = unmask_python_blocks(new_masked, blocks)
460
+ new_exercise = insert_python_lines(
461
+ new_exercise, [p["python_insert"] for p in patches if p.get("python_insert")]
462
+ )
463
+ return new_exercise, patches
464
+
465
+
466
+ def rename_underscore_injections(exercise: str) -> tuple[str, list[dict]]:
467
+ """Les `_` dans une variable injectée cassent la substitution plateforme
468
+ (indices LaTeX parasites). Renomme p_str → pStr partout (corps + python)."""
469
+ masked, blocks = mask_python_blocks(exercise)
470
+ names = {
471
+ tok.strip() for tok in INJECTION_RE.findall(masked)
472
+ if re.match(r"^[A-Za-z][A-Za-z0-9_]*$", tok.strip()) and "_" in tok
473
+ }
474
+ if not names:
475
+ return exercise, []
476
+
477
+ taken = set(re.findall(r"\b([A-Za-z_]\w*)\b", exercise))
478
+ patches: list[dict] = []
479
+ new_exercise = exercise
480
+ for old in sorted(names, key=len, reverse=True):
481
+ new = _camel(old)
482
+ i = 2
483
+ while new in taken:
484
+ new = f"{_camel(old)}{i}"
485
+ i += 1
486
+ taken.add(new)
487
+ new_exercise = re.sub(rf"\b{re.escape(old)}\b", new, new_exercise)
488
+ patches.append({
489
+ "rule": "6.3",
490
+ "location": f"{{{{{old}}}}}",
491
+ "fix": f"{{{{{new}}}}}",
492
+ "message": f"Variable injectée renommée {old} → {new} (underscore interdit dans {{{{…}}}}).",
493
+ "iteration": 0,
494
+ })
495
+ return new_exercise, patches
496
+
497
+
498
+ # ─────────────────────────────────────────────────────────────────────────────
499
+ # Solutions validées : extraction / diff pédagogique (règle 8.1)
500
+ # ─────────────────────────────────────────────────────────────────────────────
501
+
502
+ _DETAILED_SOLUTION_RE = re.compile(
503
+ r"::::\{detailedSolution\}\s*\n(.*?)\n::::",
504
+ re.DOTALL,
505
+ )
506
+
507
+ _STOPWORDS = frozenset({
508
+ # FR
509
+ "des", "les", "une", "est", "que", "qui", "par", "pour", "avec", "sur", "dans",
510
+ "ces", "son", "ses", "leur", "leurs", "cette", "donc", "ainsi", "alors", "plus",
511
+ "moins", "tout", "tous", "toute", "toutes", "aussi", "mais", "comme", "puis",
512
+ "soit", "deux", "trois", "fois",
513
+ # EN
514
+ "the", "and", "are", "for", "with", "from", "then", "this", "that", "these",
515
+ "those", "have", "has", "been", "their", "there", "where", "when", "which",
516
+ "also", "but", "more", "less", "than", "into", "only", "thus", "such", "very",
517
+ })
518
+
519
+
520
+ def extract_detailed_solutions(myst_text: str) -> list[str]:
521
+ return [m.group(1).strip() for m in _DETAILED_SOLUTION_RE.finditer(myst_text)]
522
+
523
+
524
+ def _extract_pedagogical_words(text: str) -> list[str]:
525
+ """Mots porteurs de sens pédagogique (hors placeholders, nombres, LaTeX)."""
526
+ cleaned = re.sub(r"\{\{[^}]*\}\}", " ", text)
527
+ cleaned = re.sub(r"\\[a-zA-Z]+\*?\s*\{[^}]*\}", " ", cleaned)
528
+ cleaned = re.sub(r"\\[a-zA-Z]+\*?", " ", cleaned)
529
+ cleaned = re.sub(r"-?\d+(?:[.,]\d+)?", " ", cleaned)
530
+ cleaned = re.sub(r"\{[a-zA-Z*]+\}", " ", cleaned)
531
+ cleaned = cleaned.replace("`", " ")
532
+ tokens = re.findall(r"[a-zA-ZÀ-ÿ]{3,}", cleaned)
533
+ return [t.lower() for t in tokens if t.lower() not in _STOPWORDS]
534
+
535
+
536
+ def diff_solutions(original_content: str, generated_exercise: str) -> list[dict]:
537
+ """Compare les detailedSolution source ↔ sortie (mots pédagogiques seuls).
538
+ Warning si divergence (similarité < 95 %) — règle 8.1."""
539
+ orig = extract_detailed_solutions(original_content)
540
+ gen = extract_detailed_solutions(generated_exercise)
541
+ warnings: list[dict] = []
542
+ if not orig:
543
+ return warnings
544
+ if len(orig) != len(gen):
545
+ warnings.append({
546
+ "rule": "8.1",
547
+ "message": (f"Nombre de detailedSolution différent : {len(orig)} dans la source, "
548
+ f"{len(gen)} dans la sortie."),
549
+ })
550
+ for i, (o, g) in enumerate(zip(orig, gen)):
551
+ o_words = _extract_pedagogical_words(o)
552
+ g_words = _extract_pedagogical_words(g)
553
+ if o_words == g_words:
554
+ continue
555
+ ratio = difflib.SequenceMatcher(None, o_words, g_words).ratio()
556
+ if ratio >= 0.95:
557
+ continue
558
+ severity = "FORTE divergence" if ratio < 0.70 else "divergence"
559
+ missing = [w for w in o_words if w not in g_words][:5]
560
+ added = [w for w in g_words if w not in o_words][:5]
561
+ hint = ""
562
+ if missing:
563
+ hint += f" Mots disparus : {', '.join(missing)}."
564
+ if added:
565
+ hint += f" Mots ajoutés : {', '.join(added)}."
566
+ warnings.append({
567
+ "rule": "8.1",
568
+ "message": (f"Question {i + 1} : detailedSolution {severity} vs source "
569
+ f"(similarité pédagogique = {ratio:.0%}).{hint} "
570
+ "Vérifier que le raisonnement original est préservé (règle 8.1)."),
571
+ })
572
+ return warnings
573
+
574
+
575
+ _DECIMAL_LITERAL_RE = re.compile(r"\b\d+\{,\}\d+\b")
576
+ _DECIMAL_DOT_RE = re.compile(r"(?<![\\\w])\d+\.\d+(?!\w)")
577
+ _INTERP_RE = re.compile(r"\{\{[^}]*\}\}")
578
+
579
+
580
+ def check_hardcoded_decimals_in_solutions(exercise: str) -> list[dict]:
581
+ """Règle 4.3 (ext.) : décimale littérale hors {{…}} dans une solution
582
+ → probable valeur codée en dur qui ne suivra pas la randomisation."""
583
+ warnings: list[dict] = []
584
+ for i, m in enumerate(_DETAILED_SOLUTION_RE.finditer(exercise)):
585
+ stripped = _INTERP_RE.sub(" ", m.group(1))
586
+ hits = list(_DECIMAL_LITERAL_RE.finditer(stripped)) + list(_DECIMAL_DOT_RE.finditer(stripped))
587
+ seen: set[str] = set()
588
+ unique: list[str] = []
589
+ for h in hits:
590
+ text = h.group(0)
591
+ if text in seen or text.startswith("10.") or text.endswith("e"):
592
+ continue
593
+ seen.add(text)
594
+ unique.append(text)
595
+ if len(unique) >= 3:
596
+ break
597
+ if unique:
598
+ warnings.append({
599
+ "rule": "4.3",
600
+ "message": (f"Question {i + 1} : detailedSolution contient des décimales littérales "
601
+ f"({', '.join(repr(h) for h in unique)}) hors `{{{{var}}}}`. Si l'exo "
602
+ "randomise un paramètre dont elles dérivent, elles ne suivront pas la "
603
+ "variation. Vérifier qu'elles sont injectées."),
604
+ })
605
+ return warnings
606
+
607
+
608
+ # ─────────────────────────────────────────────────────────────────────────────
609
+ # Langues : détection, réduction bilingue → mono, contrôle des décimales
610
+ # ─────────────────────────────────────────────────────────────────────────────
611
+
612
+ _ROLE_RE = {
613
+ "fr": re.compile(r"\{fr\}`([^`]*)`"),
614
+ "en": re.compile(r"\{en\}`([^`]*)`"),
615
+ }
616
+ _FR_HINTS = (" le ", " la ", " les ", " une ", " des ", " est ", " que ", " pour ",
617
+ "Calculer", "Montrer", "Déterminer", "Résoudre", "On considère", "définie")
618
+ _EN_HINTS = (" the ", " a ", " an ", " is ", " that ", " for ", " of ",
619
+ "Compute", "Show", "Determine", "Solve", "We consider", "defined")
620
+
621
+
622
+ def detect_languages(text: str) -> str:
623
+ """Retourne 'both' si les rôles {fr}`…`/{en}`…` sont présents, sinon
624
+ 'fr' ou 'en' par heuristique de mots-outils sur la prose."""
625
+ body, _ = mask_python_blocks(text)
626
+ if _ROLE_RE["fr"].search(body) and _ROLE_RE["en"].search(body):
627
+ return "both"
628
+ fr_score = sum(body.count(h) for h in _FR_HINTS)
629
+ en_score = sum(body.count(h) for h in _EN_HINTS)
630
+ return "fr" if fr_score >= en_score else "en"
631
+
632
+
633
+ def strip_language(text: str, keep: str) -> str:
634
+ """Réduction déterministe d'un exercice bilingue (rôles {fr}`…`{en}`…`)
635
+ vers une seule langue : déballe la langue gardée, supprime l'autre."""
636
+ drop = "en" if keep == "fr" else "fr"
637
+ masked, blocks = mask_python_blocks(text)
638
+ masked = _ROLE_RE[drop].sub("", masked)
639
+ masked = _ROLE_RE[keep].sub(lambda m: m.group(1), masked)
640
+ masked = re.sub(r"[ \t]+\n", "\n", masked)
641
+ masked = re.sub(r" +", " ", masked)
642
+ return unmask_python_blocks(masked, blocks)
643
+
644
+
645
+ def check_decimals_for_lang(exercise: str, lang: str) -> list[dict]:
646
+ """Décimales conformes à la langue : FR = virgule ({,}), EN = point.
647
+ En bilingue, chaque rôle est contrôlé séparément."""
648
+ body, _ = mask_python_blocks(exercise)
649
+ body = _INTERP_RE.sub(" ", body) # les valeurs injectées sont contrôlées par ailleurs
650
+ warnings: list[dict] = []
651
+
652
+ def _scan(segment: str, seg_lang: str, where: str):
653
+ if seg_lang == "fr":
654
+ hits = [h.group(0) for h in _DECIMAL_DOT_RE.finditer(segment)
655
+ if not h.group(0).startswith("10.")]
656
+ if hits:
657
+ warnings.append({
658
+ "rule": "décimales",
659
+ "message": (f"Décimales à POINT dans du texte FR ({where}) : "
660
+ f"{', '.join(sorted(set(hits))[:4])} — attendu virgule `{{,}}`."),
661
+ })
662
+ else:
663
+ hits = [h.group(0) for h in _DECIMAL_LITERAL_RE.finditer(segment)]
664
+ if hits:
665
+ warnings.append({
666
+ "rule": "décimales",
667
+ "message": (f"Décimales à VIRGULE dans du texte EN ({where}) : "
668
+ f"{', '.join(sorted(set(hits))[:4])} — attendu point décimal."),
669
+ })
670
+
671
+ if lang == "both":
672
+ _scan(" ".join(_ROLE_RE["fr"].findall(body)), "fr", "rôles {fr}")
673
+ _scan(" ".join(_ROLE_RE["en"].findall(body)), "en", "rôles {en}")
674
+ else:
675
+ _scan(body, lang, "corps")
676
+ return warnings
app/pipeline/prompts.py ADDED
@@ -0,0 +1,563 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ prompts.py
3
+ ──────────
4
+ Tous les prompts LLM du pipeline.
5
+
6
+ # v1 → les versions antérieures (STEP1_PROMPT, STEP_PAIR_PROMPT, SYSTEM_PROMPT,
7
+ # STEP_AUDIT_PROMPT) sont archivées VERBATIM dans
8
+ # app/knowledge/prompts_v1_archive.md (extraites de routes/pythonise_routes_v2.py
9
+ # avant la refonte du 2026-06-12).
10
+ #
11
+ # Changements majeurs v1 → v2 (alignement sur les conventions RÉELLES de la
12
+ # plateforme, vérifiées sur les 222 exemples pythonisés livrés + skill
13
+ # pyxiscience-pythonisation) :
14
+ # • Injections {{ }} = UNIQUEMENT des noms de variables nus, camelCase,
15
+ # suffixe Aff, sans underscore. La v1 enseignait {{latex(expr)}},
16
+ # {{lc(a, sign=True)}}, {{pxsl_res_num(...)}} — tous absents des exemples
17
+ # validés et refusés par le harnais.
18
+ # • Bloc {python} à 4 backticks (la v1 montrait 3) ; enveloppe exercise à 5.
19
+ # • Bilingue = rôles inline {fr}`…`{en}`…` UNIQUEMENT (aucun bloc
20
+ # :::{fr}/:::{en} dans les 222 exemples — la v1 les enseignait).
21
+ # • Règle du `$` collé à un chiffre (préfixe ${}) — absente de la v1.
22
+ # • Fraction (module fractions) interdit en sortie de formateur ;
23
+ # pxsl_format_number SANS kwargs ; décimales localisées FR/EN.
24
+ # • Few-shot du type détecté injecté ({fewshot}) au lieu de 5 exemples
25
+ # génériques pavés dans le prompt.
26
+ # • SYSTEM_PROMPT raccourci (le dump de 180 lignes du source de
27
+ # pxsl_res_num doublonnait le catalogue RAG).
28
+ """
29
+
30
+ # ─────────────────────────────────────────────────────────────────────────────
31
+ # STEP 1 — Analyse (variables + règles à risque + invariants)
32
+ # v1 → app/knowledge/prompts_v1_archive.md §STEP1_PROMPT
33
+ # (v2 : typo needs_matplolib corrigée → needs_matplotlib ; mention du type
34
+ # pour la sélection de few-shot ; sinon structure conservée)
35
+ # ─────────────────────────────────────────────────────────────────────────────
36
+ STEP1_PROMPT = """\
37
+ Tu es un expert en analyse d'exercices mathématiques & détection des variables Python pour PyxiScience,
38
+ pour passer d'un exercice à valeurs statiques à un exercice à valeurs aléatoires **correctes**.
39
+
40
+ EXERCICE :
41
+ {content}
42
+
43
+ ─────────────────────────────────────────────────────
44
+ MISSION : analyse cet exercice et identifie **TOUTES** les entités mathématiques
45
+ qui devront être générées aléatoirement en Python.
46
+
47
+ Couvre TOUS les types possibles : scalaires entiers/réels, fractions, listes,
48
+ vecteurs, matrices, ensembles, polynômes, fonctions, pourcentages, angles, intervalles…
49
+
50
+ Pour chaque variable :
51
+ • nom : nom Python valide court (ex: a, b, n, matA, listeNotes),
52
+ partageable entre questions
53
+ • type_python : "int"|"float"|"Fraction"|"list"|"matrix"|"set"|"vector"|"other"
54
+ • description : rôle dans l'énoncé (1 phrase)
55
+ • contraintes : contraintes mathématiques (ex: a ≠ 0, n ∈ [2,10])
56
+ • plage_python : expression Python exacte de génération aléatoire
57
+ • location : "énoncé"|"inter-question"|"question"|"solution 1"|…|"solution 5"
58
+ • valeur_exemple: valeur typique
59
+
60
+ ─────────────────────────────────────────────────────
61
+ RÈGLES DE PYTHONISATION (catalogue) — choisis dans "target_rules" celles qui
62
+ sont LE PLUS À RISQUE pour CET exercice (5 à 12 IDs maximum).
63
+
64
+ {available_rules_menu}
65
+
66
+ ─────────────────────────────────────────────────────
67
+ Réponds UNIQUEMENT en JSON valide :
68
+ {{
69
+ "exercise_type": "...",
70
+ "exercise_title": "...",
71
+ "exercise_summary": "...",
72
+ "suggested_concepts": ["..."],
73
+ "nb_questions": 1,
74
+ "variables": [
75
+ {{
76
+ "nom": "...",
77
+ "type_python": "...",
78
+ "description": "...",
79
+ "contraintes": "...",
80
+ "location": "énoncé|question|solution 1",
81
+ "plage_python": "...",
82
+ "valeur_exemple": "..."
83
+ }}
84
+ ],
85
+ "needs_fraction": false,
86
+ "needs_sympy": false,
87
+ "needs_numpy": false,
88
+ "needs_matplotlib": false,
89
+ "mathematical_structure": "...",
90
+ "target_rules": ["3.1", "4.1", "6.1"],
91
+ "property_constraints": [
92
+ "<invariant mathématique en français — ex: w_n ≥ n pour tout n>"
93
+ ],
94
+ "has_validated_solution_in_input": false
95
+ }}
96
+
97
+ Notes :
98
+ • "exercise_type" : type court et standard (ex: "équation linéaire",
99
+ "trinôme/discriminant", "fonction avec figure", "logarithme/exponentielle",
100
+ "système linéaire", "intégration par parties", "probabilités/binomiale",
101
+ "suites", "finance/intérêts") — il sert à choisir un exemple canonique.
102
+ • "target_rules" : uniquement des IDs du catalogue ci-dessus (top 5-12 à risque).
103
+ • "property_constraints" : invariants à préserver au tirage (règle 4.3). Liste vide si aucun.
104
+ • "has_validated_solution_in_input" : true SI l'énoncé contient déjà des
105
+ blocs `::::{{detailedSolution}}` rédigés (règles 8.1–8.3).
106
+ """
107
+
108
+
109
+ # ─────────────────────────────────────────────────────────────────────────────
110
+ # SYSTEM — rôle + sémantique du runtime {{ }}
111
+ # v1 → app/knowledge/prompts_v1_archive.md §SYSTEM_PROMPT
112
+ # ─────────────────────────────────────────────────────────────────────────────
113
+ SYSTEM_PROMPT = """\
114
+ Tu es professeur de mathématiques, expert en Python scientifique (sympy, random,
115
+ math, matplotlib, numpy) et en exercices PyxiScience randomisés (MyST + KaTeX).
116
+
117
+ Le code Python vit dans UN bloc ````{python} … ```` (4 backticks) terminé par
118
+ `globals()`. Les variables y définies sont injectées dans le MyST via `{{ var }}`.
119
+
120
+ ⚠️ La syntaxe `{{ var }}` est exécutée par un runtime Python maison — PAS du
121
+ Jinja. RÈGLE ABSOLUE : `{{ … }}` contient UNIQUEMENT un nom de variable nu,
122
+ en camelCase, SANS underscore, généralement suffixé `Aff` pour les affichages
123
+ (ex: `{{coefAAff}}`). JAMAIS d'appel de fonction, de calcul, de filtre ni de
124
+ logique dans `{{ }}` — tout est pré-calculé dans le bloc Python.
125
+
126
+ Deux règles d'or :
127
+ 1. Tout ce qui s'affiche est PRÉ-CALCULÉ dans une variable puis injecté tel quel.
128
+ 2. On ne code JAMAIS en dur une réponse vraie seulement pour les valeurs de la
129
+ source : si un paramètre est randomisé, la réponse affichée est RECALCULÉE.
130
+
131
+ Priorité aux helpers du catalogue PyxiScience (pxsl_latex_coefficient/lc,
132
+ pxsl_res_num, pxsl_format_number, pxsl_matrix, pxs_Interval, pxs_config…) —
133
+ appelés DANS le bloc Python, résultat stocké dans une variable `…Aff`.
134
+ Ne jamais réimplémenter un helper existant.
135
+
136
+ Exercices applicatifs : contexte ÉCONOMIE/GESTION (finance, comptabilité,
137
+ marketing, microéconomie — registre école de commerce), jamais physique/chimie.
138
+ """
139
+
140
+
141
+ # ─────────────────────────────────────────────────────────────────────────────
142
+ # STEP 2+ — Génération par paires
143
+ # v1 → app/knowledge/prompts_v1_archive.md §STEP_PAIR_PROMPT
144
+ # ─────────────────────────────────────────────────────────────────────────────
145
+ STEP_PAIR_PROMPT = """\
146
+ Tu pythonises un exercice PyxiScience MyST, niveau {niveau}.
147
+ Transformer l'exercice statique (valeurs fixes) en version randomisée
148
+ (paramètres tirés en Python + injectés dans le MyST), EN respectant à la
149
+ lettre les conventions de la plateforme ci-dessous.
150
+
151
+ ═══════════════════════════════════════════════════════════════════════════
152
+ CONVENTIONS PLATEFORME (vérifiées sur les exercices livrés — NON NÉGOCIABLES)
153
+ ═══════════════════════════════════════════════════════════════════════════
154
+
155
+ STRUCTURE :
156
+ • Enveloppe exercice : 5 backticks `````{{exercise}} … ````` (déjà gérée).
157
+ • UN bloc Python principal : 4 backticks ````{{python}} … ```` terminé par
158
+ `globals()`. Imports en tête (`import random as rd`, sympy ciblé,
159
+ `from pyxiscience.Mes_fctions_generalistes_bis import pxs_config,
160
+ pxsl_latex_coefficient as lc` …) puis `config_standard = pxs_config()`.
161
+ • Chaque question : `:::::{{question}}` (5 deux-points) avec
162
+ `:questionType:`, `:questionId:`, `:questionIndex:` (contigus depuis 0) ;
163
+ sous-blocs `::::{{questionStatement}}`, `::::{{questionHint}}`,
164
+ `::::{{detailedSolution}}`, `::::{{weightDistribution}}` (4 deux-points).
165
+ • `:weightDistribution:` : recopier les poids de la source VERBATIM
166
+ (somme = 100 par question).
167
+
168
+ INJECTIONS `{{{{ }}}}` — LA règle qui fait tout casser si violée :
169
+ • UNIQUEMENT un nom de variable NU : `{{{{coefAAff}}}}`, `{{{{resQ1Aff}}}}`.
170
+ camelCase, SANS underscore, suffixe `Aff` pour tout affichage.
171
+ • INTERDIT dans `{{{{ }}}}` : appel de fonction (`latex(...)`, `lc(...)`,
172
+ `pxsl_…(...)`, `obj.print()`), calcul (`a*b`), `round(...)`, `**kwargs`.
173
+ → TOUT se pré-calcule dans le bloc Python :
174
+ `eqAff = latex(a*x**2 + b*x + c, **config_standard)` puis `{{{{eqAff}}}}`.
175
+ • `**config_standard` est réservé à `sympy.latex(...)` DANS le bloc Python.
176
+ `pxsl_format_number()` n'accepte AUCUN kwarg. `pxsl_res_num(x, dec=…,
177
+ egal=False)` s'appelle dans le bloc Python, résultat dans une variable Aff.
178
+ • Espaces contre la triple-accolade : `x^{{ {{{{expAff}}}} }}` ✅,
179
+ jamais `x^{{{{{{expAff}}}}}}` ❌.
180
+
181
+ RÈGLE DU `$` COLLÉ À UN CHIFFRE (casse silencieuse) :
182
+ Un `$` immédiatement suivi d'un chiffre est lu comme un MONTANT en devise et
183
+ désynchronise tout le `$…$`. Préfixer par un groupe vide : `${{}}3 \\times 2$`,
184
+ et SURTOUT `${{}}{{{{nAff}}}}$` pour toute injection inline qui rend un nombre.
185
+ Pour un vrai pourcentage affiché : `\\%` partout (jamais `%` nu dans le texte) ;
186
+ ne JAMAIS échapper les `%` à l'intérieur du bloc Python (chaînes "%.2f").
187
+
188
+ TIRAGES — exclure les cas dégénérés (boucle de rejet ou énumération) :
189
+ • `for _ in range(300): … ; break` ou liste de candidats + `rd.choice(...)`
190
+ (contraintes croisées → TOUJOURS énumération en compréhension, jamais
191
+ une boucle qui peut sortir invalide).
192
+ • Exclure : exposant 0 ou 1 affiché (`^{{0}}`, `^{{1}}`), dénominateur 1
193
+ (`\\frac{{…}}{{1}}`), `\\sqrt[1]`, `\\sqrt[2]` (→ `\\sqrt`), double signe
194
+ (`+ -`), division par zéro, Δ de signe inattendu, intervalle vide.
195
+ • Exactitude : `sympy.Rational(1, 2)`, JAMAIS `1/2` flottant ni `round()`
196
+ pour une valeur exacte. Le module `fractions.Fraction` PLANTE les
197
+ formateurs plateforme — ne jamais le passer à un helper pxsl_*.
198
+ • Coefficients signés : ne JAMAIS concaténer un signe à une valeur ;
199
+ utiliser `lc(coef, sign=True, ones=True)` (pxsl_latex_coefficient) dans
200
+ le bloc Python → variable Aff.
201
+
202
+ DÉCIMALES SELON LA LANGUE : FR = virgule (`0{{,}}18`, `4,12`), milliers `\\,` ;
203
+ EN = point (`0.18`), milliers virgule. {lang_directive}
204
+
205
+ BILINGUE (si l'exercice l'est) : rôles INLINE uniquement :
206
+ {{fr}}`Calculer …`{{en}}`Compute …`
207
+ Jamais de bloc :::{{fr}}/:::{{en}}. Les injections `{{{{var}}}}` se placent
208
+ HORS des rôles : {{fr}}`Il y a `{{en}}`There are `{{{{nAff}}}}.
209
+ Symétrie totale FR/EN (même détail, mêmes placeholders). Si un nombre
210
+ décimal s'affiche, prévoir des variables séparées par langue
211
+ (`prixAffFr` virgule / `prixAffEn` point) et injecter la bonne dans chaque rôle.
212
+
213
+ FIDÉLITÉ À LA SOURCE (directive Chabane — INTOUCHABLE) :
214
+ • Même énoncé, même méthode, même structure de solution, mêmes poids.
215
+ • Ne JAMAIS AJOUTER de phrase d'énoncé, de transition ou de rappel de règle
216
+ absent de la source (même « pour aider ») — on pythonise, on n'enrichit pas.
217
+ • Conserver les commentaires utiles du bloc Python source s'il en a.
218
+ • Si la source contient des `detailedSolution` validées : INTERDICTION de
219
+ reformuler la prose — seules les valeurs littérales deviennent `{{{{var}}}}`.
220
+ • Conserver tels quels : `\\ds`, `\\dfrac`, `\\inftys` (macro maison, ne
221
+ JAMAIS la « corriger »), `\\begin{{equation*}}` avec `&=` direct,
222
+ `\\phantom{{-}}\\\\`. Pas de `$$…$$`, pas de `\\[…\\]`, pas de `\\begin{{align}}`.
223
+ • Géométrie pure : ne pas pythoniser (valeurs statiques conservées).
224
+
225
+ FIGURES matplotlib (si l'exo en a) : construites dans LE bloc Python unique,
226
+ variables du tirage réellement utilisées dans le tracé, labels DANS la fenêtre,
227
+ pas de mélange Rational+numpy (passer par float()), UN SEUL `plt.show()` final —
228
+ jamais `savefig`, jamais `matplotlib.use(...)`.
229
+
230
+ ═══════════════════════════════════════════════════════════════════════════
231
+ CATALOGUE PyxiScience (helpers à utiliser DANS le bloc Python)
232
+ ═══════════════════════════════════════════════════════════════════════════
233
+ RÈGLE D'OR DU CATALOGUE : avant d'écrire le moindre LaTeX à la main, CHERCHE
234
+ ici un helper qui fait le travail et UTILISE-LE (résultat dans une variable
235
+ `…Aff` injectée nue). Coder à la main ce qu'un helper sait faire = REJET.
236
+ • Matrices → `pxsl_matrix` (jamais `\\begin{{pmatrix}}` à la main) ; sommes/
237
+ produits/scalaires détaillés → `pxsl_sum_matrix`/`pxsl_prod_matrix`/
238
+ `pxsl_prod_scalar_matrix` ; système `Ax=B` → `pxsl_system_lin` ; résolution
239
+ pas à pas / inversion → `pxsl_resol_system` / `pxs_steps_invert_matrix` ;
240
+ échelon/RREF → `pxs_compute_ech`/`pxs_compute_ech_reduite`.
241
+ • Proba (v.a. finie) → `pxs_finiterv`, tableau de loi `pxsl_law`, moment
242
+ `pxsl_moment`, transformation `pxs_fct_finiterv`.
243
+ • Intégration par parties → `pxs_explain_IBP` (rédaction complète, injectée
244
+ via `{{{{ipp}}}}`).
245
+ • Coefficients signés → `pxsl_latex_coefficient`/`lc` ; puissances →
246
+ `pxsl_pow` ; résultat numérique → `pxsl_res_num` ; inéquation rédigée →
247
+ `pxsl_solve_general_inequality`.
248
+ • Voie par défaut pour une expression : `latex(expr, **config_standard)`.
249
+ `**config_standard` est réservé à `latex()` — JAMAIS sur un helper `pxsl_*`.
250
+ • N'appelle PAS un helper marqué « runtime à vérifier » (indi_l_r_symb,
251
+ pxs_round, Poly_with_random_coef) sans certitude qu'il est chargé.
252
+
253
+ {functions}
254
+
255
+ ═══════════════════════════════════════════════════════════════════════════
256
+ EXEMPLE CANONIQUE DU MÊME TYPE (extrait d'un exercice livré et validé —
257
+ imite sa structure, ses conventions d'affichage et son niveau de détail)
258
+ ═══════════════════════════════════════════════════════════════════════════
259
+ {fewshot}
260
+
261
+ ═══════════════════════════════════════════════════════════════════════════
262
+ CONTEXTE
263
+ ═══════════════════════════════════════════════════════════════════════════
264
+
265
+ EN-TÊTE déjà finalisé (NE PAS reproduire) :
266
+ {content}
267
+
268
+ VARIABLES DÉTECTÉES :
269
+ {analysis}
270
+
271
+ BLOCS PRÉCÉDENTS (ne pas redéfinir leurs variables, ne pas les répéter) :
272
+ {previous_blocks}
273
+
274
+ SECTION À PYTHONISER ({range_label} / {nb_total}) :
275
+ {current_segment}
276
+
277
+ ═══════════════════════════════════════════════════════════════════════════
278
+ RÈGLES D'ASSEMBLAGE PAR PAIRE
279
+ ═══════════════════════════════════════════════════════════════════════════
280
+
281
+ ⚠️ TU PRODUIS UNIQUEMENT LE CONTENU DE CETTE PAIRE — jamais celui des paires
282
+ précédentes (concaténées mécaniquement avant ta sortie).
283
+
284
+ ⚠️ EXACTEMENT {nb_current} bloc(s) `:::::{{question}}` — pas plus, pas moins.
285
+ `questionId`/`questionIndex` CONTINUS depuis la paire précédente.
286
+
287
+ ⚠️ PAIRE 1 UNIQUEMENT : tu produis le bloc ````{{python}}```` principal
288
+ (imports + tirages + calculs + variables Aff + `globals()`) puis l'énoncé
289
+ général réécrit avec injections, AVANT la première question.
290
+
291
+ ⚠️ PAIRES SUIVANTES : ni énoncé, ni questions précédentes, ni ré-imports.
292
+ Si de NOUVELLES variables sont nécessaires (ex. figure d'une partie C), un
293
+ PETIT bloc ````{{python}}```` additionnel SANS imports, terminé par `globals()`.
294
+
295
+ Format paire 1 :
296
+
297
+ ````{{python}}
298
+ <imports + tirages (cas dégénérés exclus) + calculs sympy exacts
299
+ + TOUTES les variables d'affichage …Aff ; AUCUN texte pédagogique>
300
+ globals()
301
+ ````
302
+
303
+ <énoncé général avec valeurs → {{{{varAff}}}}>
304
+
305
+ :::::{{question}}
306
+ :questionType: STQ
307
+ :questionId: N
308
+ :questionIndex: N
309
+
310
+ ::::{{questionStatement}} … ::::
311
+ ::::{{questionHint}} … ::::
312
+ ::::{{detailedSolution}} … ::::
313
+ ::::{{weightDistribution}}
314
+ :logic: …
315
+ :abstraction: …
316
+ :reasoning: …
317
+ :calculation: …
318
+ ::::
319
+ :::::
320
+
321
+ ═══════════════════════════════════════════════════════════════════════════
322
+ RÈGLES CIBLÉES POUR CET EXERCICE (depuis la base de règles)
323
+ ═══════════════════════════════════════════════════════════════════════════
324
+ {targeted_rules}
325
+
326
+ INVARIANTS MATHÉMATIQUES à préserver lors des tirages :
327
+ {property_constraints}
328
+
329
+ ═══════════════════════════════════════════════════════════════════════════
330
+ CHECKLIST FINALE (vérifie chaque point avant de répondre)
331
+ ═══════════════════════════════════════════════════════════════════════════
332
+ □ Bloc ````{{python}}```` (4 backticks) terminé par `globals()`
333
+ □ CHAQUE `{{{{ }}}}` = nom de variable NU camelCase sans underscore
334
+ □ Aucun appel/calcul/`**kwargs` dans `{{{{ }}}}` — tout pré-calculé en `…Aff`
335
+ □ Aucun `$` collé à un chiffre — `${{}}` devant toute injection inline numérique
336
+ □ Tirages sans cas dégénéré (^{{1}}, ^{{0}}, frac{{}}{{1}}, sqrt[2], double signe)
337
+ □ Coefficients signés via lc(...) pré-calculé ; décimales localisées
338
+ □ weightDistribution = poids source verbatim (somme 100) ; IDs contigus
339
+ □ Solutions validées : prose INTACTE, valeurs → {{{{var}}}}
340
+ □ {{fr}}`…`{{en}}`…` symétriques si bilingue ; `\\%` pour les pourcentages
341
+ """
342
+
343
+
344
+ # ─────────────────────────────────────────────────────────────────────────────
345
+ # AUDIT — vérification ciblée + patches textuels
346
+ # v1 → app/knowledge/prompts_v1_archive.md §STEP_AUDIT_PROMPT
347
+ # (v2 : ajout des contrôles injections nues / $+chiffre / fences 4 backticks ;
348
+ # les patches sont désormais appliqués à TOUTES les occurrences identiques)
349
+ # ─────────────────────────────────────────────────────────────────────────────
350
+ STEP_AUDIT_PROMPT = """\
351
+ Tu es l'auditeur PyxiScience. Tu reçois l'exercice pythonisé final et tu vérifies
352
+ UNIQUEMENT les règles listées ci-dessous (chacune avec son cas FAUTIF/CORRECT),
353
+ plus les 4 invariants plateforme :
354
+ (a) toute injection `{{{{ }}}}` est un nom de variable NU camelCase sans underscore ;
355
+ (b) aucun `$` non échappé collé à un chiffre (préfixe `${{}}` requis) ;
356
+ (c) bloc {{python}} à 4 backticks terminé par `globals()` ;
357
+ (d) questionId/questionIndex contigus depuis 0, weightDistribution somme 100.
358
+
359
+ RÈGLES À VÉRIFIER :
360
+
361
+ {audit_rules}
362
+
363
+ EXERCICE À AUDITER :
364
+ {exercise}
365
+
366
+ ═══════════════════════════════════════════════════════════════════════════
367
+ MISSION
368
+ ═══════════════════════════════════════════════════════════════════════════
369
+
370
+ Pour chaque règle violée, renvoie une "issue" :
371
+ • rule : ID de la règle (ex: "6.1") ou "(a)"…"(d)"
372
+ • location : snippet EXACT (1 ligne, ≤ 200 caractères), copié VERBATIM —
373
+ utilisé tel quel par str.replace() côté Python.
374
+ Si la même violation apparaît à N endroits IDENTIQUES,
375
+ une seule issue suffit (toutes les occurrences seront
376
+ remplacées).
377
+ • fix : remplacement EXACT.
378
+ • python_insert : (OPTIONNEL) ligne(s) Python à insérer avant le `globals()`
379
+ du bloc principal (ex: "eqAff = latex(eq, **config_standard)").
380
+ • can_patch : true si la correction est sûre, false sinon (warning seul).
381
+ • message : phrase explicative en français.
382
+
383
+ Ne liste PAS les règles respectées ni celles hors liste. Ne « corrige » JAMAIS
384
+ `\\inftys`, `\\ds`, `\\dfrac`, ni la prose d'une solution validée.
385
+ Un exercice MONOLINGUE (tout FR ou tout EN, sans rôles {{fr}}`…`{{en}}`…`) est
386
+ LÉGITIME — ne le signale pas ; n'exige le bilingue que s'il est déjà partiel.
387
+ Les espaces internes `{{{{ var }}}}` sont tolérés (le moteur trim) — ne les
388
+ signale pas.
389
+
390
+ Réponds UNIQUEMENT en JSON valide, sans markdown :
391
+ {{
392
+ "verdict": "OK" ou "PATCH_REQUIRED",
393
+ "issues": [
394
+ {{
395
+ "rule": "6.1",
396
+ "location": "{{{{latex(fDev, **config_standard)}}}}",
397
+ "fix": "{{{{fDevTex}}}}",
398
+ "python_insert": "fDevTex = latex(fDev, **config_standard)",
399
+ "can_patch": true,
400
+ "message": "Appel avec **kwargs dans {{{{…}}}} — variable pré-calculée."
401
+ }}
402
+ ]
403
+ }}
404
+ """
405
+
406
+
407
+ # ─────────────────────────────────────────────────────────────────────────────
408
+ # Traduction de contraintes FR → assertions Python (règle 4.3)
409
+ # (inchangé v1 — déplacé depuis routes/pythonise_routes_v2.py)
410
+ # ─────────────────────────────────────────────────────────────────────────────
411
+ TRANSLATE_CONSTRAINTS_PROMPT = """\
412
+ Tu reçois un bloc de code Python qui tire des variables aléatoires et calcule
413
+ des grandeurs dérivées, et une liste de contraintes mathématiques en français
414
+ à vérifier sur les variables produites.
415
+
416
+ CODE PYTHON :
417
+ ```python
418
+ {code}
419
+ ```
420
+
421
+ CONTRAINTES (français) :
422
+ {constraints}
423
+
424
+ MISSION :
425
+ Pour chaque contrainte, écris une expression Python booléenne qui, évaluée
426
+ dans le namespace résultant de l'exécution du code, retourne True si la
427
+ contrainte est respectée.
428
+
429
+ Règles :
430
+ • Contrainte universelle ("pour tout n") → échantillonner n = 0..10 max et
431
+ combiner avec `all(...)` (5 à 10 valeurs, pas plus).
432
+ • Notations math (≤, ≥, ≠) → `<=`, `>=`, `!=`.
433
+ • Contrainte intestable (variable absente du code) → `"assertion": null`.
434
+ • AUCUN import supplémentaire — seulement les variables du namespace + builtins.
435
+
436
+ Réponds UNIQUEMENT en JSON valide :
437
+ [
438
+ {{"description": "<contrainte originale>", "assertion": "<expression Python>" }},
439
+ {{"description": "<autre contrainte>", "assertion": null }}
440
+ ]
441
+ """
442
+
443
+
444
+ # ─────────────────────────────────────────────────────────────────────────────
445
+ # Substitution des solutions validées (règle 8.1)
446
+ # (inchangé v1 — déplacé depuis routes/pythonise_routes_v2.py)
447
+ # ─────────────────────────────────────────────────────────────────────────────
448
+ SOLUTION_SUBSTITUTION_PROMPT = """\
449
+ Tu reçois UNE solution mathématique rédigée avec des VALEURS LITTÉRALES (nombres,
450
+ fractions, expressions concrètes), et une liste de VARIABLES PYTHON disponibles
451
+ dans le bloc `{{python}}` de l'exercice pythonisé.
452
+
453
+ SOLUTION ORIGINALE (source MyST, à préserver mot à mot) :
454
+ ─────────────────────────────────
455
+ {original_solution}
456
+ ─────────────────────────────────
457
+
458
+ VARIABLES PYTHON DISPONIBLES (chaque var a une valeur d'exemple ; substitue
459
+ chaque occurrence numérique par le placeholder MyST {{{{var}}}}) :
460
+ {variables_table}
461
+
462
+ ═══════════════════════════════════════════════════════════════════════════
463
+ MISSION
464
+ ═══════════════════════════════════════════════════════════════════════════
465
+
466
+ Remplace CHAQUE valeur littérale (nombre entier, fraction, expression numérique)
467
+ qui correspond à une variable Python par son placeholder MyST `{{{{nomVar}}}}`.
468
+
469
+ ⚠️ STRICTES INTERDICTIONS :
470
+ • NE PAS ajouter de mots (Initialisation, Hérédité, Conclusion, Soit, Donc, etc.)
471
+ • NE PAS ajouter de **gras** ou *italique* si pas dans la source
472
+ • NE PAS reformuler la moindre phrase ; NE PAS modifier la ponctuation
473
+ • NE PAS ajouter de paragraphes ou de blocs equation*
474
+ • Si la source utilise déjà des `{{{{var}}}}`, les PRÉSERVER tels quels.
475
+
476
+ EXEMPLE :
477
+ Source : `On a $f(0) = 3$ et $f(2) = -1$.`
478
+ Variables : x0=0, x2=2, fx0=3, fx2=-1
479
+ Sortie : `On a $f({{{{x0}}}}) = {{{{fx0}}}}$ et $f({{{{x2}}}}) = {{{{fx2}}}}$.`
480
+
481
+ Réponds UNIQUEMENT avec le texte modifié, SANS préambule, SANS wrapper markdown,
482
+ SANS guillemets ajoutés. Si tu ne peux pas substituer, recopie la source telle quelle.
483
+ """
484
+
485
+
486
+ # ─────────────────────────────────────────────────────────────────────────────
487
+ # Traduction / bilinguisation (NOUVEAU — chantier langue cible)
488
+ # ─────────────────────────────────────────────────────────────────────────────
489
+ TRANSLATE_PROMPT = """\
490
+ Tu traduis la PROSE d'un exercice PyxiScience MyST, de {source_label} vers {target_label}.
491
+
492
+ TEXTE (les blocs Python ont été remplacés par des sentinelles <<<PYBLOCK_n>>> — à RECOPIER TELLES QUELLES) :
493
+ ─────────────────────────────────
494
+ {body}
495
+ ─────────────────────────────────
496
+
497
+ RÈGLES ABSOLUES :
498
+ • Traduire UNIQUEMENT la prose (énoncés, indications, solutions, titres).
499
+ • PRÉSERVER À L'IDENTIQUE : toutes les sentinelles <<<PYBLOCK_n>>>, tous les
500
+ placeholders `{{{{var}}}}` (mêmes noms, mêmes positions logiques), tout le
501
+ LaTeX/maths ($…$, \\begin{{equation*}}…), la structure des fences MyST
502
+ (`````, :::::, ::::), toutes les options `:clé: valeur` (dont
503
+ :questionId:, :weightDistribution: et leurs valeurs), `\\ds`, `\\dfrac`,
504
+ `\\inftys`, `\\%`.
505
+ • {format_directive}
506
+ • Décimales : virgule en FR (`0{{,}}5`), point en EN (`0.5`) — adapte les
507
+ décimales LITTÉRALES de la prose à la langue de chaque segment ; ne touche
508
+ pas aux `{{{{var}}}}`.
509
+ • Terminologie mathématique scolaire exacte ; même niveau de détail.
510
+
511
+ Réponds UNIQUEMENT avec le texte transformé, sans préambule ni wrapper.
512
+ """
513
+
514
+ TRANSLATE_FORMAT_MONO = (
515
+ "Sortie MONOLINGUE en {target_label} : remplace chaque texte source par sa "
516
+ "traduction, sans rôles {{fr}}/{{en}}."
517
+ )
518
+ TRANSLATE_FORMAT_BOTH = (
519
+ "Sortie BILINGUE : chaque segment de prose devient une paire de rôles inline "
520
+ "{fr}`texte français`{en}`english text` (JAMAIS de bloc :::{fr}/:::{en}). "
521
+ "Les injections {{var}} et le LaTeX restent HORS des rôles, partagés par les "
522
+ "deux langues : {fr}`Il y a `{en}`There are `{{nAff}}."
523
+ )
524
+
525
+
526
+ # ─────────────────────────────────────────────────────────────────────────────
527
+ # Réparation post-harnais (NOUVEAU — 1 itération max)
528
+ # ─────────────────────────────────────────────────────────────────────────────
529
+ REPAIR_PROMPT = """\
530
+ Le harnais de validation PyxiScience a REJETÉ l'exercice pythonisé ci-dessous.
531
+ Corrige-le en changeant LE MINIMUM (ne réécris pas l'exercice, ne reformule
532
+ aucune prose, ne change pas la structure ni les poids).
533
+
534
+ ÉCHECS DU HARNAIS :
535
+ {failures}
536
+
537
+ EXERCICE ACTUEL :
538
+ {exercise}
539
+
540
+ RÈGLES DE CORRECTION :
541
+ • Exception à l'exécution → corrige le bloc Python (tirage dégénéré, import
542
+ manquant, division par zéro…) par la modification la plus locale possible.
543
+ • Variable non résolue `{{{{x}}}}` → définis-la dans le bloc Python (avant
544
+ `globals()`) ou corrige le nom injecté.
545
+ • Motif interdit `$`+chiffre → préfixe `${{}}`.
546
+ • **Double signe `+ -`** (cas le plus fréquent) : un `+` littéral du texte
547
+ est suivi d'une injection qui rend une valeur NÉGATIVE (ex.
548
+ `… + {{{{dfAff}}}}` avec dfAff = "- 4 \\sin(4x)"). Correctif : supprimer le
549
+ `+` littéral ET pré-calculer la chaîne SIGNÉE dans le bloc Python
550
+ (`dfSignAff = latex(df, **config_standard)` rend déjà le signe ; ou
551
+ construire `"+ …"`/`"- …"` selon le signe) puis injecter
552
+ `… {{{{dfSignAff}}}}` sans opérateur devant.
553
+ • **`\\frac{{…}}{{1}}` / `^{{1}}` / `^{{0}}` / `\\sqrt[2]`** : presque toujours un
554
+ TIRAGE DÉGÉNÉRÉ — exclure la valeur fautive à la source
555
+ (ex. `b = rd.randint(2, 5)` au lieu de `randint(1, 5)`, ou boucle de rejet
556
+ `if b == 1: continue`). Ne PAS rafistoler le texte : corriger le tirage.
557
+ • Injection non nue → pré-calculer en variable camelCase `…Aff`.
558
+ • Le bloc {{python}} reste à 4 backticks et se termine par `globals()`.
559
+ • Ne touche NI à `\\inftys`/`\\ds`/`\\dfrac`, NI à la prose des solutions.
560
+
561
+ Réponds UNIQUEMENT avec l'exercice complet corrigé (de `````{{exercise}} à `````),
562
+ sans préambule ni wrapper markdown.
563
+ """
app/pipeline/solutions.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ solutions.py
3
+ ────────────
4
+ Substitution déterministe des solutions validées (règle 8.1 — directive
5
+ Chabane) : chaque ::::{detailedSolution} générée est remplacée par la version
6
+ SOURCE dont seules les valeurs littérales deviennent des {{var}}.
7
+ Déplacé depuis routes/pythonise_routes_v2.py (logique inchangée ; gestion
8
+ d'erreurs ciblée).
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import logging
14
+ import re
15
+ from typing import Optional
16
+
17
+ from app.llm.client import process_with_openrouter
18
+ from app.pipeline.postprocess import extract_detailed_solutions, strip_fences
19
+ from app.pipeline.prompts import SOLUTION_SUBSTITUTION_PROMPT, SYSTEM_PROMPT
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+ _DETAILED_SOLUTION_RE = re.compile(
24
+ r"::::\{detailedSolution\}\s*\n(.*?)\n::::",
25
+ re.DOTALL,
26
+ )
27
+
28
+
29
+ def _substitute_solution_via_llm(
30
+ source_text: str,
31
+ analysis: dict,
32
+ model_idx: int,
33
+ ) -> Optional[str]:
34
+ """Appel LLM ciblé : valeurs littérales de la solution source → {{var}}.
35
+ None en cas d'échec (l'appelant garde alors la solution générée)."""
36
+ variables = analysis.get("variables") or []
37
+ if not variables or not source_text.strip():
38
+ return None
39
+
40
+ variables_table = "\n".join(
41
+ f" • `{v['nom']}` (valeur exemple: `{v.get('valeur_exemple', '?')}`)"
42
+ f" — {v.get('description', '')[:60]}"
43
+ for v in variables
44
+ if isinstance(v, dict) and v.get("nom")
45
+ )
46
+ if not variables_table:
47
+ return None
48
+
49
+ try:
50
+ raw = process_with_openrouter(
51
+ prompt=SOLUTION_SUBSTITUTION_PROMPT.format(
52
+ original_solution=source_text,
53
+ variables_table=variables_table,
54
+ ),
55
+ model_idx=model_idx,
56
+ temperature=0.0,
57
+ max_tokens=4096,
58
+ system_prompt=SYSTEM_PROMPT,
59
+ )
60
+ except (RuntimeError, ValueError, OSError) as e:
61
+ logger.warning("Substitution de solution en échec : %s", e)
62
+ return None
63
+
64
+ text = strip_fences(raw).strip()
65
+ return text or None
66
+
67
+
68
+ def replace_gen_solutions_with_source(
69
+ myst_exercise: str,
70
+ source_content: str,
71
+ analysis: dict,
72
+ model_idx: int,
73
+ ) -> tuple[str, list[dict]]:
74
+ """Remplace chaque detailedSolution générée par la version source
75
+ substituée (correspondance positionnelle). Retourne (exercice, patches)."""
76
+ source_solutions = extract_detailed_solutions(source_content)
77
+ if not source_solutions:
78
+ return myst_exercise, []
79
+
80
+ patches: list[dict] = []
81
+ idx = {"i": 0}
82
+
83
+ def _sub(match):
84
+ i = idx["i"]
85
+ idx["i"] += 1
86
+ if i >= len(source_solutions):
87
+ return match.group(0)
88
+ src = source_solutions[i]
89
+ if not src.strip():
90
+ return match.group(0)
91
+ substituted = _substitute_solution_via_llm(src, analysis, model_idx)
92
+ if not substituted:
93
+ return match.group(0)
94
+
95
+ new_block = f"::::{{detailedSolution}}\n{substituted}\n::::"
96
+ if substituted.strip() != match.group(1).strip():
97
+ patches.append({
98
+ "rule": "8.1",
99
+ "location": f"detailedSolution Q{i + 1}",
100
+ "fix": "substitution déterministe (source préservée)",
101
+ "message": (f"Question {i + 1}: detailedSolution remplacée par la version "
102
+ "source (valeurs littérales → {{var}}), pédagogie préservée "
103
+ "(règle 8.1)."),
104
+ "iteration": 0,
105
+ })
106
+ return new_block
107
+
108
+ return _DETAILED_SOLUTION_RE.sub(_sub, myst_exercise), patches
app/pipeline/translate.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ translate.py
3
+ ────────────
4
+ Étape langue cible (NOUVEAU — chantier E) : FR / EN / les deux.
5
+
6
+ Stratégie (sécurité d'abord) :
7
+ • détection déterministe de la/des langue(s) source (rôles {fr}`…`{en}`…`,
8
+ sinon heuristique de mots-outils) ;
9
+ • cible == source → aucun appel LLM ;
10
+ • bilingue → mono : réduction DÉTERMINISTE (on déballe la langue gardée,
11
+ on supprime l'autre — zéro LLM, zéro risque) ;
12
+ • mono → autre langue ou bilingue : appel LLM sur le corps avec les blocs
13
+ Python MASQUÉS par sentinelles (le Python ne passe jamais par le LLM),
14
+ puis garde-fous : sentinelles intactes, MÊME ensemble de {{placeholders}},
15
+ même nombre de blocs :::::{question}. En cas d'écart → on garde la
16
+ version non traduite + warning (jamais de sortie corrompue).
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import logging
22
+ import re
23
+
24
+ from app.llm.client import process_with_openrouter
25
+ from app.pipeline.postprocess import (
26
+ INJECTION_RE,
27
+ detect_languages,
28
+ mask_python_blocks,
29
+ strip_language,
30
+ unmask_python_blocks,
31
+ )
32
+ from app.pipeline.prompts import (
33
+ TRANSLATE_FORMAT_BOTH,
34
+ TRANSLATE_FORMAT_MONO,
35
+ TRANSLATE_PROMPT,
36
+ )
37
+
38
+ logger = logging.getLogger(__name__)
39
+
40
+ _LABELS = {"fr": "le FRANÇAIS", "en": "l'ANGLAIS", "both": "le BILINGUE FR+EN"}
41
+
42
+
43
+ def _placeholders(text: str) -> set[str]:
44
+ return {tok.strip() for tok in INJECTION_RE.findall(text)}
45
+
46
+
47
+ def ensure_language(
48
+ exercise: str,
49
+ target: str,
50
+ model_idx: int,
51
+ ) -> tuple[str, list[dict], dict]:
52
+ """
53
+ Amène l'exercice dans la langue cible. Retourne
54
+ (exercice, warnings, info={"source": …, "target": …, "action": …}).
55
+ """
56
+ warnings: list[dict] = []
57
+ source = detect_languages(exercise)
58
+ info = {"source": source, "target": target, "action": "aucune"}
59
+
60
+ if target not in ("fr", "en", "both") or target == source:
61
+ return exercise, warnings, info
62
+
63
+ # Bilingue → mono : déterministe.
64
+ if source == "both" and target in ("fr", "en"):
65
+ info["action"] = f"réduction déterministe bilingue → {target}"
66
+ return strip_language(exercise, keep=target), warnings, info
67
+
68
+ # Mono → autre mono, ou mono → bilingue : LLM sur la prose seule.
69
+ # Les sentinelles internes \x00PYBLOCKn\x00 (caractère NUL) sont
70
+ # intransmissibles à un LLM — on les convertit en sentinelles texte
71
+ # copiables, puis on reconvertit au retour.
72
+ masked, blocks = mask_python_blocks(exercise)
73
+ for i in range(len(blocks)):
74
+ masked = masked.replace(f"\x00PYBLOCK{i}\x00", f"<<<PYBLOCK_{i}>>>")
75
+ fmt = (TRANSLATE_FORMAT_BOTH if target == "both"
76
+ else TRANSLATE_FORMAT_MONO.format(target_label=_LABELS[target]))
77
+ try:
78
+ raw = process_with_openrouter(
79
+ prompt=TRANSLATE_PROMPT.format(
80
+ source_label=_LABELS.get(source, source),
81
+ target_label=_LABELS[target],
82
+ body=masked,
83
+ format_directive=fmt,
84
+ ),
85
+ model_idx=model_idx,
86
+ temperature=0.0,
87
+ max_tokens=24000,
88
+ )
89
+ except (RuntimeError, ValueError, OSError) as e:
90
+ warnings.append({
91
+ "rule": "langue",
92
+ "message": f"Étape de traduction en échec ({e}) — sortie laissée en {source}.",
93
+ })
94
+ return exercise, warnings, info
95
+
96
+ translated = raw.strip()
97
+ translated = re.sub(r"^```\w*\s*\n", "", translated)
98
+ translated = re.sub(r"\n```\s*$", "", translated)
99
+ for i in range(len(blocks)):
100
+ translated = translated.replace(f"<<<PYBLOCK_{i}>>>", f"\x00PYBLOCK{i}\x00")
101
+
102
+ # Garde-fous structurels — si l'un casse, on n'applique PAS la traduction.
103
+ checks = []
104
+ for i in range(len(blocks)):
105
+ if f"\x00PYBLOCK{i}\x00" not in translated:
106
+ checks.append(f"sentinelle PYBLOCK{i} perdue")
107
+ if _placeholders(translated) != _placeholders(masked):
108
+ missing = _placeholders(masked) - _placeholders(translated)
109
+ added = _placeholders(translated) - _placeholders(masked)
110
+ checks.append(f"placeholders modifiés (perdus: {sorted(missing)[:4]}, ajoutés: {sorted(added)[:4]})")
111
+ if translated.count(":::::{question}") != masked.count(":::::{question}"):
112
+ checks.append("nombre de blocs question modifié")
113
+
114
+ if checks:
115
+ warnings.append({
116
+ "rule": "langue",
117
+ "message": ("Traduction rejetée par les garde-fous (" + " ; ".join(checks)
118
+ + ") — sortie laissée en " + source + "."),
119
+ })
120
+ return exercise, warnings, info
121
+
122
+ info["action"] = f"traduction LLM {source} → {target}"
123
+ return unmask_python_blocks(translated, blocks), warnings, info
app/rag/__init__.py ADDED
File without changes
app/rag/catalogue.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ catalogue.py
3
+ ────────────
4
+ Catalogue CURÉ des helpers PyxiScience (app/knowledge/functions_catalogue.md),
5
+ injecté par TRANCHE DE DOMAINE dans le prompt de génération.
6
+
7
+ Complète le RAG FAISS (app/rag/functions.py) : FAISS donne des hits sémantiques
8
+ sur le code réel (signatures/docstrings) ; ce catalogue donne la couche
9
+ « quel helper pour quel besoin » + les domaines que le corpus livré ne couvre
10
+ pas (matrices, proba, IBP). Les sections §0 (conventions) et §2 (briques
11
+ essentielles) sont toujours incluses ; la/les section(s) de domaine sont
12
+ choisies selon le type détecté à l'analyse.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import logging
18
+ import re
19
+ from functools import lru_cache
20
+
21
+ from app.config import KNOWLEDGE_DIR
22
+
23
+ logger = logging.getLogger(__name__)
24
+
25
+ _CATALOGUE_MD = KNOWLEDGE_DIR / "functions_catalogue.md"
26
+
27
+ # Sections toujours injectées (numéros de header `## N.`).
28
+ _ALWAYS = ("0", "2")
29
+
30
+ # Domaine → (sections, motif de déclenchement sur type/title/concepts).
31
+ _DOMAINS: list[tuple[str, tuple[str, ...], str]] = [
32
+ ("algebre_lineaire", ("6",),
33
+ r"matric|système|systeme|déterminant|determinant|gauss|invers|"
34
+ r"échelon|echelon|rref|vecteur|alg[eè]bre lin|linear algebra|pivot"),
35
+ ("probabilites", ("7",),
36
+ r"probabilit|variable al[ée]atoire|loi\b|espérance|esperance|variance|"
37
+ r"moment|binomial|distribution|tirage al[ée]atoire de v\.?a"),
38
+ ("integration", ("5",),
39
+ r"int[ée]gra|primitive|\bipp\b|parties|\bibp\b"),
40
+ ]
41
+ # §4 (généralistes) : injecté par défaut quand aucun domaine spécialisé ne sort
42
+ # (inéquations, coefficients, fractions, polynômes — le cas courant).
43
+ _DEFAULT_SECTIONS = ("4",)
44
+
45
+ _SECTION_RE = re.compile(r"(?m)^## (?P<num>\d+)\.\s.*$")
46
+
47
+
48
+ @lru_cache(maxsize=1)
49
+ def _sections() -> dict[str, str]:
50
+ """Découpe le catalogue en {num_section: texte (header inclus)}."""
51
+ if not _CATALOGUE_MD.exists():
52
+ logger.warning("Catalogue de fonctions absent : %s", _CATALOGUE_MD)
53
+ return {}
54
+ text = _CATALOGUE_MD.read_text(encoding="utf-8")
55
+ # Retire le commentaire HTML de vérification en tête.
56
+ text = re.sub(r"^<!--.*?-->\s*", "", text, count=1, flags=re.DOTALL)
57
+ matches = list(_SECTION_RE.finditer(text))
58
+ out: dict[str, str] = {}
59
+ for i, m in enumerate(matches):
60
+ end = matches[i + 1].start() if i + 1 < len(matches) else len(text)
61
+ out[m.group("num")] = text[m.start():end].strip()
62
+ return out
63
+
64
+
65
+ def select_sections(analysis: dict) -> list[str]:
66
+ """Numéros de sections à injecter pour cet exercice (ordre stable)."""
67
+ haystack = " ".join([
68
+ str(analysis.get("exercise_type", "")),
69
+ str(analysis.get("exercise_title", "")),
70
+ str(analysis.get("mathematical_structure", "")),
71
+ " ".join(str(c) for c in (analysis.get("suggested_concepts") or [])),
72
+ ]).lower()
73
+
74
+ domains = [secs for _name, secs, pat in _DOMAINS if re.search(pat, haystack)]
75
+ chosen = list(_ALWAYS)
76
+ if domains:
77
+ for secs in domains:
78
+ chosen.extend(secs)
79
+ else:
80
+ chosen.extend(_DEFAULT_SECTIONS)
81
+ # dédup en préservant l'ordre
82
+ return list(dict.fromkeys(chosen))
83
+
84
+
85
+ def catalogue_for(analysis: dict) -> str:
86
+ """Tranche curée du catalogue pour le type détecté (chaîne prête à injecter)."""
87
+ sections = _sections()
88
+ if not sections:
89
+ return ""
90
+ wanted = select_sections(analysis)
91
+ parts = [sections[n] for n in wanted if n in sections]
92
+ logger.info("Catalogue curé : sections %s injectées", wanted)
93
+ return "\n\n".join(parts)
app/rag/formatter.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ rag_formatter.py
3
+ ────────────────
4
+ Compact, LLM-optimized formatter for retrieved PyxiScience entities.
5
+
6
+ Replaces the legacy 4-section verbose catalogue (imports / signatures /
7
+ names / detailed) with a single structured block per entity, driven by
8
+ the :pxs_trigger: / :pxs_returns: / :pxs_example: / :pxs_antipattern:
9
+ meta-tags embedded in PyxiScience docstrings.
10
+
11
+ Entity dict schema expected by `build_catalogue`:
12
+
13
+ {
14
+ "qualname": "pxs_Poly.pxsl_solution",
15
+ "signature": "(mult='\\times', formula=True)",
16
+ "import_line": "from pyxiscience.Classes_Extensions import pxs_Poly",
17
+ "kind": "function" | "method" | "class",
18
+ "docstring": "<raw docstring, :pxs_*: tags intact>",
19
+ # for classes, optionally:
20
+ "methods": [{"name": str, "signature": str, "summary": str}, ...],
21
+ }
22
+
23
+ Functions and methods go through `_format_function_entity`.
24
+ Classes with a non-empty `methods` list go through `_format_class_entity`.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import re
30
+ import textwrap
31
+ from typing import Dict, List
32
+
33
+
34
+ # Regex patterns for the :pxs_*: meta-tags.
35
+ # Each one matches non-greedily up to the next :pxs_*: tag or end-of-string,
36
+ # so multi-line values are preserved.
37
+ _META_TAGS = {
38
+ "trigger": r":pxs_trigger:\s*(.+?)(?=\n\s*:pxs_|\Z)",
39
+ "returns": r":pxs_returns:\s*\|?\s*\n?(.+?)(?=\n\s*:pxs_|\Z)",
40
+ "example": r":pxs_example:\s*\|?\s*\n?(.+?)(?=\n\s*:pxs_|\Z)",
41
+ "antipattern": r":pxs_antipattern:\s*(.+?)(?=\n\s*:pxs_|\Z)",
42
+ }
43
+
44
+
45
+ def _extract_meta_tags(docstring: str) -> Dict[str, str]:
46
+ """Parse :pxs_*: tags from an enriched docstring into a flat dict."""
47
+ if not docstring:
48
+ return {}
49
+ meta: Dict[str, str] = {}
50
+ for key, pattern in _META_TAGS.items():
51
+ m = re.search(pattern, docstring, flags=re.DOTALL)
52
+ if m:
53
+ # Normalise indentation & trim trailing whitespace.
54
+ meta[key] = textwrap.dedent(m.group(1)).strip()
55
+ return meta
56
+
57
+
58
+ def _first_useful_line(docstring: str) -> str:
59
+ """
60
+ Fallback summary when no :pxs_trigger: is present.
61
+
62
+ Pulls the first non-trivial line BEFORE any :pxs_*: tag, strips
63
+ bilingual prefixes ('Fr :', '\\fr{', 'En :', etc.) and truncates.
64
+ """
65
+ if not docstring:
66
+ return ""
67
+ # Only look at the human-readable head (before the first meta-tag).
68
+ cut = re.search(r"^\s*:pxs_\w+:", docstring, flags=re.MULTILINE)
69
+ head = docstring[: cut.start()] if cut else docstring
70
+
71
+ for raw in head.splitlines():
72
+ line = raw.strip()
73
+ if not line or line.startswith((":", "---", "===", "Args:", "Returns:", "Paramètres")):
74
+ continue
75
+ # Strip bilingual markers.
76
+ line = re.sub(r"^(Fr|En|\\fr|\\en)\s*[:{]?\s*", "", line)
77
+ line = line.rstrip("}").strip()
78
+ if len(line) > 10:
79
+ return line[:140]
80
+ return ""
81
+
82
+
83
+ def _indent(text: str, prefix: str = " ") -> str:
84
+ """Indent every line of a block with a constant prefix."""
85
+ return "\n".join(prefix + line if line else line for line in text.splitlines())
86
+
87
+
88
+ # ────────────────────────────────────────────────────────────────────────
89
+ # Per-entity formatters
90
+ # ────────────────────────────────────────────────────────────────────────
91
+
92
+ def _format_function_entity(entity: Dict) -> str:
93
+ """Compact block for a standalone function or (unattached) method."""
94
+ meta = _extract_meta_tags(entity.get("docstring", ""))
95
+ lines: List[str] = []
96
+
97
+ # Header: qualified name + signature, then the import line.
98
+ lines.append(f"▸ {entity['qualname']}{entity.get('signature', '(...)')}")
99
+ lines.append(f" {entity['import_line']}")
100
+ lines.append("")
101
+
102
+ trigger = meta.get("trigger") or _first_useful_line(entity.get("docstring", ""))
103
+ if trigger:
104
+ lines.append("QUAND UTILISER")
105
+ lines.append(_indent(trigger))
106
+ lines.append("")
107
+
108
+ if meta.get("returns"):
109
+ lines.append("CE QUE ÇA RETOURNE")
110
+ lines.append(_indent(meta["returns"]))
111
+ lines.append("")
112
+
113
+ if meta.get("example"):
114
+ lines.append("EXEMPLE D'APPEL")
115
+ lines.append(_indent(meta["example"]))
116
+ lines.append("")
117
+
118
+ if meta.get("antipattern"):
119
+ lines.append("NE PAS RÉIMPLÉMENTER MANUELLEMENT")
120
+ lines.append(f" ✗ {meta['antipattern']}")
121
+ lines.append(f" ✓ Utiliser {entity['qualname']}")
122
+
123
+ while lines and lines[-1] == "":
124
+ lines.pop()
125
+ return "\n".join(lines)
126
+
127
+
128
+ def _format_class_entity(entity: Dict) -> str:
129
+ """
130
+ Compact block for a class + its methods. Expects entity['methods'] to be
131
+ a non-empty list of {name, signature, summary} dicts.
132
+ """
133
+ meta = _extract_meta_tags(entity.get("docstring", ""))
134
+ lines: List[str] = []
135
+
136
+ lines.append(f"▸ {entity['qualname']} (classe)")
137
+ lines.append(f" {entity['import_line']}")
138
+ lines.append("")
139
+
140
+ lines.append("MÉTHODES DISPONIBLES")
141
+ for m in entity["methods"]:
142
+ sig = m.get("signature", "(...)")
143
+ summary = (m.get("summary") or "").strip()
144
+ suffix = f" — {summary}" if summary else ""
145
+ lines.append(f" .{m['name']}{sig}{suffix}")
146
+ lines.append("")
147
+
148
+ trigger = meta.get("trigger") or _first_useful_line(entity.get("docstring", ""))
149
+ if trigger:
150
+ lines.append("QUAND UTILISER (la classe)")
151
+ lines.append(_indent(trigger))
152
+ lines.append("")
153
+
154
+ if meta.get("example"):
155
+ lines.append("EXEMPLE D'USAGE TYPIQUE")
156
+ lines.append(_indent(meta["example"]))
157
+ lines.append("")
158
+
159
+ if meta.get("antipattern"):
160
+ lines.append("NE PAS RÉIMPLÉMENTER MANUELLEMENT")
161
+ lines.append(f" ✗ {meta['antipattern']}")
162
+ lines.append(f" ✓ Utiliser {entity['qualname']}")
163
+
164
+ while lines and lines[-1] == "":
165
+ lines.pop()
166
+ return "\n".join(lines)
167
+
168
+
169
+ def _format_entity_for_llm(entity: Dict) -> str:
170
+ """Dispatch: class with methods → grouped block; else → function block."""
171
+ if entity.get("kind") == "class" and entity.get("methods"):
172
+ return _format_class_entity(entity)
173
+ return _format_function_entity(entity)
174
+
175
+
176
+ # ────────────────────────────────────────────────────────────────────────
177
+ # Public API
178
+ # ────────────────────────────────────────────────────────────────────────
179
+
180
+ _SEP = "━" * 55
181
+
182
+
183
+ def build_catalogue(entities: List[Dict]) -> str:
184
+ """
185
+ Assemble the full catalogue string from an ordered list of retrieved
186
+ entity dicts. Use this as the `{functions}` injection in a downstream
187
+ code-generation prompt.
188
+ """
189
+ if not entities:
190
+ return "Aucune fonction PyxiScience pertinente détectée pour cet exercice."
191
+
192
+ header = [
193
+ "FONCTIONS PYXISCIENCE DISPONIBLES — USAGE OBLIGATOIRE",
194
+ "",
195
+ "Les entités ci-dessous ont été sélectionnées comme pertinentes",
196
+ "pour cet exercice. Utilise-les plutôt que de réimplémenter",
197
+ "leur logique à la main — c'est la différence entre du code",
198
+ "PyxiScience et du code générique qui sera rejeté.",
199
+ "",
200
+ ]
201
+
202
+ blocks = [_format_entity_for_llm(e) for e in entities]
203
+ body = f"\n{_SEP}\n".join([_SEP] + blocks + [_SEP])
204
+
205
+ return "\n".join(header) + body
206
+
207
+
208
+ def build_imports_block(entities: List[Dict]) -> str:
209
+ """
210
+ Produce a de-duplicated 'from X import a, b, c' block from the entities,
211
+ grouped by module. For methods, we import the PARENT CLASS (not the
212
+ method itself — that's unimportable).
213
+ """
214
+ by_module: Dict[str, set] = {}
215
+ for e in entities:
216
+ import_line = e.get("import_line", "")
217
+ m = re.match(r"from\s+(\S+)\s+import\s+(.+)", import_line)
218
+ if not m:
219
+ continue
220
+ module, names = m.group(1), m.group(2)
221
+ by_module.setdefault(module, set()).update(
222
+ n.strip() for n in names.split(",") if n.strip()
223
+ )
224
+ if not by_module:
225
+ return "# (aucun import)"
226
+ return "\n".join(
227
+ f"from {mod} import {', '.join(sorted(names))}"
228
+ for mod, names in sorted(by_module.items())
229
+ )
app/rag/functions.py ADDED
@@ -0,0 +1,1093 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ PyxiScience RAG Pipeline — Source-Based, Corrected Edition
3
+ ===========================================================
4
+
5
+ What changed vs the legacy `rag.py`:
6
+
7
+ 1. FIXED — Method `import_line`. Legacy code emitted
8
+ from pyxiscience.Classes_Extensions import pxsl_solution
9
+ which is unimportable (pxsl_solution is a *method* of pxs_Poly).
10
+ Each method Document now carries:
11
+ import_line = "from <module> import <parent_class>"
12
+ parent_class = "<ClassName>"
13
+ qualname = "<ClassName>.<method_name>"
14
+
15
+ 2. FIXED — Class/method grouping. Each class Document now carries a
16
+ serialised `methods` list in its metadata. When a class is
17
+ retrieved, it renders as ONE grouped block (class header + all
18
+ method signatures + one-line summaries) via the compact formatter.
19
+
20
+ 3. FIXED — De-duplication at render time. If both a class AND some of
21
+ its own methods are retrieved, the methods are absorbed into the
22
+ class's rendered block instead of being emitted as duplicate
23
+ standalone blocks underneath.
24
+
25
+ 4. INTEGRATED — Compact LLM-optimized formatter (rag_formatter.py)
26
+ replaces the legacy 4-section verbose catalogue. Leverages the
27
+ :pxs_trigger: / :pxs_returns: / :pxs_example: / :pxs_antipattern:
28
+ meta-tags embedded in PyxiScience docstrings.
29
+
30
+ 5. SCHEMA — CACHE_SCHEMA_VERSION bumped 2 → 3. Old FAISS caches are
31
+ auto-invalidated on first load (see `_is_cache_stale`).
32
+
33
+ 6. EXTENDED — ALWAYS_INCLUDE now includes `pxs_Interval` (class) and
34
+ `pxsl_pow` (function). These are ubiquitous in analysis exercises
35
+ (domains, solution sets, variation tables) and polynomial display
36
+ (safe coefficient parenthesisation) but were systematically missed
37
+ by semantic retrieval because their trigger words don't appear in
38
+ exercise statements. `build_always_include_context` now emits
39
+ kind-aware diagnostics so missing/malformed baseline entries are
40
+ loud at startup.
41
+
42
+ ⚠️ After enriching docstrings (`:pxs_trigger:` / etc.), call
43
+ `clear_cache(<model_key>)` once — the embedded `page_content` has
44
+ changed but `CACHE_SCHEMA_VERSION` did not, so caches won't
45
+ auto-invalidate on content-only changes.
46
+
47
+ Public entry points (unchanged names):
48
+
49
+ retrieve_functions_context(exercise, ...)
50
+ Pure retrieval + compact catalogue. NO LLM call. This is what a
51
+ downstream code-generation prompt should inject as `{functions}`.
52
+
53
+ retrieve_raw(exercise, ...)
54
+ Just the ranked top-k hits with scores.
55
+
56
+ retrieve_functions(exercise, model=..., ...)
57
+ retrieve_functions_context + an LLM hop. Standalone Q&A only.
58
+ """
59
+
60
+ from __future__ import annotations
61
+
62
+ import logging
63
+ import os
64
+ import re
65
+ import ast
66
+ import time
67
+ from pathlib import Path
68
+ from typing import Optional, List, Dict, Any, Tuple
69
+
70
+ from langchain_openai import ChatOpenAI
71
+ from langchain_community.vectorstores import FAISS
72
+ from langchain_core.documents import Document
73
+
74
+ # HuggingFaceEmbeddings tire torch + sentence-transformers (~1 Go). Il n'est
75
+ # nécessaire QUE pour les embeddings locaux ; le défaut `openai-3-small` passe
76
+ # par l'API. Import PARESSEUX → l'app (et le déploiement slim) tourne sans torch.
77
+ def _load_hf_embeddings_cls():
78
+ from langchain_huggingface import HuggingFaceEmbeddings
79
+ return HuggingFaceEmbeddings
80
+
81
+
82
+ try:
83
+ from langchain_openai import OpenAIEmbeddings
84
+ _OPENAI_AVAILABLE = True
85
+ except ImportError:
86
+ _OPENAI_AVAILABLE = False
87
+
88
+ from app.rag.formatter import build_catalogue, build_imports_block
89
+
90
+ logger = logging.getLogger(__name__)
91
+
92
+
93
+ # =============================================================================
94
+ # 1. CONFIGURATION
95
+ # =============================================================================
96
+
97
+ from app.config import CORPUS_DIR, FAISS_CACHE
98
+
99
+ from app.keys import OPENROUTER_API_KEY, OPENAI_API_KEY
100
+
101
+ OPENROUTER_MODELS = {
102
+ "claude-haiku": "anthropic/claude-3-haiku",
103
+ "gpt-4o-mini": "openai/gpt-4o-mini",
104
+ "deepseek": "deepseek/deepseek-chat",
105
+ "gemini-flash": "google/gemini-flash-1.5",
106
+ "claude-sonnet": "anthropic/claude-4.5-sonnet",
107
+ }
108
+
109
+ SCRIPTS_DIR = CORPUS_DIR
110
+
111
+ PYXISCIENCE_SOURCE_FILES = {
112
+ "Classes_Extensions": "pyxiscience.Classes_Extensions",
113
+ "Mes_fctions_d_alg_lineaire_bis": "pyxiscience.Mes_fctions_d_alg_lineaire_bis",
114
+ "Mes_fctions_d_analyse_bis": "pyxiscience.Mes_fctions_d_analyse_bis",
115
+ "Mes_fctions_generalistes_bis": "pyxiscience.Mes_fctions_generalistes_bis",
116
+ "Mes_fctions_probabilistes_bis": "pyxiscience.Mes_fctions_probabilistes_bis",
117
+ }
118
+
119
+ # ---------------------------------------------------------------------------
120
+ # ALWAYS_INCLUDE
121
+ # ---------------------------------------------------------------------------
122
+ # Entities injected into every prompt regardless of retrieval score.
123
+ # These are "ubiquitous utilities": functions/classes that the expert
124
+ # reaches for in ≥70% of exercises but whose trigger words rarely appear
125
+ # in the exercise statement itself, so semantic retrieval misses them.
126
+ #
127
+ # Ordering is preserved in the final catalogue (ALWAYS first, then
128
+ # retrieved entities).
129
+ #
130
+ # ─ Core formatting (present from v3) ─
131
+ # pxsl_latex_coefficient — signed coefficient "+ 3x", "- x", ""
132
+ # pxsl_format_number — bilingual thousands separator + \infty
133
+ # pxsl_res_num — " = "/" \approx " result formatting
134
+ # pxsl_matrix — LaTeX matrix with auto delimiters
135
+ # pxs_config — sympy.latex kwargs (FR/EN, ln_notation, …)
136
+ #
137
+ # ─ Analysis & polynomial display (added v3.1) ─
138
+ # pxs_Interval — classe ubiquitaire pour domaines, ensembles solution,
139
+ # tableaux de variations, image d'intervalle par TVI.
140
+ # La classe porte ses méthodes (.print, .from_Interval)
141
+ # dans sa metadata → rendues groupées dans le catalogue.
142
+ # pxsl_pow — affichage sécurisé coeff^n avec parenthèses auto sur
143
+ # coeff négatif/rationnel/composé. Indispensable dans
144
+ # tout corrigé pédagogique avec substitution numérique.
145
+ # ---------------------------------------------------------------------------
146
+ ALWAYS_INCLUDE = [
147
+ "pxsl_latex_coefficient",
148
+ "pxsl_format_number",
149
+ "pxsl_res_num",
150
+ "pxsl_matrix",
151
+ "pxs_config",
152
+ # Added v3.1 — ubiquitous in analysis & polynomial display
153
+ "pxs_Interval",
154
+ "pxsl_pow",
155
+ ]
156
+
157
+ SOURCES_CACHE_ROOT = FAISS_CACHE
158
+ CACHE_SCHEMA_VERSION = 3 # bumped (method import fix)
159
+
160
+ # FAISS L2 on normalised embeddings ∈ [0, 2]; lower = better.
161
+ DEFAULT_SCORE_THRESHOLD = 1.6
162
+ DEFAULT_MODEL_KEY = "openai-3-small"
163
+
164
+
165
+ # =============================================================================
166
+ # 2. EMBEDDING MODELS REGISTRY
167
+ # =============================================================================
168
+
169
+ EMBEDDING_MODELS: Dict[str, Dict] = {
170
+ "codesearch-distilroberta": {
171
+ "model_name": "flax-sentence-embeddings/st-codesearch-distilroberta-base",
172
+ "description": "Code-search DistilRoBERTa — optimized for code retrieval (EN)",
173
+ "normalize": True, "prefix": None, "backend": "huggingface", "cost_per_1k": None,
174
+ },
175
+ "minilm-multilingual": {
176
+ "model_name": "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2",
177
+ "description": "Multilingual MiniLM — fast, decent FR/EN",
178
+ "normalize": True, "prefix": None, "backend": "huggingface", "cost_per_1k": None,
179
+ },
180
+ "mpnet-multilingual": {
181
+ "model_name": "sentence-transformers/paraphrase-multilingual-mpnet-base-v2",
182
+ "description": "Multilingual MPNet — strong FR/EN, good default",
183
+ "normalize": True, "prefix": None, "backend": "huggingface", "cost_per_1k": None,
184
+ },
185
+ "distiluse-multilingual": {
186
+ "model_name": "sentence-transformers/distiluse-base-multilingual-cased-v2",
187
+ "description": "Distilled USE multilingual",
188
+ "normalize": True, "prefix": None, "backend": "huggingface", "cost_per_1k": None,
189
+ },
190
+ "labse": {
191
+ "model_name": "sentence-transformers/LaBSE",
192
+ "description": "LaBSE — 109 languages, strong cross-lingual",
193
+ "normalize": True, "prefix": None, "backend": "huggingface", "cost_per_1k": None,
194
+ },
195
+ "e5-multilingual-small": {
196
+ "model_name": "intfloat/multilingual-e5-small",
197
+ "description": "Multilingual E5 small",
198
+ "normalize": True, "prefix": "query: ", "backend": "huggingface", "cost_per_1k": None,
199
+ },
200
+ "e5-multilingual-base": {
201
+ "model_name": "intfloat/multilingual-e5-base",
202
+ "description": "Multilingual E5 base — top HF retrieval",
203
+ "normalize": True, "prefix": "query: ", "backend": "huggingface", "cost_per_1k": None,
204
+ },
205
+ "e5-multilingual-large": {
206
+ "model_name": "intfloat/multilingual-e5-large",
207
+ "description": "Multilingual E5 large — slow",
208
+ "normalize": True, "prefix": "query: ", "backend": "huggingface", "cost_per_1k": None,
209
+ },
210
+ "all-mpnet-base": {
211
+ "model_name": "sentence-transformers/all-mpnet-base-v2",
212
+ "description": "English MPNet",
213
+ "normalize": True, "prefix": None, "backend": "huggingface", "cost_per_1k": None,
214
+ },
215
+ "all-minilm-l6": {
216
+ "model_name": "sentence-transformers/all-MiniLM-L6-v2",
217
+ "description": "English MiniLM L6",
218
+ "normalize": True, "prefix": None, "backend": "huggingface", "cost_per_1k": None,
219
+ },
220
+ "openai-3-small": {
221
+ "model_name": "text-embedding-3-small",
222
+ "description": "OpenAI 3-small — 1536-dim, cheap, multilingual",
223
+ "normalize": True, "prefix": None, "backend": "openai",
224
+ "cost_per_1k": 0.00002, "dimensions": 1536,
225
+ },
226
+ "openai-3-large": {
227
+ "model_name": "text-embedding-3-large",
228
+ "description": "OpenAI 3-large — 3072-dim",
229
+ "normalize": True, "prefix": None, "backend": "openai",
230
+ "cost_per_1k": 0.00013, "dimensions": 3072,
231
+ },
232
+ "openai-ada-002": {
233
+ "model_name": "text-embedding-ada-002",
234
+ "description": "OpenAI ada-002 — legacy",
235
+ "normalize": True, "prefix": None, "backend": "openai",
236
+ "cost_per_1k": 0.00010, "dimensions": 1536,
237
+ },
238
+ }
239
+
240
+
241
+ # =============================================================================
242
+ # 3. SOURCE FILE PARSER — CORRECTED
243
+ # =============================================================================
244
+
245
+ def _extract_signature(node: ast.AST) -> str:
246
+ """Signature like 'f(x, y=0, **kwargs)' via ast.unparse (Py ≥ 3.9)."""
247
+ try:
248
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
249
+ return f"{node.name}({ast.unparse(node.args)})"
250
+ if isinstance(node, ast.ClassDef):
251
+ # Prefer __init__ signature; fallback to generic "..."
252
+ for item in node.body:
253
+ if (isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef))
254
+ and item.name == "__init__"):
255
+ args_src = ast.unparse(item.args)
256
+ args_src = re.sub(r"^self\s*,?\s*", "", args_src)
257
+ return f"{node.name}({args_src})"
258
+ return f"{node.name}(...)"
259
+ except Exception:
260
+ pass
261
+ return f"{getattr(node, 'name', '?')}(...)"
262
+
263
+
264
+ def _method_signature(node: ast.AST) -> str:
265
+ """Method signature with leading `self` stripped."""
266
+ try:
267
+ args_src = ast.unparse(node.args)
268
+ args_src = re.sub(r"^self\s*,?\s*", "", args_src)
269
+ return f"({args_src})"
270
+ except Exception:
271
+ return "(...)"
272
+
273
+
274
+ def _summary_from_docstring(docstring: str) -> str:
275
+ """
276
+ One-line purpose extracted from the first non-trivial line of the
277
+ docstring, up to the first :pxs_*: tag. Used to annotate methods
278
+ in a class-grouped block.
279
+ """
280
+ if not docstring:
281
+ return ""
282
+ cut = re.search(r"^\s*:pxs_\w+:", docstring, flags=re.MULTILINE)
283
+ head = docstring[: cut.start()] if cut else docstring
284
+ for raw in head.splitlines():
285
+ line = raw.strip()
286
+ if not line or line.startswith(("Args:", "Returns:", "Paramètres", "Retourne",
287
+ "Lève", "Exemples", "---", "===")):
288
+ continue
289
+ return line[:90]
290
+ return ""
291
+
292
+
293
+ def _page_content_for_embedding(doc_meta: Dict[str, Any], docstring: str,
294
+ source_snippet: str) -> str:
295
+ """
296
+ Text fed to the embedder. Keep it dense in retrieval signal: qualname,
297
+ signature, the full docstring (incl. :pxs_*: tags — triggers matter a
298
+ lot for semantic match), and a trimmed source snippet.
299
+ """
300
+ head = (
301
+ f"NAME : {doc_meta['qualname']}\n"
302
+ f"SIGNATURE: {doc_meta['signature']}\n"
303
+ f"IMPORT : {doc_meta['import_line']}\n"
304
+ f"KIND : {doc_meta['kind']}\n"
305
+ )
306
+ body = head
307
+ if docstring:
308
+ body += f"\nDESCRIPTION:\n{docstring}\n"
309
+ body += f"\nSOURCE:\n{source_snippet}"
310
+ return body
311
+
312
+
313
+ def parse_python_source(filepath: str, module_name: str) -> List[Document]:
314
+ """
315
+ AST-walk a Python source file and emit one Document per top-level
316
+ function, class, and method.
317
+
318
+ Key fix: methods' `import_line` references the PARENT CLASS, not
319
+ the method name. Classes carry a serialised `methods` list so the
320
+ renderer can group them.
321
+ """
322
+ with open(filepath, "r", encoding="utf-8") as fh:
323
+ source = fh.read()
324
+ try:
325
+ tree = ast.parse(source)
326
+ except SyntaxError as e:
327
+ logger.info(f" ⚠️ SyntaxError in {filepath}: {e}")
328
+ return []
329
+
330
+ lines = source.splitlines()
331
+
332
+ def get_source_block(node, limit: int = 1200) -> str:
333
+ start = node.lineno - 1
334
+ end = getattr(node, "end_lineno", start + 40)
335
+ block = "\n".join(lines[start:end])
336
+ return block[:limit] + ("\n..." if len(block) > limit else "")
337
+
338
+ docs: List[Document] = []
339
+
340
+ for node in ast.iter_child_nodes(tree):
341
+
342
+ # ── Top-level function ────────────────────────────────────────
343
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
344
+ name = node.name
345
+ docstring = ast.get_docstring(node) or ""
346
+ signature = _extract_signature(node)
347
+ meta = {
348
+ "schema_version": CACHE_SCHEMA_VERSION,
349
+ "qualname": name,
350
+ "base_name": name,
351
+ "parent_class": "",
352
+ "module_name": module_name,
353
+ "import_line": f"from {module_name} import {name}",
354
+ "signature": signature.replace(name, "", 1), # "(...)" only
355
+ "kind": "function",
356
+ "docstring": docstring,
357
+ "filepath": filepath,
358
+ "methods": [], # unused for functions
359
+ }
360
+ # Keep full signature string alongside for downstream convenience
361
+ meta["signature"] = re.sub(r"^[^(]*", "", signature) or "(...)"
362
+ snippet = get_source_block(node)
363
+ docs.append(Document(
364
+ page_content=_page_content_for_embedding(meta, docstring, snippet),
365
+ metadata=meta,
366
+ ))
367
+ continue
368
+
369
+ # ── Class ─────────────────────────────────────────────────────
370
+ if isinstance(node, ast.ClassDef):
371
+ cls_name = node.name
372
+ cls_docstring = ast.get_docstring(node) or ""
373
+ cls_signature = _extract_signature(node) # e.g. "pxs_Poly(x, ...)"
374
+ cls_signature = re.sub(r"^[^(]*", "", cls_signature) or "(...)"
375
+
376
+ # Collect methods first so we can stash them on the class doc.
377
+ method_nodes = [
378
+ item for item in node.body
379
+ if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef))
380
+ ]
381
+
382
+ methods_meta: List[Dict[str, str]] = []
383
+ for m in method_nodes:
384
+ msig = _method_signature(m)
385
+ mdoc = ast.get_docstring(m) or ""
386
+ methods_meta.append({
387
+ "name": m.name,
388
+ "signature": msig,
389
+ "summary": _summary_from_docstring(mdoc),
390
+ })
391
+
392
+ # Class Document (retrievable on its own; renders grouped).
393
+ cls_meta = {
394
+ "schema_version": CACHE_SCHEMA_VERSION,
395
+ "qualname": cls_name,
396
+ "base_name": cls_name,
397
+ "parent_class": "",
398
+ "module_name": module_name,
399
+ "import_line": f"from {module_name} import {cls_name}",
400
+ "signature": cls_signature,
401
+ "kind": "class",
402
+ "docstring": cls_docstring,
403
+ "filepath": filepath,
404
+ "methods": methods_meta,
405
+ }
406
+ docs.append(Document(
407
+ page_content=_page_content_for_embedding(
408
+ cls_meta, cls_docstring, get_source_block(node, limit=600)
409
+ ),
410
+ metadata=cls_meta,
411
+ ))
412
+
413
+ # Method Documents (retrievable individually; FIXED import line).
414
+ for m in method_nodes:
415
+ m_name = m.name
416
+ m_doc = ast.get_docstring(m) or ""
417
+ m_sig = _method_signature(m)
418
+ m_qual = f"{cls_name}.{m_name}"
419
+ m_meta = {
420
+ "schema_version": CACHE_SCHEMA_VERSION,
421
+ "qualname": m_qual,
422
+ "base_name": m_name,
423
+ "parent_class": cls_name,
424
+ "module_name": module_name,
425
+ # ⚠️ Methods are not importable on their own — import the class.
426
+ "import_line": f"from {module_name} import {cls_name}",
427
+ "signature": m_sig,
428
+ "kind": "method",
429
+ "docstring": m_doc,
430
+ "filepath": filepath,
431
+ "methods": [],
432
+ }
433
+ docs.append(Document(
434
+ page_content=_page_content_for_embedding(
435
+ m_meta, m_doc, get_source_block(m)
436
+ ),
437
+ metadata=m_meta,
438
+ ))
439
+
440
+ return docs
441
+
442
+
443
+ def load_all_sources(scripts_dir: str | Path = SCRIPTS_DIR) -> List[Document]:
444
+ all_docs: List[Document] = []
445
+ for filename, module_name in PYXISCIENCE_SOURCE_FILES.items():
446
+ candidates = [
447
+ os.path.join(scripts_dir, filename),
448
+ os.path.join(scripts_dir, filename + ".py"),
449
+ ]
450
+ filepath = next((p for p in candidates if os.path.exists(p)), None)
451
+ if filepath is None:
452
+ logger.info(f" ⚠️ Not found: {filename} (skipping)")
453
+ continue
454
+ logger.info(f" 📄 Parsing {filename} → {module_name}")
455
+ docs = parse_python_source(filepath, module_name)
456
+ all_docs.extend(docs)
457
+ logger.info(f" → {len(docs)} functions/classes/methods indexed")
458
+ return all_docs
459
+
460
+
461
+ def build_always_include_context(all_docs: List[Document]) -> List[Document]:
462
+ """
463
+ Resolve ALWAYS_INCLUDE names → Documents. We match on `qualname` (which
464
+ equals the bare name for top-level functions and classes).
465
+
466
+ Kind-aware diagnostics:
467
+ - A missing entry is a hard warning (the entity won't be injected).
468
+ - A class with no methods is a soft warning (likely a parser
469
+ regression — its methods won't be listed in the catalogue block).
470
+ - Duplicate base_names across modules (e.g. `pxsl_pow` defined in
471
+ two source files) are flagged so the user can dedupe canonically.
472
+ """
473
+ # Detect duplicates across modules BEFORE dedup-by-qualname.
474
+ base_name_locations: Dict[str, List[str]] = {}
475
+ for d in all_docs:
476
+ if d.metadata.get("parent_class"):
477
+ continue # skip methods (their name collides with siblings by design)
478
+ base = d.metadata["base_name"]
479
+ base_name_locations.setdefault(base, []).append(d.metadata["module_name"])
480
+
481
+ for name in ALWAYS_INCLUDE:
482
+ locs = base_name_locations.get(name, [])
483
+ if len(locs) > 1:
484
+ logger.info(
485
+ f" ⚠️ ALWAYS_INCLUDE '{name}' defined in MULTIPLE modules: "
486
+ f"{locs} — last one wins in the index, consider deduping."
487
+ )
488
+
489
+ # The actual resolution index — one doc per top-level qualname
490
+ # (duplicates get clobbered; that's the existing behaviour).
491
+ index = {d.metadata["qualname"]: d for d in all_docs if not d.metadata["parent_class"]}
492
+
493
+ result: List[Document] = []
494
+ for name in ALWAYS_INCLUDE:
495
+ doc = index.get(name)
496
+ if doc is None:
497
+ logger.info(
498
+ f" ⚠️ ALWAYS_INCLUDE '{name}' not found in sources — "
499
+ f"check PYXISCIENCE_SOURCE_FILES and that the symbol is "
500
+ f"defined at module top-level."
501
+ )
502
+ continue
503
+
504
+ kind = doc.metadata.get("kind", "?")
505
+ if kind == "class" and not doc.metadata.get("methods"):
506
+ logger.info(
507
+ f" ⚠️ ALWAYS_INCLUDE class '{name}' has no methods in its "
508
+ f"metadata — likely a parser issue. Catalogue will show the "
509
+ f"class header only."
510
+ )
511
+
512
+ logger.info(f" ✓ ALWAYS_INCLUDE '{name}' → {kind} "
513
+ f"({doc.metadata['module_name']})")
514
+ result.append(doc)
515
+
516
+ return result
517
+
518
+
519
+ # =============================================================================
520
+ # 4. EMBEDDINGS + VECTORSTORE
521
+ # =============================================================================
522
+
523
+ _vs_cache: Dict[str, FAISS] = {}
524
+ _emb_cache: Dict[str, object] = {}
525
+ _always_docs: List[Document] = []
526
+
527
+
528
+ def _resolve_openai_key() -> str:
529
+ if not _OPENAI_AVAILABLE:
530
+ raise RuntimeError("pip install langchain-openai")
531
+ key = OPENAI_API_KEY
532
+ if not key or len(key) < 20:
533
+ raise RuntimeError("OpenAI embedding models require OPENAI_API_KEY.")
534
+ return key
535
+
536
+
537
+ def _get_embeddings(model_key: str = DEFAULT_MODEL_KEY) -> object:
538
+ if model_key in _emb_cache:
539
+ return _emb_cache[model_key]
540
+ cfg = EMBEDDING_MODELS.get(model_key)
541
+ if cfg is None:
542
+ raise ValueError(
543
+ f"Unknown model key '{model_key}'. "
544
+ f"Available: {list(EMBEDDING_MODELS.keys())}"
545
+ )
546
+ backend = cfg.get("backend", "huggingface")
547
+ logger.info(f" 🔧 Loading embedding model [{backend}]: {cfg['model_name']} ...")
548
+ if backend == "openai":
549
+ emb = OpenAIEmbeddings(
550
+ model=cfg["model_name"],
551
+ openai_api_key=_resolve_openai_key(),
552
+ )
553
+ else:
554
+ HuggingFaceEmbeddings = _load_hf_embeddings_cls()
555
+ emb = HuggingFaceEmbeddings(
556
+ model_name=cfg["model_name"],
557
+ model_kwargs={"device": "cpu"},
558
+ encode_kwargs={"normalize_embeddings": cfg["normalize"]},
559
+ )
560
+ _emb_cache[model_key] = emb
561
+ return emb
562
+
563
+
564
+ def _cache_path_for(model_key: str) -> Path:
565
+ return SOURCES_CACHE_ROOT / model_key
566
+
567
+
568
+ def _is_cache_stale(vs: FAISS) -> Tuple[bool, str]:
569
+ """Detect old caches built with a prior metadata schema."""
570
+ try:
571
+ if not vs.index_to_docstore_id:
572
+ return True, "empty index"
573
+ first_id = vs.index_to_docstore_id[0]
574
+ first_doc = vs.docstore.search(first_id)
575
+ if not isinstance(first_doc, Document):
576
+ return True, f"docstore returned {type(first_doc)}"
577
+ meta = first_doc.metadata or {}
578
+ version = meta.get("schema_version", 0)
579
+ if version < CACHE_SCHEMA_VERSION:
580
+ return True, f"schema v{version} < current v{CACHE_SCHEMA_VERSION}"
581
+ # Sanity: v3 requires 'qualname' and 'parent_class' in every doc.
582
+ if "qualname" not in meta or "parent_class" not in meta:
583
+ return True, "missing qualname/parent_class metadata"
584
+ return False, ""
585
+ except Exception as e:
586
+ return True, f"inspection failed: {e}"
587
+
588
+
589
+ def setup_vectorstore(
590
+ scripts_dir: str | Path = SCRIPTS_DIR,
591
+ model_key: str = DEFAULT_MODEL_KEY,
592
+ use_cache: bool = True,
593
+ force_rebuild: bool = False,
594
+ ) -> FAISS:
595
+ global _always_docs
596
+
597
+ if model_key in _vs_cache and not force_rebuild:
598
+ if not _always_docs:
599
+ _always_docs = build_always_include_context(load_all_sources(scripts_dir))
600
+ return _vs_cache[model_key]
601
+
602
+ cache_path = _cache_path_for(model_key)
603
+ emb = _get_embeddings(model_key)
604
+
605
+ # Try cache.
606
+ if use_cache and not force_rebuild and cache_path.exists():
607
+ try:
608
+ logger.info(f"📦 Loading sources vectorstore from cache ({model_key})...")
609
+ vs = FAISS.load_local(
610
+ str(cache_path), emb, allow_dangerous_deserialization=True
611
+ )
612
+ stale, reason = _is_cache_stale(vs)
613
+ if stale:
614
+ logger.info(f"♻️ Cache stale ({reason}) — rebuilding")
615
+ else:
616
+ logger.info(f"✅ Loaded {vs.index.ntotal} vectors (schema v{CACHE_SCHEMA_VERSION})")
617
+ _vs_cache[model_key] = vs
618
+ _always_docs = build_always_include_context(load_all_sources(scripts_dir))
619
+ return vs
620
+ except Exception as e:
621
+ logger.info(f"⚠️ Cache load failed, rebuilding: {e}")
622
+
623
+ # Rebuild.
624
+ logger.info(f"🔨 Building sources vectorstore with '{model_key}'...")
625
+ all_docs = load_all_sources(scripts_dir)
626
+ _always_docs = build_always_include_context(all_docs)
627
+
628
+ if not all_docs:
629
+ raise RuntimeError(f"No documents found in {scripts_dir}.")
630
+
631
+ # E5-style models want a 'passage: ' prefix on indexed docs,
632
+ # 'query: ' on the query.
633
+ cfg = EMBEDDING_MODELS[model_key]
634
+ if cfg.get("prefix"):
635
+ passage_prefix = cfg["prefix"].replace("query: ", "passage: ")
636
+ for d in all_docs:
637
+ d.page_content = passage_prefix + d.page_content
638
+
639
+ logger.info(f"🧮 Embedding {len(all_docs)} entities with '{model_key}'...")
640
+ vs = FAISS.from_documents(all_docs, emb)
641
+ _vs_cache[model_key] = vs
642
+
643
+ if use_cache:
644
+ cache_path.mkdir(parents=True, exist_ok=True)
645
+ vs.save_local(str(cache_path))
646
+ logger.info(f"💾 Cache saved → {cache_path}")
647
+
648
+ return vs
649
+
650
+
651
+ # =============================================================================
652
+ # 5. DEDUPLICATION + ENTITY CONVERSION
653
+ # =============================================================================
654
+
655
+ def _doc_to_entity(doc: Document) -> Dict[str, Any]:
656
+ """Document → entity dict understood by rag_formatter.build_catalogue."""
657
+ m = doc.metadata
658
+ return {
659
+ "qualname": m["qualname"],
660
+ "signature": m.get("signature", "(...)"),
661
+ "import_line": m["import_line"],
662
+ "kind": m["kind"],
663
+ "docstring": m.get("docstring", ""),
664
+ "methods": list(m.get("methods", [])) if m["kind"] == "class" else [],
665
+ # Extra fields preserved for debugging/telemetry:
666
+ "module_name": m["module_name"],
667
+ "parent_class": m.get("parent_class", ""),
668
+ }
669
+
670
+
671
+ def _merge_docs(retrieved_docs: List[Document],
672
+ always_docs: List[Document]) -> List[Document]:
673
+ """
674
+ Merge ALWAYS_INCLUDE + retrieved, de-duplicated by qualname,
675
+ preserving ALWAYS order first.
676
+ """
677
+ seen: set = set()
678
+ merged: List[Document] = []
679
+ for doc in always_docs + retrieved_docs:
680
+ q = doc.metadata["qualname"]
681
+ if q in seen:
682
+ continue
683
+ seen.add(q)
684
+ merged.append(doc)
685
+ return merged
686
+
687
+
688
+ def _absorb_methods_into_classes(docs: List[Document]) -> List[Document]:
689
+ """
690
+ If a class Document AND some of its methods are both in `docs`, keep
691
+ the class and drop the loose methods (the class block already lists
692
+ them). Standalone methods whose class is NOT retrieved stay as-is.
693
+ """
694
+ retrieved_classes = {
695
+ d.metadata["qualname"] for d in docs if d.metadata["kind"] == "class"
696
+ }
697
+ if not retrieved_classes:
698
+ return docs
699
+ return [
700
+ d for d in docs
701
+ if not (d.metadata["kind"] == "method"
702
+ and d.metadata.get("parent_class") in retrieved_classes)
703
+ ]
704
+
705
+
706
+ def _flatten_metadata(docs: List[Document]) -> List[Dict[str, Any]]:
707
+ return [
708
+ {
709
+ "qualname": d.metadata["qualname"],
710
+ "import_line": d.metadata["import_line"],
711
+ "signature": d.metadata.get("signature", ""),
712
+ "docstring": (d.metadata.get("docstring") or "")[:300],
713
+ "kind": d.metadata["kind"],
714
+ "module_name": d.metadata["module_name"],
715
+ "parent_class": d.metadata.get("parent_class", ""),
716
+ }
717
+ for d in docs
718
+ ]
719
+
720
+
721
+ # =============================================================================
722
+ # 6. PUBLIC API — retrieval-only (NO LLM)
723
+ # =============================================================================
724
+
725
+ def retrieve_functions_context(
726
+ exercise: str,
727
+ embedding_model: str = DEFAULT_MODEL_KEY,
728
+ top_k: int = 12,
729
+ score_threshold: float = DEFAULT_SCORE_THRESHOLD,
730
+ force_rebuild: bool = False,
731
+ verbose: bool = True,
732
+ ) -> Dict[str, Any]:
733
+ """
734
+ Retrieve relevant PyxiScience entities and build a prompt-ready catalogue.
735
+
736
+ NO LLM CALL. Drop `result["catalogue"]` into your downstream prompt's
737
+ `{functions}` slot.
738
+
739
+ Returns:
740
+ {
741
+ "catalogue": str, # drop-in for {functions}
742
+ "imports_block": str, # importable header
743
+ "entities": List[dict], # formatted entity dicts (ordered)
744
+ "retrieved": List[dict], # flat meta for retrieved hits
745
+ "always_included": List[dict], # flat meta for baseline
746
+ "embedding_model": str,
747
+ "top_k": int,
748
+ "kept": int, # survived score_threshold
749
+ }
750
+ """
751
+ if embedding_model not in EMBEDDING_MODELS:
752
+ raise ValueError(
753
+ f"Unknown embedding_model '{embedding_model}'. "
754
+ f"Available: {list(EMBEDDING_MODELS.keys())}"
755
+ )
756
+
757
+ t0 = time.time()
758
+ vs = setup_vectorstore(model_key=embedding_model, force_rebuild=force_rebuild)
759
+
760
+ cfg = EMBEDDING_MODELS[embedding_model]
761
+ query_text = (cfg.get("prefix") or "") + exercise
762
+
763
+ hits = vs.similarity_search_with_score(query_text, k=top_k)
764
+ retrieved_docs = [doc for doc, score in hits if score < score_threshold]
765
+
766
+ if verbose:
767
+ logger.info("\n" + "═" * 70)
768
+ logger.info(f"🔍 RETRIEVAL [{embedding_model}, top-{top_k}, thr<{score_threshold}]")
769
+ logger.info("═" * 70)
770
+ for doc, score in hits:
771
+ if score < 1.2: label = "✅"
772
+ elif score < score_threshold: label = "⚠️ "
773
+ else: label = "❌"
774
+ qn = doc.metadata.get("qualname", "?")
775
+ logger.info(f" {label} score={score:.3f} → {qn}")
776
+ logger.info(f"\n → kept {len(retrieved_docs)} / {len(hits)}")
777
+ logger.info("═" * 70)
778
+
779
+ # Merge with ALWAYS_INCLUDE → absorb methods into retrieved classes.
780
+ merged = _merge_docs(retrieved_docs, _always_docs)
781
+ merged = _absorb_methods_into_classes(merged)
782
+
783
+ entities = [_doc_to_entity(d) for d in merged]
784
+ catalogue = build_catalogue(entities)
785
+ imports = build_imports_block(entities)
786
+
787
+ out = {
788
+ "catalogue": catalogue,
789
+ "imports_block": imports,
790
+ "entities": entities,
791
+ "retrieved": _flatten_metadata(retrieved_docs),
792
+ "always_included": _flatten_metadata(_always_docs),
793
+ "embedding_model": embedding_model,
794
+ "top_k": top_k,
795
+ "kept": len(retrieved_docs),
796
+ }
797
+
798
+ if verbose:
799
+ logger.info(f"⏱️ retrieve_functions_context in {time.time() - t0:.2f}s")
800
+
801
+ return out
802
+
803
+
804
+ def retrieve_raw(
805
+ exercise: str,
806
+ embedding_model: str = DEFAULT_MODEL_KEY,
807
+ top_k: int = 12,
808
+ force_rebuild: bool = False,
809
+ ) -> List[Dict[str, Any]]:
810
+ """Lightweight retrieval — just the ranked list of hits with scores."""
811
+ if embedding_model not in EMBEDDING_MODELS:
812
+ raise ValueError(
813
+ f"Unknown embedding_model '{embedding_model}'. "
814
+ f"Available: {list(EMBEDDING_MODELS.keys())}"
815
+ )
816
+ vs = setup_vectorstore(model_key=embedding_model, force_rebuild=force_rebuild)
817
+ cfg = EMBEDDING_MODELS[embedding_model]
818
+ query_text = (cfg.get("prefix") or "") + exercise
819
+ hits = vs.similarity_search_with_score(query_text, k=top_k)
820
+ return [
821
+ {
822
+ "rank": i + 1,
823
+ "score": float(score),
824
+ "qualname": d.metadata["qualname"],
825
+ "signature": d.metadata.get("signature", ""),
826
+ "import_line": d.metadata["import_line"],
827
+ "module_name": d.metadata["module_name"],
828
+ "kind": d.metadata["kind"],
829
+ "parent_class": d.metadata.get("parent_class", ""),
830
+ "docstring": (d.metadata.get("docstring") or "")[:200],
831
+ }
832
+ for i, (d, score) in enumerate(hits)
833
+ ]
834
+
835
+
836
+ # =============================================================================
837
+ # 7. LLM WRAPPER — retrieve_functions (standalone Q&A)
838
+ # =============================================================================
839
+
840
+ _llm: Optional[ChatOpenAI] = None
841
+
842
+
843
+ def get_llm(model_key: str = "gpt-4o-mini") -> ChatOpenAI:
844
+ global _llm
845
+ if _llm is None:
846
+ _llm = ChatOpenAI(
847
+ model=OPENROUTER_MODELS.get(model_key, model_key),
848
+ openai_api_key=OPENROUTER_API_KEY,
849
+ openai_api_base="https://openrouter.ai/api/v1",
850
+ temperature=0,
851
+ timeout=60,
852
+ max_retries=2,
853
+ default_headers={
854
+ "HTTP-Referer": "http://localhost:8501",
855
+ "X-Title": "PyxiScience RAG",
856
+ },
857
+ )
858
+ return _llm
859
+
860
+
861
+ def retrieve_functions(
862
+ exercise: str,
863
+ model: str = "gpt-4o-mini",
864
+ embedding_model: str = DEFAULT_MODEL_KEY,
865
+ top_k: int = 12,
866
+ force_rebuild: bool = False,
867
+ verbose: bool = True,
868
+ ) -> Dict[str, Any]:
869
+ """
870
+ Standalone Q&A: retrieve + ask an LLM which functions to use and how.
871
+
872
+ If you already have your own downstream code-generation prompt, use
873
+ `retrieve_functions_context` instead and skip this LLM hop.
874
+ """
875
+ global _llm
876
+
877
+ t0 = time.time()
878
+ logger.info(f"🤖 LLM: {model}")
879
+ logger.info(f"🧠 Embeddings: {embedding_model}")
880
+ _llm = get_llm(model)
881
+
882
+ ctx = retrieve_functions_context(
883
+ exercise=exercise,
884
+ embedding_model=embedding_model,
885
+ top_k=top_k,
886
+ force_rebuild=force_rebuild,
887
+ verbose=verbose,
888
+ )
889
+
890
+ prompt = f"""Tu es un expert Python / mathématiques pour la bibliothèque **PyxiScience**.
891
+
892
+ Ta mission : résoudre l'exercice ci-dessous **en utilisant le catalogue de
893
+ fonctions PyxiScience fourni**. Tu n'as pas le droit de réimplémenter ce qui
894
+ existe déjà dans le catalogue.
895
+
896
+ ═══════════════════════════════════════════════════════════════════════════
897
+ RÈGLES IMPÉRATIVES
898
+ ═══════════════════════════════════════════════════════════════════════════
899
+
900
+ 1. **USAGE OBLIGATOIRE** — Dès qu'une fonction du catalogue couvre un
901
+ besoin, tu DOIS l'utiliser.
902
+ 2. **INTERDICTION DE RÉIMPLÉMENTER** — Si tu écris une fonction qui existe
903
+ déjà dans le catalogue, STOP, importe celle du catalogue.
904
+ 3. **IMPORTS EXACTS** — Recopie les lignes d'import EXACTES du catalogue.
905
+ Pour une méthode, tu importes la CLASSE et tu l'appelles via une instance.
906
+ 4. **SIGNATURES EXACTES** — Appelle chaque fonction avec la signature
907
+ EXACTE donnée.
908
+ 5. **pxs_config() EN PREMIER** — `config = pxs_config()` en tête du script,
909
+ puis `**config` aux `latex(...)` et aux `pxsl_*` qui l'acceptent.
910
+ 6. **BIBLIOTHÈQUES EXTERNES EN DERNIER RECOURS** — sympy / numpy /
911
+ matplotlib uniquement si rien dans le catalogue ne convient.
912
+
913
+ ═══════════════════════════════════════════════════════════════════════════
914
+ CATALOGUE
915
+ ═══════════════════════════════════════════════════════════════════════════
916
+ {ctx['catalogue']}
917
+
918
+ ═══════════════════════════════════════════════════════════════════════════
919
+ EXERCICE
920
+ ═══════════════════════════════════════════════════════════════════════════
921
+ {exercise}
922
+
923
+ ═══════════════════════════════════════════════════════════════════════════
924
+ FORMAT DE RÉPONSE
925
+ ═══════════════════════════════════════════════════════════════════════════
926
+
927
+ ### 1. Plan d'attaque
928
+ étape → `nom_fonction(signature)` — justification.
929
+ Étape sans fonction adéquate → `(aucune — fallback sympy/numpy)`.
930
+
931
+ ### 2. Imports
932
+ ```python
933
+ {ctx['imports_block']}
934
+ ```
935
+
936
+ ### 3. Code complet
937
+ ```python
938
+ config = pxs_config()
939
+ # ... code appelant EFFECTIVEMENT les fonctions du catalogue ...
940
+ ```
941
+
942
+ ### 4. Vérification
943
+ Pour chaque fonction PyxiScience utilisée :
944
+ - [ ] importée (classe pour une méthode) ?
945
+ - [ ] appelée ?
946
+ - [ ] signature respectée ?
947
+
948
+ Génère maintenant ta réponse :"""
949
+
950
+ response = _llm.invoke(prompt)
951
+ answer = response.content
952
+
953
+ logger.info(f"⏱️ Total (retrieve + LLM): {time.time() - t0:.1f}s")
954
+
955
+ if verbose:
956
+ logger.info("\n" + "═" * 70)
957
+ logger.info("📝 RÉPONSE FINALE:")
958
+ logger.info("═" * 70)
959
+ logger.info(answer)
960
+ logger.info("═" * 70)
961
+
962
+ return {**ctx, "answer": answer, "llm_model": model}
963
+
964
+
965
+ # =============================================================================
966
+ # 8. UTILITIES (cache + benchmark)
967
+ # =============================================================================
968
+
969
+ def list_embedding_models() -> None:
970
+ logger.info(f"\n{'═'*92}")
971
+ logger.info(" Available Embedding Models")
972
+ logger.info(f"{'═'*92}")
973
+ logger.info(f" {'Key':<28} {'Backend':<14} {'Dims':<6} {'Cost/1k':<12} {'Model'}")
974
+ logger.info(f" {'─'*28} {'─'*14} {'─'*6} {'─'*12} {'─'*36}")
975
+ for k, v in EMBEDDING_MODELS.items():
976
+ star = " ★" if k == DEFAULT_MODEL_KEY else ""
977
+ backend = v.get("backend", "huggingface")
978
+ dims = str(v.get("dimensions", "—"))
979
+ cost = f"${v['cost_per_1k']:.5f}" if v.get("cost_per_1k") else "free"
980
+ icon = "💰" if backend == "openai" else "🤗"
981
+ logger.info(f" {k:<28} {icon} {backend:<12} {dims:<6} {cost:<12} {v['model_name']}{star}")
982
+ logger.info(f"\n ★ = default 💰 = OPENAI_API_KEY required 🤗 = local/free\n")
983
+
984
+
985
+ def list_cached_models() -> List[str]:
986
+ if not SOURCES_CACHE_ROOT.exists():
987
+ return []
988
+ return [p.name for p in SOURCES_CACHE_ROOT.iterdir() if p.is_dir()]
989
+
990
+
991
+ def clear_cache(embedding_model: Optional[str] = None) -> None:
992
+ import shutil
993
+ if embedding_model:
994
+ p = _cache_path_for(embedding_model)
995
+ if p.exists():
996
+ shutil.rmtree(p)
997
+ logger.info(f"🗑️ Deleted cache for '{embedding_model}'")
998
+ _vs_cache.pop(embedding_model, None)
999
+ _emb_cache.pop(embedding_model, None)
1000
+ else:
1001
+ if SOURCES_CACHE_ROOT.exists():
1002
+ shutil.rmtree(SOURCES_CACHE_ROOT)
1003
+ logger.info("🗑️ Deleted all caches")
1004
+ _vs_cache.clear()
1005
+ _emb_cache.clear()
1006
+
1007
+
1008
+ def benchmark_embedding_models(
1009
+ test_queries: List[str],
1010
+ top_k: int = 5,
1011
+ model_keys: Optional[List[str]] = None,
1012
+ force_rebuild: bool = False,
1013
+ ) -> Dict[str, Dict[str, List[Dict]]]:
1014
+ keys = model_keys or list(EMBEDDING_MODELS.keys())
1015
+ results: Dict[str, Dict[str, List[Dict]]] = {}
1016
+ logger.info(f"\n{'═'*72}")
1017
+ logger.info(f" 🔬 BENCHMARK — {len(keys)} models × {len(test_queries)} queries")
1018
+ logger.info(f"{'═'*72}\n")
1019
+ for mk in keys:
1020
+ logger.info(f" ▶ {mk} ({EMBEDDING_MODELS[mk]['description']})")
1021
+ results[mk] = {}
1022
+ for q in test_queries:
1023
+ t0 = time.time()
1024
+ try:
1025
+ hits = retrieve_raw(q, embedding_model=mk, top_k=top_k,
1026
+ force_rebuild=force_rebuild)
1027
+ latency = time.time() - t0
1028
+ results[mk][q] = hits
1029
+ top1 = hits[0]["qualname"] if hits else "—"
1030
+ logger.info(f" ✅ [{latency:.2f}s] '{q[:50]}...' → top1={top1}")
1031
+ except Exception as e:
1032
+ logger.info(f" ❌ '{q[:50]}...' → ERROR: {e}")
1033
+ results[mk][q] = []
1034
+ force_rebuild = False # only rebuild once, on first model
1035
+ logger.info()
1036
+ return results
1037
+
1038
+
1039
+ # =============================================================================
1040
+ # 9. MAIN — smoke test
1041
+ # =============================================================================
1042
+
1043
+ if __name__ == "__main__":
1044
+ exercise_text = r"""
1045
+ `````{exercise}
1046
+ :id: f1e09b57-8f62-4926-a484-1893f724a627
1047
+ :title: Exercice 1 Asie J1 5 septembre juin 2025 Fonction exponentielle et équation différentielle
1048
+ :modules: annales_bac, Analysis
1049
+ :recommendedExecutionTime: 25
1050
+ :level: Intermediate
1051
+ :chap: Fonctions exponentielles et équations différentielles
1052
+ :involvedConcepts: TYPE_BAC, Dérivation, équation différentielle, convexité, théorème des valeurs intermédiaires, intégration par parties
1053
+ :originalSource: Baccalauréat - Exercice sur les fonctions exponentielles
1054
+ :visibility: All
1055
+ :variations:
1056
+ :comment: Exercice d'analyse avec affirmations vrai/faux sur une fonction exponentielle
1057
+
1058
+ {fr}`Soit $f$ la fonction définie sur $\mathbb{R}$ par $f(x) = x\,\mathrm{e}^{-2x}$.
1059
+
1060
+ On admet que $f$ est deux fois dérivable sur $\mathbb{R}$.`
1061
+
1062
+ $\textit{Pour chacune des affirmations suivantes, préciser si elle est vraie ou fausse, puis justifier
1063
+ la réponse donnée. Toute réponse non argumentée ne sera pas prise en compte.}$
1064
+
1065
+ (contenu tronqué dans le smoke test — l'exercice complet est transmis en contexte)
1066
+ `````
1067
+ """
1068
+
1069
+ list_embedding_models()
1070
+
1071
+ logger.info("\n>>> retrieve_functions_context (no LLM)")
1072
+ ctx = retrieve_functions_context(
1073
+ exercise=exercise_text,
1074
+ embedding_model="openai-3-large",
1075
+ top_k=12,
1076
+ force_rebuild=False,
1077
+ )
1078
+ logger.info("\n── CATALOGUE (injectable as {functions}) ──\n")
1079
+ logger.info(ctx["catalogue"] + "\n...")
1080
+ logger.info(f"\n── imports_block ──\n{ctx['imports_block']}")
1081
+ logger.info(f"\n── {len(ctx['entities'])} entities "
1082
+ f"({len(ctx['retrieved'])} retrieved + {len(ctx['always_included'])} always) ──")
1083
+
1084
+ # Sanity checks on the new ALWAYS_INCLUDE entries
1085
+ entity_names = [e["qualname"] for e in ctx["entities"]]
1086
+ logger.info("\n── SANITY ──")
1087
+ logger.info(f" pxs_Interval present: {'pxs_Interval' in entity_names}")
1088
+ logger.info(f" pxsl_pow present: {'pxsl_pow' in entity_names}")
1089
+ for e in ctx["entities"]:
1090
+ if e["qualname"] == "pxs_Interval":
1091
+ method_names = [m["name"] for m in e.get("methods", [])]
1092
+ logger.info(f" pxs_Interval methods: {method_names}")
1093
+ break
app/rag/notions.py ADDED
@@ -0,0 +1,526 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ PyxiScience — LLM Notion Retriever (OpenRouter backend)
3
+ =========================================================
4
+ Selects relevant notions from the PyxiScience taxonomy (notions.xlsx) for a
5
+ given exercise by asking an LLM judge — replacing the FAISS/cosine retriever.
6
+
7
+ All LLM calls go through OpenRouter (https://openrouter.ai), which exposes an
8
+ OpenAI-compatible API. Any OpenRouter-hosted model is usable by setting
9
+ `DEFAULT_LLM_MODEL` or the `model=` kwarg, e.g.:
10
+ "openai/gpt-4o"
11
+ "openai/gpt-4o-mini"
12
+ "anthropic/claude-sonnet-4.5"
13
+ "anthropic/claude-opus-4.1"
14
+ "google/gemini-2.5-pro"
15
+
16
+ Why LLM over cosine?
17
+ • Short bilingual strings ("Mean Value Theorem" / "Théorème des
18
+ accroissements finis") don't give embedding models enough lexical
19
+ signal to rank precisely.
20
+ • The LLM can reason about *which notion is actually exercised* rather
21
+ than which string is most surface-similar.
22
+ • Bonus: it can suggest GENERAL notions that the exercise covers but
23
+ the catalogue is missing — a prerequisite for evolving the taxonomy.
24
+
25
+ Public API (drop-in compatible with the previous retriever):
26
+ retrieve_notions(text, ...) -> List[Dict[str, str]]
27
+ retrieve_notions_for_exercise(myst, ...) -> List[Dict[str, str]]
28
+ enrich_exercise_with_notions(myst, ...) -> (block, csv_ids)
29
+
30
+ Extra:
31
+ retrieve_notions_llm(text, ...) -> rich dict with suggestions
32
+
33
+ Author: PyxiScience Team
34
+ Version: 1.0
35
+ """
36
+
37
+ from __future__ import annotations
38
+
39
+ import json
40
+ import logging
41
+ import time
42
+ from pathlib import Path
43
+ from typing import Dict, List, Optional, Tuple
44
+
45
+ import pandas as pd
46
+ from openai import OpenAI
47
+
48
+ from app.keys import OPENROUTER_API_KEY
49
+
50
+ logger = logging.getLogger(__name__)
51
+
52
+
53
+ # =============================================================================
54
+ # 1. CONFIGURATION
55
+ # =============================================================================
56
+
57
+ from app.config import NOTIONS_XLSX as DEFAULT_NOTIONS_XLSX, NOTIONS_MODEL
58
+
59
+ COL_FR = "FR_Name"
60
+ COL_EN = "EN_Name"
61
+ COL_ID = "Name_ID"
62
+
63
+ # Default LLM. Any model hosted on OpenRouter works — use `provider/model` form.
64
+ # See https://openrouter.ai/models for the full list.
65
+ DEFAULT_LLM_MODEL = NOTIONS_MODEL
66
+ DEFAULT_TOP_K = 5
67
+ DEFAULT_MAX_SUGGESTIONS = 2
68
+ DEFAULT_TEMPERATURE = 0.0
69
+
70
+ OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1"
71
+
72
+ # Optional OpenRouter attribution headers (shown on their leaderboards + dashboard).
73
+ # Safe to leave as-is; override in your own deployment if you want.
74
+ OPENROUTER_HEADERS = {
75
+ "HTTP-Referer": "https://pyxiscience.com",
76
+ "X-Title": "PyxiScience Notion Retriever",
77
+ }
78
+
79
+
80
+ # =============================================================================
81
+ # 2. CATALOGUE LOADING (cached in memory per xlsx path)
82
+ # =============================================================================
83
+
84
+ _catalogue_cache: Dict[Path, Tuple[str, Dict[str, Dict[str, str]]]] = {}
85
+
86
+
87
+ def load_notions_catalogue(
88
+ xlsx_path: str | Path = DEFAULT_NOTIONS_XLSX,
89
+ ) -> Tuple[str, Dict[str, Dict[str, str]]]:
90
+ """
91
+ Read the notions Excel file.
92
+
93
+ Returns
94
+ -------
95
+ catalogue_text : str
96
+ One line per notion, formatted as `ID | FR | EN`. This is the
97
+ exact text shipped to the LLM.
98
+ id_map : dict
99
+ {name_id: {"fr_name": ..., "en_name": ...}} — used to validate
100
+ returned IDs and enrich the LLM response.
101
+ """
102
+ xlsx_path = Path(xlsx_path)
103
+ if xlsx_path in _catalogue_cache:
104
+ return _catalogue_cache[xlsx_path]
105
+
106
+ df = pd.read_excel(xlsx_path, dtype=str).fillna("")
107
+
108
+ missing = [c for c in (COL_FR, COL_EN, COL_ID) if c not in df.columns]
109
+ if missing:
110
+ raise ValueError(
111
+ f"Missing columns in '{xlsx_path}': {missing}\n"
112
+ f"Found: {list(df.columns)}"
113
+ )
114
+
115
+ lines: List[str] = []
116
+ id_map: Dict[str, Dict[str, str]] = {}
117
+
118
+ for _, row in df.iterrows():
119
+ nid = row[COL_ID].strip()
120
+ fr = row[COL_FR].strip()
121
+ en = row[COL_EN].strip()
122
+ if not nid:
123
+ continue
124
+ lines.append(f"{nid} | {fr} | {en}")
125
+ id_map[nid] = {"fr_name": fr, "en_name": en}
126
+
127
+ catalogue_text = "\n".join(lines)
128
+ _catalogue_cache[xlsx_path] = (catalogue_text, id_map)
129
+ logger.info(f" 📋 Loaded {len(id_map)} notions from '{xlsx_path.name}'")
130
+ return catalogue_text, id_map
131
+
132
+
133
+ # =============================================================================
134
+ # 3. PROMPT
135
+ # =============================================================================
136
+
137
+ SYSTEM_PROMPT = """You are a mathematical content classifier for PyxiScience, a bilingual (FR/EN) math education platform.
138
+
139
+ TASK
140
+ Given a math exercise and a CATALOGUE of notions (format per line: `ID | FR name | EN name`),
141
+ identify which notions are actually *exercised* by the problem — not merely mentioned.
142
+
143
+ RULES
144
+ 1. Return ONLY a valid JSON object matching the schema below. No markdown fences, no commentary.
145
+ 2. `selected_notion_ids` must contain IDs that EXACTLY appear in the catalogue (copy them verbatim).
146
+ Do NOT invent, paraphrase, or alter IDs. If a concept is missing from the catalogue, put it in
147
+ `suggested_new_notions` — never in `selected_notion_ids`.
148
+ 3. Rank `selected_notion_ids` from most to least relevant. Keep only notions whose content is
149
+ genuinely needed to solve the exercise. Quality > quantity — it is fine to return fewer than
150
+ the requested top_k if the exercise only exercises one or two notions.
151
+ 4. `relevance` ∈ [0, 1]. Reserve ≥ 0.8 for central notions, 0.4–0.7 for supporting ones.
152
+ 5. `rationale` must be a short, concrete sentence (FR or EN) explaining the link.
153
+ 6. `suggested_new_notions` are GENERAL mathematical concepts that:
154
+ (a) are clearly exercised by the problem,
155
+ (b) are NOT already in the catalogue — check both IDs AND FR/EN names,
156
+ (c) are broad enough to be reused across many exercises (avoid hyper-specific tricks,
157
+ avoid renaming existing notions).
158
+ Be conservative: 0–2 suggestions is ideal, never more than 3. If nothing is missing, return [].
159
+ 7. `proposed_id` follows PyxiScience convention: `Capitalised_Words_In_Snake_Case`
160
+ (e.g. `Polar_Equation_Conversion`, `Partial_Fraction_Decomposition`).
161
+
162
+ OUTPUT JSON SCHEMA
163
+ {
164
+ "selected_notion_ids": [
165
+ {
166
+ "name_id": "<exact ID from catalogue>",
167
+ "relevance": <float in [0,1]>,
168
+ "rationale": "<one short sentence>"
169
+ }
170
+ ],
171
+ "suggested_new_notions": [
172
+ {
173
+ "proposed_id": "<Snake_Case_Id>",
174
+ "fr_name": "<FR label>",
175
+ "en_name": "<EN label>",
176
+ "rationale": "<why it's missing AND why it's relevant>"
177
+ }
178
+ ]
179
+ }
180
+ """
181
+
182
+
183
+ def _build_user_prompt(
184
+ exercise_text: str,
185
+ catalogue_text: str,
186
+ top_k: int,
187
+ max_suggestions: int,
188
+ ) -> str:
189
+ n_notions = len(catalogue_text.splitlines())
190
+ return (
191
+ f"CATALOGUE ({n_notions} notions)\n"
192
+ f"═══════════════════════════════════════════════════════════════\n"
193
+ f"{catalogue_text}\n"
194
+ f"═══════════════════════════════════════════════════════════════\n\n"
195
+ f"EXERCISE\n"
196
+ f"═══════════════════════════════════════════════════════════════\n"
197
+ f"{exercise_text}\n"
198
+ f"═══════════════════════════════════════════════════════════════\n\n"
199
+ f"Return up to {top_k} selected notions (ranked best→worst) and up to "
200
+ f"{max_suggestions} suggested new notions.\n"
201
+ f"Reminder: every `name_id` in `selected_notion_ids` MUST appear verbatim "
202
+ f"in the catalogue above."
203
+ )
204
+
205
+
206
+ # =============================================================================
207
+ # 4. LLM CLIENT
208
+ # =============================================================================
209
+
210
+ _client: Optional[OpenAI] = None
211
+
212
+
213
+ def _get_client() -> OpenAI:
214
+ """
215
+ Return a cached OpenAI-compatible client pointed at OpenRouter.
216
+ """
217
+ global _client
218
+ if _client is None:
219
+ if not OPENROUTER_API_KEY or len(OPENROUTER_API_KEY) < 20:
220
+ raise RuntimeError(
221
+ "OPENROUTER_API_KEY is missing or invalid. Set it in core.ld."
222
+ )
223
+ _client = OpenAI(
224
+ api_key=OPENROUTER_API_KEY,
225
+ base_url=OPENROUTER_BASE_URL,
226
+ default_headers=OPENROUTER_HEADERS,
227
+ )
228
+ return _client
229
+
230
+
231
+ def _call_llm(
232
+ system: str,
233
+ user: str,
234
+ model: str,
235
+ temperature: float = DEFAULT_TEMPERATURE,
236
+ ) -> Dict:
237
+ """Single LLM call via OpenRouter, forcing JSON-object output."""
238
+ client = _get_client()
239
+ response = client.chat.completions.create(
240
+ model=model,
241
+ temperature=temperature,
242
+ response_format={"type": "json_object"},
243
+ messages=[
244
+ {"role": "system", "content": system},
245
+ {"role": "user", "content": user},
246
+ ],
247
+ )
248
+ raw = response.choices[0].message.content or "{}"
249
+ try:
250
+ return json.loads(raw)
251
+ except json.JSONDecodeError as e:
252
+ raise RuntimeError(
253
+ f"LLM returned non-JSON content despite json_object mode.\n"
254
+ f"Model: {model}\n"
255
+ f"Raw: {raw[:500]}\n"
256
+ f"Error: {e}"
257
+ )
258
+
259
+
260
+ # =============================================================================
261
+ # 5. PUBLIC API — rich version
262
+ # =============================================================================
263
+
264
+ def retrieve_notions_llm(
265
+ exercise_text: str,
266
+ xlsx_path: str | Path = DEFAULT_NOTIONS_XLSX,
267
+ top_k: int = DEFAULT_TOP_K,
268
+ max_suggestions: int = DEFAULT_MAX_SUGGESTIONS,
269
+ model: str = DEFAULT_LLM_MODEL,
270
+ temperature: float = DEFAULT_TEMPERATURE,
271
+ verbose: bool = True,
272
+ ) -> Dict:
273
+ """
274
+ Retrieve relevant notions for an exercise using an LLM judge.
275
+
276
+ Returns
277
+ -------
278
+ {
279
+ "selected": [ {rank, name_id, fr_name, en_name, relevance, rationale}, ... ],
280
+ "suggested": [ {proposed_id, fr_name, en_name, rationale}, ... ],
281
+ "elapsed_s": float,
282
+ "model": str,
283
+ }
284
+ """
285
+ t0 = time.time()
286
+
287
+ catalogue_text, id_map = load_notions_catalogue(xlsx_path)
288
+ user_prompt = _build_user_prompt(
289
+ exercise_text, catalogue_text, top_k, max_suggestions
290
+ )
291
+ data = _call_llm(SYSTEM_PROMPT, user_prompt, model=model, temperature=temperature)
292
+
293
+ # -------- Validate & enrich `selected` --------
294
+ selected: List[Dict] = []
295
+ for rank, item in enumerate(data.get("selected_notion_ids", [])[:top_k], start=1):
296
+ nid = (item.get("name_id") or "").strip()
297
+ if nid not in id_map:
298
+ if verbose:
299
+ logger.info(f" ⚠️ LLM returned unknown notion_id '{nid}' — dropping")
300
+ continue
301
+ meta = id_map[nid]
302
+ selected.append({
303
+ "rank": rank,
304
+ "name_id": nid,
305
+ "fr_name": meta["fr_name"],
306
+ "en_name": meta["en_name"],
307
+ "relevance": float(item.get("relevance", 0.0) or 0.0),
308
+ "rationale": (item.get("rationale") or "").strip(),
309
+ })
310
+ # Re-rank in case of drops so ranks stay contiguous
311
+ for i, s in enumerate(selected, start=1):
312
+ s["rank"] = i
313
+
314
+ # -------- Validate & dedupe `suggested` --------
315
+ existing_ids = set(id_map.keys())
316
+ existing_names_fr = {v["fr_name"].lower() for v in id_map.values()}
317
+ existing_names_en = {v["en_name"].lower() for v in id_map.values()}
318
+
319
+ suggested: List[Dict] = []
320
+ for item in data.get("suggested_new_notions", [])[:max_suggestions]:
321
+ pid = (item.get("proposed_id") or "").strip()
322
+ fr = (item.get("fr_name") or "").strip()
323
+ en = (item.get("en_name") or "").strip()
324
+ if not (pid and fr and en):
325
+ continue
326
+ if pid in existing_ids:
327
+ if verbose:
328
+ logger.info(f" ⚠️ Suggested ID '{pid}' already exists — skipping")
329
+ continue
330
+ if fr.lower() in existing_names_fr or en.lower() in existing_names_en:
331
+ if verbose:
332
+ logger.info(f" ⚠️ Suggested name '{fr} / {en}' duplicates an existing notion — skipping")
333
+ continue
334
+ suggested.append({
335
+ "proposed_id": pid,
336
+ "fr_name": fr,
337
+ "en_name": en,
338
+ "rationale": (item.get("rationale") or "").strip(),
339
+ })
340
+
341
+ result = {
342
+ "selected": selected,
343
+ "suggested": suggested,
344
+ "elapsed_s": round(time.time() - t0, 2),
345
+ "model": model,
346
+ }
347
+
348
+ if verbose:
349
+ _print_result(result)
350
+
351
+ return result
352
+
353
+
354
+ # =============================================================================
355
+ # 6. DROP-IN REPLACEMENTS for the old API
356
+ # =============================================================================
357
+
358
+ def retrieve_notions(
359
+ text: str,
360
+ xlsx_path: str | Path = DEFAULT_NOTIONS_XLSX,
361
+ top_k: int = DEFAULT_TOP_K,
362
+ model: str = DEFAULT_LLM_MODEL,
363
+ verbose: bool = True,
364
+ **_ignored, # swallows old kwargs: model_key, use_cache, force_rebuild
365
+ ) -> List[Dict[str, str]]:
366
+ """
367
+ Old-shape output for backward compatibility with the FAISS retriever:
368
+ [{"rank", "name_id", "fr_name", "en_name", "score"}, ...]
369
+ where `score` is the LLM relevance (higher = more relevant, unlike
370
+ the cosine distance returned by the old retriever).
371
+ """
372
+ result = retrieve_notions_llm(
373
+ exercise_text=text,
374
+ xlsx_path=xlsx_path,
375
+ top_k=top_k,
376
+ model=model,
377
+ verbose=verbose,
378
+ )
379
+ return [
380
+ {
381
+ "rank": str(s["rank"]),
382
+ "name_id": s["name_id"],
383
+ "fr_name": s["fr_name"],
384
+ "en_name": s["en_name"],
385
+ "score": f"{s['relevance']:.4f}",
386
+ }
387
+ for s in result["selected"]
388
+ ]
389
+
390
+
391
+ def retrieve_notions_for_exercise(
392
+ exercise_myst: str,
393
+ xlsx_path: str | Path = DEFAULT_NOTIONS_XLSX,
394
+ top_k: int = DEFAULT_TOP_K,
395
+ model: str = DEFAULT_LLM_MODEL,
396
+ **kwargs,
397
+ ) -> List[Dict[str, str]]:
398
+ """Pass the raw MyST exercise block — the LLM handles markup natively."""
399
+ return retrieve_notions(
400
+ exercise_myst, xlsx_path=xlsx_path, top_k=top_k, model=model, **kwargs
401
+ )
402
+
403
+
404
+ def enrich_exercise_with_notions(
405
+ exercise_myst: str,
406
+ xlsx_path: str | Path = DEFAULT_NOTIONS_XLSX,
407
+ top_k: int = DEFAULT_TOP_K,
408
+ max_suggestions: int = DEFAULT_MAX_SUGGESTIONS,
409
+ model: str = DEFAULT_LLM_MODEL,
410
+ ) -> Tuple[str, str]:
411
+ """
412
+ Same signature/return as before: (formatted_block, comma_separated_ids).
413
+ The formatted block now also lists any SUGGESTED new notions, so you
414
+ can feed them back into your taxonomy pipeline.
415
+ """
416
+ result = retrieve_notions_llm(
417
+ exercise_text=exercise_myst,
418
+ xlsx_path=xlsx_path,
419
+ top_k=top_k,
420
+ max_suggestions=max_suggestions,
421
+ model=model,
422
+ verbose=False,
423
+ )
424
+
425
+ lines = ["═" * 70]
426
+ lines.append(
427
+ f" NOTIONS RETRIEVED via LLM "
428
+ f"[{result['model']} · {result['elapsed_s']}s]"
429
+ )
430
+ lines.append("═" * 70)
431
+ for s in result["selected"]:
432
+ lines.append(
433
+ f" [{s['rank']}] {s['name_id']:<32} relevance={s['relevance']:.2f}\n"
434
+ f" → {s['fr_name']} / {s['en_name']}\n"
435
+ f" ↳ {s['rationale']}"
436
+ )
437
+
438
+ if result["suggested"]:
439
+ lines.append("─" * 70)
440
+ lines.append(" ★ SUGGESTED NEW NOTIONS (not in catalogue)")
441
+ lines.append("─" * 70)
442
+ for g in result["suggested"]:
443
+ lines.append(
444
+ f" + {g['proposed_id']}\n"
445
+ f" → {g['fr_name']} / {g['en_name']}\n"
446
+ f" ↳ {g['rationale']}"
447
+ )
448
+
449
+ lines.append("═" * 70)
450
+ lines.append("Utilise ces notions comme :involvedConcepts: si pertinent.")
451
+
452
+ ids_csv = ", ".join(s["name_id"] for s in result["selected"])
453
+ return "\n".join(lines), ids_csv
454
+
455
+
456
+ # =============================================================================
457
+ # 7. PRETTY PRINTER
458
+ # =============================================================================
459
+
460
+ def _print_result(result: Dict) -> None:
461
+ w = 72
462
+ logger.info(f"\n{'═'*w}")
463
+ logger.info(f" 🏷️ LLM NOTION RETRIEVAL "
464
+ f"[model: {result['model']} · {result['elapsed_s']}s]")
465
+ logger.info("═" * w)
466
+ logger.info(f" {'Rank':<5} {'Rel.':<6} {'Name_ID':<32} FR / EN")
467
+ logger.info(f" {'─'*5} {'─'*6} {'─'*32} {'─'*25}")
468
+ for s in result["selected"]:
469
+ label = f"{s['fr_name']} / {s['en_name']}"
470
+ if len(label) > 25:
471
+ label = label[:22] + "..."
472
+ logger.info(f" {s['rank']:<5} {s['relevance']:<6.2f} {s['name_id']:<32} {label}")
473
+ if s["rationale"]:
474
+ logger.info(f" ↳ {s['rationale']}")
475
+
476
+ if result["suggested"]:
477
+ logger.info(f"\n ★ SUGGESTED NEW NOTIONS")
478
+ for g in result["suggested"]:
479
+ logger.info(f" + {g['proposed_id']} — {g['fr_name']} / {g['en_name']}")
480
+ if g["rationale"]:
481
+ logger.info(f" ↳ {g['rationale']}")
482
+ logger.info(f"{'═'*w}\n")
483
+
484
+
485
+ # =============================================================================
486
+ # 8. DEMO
487
+ # =============================================================================
488
+
489
+ if __name__ == "__main__":
490
+ import argparse
491
+
492
+ parser = argparse.ArgumentParser(description="LLM-based notion retriever")
493
+ parser.add_argument("--xlsx", default=str(DEFAULT_NOTIONS_XLSX))
494
+ parser.add_argument("--model", default=DEFAULT_LLM_MODEL)
495
+ parser.add_argument("--topk", type=int, default=DEFAULT_TOP_K)
496
+ parser.add_argument("--suggest", type=int, default=DEFAULT_MAX_SUGGESTIONS)
497
+ parser.add_argument("--query", default=None, help="Raw exercise text or MyST block")
498
+ args = parser.parse_args()
499
+
500
+ demo_query = args.query or r"""
501
+ `````{exercise}
502
+ :id: 9dfb0461-1ece-4f6d-b24d-26564e3f12ba
503
+ :title: Polar Coordinates - exo 20
504
+ :chap: Polar_Coordinates
505
+
506
+ :::::{question}
507
+ :questionType: STQ
508
+ ::::{questionStatement}
509
+ Find a polar equation for the curve represented by the given Cartesian equation
510
+ $3 y^2 = x$.
511
+ ::::
512
+ ::::{detailedSolution}
513
+ Substitute $x = r \cos(\theta)$ and $y = r \sin(\theta)$, then solve for $r$.
514
+ Result: $r = \tfrac{1}{3} \cot(\theta)\csc(\theta)$.
515
+ ::::
516
+ :::::
517
+ `````
518
+ """
519
+
520
+ retrieve_notions_llm(
521
+ exercise_text=demo_query,
522
+ xlsx_path=Path(args.xlsx),
523
+ top_k=args.topk,
524
+ max_suggestions=args.suggest,
525
+ model=args.model,
526
+ )
app/server.py ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ server.py
3
+ ─────────
4
+ Routes Flask — le minimum pour une app mono-fonctionnalité :
5
+
6
+ GET / UI
7
+ GET /health sanity check
8
+ GET /api/models roster des modèles + défauts
9
+ POST /api/jobs lance un job (1 fichier OU batch) → {job_id}
10
+ GET /api/jobs/<id> suivi + résultats (par fichier)
11
+
12
+ Le job store reste en mémoire (mono-poste, mono-process — assumé) ; un job
13
+ batch traite ses fichiers SÉQUENTIELLEMENT et continue si l'un échoue.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import io
19
+ import logging
20
+ import os
21
+ import re
22
+ import secrets
23
+ import threading
24
+ import time
25
+ import uuid
26
+ import zipfile
27
+
28
+ from flask import Response, jsonify, render_template, request, send_file
29
+
30
+ from app.config import (
31
+ AVAILABLE_MODELS,
32
+ DEFAULT_LANG,
33
+ DEFAULT_MODEL_IDX,
34
+ JOB_TTL,
35
+ )
36
+ from app.pipeline.orchestrator import run_exercise
37
+
38
+ logger = logging.getLogger(__name__)
39
+
40
+ _JOBS: dict = {}
41
+ _JOBS_LOCK = threading.Lock()
42
+
43
+ VALID_LANGS = ("fr", "en", "both")
44
+ VALID_LEVELS = ("", "Intermediate", "Advanced")
45
+
46
+
47
+ def _set_job(job_id: str, **kwargs):
48
+ with _JOBS_LOCK:
49
+ if job_id in _JOBS:
50
+ _JOBS[job_id].update(kwargs)
51
+
52
+
53
+ def _get_job(job_id: str):
54
+ with _JOBS_LOCK:
55
+ job = _JOBS.get(job_id)
56
+ return dict(job) if job else None
57
+
58
+
59
+ def _safe_md_name(filename: str, used: set) -> str:
60
+ """Nom de fichier .md sûr et unique pour la sortie pythonisée
61
+ (suffixe _pythonise pour ne pas écraser la source)."""
62
+ base = re.sub(r"\.(md|txt)$", "", filename or "", flags=re.IGNORECASE)
63
+ base = re.sub(r"[^\w.\-() ]+", "_", base).strip() or "exercice"
64
+ name = f"{base}_pythonise.md"
65
+ i = 2
66
+ while name in used:
67
+ name = f"{base}_pythonise_{i}.md"
68
+ i += 1
69
+ used.add(name)
70
+ return name
71
+
72
+
73
+ def _purge_old_jobs():
74
+ cutoff = time.time() - JOB_TTL
75
+ with _JOBS_LOCK:
76
+ for jid in [jid for jid, j in _JOBS.items()
77
+ if j.get("status") in ("done", "error") and (j.get("finished_at") or 0) < cutoff]:
78
+ del _JOBS[jid]
79
+
80
+
81
+ def _run_job(job_id: str, files: list[dict], level: str, model_idx: int, lang: str):
82
+ """Worker de job : boucle séquentielle sur les fichiers, robuste."""
83
+ results: list[dict] = []
84
+ for i, f in enumerate(files):
85
+ name = f.get("filename") or f"fichier_{i + 1}.md"
86
+ _set_job(job_id, current_file=name, files_done=i,
87
+ step_label=f"[{i + 1}/{len(files)}] {name} — démarrage…")
88
+
89
+ def set_step(label: str, _i=i, _name=name):
90
+ _set_job(job_id, step_label=f"[{_i + 1}/{len(files)}] {_name} — {label}")
91
+
92
+ try:
93
+ result = run_exercise(
94
+ content=f["content"],
95
+ filename=name,
96
+ level=level,
97
+ model_idx=model_idx,
98
+ lang=lang,
99
+ set_step=set_step,
100
+ )
101
+ results.append({"filename": name, "status": "done", "result": result})
102
+ logger.info("Fichier %s : harnais %s, %d warnings, %.1fs, %.4f$",
103
+ name, "VERT" if result["harness"]["ok"] else "ROUGE",
104
+ len(result["warnings"]), result["duration_s"],
105
+ result["cost"]["usd"])
106
+ except Exception as exc:
107
+ logger.exception("Échec du pipeline sur %s", name)
108
+ results.append({"filename": name, "status": "error", "error": str(exc)})
109
+ _set_job(job_id, results=list(results), files_done=i + 1)
110
+
111
+ ok = sum(1 for r in results
112
+ if r["status"] == "done" and r["result"]["harness"]["ok"])
113
+ warn = sum(1 for r in results
114
+ if r["status"] == "done" and not r["result"]["harness"]["ok"])
115
+ err = sum(1 for r in results if r["status"] == "error")
116
+ total_cost = round(sum(r["result"]["cost"]["usd"] for r in results
117
+ if r["status"] == "done"), 4)
118
+ _set_job(
119
+ job_id,
120
+ status="done",
121
+ step_label="Terminé",
122
+ finished_at=time.time(),
123
+ summary={"total": len(files), "verts": ok, "rouges": warn,
124
+ "erreurs": err, "cost_usd": total_cost},
125
+ )
126
+ _purge_old_jobs()
127
+
128
+
129
+ def _auth_ok() -> bool:
130
+ """Basic Auth si APP_PASSWORD est défini ; ouvert sinon (dev local)."""
131
+ password = os.getenv("APP_PASSWORD", "")
132
+ if not password:
133
+ return True
134
+ auth = request.authorization
135
+ user = os.getenv("APP_USER", "pyxi")
136
+ return bool(
137
+ auth
138
+ and auth.username == user
139
+ and secrets.compare_digest(auth.password or "", password)
140
+ )
141
+
142
+
143
+ def register_routes(app):
144
+
145
+ @app.before_request
146
+ def _gate():
147
+ # /health reste ouvert (sonde de l'hébergeur) ; tout le reste est protégé
148
+ # dès qu'un APP_PASSWORD est configuré (déploiement public).
149
+ if request.path == "/health" or _auth_ok():
150
+ return None
151
+ return Response(
152
+ "Authentification requise.",
153
+ 401,
154
+ {"WWW-Authenticate": 'Basic realm="Pythonise Exercice"'},
155
+ )
156
+
157
+ @app.route("/")
158
+ def index():
159
+ return render_template("index.html")
160
+
161
+ @app.route("/health")
162
+ def health():
163
+ return jsonify({
164
+ "status": "ok",
165
+ "openrouter_api_key": bool(os.getenv("OPENROUTER_API_KEY")),
166
+ "openai_api_key": bool(os.getenv("OPENAI_API_KEY")),
167
+ })
168
+
169
+ @app.route("/api/models", methods=["GET"])
170
+ def models():
171
+ return jsonify({
172
+ "models": {str(k): v for k, v in AVAILABLE_MODELS.items()},
173
+ "default_idx": DEFAULT_MODEL_IDX,
174
+ "default_lang": DEFAULT_LANG,
175
+ })
176
+
177
+ @app.route("/api/jobs", methods=["POST"])
178
+ def start_job():
179
+ """Body : {files: [{filename, content}, …], level?, model_idx?, lang?}
180
+ (rétro-compat : {content, filename} accepté pour un fichier unique)."""
181
+ data = request.get_json(force=True, silent=True) or {}
182
+
183
+ files = data.get("files")
184
+ if not files and data.get("content"):
185
+ files = [{"filename": data.get("filename", "exercise.md"),
186
+ "content": data["content"]}]
187
+ if not isinstance(files, list) or not files:
188
+ return jsonify({"error": "Champ 'files' manquant ou vide."}), 400
189
+ clean_files = []
190
+ for f in files:
191
+ if not isinstance(f, dict) or not str(f.get("content", "")).strip():
192
+ return jsonify({"error": "Chaque fichier doit avoir un 'content' non vide."}), 400
193
+ clean_files.append({
194
+ "filename": str(f.get("filename") or "exercise.md"),
195
+ "content": str(f["content"]).strip(),
196
+ })
197
+
198
+ level = (data.get("level") or "").strip()
199
+ if level not in VALID_LEVELS:
200
+ return jsonify({"error": f"'level' invalide : {level!r}."}), 400
201
+
202
+ lang = (data.get("lang") or DEFAULT_LANG).strip()
203
+ if lang not in VALID_LANGS:
204
+ return jsonify({"error": f"'lang' invalide : {lang!r} (fr|en|both)."}), 400
205
+
206
+ try:
207
+ model_idx = int(data.get("model_idx", DEFAULT_MODEL_IDX))
208
+ except (TypeError, ValueError):
209
+ return jsonify({"error": "'model_idx' doit être un entier."}), 400
210
+ if model_idx not in AVAILABLE_MODELS:
211
+ return jsonify({
212
+ "error": f"'model_idx' inconnu : {model_idx}. Valides : {sorted(AVAILABLE_MODELS)}."
213
+ }), 400
214
+
215
+ job_id = uuid.uuid4().hex
216
+ with _JOBS_LOCK:
217
+ _JOBS[job_id] = {
218
+ "status": "running",
219
+ "step_label": "Démarrage…",
220
+ "current_file": clean_files[0]["filename"],
221
+ "files_total": len(clean_files),
222
+ "files_done": 0,
223
+ "results": [],
224
+ "summary": None,
225
+ "error": None,
226
+ "started_at": time.time(),
227
+ "finished_at": None,
228
+ }
229
+
230
+ threading.Thread(
231
+ target=_run_job,
232
+ args=(job_id, clean_files, level, model_idx, lang),
233
+ daemon=True,
234
+ ).start()
235
+ return jsonify({"job_id": job_id}), 202
236
+
237
+ @app.route("/api/jobs/<job_id>", methods=["GET"])
238
+ def job_status(job_id: str):
239
+ job = _get_job(job_id)
240
+ if not job:
241
+ return jsonify({"error": "Job inconnu."}), 404
242
+ return jsonify({
243
+ "status": job["status"],
244
+ "step_label": job["step_label"],
245
+ "current_file": job.get("current_file"),
246
+ "files_total": job["files_total"],
247
+ "files_done": job["files_done"],
248
+ "results": job["results"],
249
+ "summary": job.get("summary"),
250
+ "error": job.get("error"),
251
+ })
252
+
253
+ @app.route("/api/jobs/<job_id>/download", methods=["GET"])
254
+ def job_download_zip(job_id: str):
255
+ """ZIP de toutes les sorties .md prêtes du job + un récapitulatif."""
256
+ job = _get_job(job_id)
257
+ if not job:
258
+ return jsonify({"error": "Job inconnu (peut-être purgé)."}), 404
259
+ done = [r for r in (job.get("results") or []) if r.get("status") == "done"]
260
+ if not done:
261
+ return jsonify({"error": "Aucun fichier prêt à télécharger."}), 404
262
+
263
+ buf = io.BytesIO()
264
+ used: set = set()
265
+ recap = ["# Récapitulatif de pythonisation", ""]
266
+ with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
267
+ for r in done:
268
+ name = _safe_md_name(r["filename"], used)
269
+ zf.writestr(name, r["result"]["exercise"])
270
+ h = r["result"]["harness"]
271
+ recap.append(
272
+ f"- {name} — harnais {'VERT' if h['ok'] else 'ROUGE'} "
273
+ f"({h['seeds']} graines) · {len(r['result']['warnings'])} warnings "
274
+ f"· {r['result']['cost']['usd']} $"
275
+ )
276
+ for r in (job.get("results") or []):
277
+ if r.get("status") == "error":
278
+ recap.append(f"- {r['filename']} — ERREUR : {r.get('error')}")
279
+ zf.writestr("_recapitulatif.md", "\n".join(recap) + "\n")
280
+ buf.seek(0)
281
+ return send_file(
282
+ buf, mimetype="application/zip", as_attachment=True,
283
+ download_name=f"pythonise_{job_id[:8]}.zip",
284
+ )
app/validation/__init__.py ADDED
File without changes
app/validation/harness.py ADDED
@@ -0,0 +1,293 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ harness.py — porte de qualité déterministe du pipeline.
3
+
4
+ Miroir importable du harnais de référence
5
+ (.claude/skills/validation-harness/harness.py) : mêmes contrôles, même
6
+ sévérité, mais API Python (validate_text) au lieu d'un CLI. Toute sortie du
7
+ pipeline DOIT passer ici avant d'être rendue ; un verdict rouge déclenche
8
+ une (1) boucle de réparation LLM puis, à défaut, un warning fort.
9
+
10
+ Contrôles :
11
+ 1. STATIQUE — {{ }} = identifiant nu camelCase sans _ ; questionId/Index
12
+ uniques et contigus dès 0 ; bloc {python} présent.
13
+ 2. EXEC — tous les blocs {python} (concaténés) s'exécutent sur N
14
+ graines, 0 exception. Stubs pyxiscience légers.
15
+ 3. INJECTION — chaque {{ var }} se résout dans le namespace, 0 inconnue.
16
+ 4. INTERDITS — motifs interdits sur le corps rendu (skill §6).
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import io
22
+ import logging
23
+ import random
24
+ import re
25
+ import sys
26
+ import traceback
27
+ import types
28
+ import warnings as _warnings
29
+ from contextlib import redirect_stdout
30
+
31
+ logger = logging.getLogger(__name__)
32
+
33
+ try:
34
+ import matplotlib
35
+ matplotlib.use("Agg")
36
+ import matplotlib.pyplot as _plt
37
+ _HAS_MPL = True
38
+ except Exception:
39
+ _plt = None
40
+ _HAS_MPL = False
41
+
42
+
43
+ # ── Stubs pyxiscience (identiques au harnais de référence) ───────────────────
44
+
45
+ def install_pyxiscience_stubs() -> None:
46
+ if "pyxiscience" in sys.modules:
47
+ return
48
+
49
+ class _Universal:
50
+ def __init__(self, *a, **k): pass
51
+ def __call__(self, *a, **k): return _Universal()
52
+ def __getattr__(self, _): return _Universal()
53
+ def __getitem__(self, _): return _Universal()
54
+ def __iter__(self): return iter(())
55
+ def __str__(self): return ""
56
+ def __repr__(self): return ""
57
+ def __mul__(self, o): return self
58
+ __rmul__ = __add__ = __radd__ = __sub__ = __rsub__ = __mul__
59
+
60
+ def _passthrough(*a, **k):
61
+ return str(a[0]) if a else ""
62
+
63
+ def _pxs_config(*a, **k):
64
+ # dict VIDE : utilisable comme **config_standard sans faire planter
65
+ # sympy.latex (qui rejette toute clé inconnue).
66
+ return {}
67
+
68
+ def _make_module(name: str) -> types.ModuleType:
69
+ mod = types.ModuleType(name)
70
+
71
+ def __getattr__(attr): # PEP 562
72
+ if attr == "pxs_config":
73
+ return _pxs_config
74
+ # Classe si CamelCase OU motif pxs_Xxx (pxs_Interval, pxs_Plotable…)
75
+ if attr and (attr[0].isupper() or re.match(r"pxs_[A-Z]", attr)):
76
+ return _Universal
77
+ return _passthrough
78
+
79
+ mod.__getattr__ = __getattr__
80
+ return mod
81
+
82
+ root = _make_module("pyxiscience")
83
+ sys.modules["pyxiscience"] = root
84
+ for sub in (
85
+ "Mes_fctions_generalistes_bis",
86
+ "Mes_fctions_d_analyse_bis",
87
+ "Mes_fctions_d_alg_lineaire_bis",
88
+ "Mes_fctions_probabilistes_bis",
89
+ "Classes_Extensions",
90
+ ):
91
+ full = f"pyxiscience.{sub}"
92
+ sys.modules[full] = _make_module(full)
93
+ setattr(root, sub, sys.modules[full])
94
+
95
+
96
+ # ── Extraction (fences 3 ou 4 backticks, lecture tolérante) ──────────────────
97
+
98
+ PY_FENCE_ANY_RE = re.compile(r"(?ms)^(`{3,4})\{python\}[ \t]*\n(.*?)\n\1[ \t]*$")
99
+ INJECTION_RE = re.compile(r"\{\{(.*?)\}\}", re.DOTALL)
100
+ VALID_TOKEN_RE = re.compile(r"^[A-Za-z][A-Za-z0-9]*$")
101
+
102
+
103
+ def extract_python_code(text: str) -> str | None:
104
+ """Concatène TOUS les blocs {python} (namespace partagé, ordre document)."""
105
+ blocks = [m.group(2) for m in PY_FENCE_ANY_RE.finditer(text)]
106
+ return "\n\n".join(blocks) if blocks else None
107
+
108
+
109
+ def strip_python_blocks(text: str) -> str:
110
+ return PY_FENCE_ANY_RE.sub("", text)
111
+
112
+
113
+ # ── Contrôles statiques ──────────────────────────────────────────────────────
114
+
115
+ def check_injection_tokens(text: str) -> list[str]:
116
+ errs: list[str] = []
117
+ if "{{{" in text:
118
+ errs.append("triple-accolade `{{{` détectée (casse la substitution)")
119
+ for raw in INJECTION_RE.findall(strip_python_blocks(text)):
120
+ tok = raw.strip()
121
+ if not tok:
122
+ errs.append("injection vide `{{ }}`")
123
+ continue
124
+ if VALID_TOKEN_RE.match(tok):
125
+ continue
126
+ why = []
127
+ if "_" in tok:
128
+ why.append("underscore")
129
+ if "(" in tok or ")" in tok:
130
+ why.append("appel de fonction")
131
+ if any(c in tok for c in "+*/\\,"):
132
+ why.append("calcul/opérateur")
133
+ if "." in tok:
134
+ why.append("attribut")
135
+ if " " in tok:
136
+ why.append("espace / plusieurs tokens")
137
+ if not why:
138
+ why.append("pas un identifiant nu")
139
+ errs.append(f"injection invalide `{{{{ {tok} }}}}` : {', '.join(why)}")
140
+ return errs
141
+
142
+
143
+ def check_question_ids(text: str) -> list[str]:
144
+ errs: list[str] = []
145
+ for field in ("questionId", "questionIndex"):
146
+ ids = [int(x) for x in re.findall(rf":{field}:\s*(\d+)", text)]
147
+ if not ids:
148
+ continue
149
+ if len(ids) != len(set(ids)):
150
+ errs.append(f":{field}: contient des doublons : {ids}")
151
+ if sorted(ids) != list(range(len(ids))):
152
+ errs.append(f":{field}: non contigu à partir de 0 : {ids}")
153
+ return errs
154
+
155
+
156
+ # ── Motifs interdits (corps rendu — skill §6) ────────────────────────────────
157
+
158
+ FORBIDDEN = [
159
+ (r"(?<!\\)\$[0-9]", r"`$` (non échappé) collé à un chiffre — préfixer par ${} ou passer en display"),
160
+ (r"\{\{\{", r"triple-accolade `{{{`"),
161
+ (r"\^\{\s*0\s*\}", r"`^{0}`"),
162
+ (r"\^\{\s*1\s*\}", r"`^{1}`"),
163
+ (r"\\sqrt\[1\]", r"`\sqrt[1]`"),
164
+ (r"\\sqrt\[2\]", r"`\sqrt[2]` (utiliser `\sqrt`)"),
165
+ (r"\\frac\{\s*\}\{", r"`\frac{}{…}` (numérateur vide)"),
166
+ (r"\\frac\{[^{}]*\}\{\s*1\s*\}", r"`\frac{…}{1}`"),
167
+ (r"\blatex\(", r"`latex(` ayant fui dans le rendu"),
168
+ (r"\bround\(", r"`round(` dans le rendu"),
169
+ (r"\bpxsl_matrix\b", r"`pxsl_matrix` dans le rendu"),
170
+ (r"-\s*\+", r"double signe `- +`"),
171
+ (r"\+\s*-", r"double signe `+ -`"),
172
+ ]
173
+ FORBIDDEN = [(re.compile(p), msg) for p, msg in FORBIDDEN]
174
+
175
+
176
+ def scan_forbidden(body: str) -> list[str]:
177
+ errs = []
178
+ for rx, msg in FORBIDDEN:
179
+ m = rx.search(body)
180
+ if m:
181
+ start = max(0, m.start() - 30)
182
+ ctx = body[start:m.end() + 30].replace("\n", " ")
183
+ errs.append(f"{msg} …{ctx}…")
184
+ return errs
185
+
186
+
187
+ # ── Rendu (substitution des injections) ──────────────────────────────────────
188
+
189
+ def render_body(body_tmpl: str, env: dict) -> tuple[str, list[str]]:
190
+ unresolved: list[str] = []
191
+
192
+ def repl(m):
193
+ name = m.group(1).strip()
194
+ if name in env:
195
+ try:
196
+ return str(env[name])
197
+ except Exception:
198
+ return f"<<ERR:{name}>>"
199
+ unresolved.append(name)
200
+ return f"<<{name}>>"
201
+
202
+ return INJECTION_RE.sub(repl, body_tmpl), unresolved
203
+
204
+
205
+ # ── Validation principale ────────────────────────────────────────────────────
206
+
207
+ def validate_text(text: str, seeds: int = 100) -> dict:
208
+ """
209
+ Valide un exercice pythonisé (texte MyST complet).
210
+
211
+ Retourne :
212
+ {
213
+ "ok": bool,
214
+ "seeds": int,
215
+ "static_errors": [str],
216
+ "n_exec_errors": int, "n_unresolved": int, "n_forbidden": int,
217
+ "first_failures": [str], # ≤ 8, lisibles
218
+ }
219
+ """
220
+ static_errors = check_injection_tokens(text) + check_question_ids(text)
221
+ code = extract_python_code(text)
222
+ if code is None:
223
+ static_errors.append("aucun bloc `{python}` trouvé")
224
+
225
+ report = {
226
+ "ok": False,
227
+ "seeds": seeds,
228
+ "static_errors": static_errors,
229
+ "n_exec_errors": 0,
230
+ "n_unresolved": 0,
231
+ "n_forbidden": 0,
232
+ "first_failures": [],
233
+ }
234
+ if code is None:
235
+ return report
236
+
237
+ body_tmpl = strip_python_blocks(text)
238
+ install_pyxiscience_stubs()
239
+ failures: list[str] = []
240
+
241
+ for s in range(seeds):
242
+ random.seed(s)
243
+ env: dict = {"rd": random, "random": random}
244
+ try:
245
+ with redirect_stdout(io.StringIO()), _warnings.catch_warnings():
246
+ _warnings.simplefilter("ignore") # plt.show() sous Agg, etc.
247
+ exec(code, env) # noqa: S102 — sandbox stubs + contenu maison
248
+ except Exception:
249
+ report["n_exec_errors"] += 1
250
+ if len(failures) < 5:
251
+ tb = traceback.format_exc().strip().splitlines()
252
+ failures.append(f"seed {s} : exception — {tb[-1]}")
253
+ if _HAS_MPL:
254
+ _plt.close("all")
255
+ continue
256
+ if _HAS_MPL:
257
+ _plt.close("all")
258
+
259
+ rendered, unresolved = render_body(body_tmpl, env)
260
+ if unresolved:
261
+ report["n_unresolved"] += 1
262
+ if len(failures) < 8:
263
+ failures.append(f"seed {s} : variable(s) non résolue(s) : {sorted(set(unresolved))}")
264
+ fb = scan_forbidden(rendered)
265
+ if fb:
266
+ report["n_forbidden"] += 1
267
+ if len(failures) < 8:
268
+ failures.append(f"seed {s} : motif interdit : {fb[0]}")
269
+
270
+ report["first_failures"] = failures
271
+ report["ok"] = (
272
+ not static_errors
273
+ and report["n_exec_errors"] == 0
274
+ and report["n_unresolved"] == 0
275
+ and report["n_forbidden"] == 0
276
+ )
277
+ return report
278
+
279
+
280
+ def format_report(report: dict) -> str:
281
+ """Résumé texte court (pour warnings / prompt de réparation)."""
282
+ lines = []
283
+ for e in report["static_errors"]:
284
+ lines.append(f"[STATIQUE] {e}")
285
+ n = report["seeds"]
286
+ if report["n_exec_errors"]:
287
+ lines.append(f"[EXEC] {report['n_exec_errors']}/{n} graines en exception")
288
+ if report["n_unresolved"]:
289
+ lines.append(f"[INJECTION] {report['n_unresolved']}/{n} graines avec variables non résolues")
290
+ if report["n_forbidden"]:
291
+ lines.append(f"[INTERDITS] {report['n_forbidden']}/{n} graines avec motif interdit")
292
+ lines.extend(f" • {f}" for f in report["first_failures"])
293
+ return "\n".join(lines) if lines else "VERT"
app/validation/sandbox.py ADDED
@@ -0,0 +1,587 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ exec_validator.py
3
+ ─────────────────
4
+ Sandboxed execution of the Python block produced by the pythonisation pipeline,
5
+ used to validate at runtime the rules that cannot be checked statically :
6
+
7
+ • règle 4.3 — la propriété démontrée doit être vraie sur 100 % des seeds
8
+ (validation multi-seed avec assertions Python).
9
+ • règle 11.1 — toute variable de tirage utilisée dans l'énoncé doit être
10
+ utilisée dans le tracé matplotlib (analyse AST).
11
+ • règle 11.4 — pas de mélange Rational(sympy) * np.array (analyse AST).
12
+ • règle 11.3 — labels du graphique dans la fenêtre [xlim, ylim] (matplotlib
13
+ backend Agg + extraction des Text/Line objects).
14
+
15
+ Toutes les exécutions sont :
16
+ • Isolées dans un namespace neuf (pas de leak entre seeds)
17
+ • Pré-seedées via `random.seed(N)` (déterministe par seed)
18
+ • Time-boxées (signal.alarm, défaut 5 s par exec)
19
+ • Avec PyxiScience mocké via `sys.modules` (le vrai package n'est pas
20
+ installé localement et n'est de toute façon pas nécessaire pour la
21
+ validation des tirages / contraintes math / position des labels).
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import ast
27
+ import builtins
28
+ import re
29
+ import signal
30
+ import sys
31
+ import threading
32
+ import types
33
+ from typing import Any, Optional
34
+
35
+
36
+ # ─────────────────────────────────────────────────────────────────────────────
37
+ # 1. PyxiScience stubs (the real package isn't installed locally)
38
+ # ─────────────────────────────────────────────────────────────────────────────
39
+
40
+ _STUBS_INSTALLED = False
41
+
42
+
43
+ def _passthrough(*args, **kwargs):
44
+ """Universal callable stub: returns first arg cast to str if any, else ''."""
45
+ if not args:
46
+ return ""
47
+ # latex(...) and pxsl_* helpers all return strings; mirror that shape.
48
+ return str(args[0])
49
+
50
+
51
+ def _config_stub(*args, **kwargs):
52
+ """
53
+ Stub for `pxs_config()`. Must return a `dict` so that downstream code
54
+ like `latex(expr, **config_standard)` (where `config_standard = pxs_config()`)
55
+ doesn't crash with "argument of type 'str' is not iterable".
56
+ """
57
+ return {}
58
+
59
+
60
+ class _StubObject:
61
+ """Universal class stub with arbitrary attribute access."""
62
+
63
+ def __init__(self, *args, **kwargs):
64
+ self._args = args
65
+ self._kwargs = kwargs
66
+
67
+ def print(self):
68
+ return ""
69
+
70
+ def __call__(self, *args, **kwargs):
71
+ return _StubObject(*args, **kwargs)
72
+
73
+ def __getattr__(self, name):
74
+ # Any method access returns a no-op callable
75
+ return _passthrough
76
+
77
+ def __repr__(self):
78
+ return f"_StubObject({self._args!r})"
79
+
80
+
81
+ def install_pyxiscience_stubs() -> None:
82
+ """
83
+ Register stub modules for `pyxiscience.*` in sys.modules so that generated
84
+ Python blocks can `import` PyxiScience helpers without crashing. Idempotent.
85
+ """
86
+ global _STUBS_INSTALLED
87
+ if _STUBS_INSTALLED:
88
+ return
89
+
90
+ if "pyxiscience" in sys.modules:
91
+ _STUBS_INSTALLED = True
92
+ return
93
+
94
+ pyxiscience = types.ModuleType("pyxiscience")
95
+ sys.modules["pyxiscience"] = pyxiscience
96
+
97
+ submodules = [
98
+ "Mes_fctions_generalistes_bis",
99
+ "Classes_Extensions",
100
+ "Mes_fctions_d_analyse_bis",
101
+ "Mes_fctions_d_analyse", # alias without _bis (cf. Exo 2 Am. Sud)
102
+ "Mes_fctions_d_alg_lineaire_bis",
103
+ "Mes_fctions_probabilistes_bis",
104
+ ]
105
+ helper_names = [
106
+ "pxs_config", "pxsl_latex_coefficient", "pxsl_format_number",
107
+ "pxsl_res_num", "pxsl_matrix", "pxsl_pow", "pxsl_par", "pxsl_mult",
108
+ "pxs_explain_IBP", "pxs_nvirgzero", "_pxsl_choose_udv",
109
+ "pxs_variation_number", "myst",
110
+ "pxsl_latex_avec_formatage", # cf. Exo 2 Am Sud
111
+ "pxsl_choose_udv",
112
+ ]
113
+ class_names = ["pxs_Interval", "pxs_Plotable"]
114
+
115
+ for sub in submodules:
116
+ m = types.ModuleType(f"pyxiscience.{sub}")
117
+ for name in helper_names:
118
+ setattr(m, name, _passthrough)
119
+ # Special-case: pxs_config must return a dict (used as **kwargs).
120
+ setattr(m, "pxs_config", _config_stub)
121
+ for name in class_names:
122
+ setattr(m, name, _StubObject)
123
+ sys.modules[f"pyxiscience.{sub}"] = m
124
+ setattr(pyxiscience, sub, m)
125
+
126
+ # Top-level convenience attribute (some code does `import pyxiscience`)
127
+ pyxiscience.pxs_variation_number = 1 # règle 13.2
128
+
129
+ # Stub `src.scripts.pxs_runtime` for `myst()` helper used in conditional text.
130
+ # Observed in real exos like the binomiale exercise:
131
+ # from src.scripts.pxs_runtime import myst
132
+ # shot_name = myst(r"{fr}`...`{en}`...`")
133
+ src_mod = types.ModuleType("src")
134
+ scripts_mod = types.ModuleType("src.scripts")
135
+ runtime_mod = types.ModuleType("src.scripts.pxs_runtime")
136
+ runtime_mod.myst = _passthrough
137
+ sys.modules["src"] = src_mod
138
+ sys.modules["src.scripts"] = scripts_mod
139
+ sys.modules["src.scripts.pxs_runtime"] = runtime_mod
140
+ src_mod.scripts = scripts_mod
141
+ scripts_mod.pxs_runtime = runtime_mod
142
+
143
+ _STUBS_INSTALLED = True
144
+
145
+
146
+ # ─────────────────────────────────────────────────────────────────────────────
147
+ # 2. Extract the main python block from an assembled exercise
148
+ # ─────────────────────────────────────────────────────────────────────────────
149
+
150
+ # Fence {python} à 3 OU 4 backticks (l'app émet 4 — convention plateforme —
151
+ # mais la lecture reste tolérante pour les contenus legacy).
152
+ _PYTHON_FENCE_RE = re.compile(r"(?ms)^(`{3,4})\{python\}[ \t]*\n(.*?)\n\1[ \t]*$")
153
+
154
+
155
+ def extract_main_python_block(exercise: str) -> Optional[str]:
156
+ """
157
+ Return the contents of the FIRST {python} block in the assembled
158
+ exercise (which by convention holds the imports + random sampling +
159
+ main computations — règle 3.1). Returns None if absent.
160
+ """
161
+ m = _PYTHON_FENCE_RE.search(exercise)
162
+ return m.group(2) if m else None
163
+
164
+
165
+ def extract_all_python_blocks(exercise: str) -> list[str]:
166
+ """Return all {python} block bodies, in order."""
167
+ return [m.group(2) for m in _PYTHON_FENCE_RE.finditer(exercise)]
168
+
169
+
170
+ # ─────────────────────────────────────────────────────────────────────────────
171
+ # 3. Sandboxed exec with timeout
172
+ # ─────────────────────────────────────────────────────────────────────────────
173
+
174
+ class ExecTimeout(Exception):
175
+ """Raised when exec exceeds its time budget."""
176
+
177
+
178
+ def _timeout_handler(signum, frame):
179
+ raise ExecTimeout("exec exceeded its time budget")
180
+
181
+
182
+ def _exec_with_timeout(code: str, namespace: dict, timeout: float) -> None:
183
+ """
184
+ Run `exec(code, namespace)` under a timeout.
185
+
186
+ Two strategies:
187
+ • Main thread → use `signal.SIGALRM` (cheap, interruptible).
188
+ • Background thread (Flask worker) → use a daemon thread + `Event.wait`.
189
+ The daemon thread can't actually be killed in Python; it survives the
190
+ timeout but doesn't block subsequent execs since each call spawns a
191
+ fresh daemon. Acceptable for short math-only workloads.
192
+ """
193
+ compiled = compile(code, "<sandbox>", "exec")
194
+
195
+ if threading.current_thread() is threading.main_thread():
196
+ old_handler = signal.signal(signal.SIGALRM, _timeout_handler)
197
+ signal.setitimer(signal.ITIMER_REAL, timeout)
198
+ try:
199
+ exec(compiled, namespace)
200
+ finally:
201
+ signal.setitimer(signal.ITIMER_REAL, 0)
202
+ signal.signal(signal.SIGALRM, old_handler)
203
+ return
204
+
205
+ # Background-thread variant: run in a daemon child thread.
206
+ captured: dict[str, Optional[BaseException]] = {"exc": None}
207
+ done = threading.Event()
208
+
209
+ def _target() -> None:
210
+ try:
211
+ exec(compiled, namespace)
212
+ except BaseException as e: # noqa: BLE001 — re-raised below
213
+ captured["exc"] = e
214
+ finally:
215
+ done.set()
216
+
217
+ worker = threading.Thread(target=_target, daemon=True)
218
+ worker.start()
219
+ if not done.wait(timeout):
220
+ raise ExecTimeout(f"exec exceeded {timeout}s")
221
+ if captured["exc"] is not None:
222
+ raise captured["exc"]
223
+
224
+
225
+ def exec_python_block(
226
+ code: str,
227
+ seed: int = 0,
228
+ extra_globals: Optional[dict] = None,
229
+ timeout: float = 5.0,
230
+ ) -> dict:
231
+ """
232
+ Execute `code` once, pre-seeding `random` with `seed`.
233
+ Returns:
234
+ {"success": bool, "ns": dict | None, "error": str | None}
235
+ On success, `ns` contains the namespace after exec (variables available
236
+ for assertion evaluation).
237
+
238
+ Stubs `pyxiscience.*` and disallows obvious filesystem / network builtins
239
+ by stripping them from the namespace.
240
+ """
241
+ install_pyxiscience_stubs()
242
+
243
+ namespace: dict[str, Any] = {
244
+ "__name__": "__sandbox__",
245
+ "__builtins__": _safe_builtins(),
246
+ }
247
+ if extra_globals:
248
+ namespace.update(extra_globals)
249
+
250
+ # Pre-seed both random and numpy.random (cheap; ignored if numpy not used).
251
+ preamble = (
252
+ f"import random as _rnd_internal; _rnd_internal.seed({seed})\n"
253
+ f"try:\n"
254
+ f" import numpy as _np_internal; _np_internal.random.seed({seed})\n"
255
+ f"except Exception:\n"
256
+ f" pass\n"
257
+ )
258
+ full_code = preamble + code
259
+
260
+ try:
261
+ _exec_with_timeout(full_code, namespace, timeout)
262
+ return {"success": True, "ns": namespace, "error": None}
263
+ except ExecTimeout as e:
264
+ return {"success": False, "ns": None, "error": f"timeout ({timeout}s)"}
265
+ except Exception as e:
266
+ return {"success": False, "ns": None, "error": f"{type(e).__name__}: {e}"}
267
+
268
+
269
+ def _safe_builtins() -> dict:
270
+ """
271
+ Return a copy of builtins with dangerous filesystem/network names removed.
272
+ The sandboxed code is generated by an LLM operating on math content; we
273
+ don't want it to accidentally `open(...)` or `__import__('subprocess')`.
274
+ """
275
+ blocked = {
276
+ "open", "input", "exit", "quit", "compile", "eval", "exec",
277
+ "__import__", # block dynamic imports — explicit imports in code still work via the import statement
278
+ }
279
+ safe: dict[str, Any] = {}
280
+ for name in dir(builtins):
281
+ if name in blocked:
282
+ continue
283
+ safe[name] = getattr(builtins, name)
284
+ # `__import__` we restore but wrap to whitelist
285
+ safe["__import__"] = _safe_import
286
+ return safe
287
+
288
+
289
+ _ALLOWED_TOP_LEVEL_MODULES = {
290
+ "random", "math", "sympy", "numpy", "fractions", "pandas",
291
+ "matplotlib", "scipy", "itertools", "functools", "collections",
292
+ "decimal", "statistics", "operator", "copy", "re", "json",
293
+ "pyxiscience", # stubbed
294
+ "src", # stubbed (for `from src.scripts.pxs_runtime import myst`)
295
+ }
296
+
297
+
298
+ def _safe_import(name, *args, **kwargs):
299
+ top = name.split(".")[0]
300
+ if top not in _ALLOWED_TOP_LEVEL_MODULES:
301
+ raise ImportError(f"import of {name!r} blocked in sandbox")
302
+ return builtins.__import__(name, *args, **kwargs)
303
+
304
+
305
+ # ─────────────────────────────────────────────────────────────────────────────
306
+ # 4. Multi-seed validation for règle 4.3
307
+ # ─────────────────────────────────────────────────────────────────────────────
308
+
309
+ def multi_seed_validate(
310
+ code: str,
311
+ assertions: list[dict],
312
+ num_seeds: int = 100,
313
+ timeout_per_seed: float = 3.0,
314
+ ) -> dict:
315
+ """
316
+ Run `code` num_seeds times with seeds 0..num_seeds-1 and evaluate each
317
+ assertion in the resulting namespace. Each assertion is a dict with:
318
+ {"description": "...", "assertion": "<python boolean expression>"}
319
+
320
+ Returns:
321
+ {
322
+ "num_seeds": int,
323
+ "num_exec_errors": int,
324
+ "violations": [
325
+ {"seed": int, "assertion": "...", "description": "...", "value": "False" | "<exception>"},
326
+ ... # capped at 5 per assertion
327
+ ],
328
+ "summary_per_assertion": {assertion_str: {"violations": int, "errors": int}}
329
+ }
330
+ """
331
+ summary: dict[str, dict[str, int]] = {
332
+ a["assertion"]: {"violations": 0, "errors": 0}
333
+ for a in assertions if "assertion" in a
334
+ }
335
+ violations: list[dict] = []
336
+ num_exec_errors = 0
337
+ first_exec_error: Optional[str] = None
338
+ capped_assertions: set[str] = set()
339
+
340
+ for seed in range(num_seeds):
341
+ res = exec_python_block(code, seed=seed, timeout=timeout_per_seed)
342
+ if not res["success"]:
343
+ num_exec_errors += 1
344
+ if first_exec_error is None:
345
+ first_exec_error = res["error"]
346
+ continue
347
+ ns = res["ns"]
348
+ for a in assertions:
349
+ assertion = a.get("assertion")
350
+ description = a.get("description", "")
351
+ if not isinstance(assertion, str) or not assertion.strip():
352
+ continue
353
+ try:
354
+ ok = bool(eval(assertion, ns))
355
+ if not ok:
356
+ summary[assertion]["violations"] += 1
357
+ if assertion not in capped_assertions and len(
358
+ [v for v in violations if v["assertion"] == assertion]
359
+ ) < 5:
360
+ violations.append({
361
+ "seed": seed,
362
+ "assertion": assertion,
363
+ "description": description,
364
+ "value": "False",
365
+ })
366
+ except Exception as e:
367
+ summary[assertion]["errors"] += 1
368
+ if assertion not in capped_assertions and len(
369
+ [v for v in violations if v["assertion"] == assertion]
370
+ ) < 5:
371
+ violations.append({
372
+ "seed": seed,
373
+ "assertion": assertion,
374
+ "description": description,
375
+ "value": f"{type(e).__name__}: {e}",
376
+ })
377
+
378
+ return {
379
+ "num_seeds": num_seeds,
380
+ "num_exec_errors": num_exec_errors,
381
+ "first_exec_error": first_exec_error,
382
+ "violations": violations,
383
+ "summary_per_assertion": summary,
384
+ }
385
+
386
+
387
+ # ─────────────────────────────────────────────────────────────────────────────
388
+ # 5. Static AST checks for règles 11.1 (unused random vars in plot)
389
+ # and 11.4 (Rational sympy * numpy array)
390
+ # ─────────────────────────────────────────────────────────────────────────────
391
+
392
+ # Names of plotting functions to look for (matplotlib API used in PyxiScience).
393
+ _PLOT_FN_NAMES = {
394
+ "plot", "scatter", "fill_between", "fill", "vlines", "hlines",
395
+ "axhline", "axvline", "text", "annotate", "errorbar", "stem",
396
+ "step", "imshow", "contour", "contourf", "quiver", "stairs",
397
+ }
398
+
399
+
400
+ def static_check_unused_random_vars(
401
+ code: str,
402
+ random_var_names: list[str],
403
+ markdown_text: str = "",
404
+ ) -> list[str]:
405
+ """
406
+ Règle 11.1 : any variable sampled randomly should be referenced either
407
+ in the rest of the Python code (Load context) OR somewhere in the MyST
408
+ markdown (`{{var}}` placeholder). Otherwise it's dead code.
409
+
410
+ `markdown_text` should be the assembled exercise WITHOUT the Python
411
+ blocks (or the whole exercise — both work because the regex looks for
412
+ `{{var}}` patterns which only appear in MyST sections).
413
+
414
+ Returns the list of names that have ZERO references anywhere. Empty
415
+ list = règle respectée.
416
+ """
417
+ if not random_var_names:
418
+ return []
419
+
420
+ referenced: set[str] = set()
421
+
422
+ # 1) References in the Python code (Load context).
423
+ try:
424
+ tree = ast.parse(code)
425
+ for node in ast.walk(tree):
426
+ if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load):
427
+ if node.id in random_var_names:
428
+ referenced.add(node.id)
429
+ except SyntaxError:
430
+ pass # leniency: don't false-positive on parse failures
431
+
432
+ # 2) References in the MyST markdown ({{var}} or {{var.foo}} or {{f(var)}}).
433
+ if markdown_text:
434
+ for name in random_var_names:
435
+ if name in referenced:
436
+ continue
437
+ if re.search(rf"\{{\{{[^}}]*\b{re.escape(name)}\b[^}}]*\}}\}}", markdown_text):
438
+ referenced.add(name)
439
+
440
+ return [v for v in random_var_names if v not in referenced]
441
+
442
+
443
+ def static_check_rational_numpy_mix(code: str) -> list[dict]:
444
+ """
445
+ Règle 11.4 : detect `Rational(...) * <np.array_expr>` or similar
446
+ sympy-Rational ↔ numpy mixes that crash at runtime.
447
+
448
+ Detection is intentionally narrow to avoid false positives. We flag:
449
+ Rational(...) * <expr_referencing_np>
450
+ <expr_referencing_np> * Rational(...)
451
+ where `<expr_referencing_np>` contains a `np.something` or a name we
452
+ recognise as a numpy array (heuristic: contains `_graph` suffix).
453
+ """
454
+ issues: list[dict] = []
455
+ try:
456
+ tree = ast.parse(code)
457
+ except SyntaxError:
458
+ return issues
459
+
460
+ def _is_rational_call(node: ast.AST) -> bool:
461
+ return (
462
+ isinstance(node, ast.Call)
463
+ and isinstance(node.func, ast.Name)
464
+ and node.func.id == "Rational"
465
+ )
466
+
467
+ def _references_numpy(node: ast.AST) -> bool:
468
+ for sub in ast.walk(node):
469
+ if isinstance(sub, ast.Attribute) and isinstance(sub.value, ast.Name):
470
+ if sub.value.id in {"np", "numpy"}:
471
+ return True
472
+ if isinstance(sub, ast.Name) and (
473
+ sub.id.endswith("_graph") or sub.id.endswith("_arr")
474
+ ):
475
+ return True
476
+ return False
477
+
478
+ for node in ast.walk(tree):
479
+ if isinstance(node, ast.BinOp) and isinstance(node.op, (ast.Mult, ast.Add, ast.Sub)):
480
+ left, right = node.left, node.right
481
+ if (_is_rational_call(left) and _references_numpy(right)) or (
482
+ _is_rational_call(right) and _references_numpy(left)
483
+ ):
484
+ issues.append({
485
+ "rule": "11.4",
486
+ "message": (
487
+ "Mélange Rational(sympy) ↔ numpy détecté à la ligne "
488
+ f"{getattr(node, 'lineno', '?')} — convertir Rational en float() "
489
+ "AVANT toute opération numpy."
490
+ ),
491
+ })
492
+ return issues
493
+
494
+
495
+ # ─────────────────────────────────────────────────────────────────────────────
496
+ # 6. Dynamic matplotlib check for règle 11.3 (labels in plot window)
497
+ # ─────────────────────────────────────────���───────────────────────────────────
498
+
499
+ def dynamic_check_matplotlib(code: str, timeout: float = 8.0) -> list[dict]:
500
+ """
501
+ Execute `code` with a headless matplotlib backend, then inspect every
502
+ Text artist on every axis and flag any whose position falls outside
503
+ [xlim, ylim] (règle 11.3).
504
+
505
+ Notes:
506
+ • Only runs if `matplotlib` is imported in the code (avoid pointless exec).
507
+ • Uses `matplotlib.use("Agg", force=True)` BEFORE the user code imports
508
+ matplotlib — this is achieved by pre-importing pyplot in the namespace
509
+ with the Agg backend already set.
510
+ • `plt.show()` becomes a no-op under Agg, so the user code runs to
511
+ completion without opening a window.
512
+ """
513
+ if "matplotlib" not in code:
514
+ return []
515
+
516
+ import matplotlib
517
+ matplotlib.use("Agg", force=True)
518
+ import matplotlib.pyplot as plt
519
+
520
+ # Reset figure state to isolate runs (close any leftovers).
521
+ plt.close("all")
522
+
523
+ # Inject `plt`/`matplotlib` already set up into the namespace so the user
524
+ # code's `import matplotlib.pyplot as plt` finds the Agg backend.
525
+ extra = {}
526
+
527
+ res = exec_python_block(code, seed=0, extra_globals=extra, timeout=timeout)
528
+ issues: list[dict] = []
529
+ if not res["success"]:
530
+ # Don't fault the user; runtime errors are caught elsewhere.
531
+ plt.close("all")
532
+ return []
533
+
534
+ for fig_num in plt.get_fignums():
535
+ fig = plt.figure(fig_num)
536
+ for ax in fig.get_axes():
537
+ try:
538
+ xmin, xmax = ax.get_xlim()
539
+ ymin, ymax = ax.get_ylim()
540
+ except Exception:
541
+ continue
542
+ for text_artist in ax.texts:
543
+ try:
544
+ x, y = text_artist.get_position()
545
+ except Exception:
546
+ continue
547
+ # Numeric only; skip annotations with non-numeric positions.
548
+ if not (isinstance(x, (int, float)) and isinstance(y, (int, float))):
549
+ continue
550
+ out_of_bounds = (x < xmin or x > xmax or y < ymin or y > ymax)
551
+ if out_of_bounds:
552
+ label = text_artist.get_text()
553
+ snippet = label.strip()[:40].replace("\n", " ")
554
+ issues.append({
555
+ "rule": "11.3",
556
+ "message": (
557
+ f"Label « {snippet} » à ({x:.2f}, {y:.2f}) sort de la fenêtre "
558
+ f"[{xmin:.1f}, {xmax:.1f}] × [{ymin:.1f}, {ymax:.1f}]. "
559
+ "Matplotlib va étendre l'axe et compresser le graphique."
560
+ ),
561
+ })
562
+ plt.close("all")
563
+ return issues
564
+
565
+
566
+ # ─────────────────────────────────────────────────────────────────────────────
567
+ # 7. Smoke test (run module directly: `python utils/exec_validator.py`)
568
+ # ─────────────────────────────────────────────────────────────────────────────
569
+ if __name__ == "__main__":
570
+ code = """
571
+ import random as rd
572
+ from sympy import Rational
573
+ a = rd.randint(1, 10)
574
+ b = rd.choice([2, 3, 4])
575
+ result = Rational(a, b)
576
+ """
577
+ print("[smoke] running 10 seeds with simple code...")
578
+ out = multi_seed_validate(
579
+ code,
580
+ assertions=[
581
+ {"description": "a est positif", "assertion": "a > 0"},
582
+ {"description": "b est dans {2,3,4}", "assertion": "b in (2, 3, 4)"},
583
+ {"description": "a < b (BUG attendu sur certains seeds)", "assertion": "a < b"},
584
+ ],
585
+ num_seeds=10,
586
+ )
587
+ print(out)
app/web/templates/index.html ADDED
@@ -0,0 +1,827 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="fr">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <title>Pythonise Exercice — v2</title>
6
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
7
+
8
+ <link rel="preconnect" href="https://fonts.googleapis.com">
9
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
10
+ <link href="https://fonts.googleapis.com/css2?family=Geist:wght@400;500;600;700&family=Geist+Mono:wght@400;500&display=swap" rel="stylesheet">
11
+
12
+ <style>
13
+ :root {
14
+ --bg: #f7f7f8;
15
+ --panel: #ffffff;
16
+ --panel-alt: #fafafb;
17
+ --panel-hover: #f4f4f5;
18
+ --border: #e4e4e7;
19
+ --border-soft: #eeeef0;
20
+ --border-strong: #d4d4d8;
21
+ --text: #09090b;
22
+ --text-2: #27272a;
23
+ --text-muted: #71717a;
24
+ --text-soft: #a1a1aa;
25
+ --primary: #18181b;
26
+ --primary-hover: #27272a;
27
+ --primary-fg: #fafafa;
28
+ --accent: #2563eb;
29
+ --success: #16a34a;
30
+ --success-bg: #f0fdf4;
31
+ --success-border:#bbf7d0;
32
+ --error: #dc2626;
33
+ --error-bg: #fef2f2;
34
+ --error-border: #fecaca;
35
+ --warn: #ca8a04;
36
+ --warn-bg: #fefce8;
37
+ --sans: 'Geist', -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, sans-serif;
38
+ --mono: 'Geist Mono', 'JetBrains Mono', "SF Mono", Menlo, monospace;
39
+ --radius: 10px;
40
+ --radius-sm: 6px;
41
+ --radius-xs: 4px;
42
+ --shadow-xs: 0 1px 2px rgba(9, 9, 11, 0.04);
43
+ --shadow-sm: 0 1px 2px rgba(9, 9, 11, 0.04), 0 2px 8px rgba(9, 9, 11, 0.03);
44
+ --shadow-focus: 0 0 0 3px rgba(37, 99, 235, 0.12);
45
+ }
46
+
47
+ * { box-sizing: border-box; }
48
+ html, body { margin: 0; padding: 0; }
49
+ [hidden] { display: none !important; }
50
+
51
+ body {
52
+ background: var(--bg);
53
+ color: var(--text);
54
+ font-family: var(--sans);
55
+ font-size: 14px;
56
+ line-height: 1.55;
57
+ -webkit-font-smoothing: antialiased;
58
+ }
59
+ .container { max-width: 1320px; margin: 0 auto; padding: 40px 32px 56px; }
60
+
61
+ .header {
62
+ display: flex; align-items: center; justify-content: space-between; gap: 16px;
63
+ margin-bottom: 28px; padding-bottom: 24px;
64
+ border-bottom: 1px solid var(--border-soft); flex-wrap: wrap;
65
+ }
66
+ .header-left { display: flex; align-items: center; gap: 14px; }
67
+ .header-mark {
68
+ width: 36px; height: 36px; border-radius: 8px;
69
+ background: var(--primary); color: var(--primary-fg);
70
+ display: flex; align-items: center; justify-content: center;
71
+ font-family: var(--mono); font-weight: 500; font-size: 13px;
72
+ }
73
+ .header-text h1 { margin: 0 0 2px; font-size: 17px; font-weight: 600; }
74
+ .header-text p { margin: 0; color: var(--text-muted); font-size: 13px; }
75
+ .header-status {
76
+ display: inline-flex; align-items: center; gap: 8px; font-size: 12px;
77
+ color: var(--text-muted); font-weight: 500; padding: 6px 12px;
78
+ background: var(--panel); border: 1px solid var(--border); border-radius: 999px;
79
+ }
80
+ .header-status .dot {
81
+ width: 6px; height: 6px; border-radius: 50%; background: var(--success);
82
+ box-shadow: 0 0 0 3px rgba(22, 163, 74, 0.15);
83
+ }
84
+
85
+ .grid { display: grid; grid-template-columns: 1fr 1fr; gap: 24px; }
86
+ @media (max-width: 960px) { .grid { grid-template-columns: 1fr; } }
87
+
88
+ .panel {
89
+ background: var(--panel); border: 1px solid var(--border);
90
+ border-radius: var(--radius); box-shadow: var(--shadow-sm);
91
+ padding: 24px; display: flex; flex-direction: column; min-width: 0;
92
+ }
93
+ .panel-title {
94
+ font-size: 11px; font-weight: 600; color: var(--text-muted);
95
+ margin: 0 0 16px; letter-spacing: 0.08em; text-transform: uppercase;
96
+ }
97
+
98
+ .field { margin-bottom: 14px; }
99
+ .field-label {
100
+ display: block; font-size: 12px; font-weight: 500; color: var(--text-2);
101
+ margin-bottom: 6px;
102
+ }
103
+ textarea, input[type="text"], select {
104
+ width: 100%; background: var(--panel); border: 1px solid var(--border);
105
+ border-radius: var(--radius-sm); padding: 10px 12px; font-family: inherit;
106
+ font-size: 13px; line-height: 1.55; color: var(--text);
107
+ transition: border-color 0.15s ease, box-shadow 0.15s ease;
108
+ }
109
+ textarea {
110
+ font-family: var(--mono); font-size: 12.5px; line-height: 1.6;
111
+ height: 320px; resize: vertical; min-height: 160px;
112
+ }
113
+ textarea:focus, input[type="text"]:focus, select:focus {
114
+ outline: none; border-color: var(--accent); box-shadow: var(--shadow-focus);
115
+ }
116
+ select {
117
+ appearance: none; -webkit-appearance: none;
118
+ background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12'><path fill='none' stroke='%2371717a' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round' d='M3 5 L6 8 L9 5'/></svg>");
119
+ background-repeat: no-repeat; background-position: right 10px center;
120
+ background-size: 12px; padding-right: 32px; cursor: pointer; font-weight: 500;
121
+ }
122
+
123
+ .meta { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 12px 14px; margin: 18px 0 20px; }
124
+ .meta-full { grid-column: 1 / -1; }
125
+
126
+ .actions { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
127
+ .btn {
128
+ display: inline-flex; align-items: center; gap: 6px; padding: 9px 16px;
129
+ border-radius: var(--radius-sm); border: 1px solid var(--border);
130
+ background: var(--panel); color: var(--text); font-family: inherit;
131
+ font-size: 13px; font-weight: 500; cursor: pointer;
132
+ transition: all 0.15s ease; box-shadow: var(--shadow-xs);
133
+ }
134
+ .btn:hover:not(:disabled) { background: var(--panel-hover); border-color: var(--border-strong); }
135
+ .btn:disabled { opacity: 0.45; cursor: not-allowed; }
136
+ .btn--primary { background: var(--primary); border-color: var(--primary); color: var(--primary-fg); }
137
+ .btn--primary:hover:not(:disabled) { background: var(--primary-hover); }
138
+ .btn--ghost { background: transparent; border-color: transparent; color: var(--text-muted); box-shadow: none; padding: 7px 12px; }
139
+ .btn--ghost:hover:not(:disabled) { background: var(--panel-hover); color: var(--text); }
140
+ .btn--small { padding: 5px 11px; font-size: 12px; }
141
+
142
+ /* Batch file list */
143
+ .filelist { list-style: none; padding: 0; margin: 10px 0 0; }
144
+ .filelist li {
145
+ display: flex; align-items: center; gap: 8px;
146
+ font-family: var(--mono); font-size: 12px; color: var(--text-2);
147
+ padding: 5px 8px; border: 1px solid var(--border-soft);
148
+ border-radius: var(--radius-xs); margin-bottom: 4px; background: var(--panel-alt);
149
+ }
150
+ .filelist .rm { margin-left: auto; cursor: pointer; color: var(--text-soft); border: none; background: none; font-size: 13px; }
151
+ .filelist .rm:hover { color: var(--error); }
152
+
153
+ .progress { margin-top: 18px; padding-top: 16px; border-top: 1px solid var(--border-soft); }
154
+ .progress-line { display: flex; align-items: center; gap: 10px; font-size: 13px; color: var(--text-2); }
155
+ .progress-spinner {
156
+ width: 12px; height: 12px; border: 1.5px solid var(--border-strong);
157
+ border-top-color: var(--text); border-radius: 50%;
158
+ animation: spin 0.7s linear infinite; flex-shrink: 0;
159
+ }
160
+ .progress-label { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
161
+ .progress-step {
162
+ font-family: var(--mono); font-size: 11px; color: var(--text-muted);
163
+ padding: 2px 7px; background: var(--bg); border: 1px solid var(--border-soft);
164
+ border-radius: var(--radius-xs); white-space: nowrap;
165
+ }
166
+ .progress-bar { margin-top: 10px; height: 3px; background: var(--border-soft); border-radius: 3px; overflow: hidden; position: relative; }
167
+ .progress-bar-fill { position: absolute; inset: 0; background: var(--text); transform: translateX(-100%); border-radius: 3px; }
168
+ .progress.is-running .progress-bar-fill { animation: slide 1.6s cubic-bezier(0.4, 0, 0.2, 1) infinite; }
169
+ .progress.is-done .progress-bar-fill { transform: translateX(0); background: var(--success); }
170
+ .progress.is-error .progress-bar-fill { transform: translateX(0); background: var(--error); }
171
+ .progress.is-idle .progress-spinner, .progress.is-done .progress-spinner, .progress.is-error .progress-spinner { display: none; }
172
+
173
+ @keyframes spin { to { transform: rotate(360deg); } }
174
+ @keyframes slide {
175
+ 0% { transform: translateX(-100%) scaleX(0.35); }
176
+ 50% { transform: translateX(0%) scaleX(0.65); }
177
+ 100% { transform: translateX(100%) scaleX(0.35); }
178
+ }
179
+ @keyframes fadeIn { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: translateY(0); } }
180
+
181
+ .status {
182
+ margin-top: 12px; padding: 10px 14px; border-radius: var(--radius-sm);
183
+ font-size: 13px; border: 1px solid transparent; animation: fadeIn 0.2s ease-out;
184
+ display: flex; align-items: center; gap: 8px;
185
+ }
186
+ .status::before { content: ''; width: 6px; height: 6px; border-radius: 50%; flex-shrink: 0; }
187
+ .status.is-error { background: var(--error-bg); border-color: var(--error-border); color: #991b1b; }
188
+ .status.is-error::before { background: var(--error); }
189
+ .status.is-done { background: var(--success-bg); border-color: var(--success-border); color: #166534; }
190
+ .status.is-done::before { background: var(--success); }
191
+ .status.is-warn { background: var(--warn-bg); border-color: #fde68a; color: #854d0e; }
192
+ .status.is-warn::before { background: var(--warn); }
193
+
194
+ /* Résumé batch + sélecteur de fichier résultat */
195
+ .result-files { display: flex; gap: 6px; flex-wrap: wrap; margin-bottom: 12px; }
196
+ .result-file {
197
+ display: inline-flex; align-items: center; gap: 6px;
198
+ font-family: var(--mono); font-size: 11.5px; padding: 4px 10px;
199
+ border: 1px solid var(--border); border-radius: 999px;
200
+ background: var(--panel); cursor: pointer; color: var(--text-2);
201
+ }
202
+ .result-file.is-active { border-color: var(--text); background: var(--panel-hover); }
203
+ .verdict-dot { width: 7px; height: 7px; border-radius: 50%; }
204
+ .verdict-dot.ok { background: var(--success); }
205
+ .verdict-dot.ko { background: var(--error); }
206
+ .verdict-dot.err { background: var(--warn); }
207
+
208
+ .tabs {
209
+ display: flex; align-items: center; gap: 2px; margin-bottom: 14px;
210
+ padding: 4px; background: var(--bg); border: 1px solid var(--border-soft);
211
+ border-radius: var(--radius-sm); flex-wrap: wrap;
212
+ }
213
+ .tab {
214
+ background: transparent; border: none; padding: 6px 12px; font-family: inherit;
215
+ font-size: 13px; font-weight: 500; color: var(--text-muted); cursor: pointer;
216
+ border-radius: var(--radius-xs); transition: all 0.15s ease;
217
+ }
218
+ .tab.is-active { color: var(--text); background: var(--panel); box-shadow: var(--shadow-xs); }
219
+ .tab-badge {
220
+ display: inline-block; margin-left: 5px; padding: 0 6px; min-width: 18px;
221
+ height: 16px; font-size: 10px; font-family: var(--mono); font-weight: 500;
222
+ background: var(--text); color: var(--primary-fg); border-radius: 8px;
223
+ line-height: 16px; text-align: center; vertical-align: 1px;
224
+ }
225
+ .tab-spacer { flex: 1; }
226
+ .tab-panels { flex: 1; min-height: 0; display: flex; flex-direction: column; }
227
+ .tab-panel { display: none; flex: 1; min-height: 0; flex-direction: column; }
228
+ .tab-panel.is-active { display: flex; animation: fadeIn 0.18s ease-out; }
229
+
230
+ .output {
231
+ background: var(--panel-alt); border: 1px solid var(--border-soft);
232
+ border-radius: var(--radius-sm); padding: 16px 18px; margin: 0;
233
+ font-family: var(--mono); font-size: 12.5px; line-height: 1.65;
234
+ color: var(--text-2); min-height: 380px; max-height: 620px;
235
+ overflow: auto; white-space: pre-wrap; word-break: break-word;
236
+ }
237
+ .output .empty { color: var(--text-soft); font-family: var(--sans); font-size: 13px; }
238
+ .output--audit { font-family: var(--sans); font-size: 13px; line-height: 1.6; white-space: normal; color: var(--text); }
239
+
240
+ .output::-webkit-scrollbar { width: 10px; height: 10px; }
241
+ .output::-webkit-scrollbar-thumb { background: var(--border); border-radius: 5px; border: 2px solid var(--panel-alt); }
242
+
243
+ .audit-section + .audit-section { margin-top: 24px; }
244
+ .audit-heading {
245
+ font-size: 11px; font-weight: 600; color: var(--text-muted);
246
+ text-transform: uppercase; letter-spacing: 0.08em; margin: 0 0 12px;
247
+ display: flex; align-items: center; gap: 8px;
248
+ }
249
+ .audit-heading .count {
250
+ color: var(--text-soft); font-weight: 500; font-family: var(--mono);
251
+ font-size: 10px; padding: 1px 6px; background: var(--bg); border-radius: 999px;
252
+ }
253
+ .audit-list { list-style: none; padding: 0; margin: 0; }
254
+ .audit-patch { padding: 14px 0; border-top: 1px solid var(--border-soft); }
255
+ .audit-patch:first-child { border-top: none; padding-top: 0; }
256
+ .audit-rule {
257
+ display: inline-flex; font-family: var(--mono); font-size: 11px; font-weight: 500;
258
+ color: var(--text-2); background: var(--bg); border: 1px solid var(--border);
259
+ padding: 2px 8px; border-radius: var(--radius-xs); margin-bottom: 10px;
260
+ }
261
+ .audit-diff { display: grid; grid-template-columns: 1fr; gap: 6px; }
262
+ .audit-before, .audit-after {
263
+ font-family: var(--mono); font-size: 12px; padding: 10px 12px; margin: 0;
264
+ border-radius: var(--radius-xs); white-space: pre-wrap; line-height: 1.55;
265
+ border-left: 2px solid;
266
+ }
267
+ .audit-before { background: var(--error-bg); border-left-color: var(--error); color: #991b1b; text-decoration: line-through; }
268
+ .audit-after { background: var(--success-bg); border-left-color: var(--success); color: #166534; }
269
+ .audit-warnings { list-style: none; padding: 0; margin: 0; }
270
+ .audit-warnings li {
271
+ padding: 10px 0 10px 18px; border-top: 1px solid var(--border-soft);
272
+ position: relative; color: var(--text-2); font-size: 13px;
273
+ }
274
+ .audit-warnings li:first-child { border-top: none; }
275
+ .audit-warnings li::before {
276
+ content: ''; position: absolute; left: 0; top: 17px; width: 5px; height: 5px;
277
+ border-radius: 50%; background: var(--warn); box-shadow: 0 0 0 3px rgba(202, 138, 4, 0.15);
278
+ }
279
+ .audit-warnings .rule-ref {
280
+ display: inline-block; font-family: var(--mono); font-size: 11px; font-weight: 500;
281
+ color: var(--text-muted); background: var(--bg); padding: 1px 6px;
282
+ border-radius: var(--radius-xs); margin-right: 6px;
283
+ }
284
+
285
+ /* Bandeau verdict + coût */
286
+ .meta-result {
287
+ display: flex; gap: 8px; flex-wrap: wrap; align-items: center;
288
+ margin: 0 0 12px;
289
+ }
290
+ .pill {
291
+ display: inline-flex; align-items: center; gap: 6px;
292
+ font-size: 12px; font-weight: 600; padding: 4px 12px; border-radius: 999px;
293
+ border: 1px solid;
294
+ }
295
+ .pill--ok { color: #166534; background: var(--success-bg); border-color: var(--success-border); }
296
+ .pill--ko { color: #991b1b; background: var(--error-bg); border-color: var(--error-border); }
297
+ .pill--info { color: var(--text-2); background: var(--bg); border-color: var(--border); font-weight: 500; font-family: var(--mono); font-size: 11.5px; }
298
+
299
+ .token.comment { color: #9ca3af; font-style: italic; }
300
+ .token.keyword, .token.boolean, .token.important { color: #9333ea; font-weight: 500; }
301
+ .token.string, .token.attr-value { color: #15803d; }
302
+ .token.function, .token.class-name { color: #1d4ed8; }
303
+ .token.number, .token.constant { color: #c2410c; }
304
+ .token.operator, .token.punctuation { color: #52525b; }
305
+ .token.title, .token.heading { font-weight: 600; color: var(--text); }
306
+
307
+ .footer {
308
+ margin-top: 40px; padding-top: 20px; border-top: 1px solid var(--border-soft);
309
+ text-align: center; font-size: 12px; color: var(--text-soft);
310
+ }
311
+ .footer code {
312
+ font-family: var(--mono); font-size: 11px; padding: 1px 6px;
313
+ background: var(--panel); border: 1px solid var(--border-soft);
314
+ border-radius: var(--radius-xs); color: var(--text-muted);
315
+ }
316
+ </style>
317
+ </head>
318
+ <body>
319
+
320
+ <div class="container">
321
+
322
+ <header class="header">
323
+ <div class="header-left">
324
+ <div class="header-mark">Py</div>
325
+ <div class="header-text">
326
+ <h1>Pythonise Exercice</h1>
327
+ <p>PyxiScience MyST → version pythonisée · validée au harnais</p>
328
+ </div>
329
+ </div>
330
+ <div class="header-status"><span class="dot"></span> service actif</div>
331
+ </header>
332
+
333
+ <div class="grid">
334
+
335
+ <!-- INPUT PANEL -->
336
+ <section class="panel">
337
+ <h2 class="panel-title">Source</h2>
338
+
339
+ <div class="field">
340
+ <textarea id="input" placeholder="Collez ici l'énoncé MyST à pythoniser… (ou chargez un/des fichiers .md ci-dessous)"></textarea>
341
+ </div>
342
+
343
+ <ul class="filelist" id="filelist" hidden></ul>
344
+
345
+ <div class="meta">
346
+ <div>
347
+ <label class="field-label" for="model-select">Modèle</label>
348
+ <select id="model-select" aria-label="Modèle LLM"></select>
349
+ </div>
350
+ <div>
351
+ <label class="field-label" for="lang-select">Langue cible</label>
352
+ <select id="lang-select">
353
+ <option value="fr">Français</option>
354
+ <option value="en">Anglais</option>
355
+ <option value="both">Les deux (bilingue)</option>
356
+ </select>
357
+ </div>
358
+ <div>
359
+ <label class="field-label" for="level">Niveau</label>
360
+ <select id="level">
361
+ <option value="">—</option>
362
+ <option value="Intermediate">Intermédiaire</option>
363
+ <option value="Advanced">Avancé</option>
364
+ </select>
365
+ </div>
366
+ <div class="meta-full">
367
+ <label class="field-label" for="filename">Nom du fichier <span style="opacity:0.6;font-weight:400">(si saisie manuelle)</span></label>
368
+ <input type="text" id="filename" value="exercise.md" placeholder="exercise.md">
369
+ </div>
370
+ </div>
371
+
372
+ <div class="actions">
373
+ <button class="btn btn--primary" id="run-btn" type="button" onclick="run()">Lancer la pythonisation</button>
374
+ <button class="btn" type="button" onclick="document.getElementById('file-input').click()">Charger des fichiers .md</button>
375
+ <input type="file" id="file-input" accept=".md,.txt,text/markdown,text/plain" multiple hidden onchange="loadFiles(event)">
376
+ <button class="btn btn--ghost" type="button" onclick="clearAll()">Effacer</button>
377
+ </div>
378
+
379
+ <div class="progress is-idle" id="progress">
380
+ <div class="progress-line">
381
+ <span class="progress-spinner"></span>
382
+ <span class="progress-label" id="step-label">En attente</span>
383
+ <span class="progress-step" id="step-counter">—</span>
384
+ </div>
385
+ <div class="progress-bar"><span class="progress-bar-fill"></span></div>
386
+ </div>
387
+
388
+ <div id="status" class="status" hidden></div>
389
+ </section>
390
+
391
+ <!-- OUTPUT PANEL -->
392
+ <section class="panel">
393
+ <h2 class="panel-title">Résultat</h2>
394
+
395
+ <div class="result-files" id="result-files" hidden></div>
396
+ <div class="meta-result" id="meta-result" hidden></div>
397
+
398
+ <nav class="tabs" id="tabs">
399
+ <button class="tab is-active" type="button" data-tab="exercice">Exercice</button>
400
+ <button class="tab" type="button" data-tab="audit">Audit<span class="tab-badge" id="audit-badge" hidden>0</span></button>
401
+ <button class="tab" type="button" data-tab="analysis">Analyse</button>
402
+ <button class="tab" type="button" data-tab="notions">Notions</button>
403
+ <span class="tab-spacer"></span>
404
+ <button class="btn btn--ghost btn--small" id="dl-btn" type="button" onclick="downloadActiveMd()" disabled>Télécharger .md</button>
405
+ <button class="btn btn--ghost btn--small" id="dlzip-btn" type="button" onclick="downloadZip()" hidden>Tout (.zip)</button>
406
+ <button class="btn btn--ghost btn--small" id="copy-btn" type="button" onclick="copyActive()" disabled>Copier</button>
407
+ </nav>
408
+
409
+ <div class="tab-panels">
410
+ <div class="tab-panel is-active" id="panel-exercice">
411
+ <pre class="output" id="output-exercice"><code class="empty language-markdown">L'exercice pythonisé apparaîtra ici.</code></pre>
412
+ </div>
413
+ <div class="tab-panel" id="panel-audit">
414
+ <div class="output output--audit" id="output-audit"><p class="empty">Aucun audit pour le moment.</p></div>
415
+ </div>
416
+ <div class="tab-panel" id="panel-analysis">
417
+ <pre class="output" id="output-analysis"><code class="empty language-json">{}</code></pre>
418
+ </div>
419
+ <div class="tab-panel" id="panel-notions">
420
+ <pre class="output" id="output-notions"><code class="empty">—</code></pre>
421
+ </div>
422
+ </div>
423
+ </section>
424
+
425
+ </div>
426
+
427
+ <footer class="footer">
428
+ <code>v2</code> · Pythonisation PyxiScience · porte harnais déterministe · OpenRouter
429
+ </footer>
430
+
431
+ </div>
432
+
433
+ <script src="https://unpkg.com/prismjs@1.29.0/components/prism-core.min.js"></script>
434
+ <script src="https://unpkg.com/prismjs@1.29.0/components/prism-markup.min.js"></script>
435
+ <script src="https://unpkg.com/prismjs@1.29.0/components/prism-python.min.js"></script>
436
+ <script src="https://unpkg.com/prismjs@1.29.0/components/prism-json.min.js"></script>
437
+ <script src="https://unpkg.com/prismjs@1.29.0/components/prism-markdown.min.js"></script>
438
+
439
+ <script>
440
+ 'use strict';
441
+
442
+ const POLL_MS = 1000;
443
+ let currentJobId = null;
444
+ let pollTimer = null;
445
+ let activeTab = "exercice";
446
+ let loadedFiles = []; // [{filename, content}]
447
+ let jobResults = []; // résultats par fichier
448
+ let activeResultIdx = 0;
449
+
450
+ document.addEventListener("DOMContentLoaded", () => { fetchModels(); bindTabs(); });
451
+
452
+ async function fetchModels() {
453
+ try {
454
+ const res = await fetch("/api/models");
455
+ if (!res.ok) return;
456
+ const { models, default_idx, default_lang } = await res.json();
457
+ const sel = document.getElementById("model-select");
458
+ sel.innerHTML = "";
459
+ for (const [idx, slug] of Object.entries(models).sort((a, b) => Number(a[0]) - Number(b[0]))) {
460
+ const opt = document.createElement("option");
461
+ opt.value = idx;
462
+ opt.textContent = prettyModelName(slug);
463
+ if (Number(idx) === default_idx) opt.selected = true;
464
+ sel.appendChild(opt);
465
+ }
466
+ if (default_lang) document.getElementById("lang-select").value = default_lang;
467
+ } catch (e) { console.warn("/api/models:", e); }
468
+ }
469
+
470
+ function prettyModelName(slug) {
471
+ const [, name = slug] = slug.split("/");
472
+ return name
473
+ .replace(/^claude-/, "Claude ").replace(/^gpt-/, "GPT-")
474
+ .replace(/^gemini-/, "Gemini ").replace(/-/g, " ")
475
+ .replace(/\b\w/g, c => c.toUpperCase()).replace(/Gpt/g, "GPT");
476
+ }
477
+
478
+ /* ─── Tabs ─── */
479
+ function bindTabs() {
480
+ document.querySelectorAll("#tabs .tab").forEach(btn => {
481
+ btn.addEventListener("click", () => switchTab(btn.dataset.tab));
482
+ });
483
+ }
484
+ function switchTab(name) {
485
+ activeTab = name;
486
+ document.querySelectorAll("#tabs .tab").forEach(btn =>
487
+ btn.classList.toggle("is-active", btn.dataset.tab === name));
488
+ document.querySelectorAll(".tab-panel").forEach(panel =>
489
+ panel.classList.toggle("is-active", panel.id === `panel-${name}`));
490
+ updateCopyState();
491
+ }
492
+ function activeDoneResult() {
493
+ const e = jobResults[activeResultIdx];
494
+ return (e && e.status === "done" && e.result) ? e : null;
495
+ }
496
+
497
+ function updateCopyState() {
498
+ // Copier (panneau actif)
499
+ const text = currentPanelText();
500
+ document.getElementById("copy-btn").disabled =
501
+ !text || !text.trim() || text.trim() === "—" || text.trim() === "{}";
502
+ // Télécharger .md (résultat affiché)
503
+ const r = activeDoneResult();
504
+ const dl = document.getElementById("dl-btn");
505
+ if (dl) dl.disabled = !(r && r.result.exercise);
506
+ // Tout (.zip) — seulement en batch (≥ 2 fichiers prêts)
507
+ const doneCount = jobResults.filter(x => x.status === "done").length;
508
+ const zip = document.getElementById("dlzip-btn");
509
+ if (zip) zip.hidden = !(doneCount >= 2 && currentJobId);
510
+ }
511
+
512
+ function triggerDownload(blob, filename) {
513
+ const url = URL.createObjectURL(blob);
514
+ const a = document.createElement("a");
515
+ a.href = url; a.download = filename;
516
+ document.body.appendChild(a); a.click(); a.remove();
517
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
518
+ }
519
+
520
+ function downloadActiveMd() {
521
+ const r = activeDoneResult();
522
+ if (!r || !r.result.exercise) return;
523
+ const base = (r.filename || "exercice").replace(/\.(md|txt)$/i, "");
524
+ triggerDownload(
525
+ new Blob([r.result.exercise], { type: "text/markdown;charset=utf-8" }),
526
+ base + "_pythonise.md"
527
+ );
528
+ }
529
+
530
+ function downloadZip() {
531
+ if (!currentJobId) return;
532
+ const a = document.createElement("a");
533
+ a.href = `/api/jobs/${currentJobId}/download`;
534
+ a.download = ""; // nom fixé par le serveur (Content-Disposition)
535
+ document.body.appendChild(a); a.click(); a.remove();
536
+ }
537
+ function currentPanelText() {
538
+ const map = { exercice: "output-exercice", audit: "output-audit",
539
+ analysis: "output-analysis", notions: "output-notions" };
540
+ const el = document.getElementById(map[activeTab]);
541
+ if (!el) return "";
542
+ if (activeTab === "audit") return el.innerText || "";
543
+ const code = el.querySelector("code");
544
+ return code ? code.textContent : (el.textContent || "");
545
+ }
546
+
547
+ /* ─── Progress + status ─── */
548
+ function setProgress(state, label, step) {
549
+ const prog = document.getElementById("progress");
550
+ prog.classList.remove("is-idle", "is-running", "is-done", "is-error");
551
+ prog.classList.add(`is-${state}`);
552
+ if (label !== undefined) document.getElementById("step-label").textContent = label;
553
+ if (step !== undefined) document.getElementById("step-counter").textContent = step;
554
+ }
555
+ function setStatus(state, text) {
556
+ const el = document.getElementById("status");
557
+ el.className = "status" + (state ? ` is-${state}` : "");
558
+ el.textContent = text;
559
+ el.hidden = false;
560
+ }
561
+ function hideStatus() { document.getElementById("status").hidden = true; }
562
+
563
+ /* ─── Fichiers (batch) ─── */
564
+ function loadFiles(event) {
565
+ const files = Array.from(event.target.files || []);
566
+ if (!files.length) return;
567
+ let pending = files.length;
568
+ files.forEach(file => {
569
+ const reader = new FileReader();
570
+ reader.onload = (e) => {
571
+ loadedFiles.push({ filename: file.name, content: String(e.target.result || "") });
572
+ if (--pending === 0) renderFileList();
573
+ };
574
+ reader.onerror = () => { if (--pending === 0) renderFileList(); };
575
+ reader.readAsText(file, "UTF-8");
576
+ });
577
+ event.target.value = "";
578
+ }
579
+ function renderFileList() {
580
+ const ul = document.getElementById("filelist");
581
+ ul.innerHTML = "";
582
+ ul.hidden = loadedFiles.length === 0;
583
+ loadedFiles.forEach((f, i) => {
584
+ const li = document.createElement("li");
585
+ li.innerHTML = `📄 ${escapeHtml(f.filename)} <span style="color:var(--text-soft)">(${(f.content.length / 1024).toFixed(1)} ko)</span>
586
+ <button class="rm" title="Retirer" onclick="removeFile(${i})">✕</button>`;
587
+ ul.appendChild(li);
588
+ });
589
+ }
590
+ function removeFile(i) { loadedFiles.splice(i, 1); renderFileList(); }
591
+
592
+ /* ─── Rendu des sorties ─── */
593
+ function setExerciseOutput(text) {
594
+ const pre = document.getElementById("output-exercice");
595
+ pre.innerHTML = "";
596
+ const code = document.createElement("code");
597
+ code.className = "language-markdown";
598
+ if (!text) { code.classList.add("empty"); code.textContent = "L'exercice pythonisé apparaîtra ici."; }
599
+ else { code.textContent = text; if (window.Prism) Prism.highlightElement(code); }
600
+ pre.appendChild(code);
601
+ updateCopyState();
602
+ }
603
+ function setAnalysisOutput(obj) {
604
+ const pre = document.getElementById("output-analysis");
605
+ pre.innerHTML = "";
606
+ const code = document.createElement("code");
607
+ code.className = "language-json";
608
+ if (!obj) { code.classList.add("empty"); code.textContent = "{}"; }
609
+ else { code.textContent = JSON.stringify(obj, null, 2); if (window.Prism) Prism.highlightElement(code); }
610
+ pre.appendChild(code);
611
+ }
612
+ function setNotionsOutput(text) {
613
+ const pre = document.getElementById("output-notions");
614
+ pre.innerHTML = "";
615
+ const code = document.createElement("code");
616
+ if (!text || text === "—") { code.classList.add("empty"); code.textContent = "—"; }
617
+ else { code.textContent = text; }
618
+ pre.appendChild(code);
619
+ }
620
+ function setAuditOutput(result) {
621
+ const container = document.getElementById("output-audit");
622
+ const patches = result.audit_patches || [];
623
+ const warnings = result.warnings || [];
624
+ const badge = document.getElementById("audit-badge");
625
+ if (!patches.length && !warnings.length) {
626
+ container.innerHTML = `<p class="empty">Aucun patch ni warning — l'audit a validé l'exercice.</p>`;
627
+ badge.hidden = true;
628
+ return;
629
+ }
630
+ badge.hidden = false;
631
+ badge.textContent = String(patches.length + warnings.length);
632
+ let html = "";
633
+ if (patches.length) {
634
+ html += `<section class="audit-section"><h3 class="audit-heading">Patches appliqués <span class="count">${patches.length}</span></h3><ul class="audit-list">`;
635
+ for (const p of patches) {
636
+ html += `<li class="audit-patch">
637
+ <span class="audit-rule">règle ${escapeHtml(p.rule || "?")}</span>
638
+ <div class="audit-diff">
639
+ <pre class="audit-before"><code>${escapeHtml(p.location || "")}</code></pre>
640
+ <pre class="audit-after"><code>${escapeHtml(p.fix || "")}</code></pre>
641
+ </div></li>`;
642
+ }
643
+ html += `</ul></section>`;
644
+ }
645
+ if (warnings.length) {
646
+ html += `<section class="audit-section"><h3 class="audit-heading">Warnings <span class="count">${warnings.length}</span></h3><ul class="audit-warnings">`;
647
+ for (const w of warnings) {
648
+ let ruleRef = "", txt = w;
649
+ if (typeof w === "object" && w !== null) {
650
+ if (w.rule) ruleRef = `<span class="rule-ref">règle ${escapeHtml(w.rule)}</span>`;
651
+ txt = w.message || JSON.stringify(w);
652
+ }
653
+ html += `<li>${ruleRef}${escapeHtml(String(txt))}</li>`;
654
+ }
655
+ html += `</ul></section>`;
656
+ }
657
+ container.innerHTML = html;
658
+ }
659
+
660
+ /* Bandeau verdict + coût + langue pour le fichier affiché */
661
+ function setMetaResult(entry) {
662
+ const el = document.getElementById("meta-result");
663
+ if (!entry) { el.hidden = true; return; }
664
+ el.hidden = false;
665
+ if (entry.status === "error") {
666
+ el.innerHTML = `<span class="pill pill--ko">✗ Erreur pipeline</span>
667
+ <span class="pill pill--info">${escapeHtml(entry.error || "")}</span>`;
668
+ return;
669
+ }
670
+ const r = entry.result;
671
+ const h = r.harness || {};
672
+ const verdict = h.ok
673
+ ? `<span class="pill pill--ok">✓ Harnais VERT (${h.seeds} graines)</span>`
674
+ : `<span class="pill pill--ko">✗ Harnais ROUGE (${h.seeds} graines)</span>`;
675
+ const cost = r.cost ? `<span class="pill pill--info">${r.cost.usd.toFixed(4)} $ · ${r.cost.requests} appels</span>` : "";
676
+ const lang = r.lang ? `<span class="pill pill--info">langue : ${escapeHtml(r.lang.source)} → ${escapeHtml(r.lang.target)} (${escapeHtml(r.lang.action)})</span>` : "";
677
+ const dur = r.duration_s ? `<span class="pill pill--info">${r.duration_s}s</span>` : "";
678
+ el.innerHTML = verdict + cost + lang + dur;
679
+ }
680
+
681
+ /* Sélecteur de fichier (batch) */
682
+ function renderResultFiles() {
683
+ const el = document.getElementById("result-files");
684
+ if (jobResults.length <= 1) { el.hidden = true; return; }
685
+ el.hidden = false;
686
+ el.innerHTML = "";
687
+ jobResults.forEach((r, i) => {
688
+ const cls = r.status === "error" ? "err" : (r.result?.harness?.ok ? "ok" : "ko");
689
+ const span = document.createElement("span");
690
+ span.className = "result-file" + (i === activeResultIdx ? " is-active" : "");
691
+ span.innerHTML = `<span class="verdict-dot ${cls}"></span>${escapeHtml(r.filename)}`;
692
+ span.onclick = () => { activeResultIdx = i; showResult(i); renderResultFiles(); };
693
+ el.appendChild(span);
694
+ });
695
+ }
696
+ function showResult(i) {
697
+ const entry = jobResults[i];
698
+ if (!entry) return;
699
+ setMetaResult(entry);
700
+ if (entry.status === "error") {
701
+ setExerciseOutput(""); setAnalysisOutput(null); setNotionsOutput(""); setAuditOutput({});
702
+ return;
703
+ }
704
+ const r = entry.result;
705
+ setExerciseOutput(r.exercise || "");
706
+ setAnalysisOutput(r.analysis || null);
707
+ setNotionsOutput(r.notions || "—");
708
+ setAuditOutput(r);
709
+ }
710
+
711
+ /* ─── Run + poll ─── */
712
+ async function run() {
713
+ let files = loadedFiles.slice();
714
+ const manual = document.getElementById("input").value.trim();
715
+ if (!files.length && manual) {
716
+ files = [{ filename: document.getElementById("filename").value.trim() || "exercise.md",
717
+ content: manual }];
718
+ }
719
+ if (!files.length) { setStatus("error", "Saisissez un énoncé ou chargez des fichiers .md."); return; }
720
+
721
+ const payload = {
722
+ files,
723
+ level: document.getElementById("level").value,
724
+ lang: document.getElementById("lang-select").value,
725
+ model_idx: Number(document.getElementById("model-select").value || 0),
726
+ };
727
+
728
+ if (pollTimer) { clearTimeout(pollTimer); pollTimer = null; }
729
+ currentJobId = null;
730
+ jobResults = []; activeResultIdx = 0;
731
+ document.getElementById("run-btn").disabled = true;
732
+ hideStatus();
733
+ setExerciseOutput(""); setAnalysisOutput(null); setNotionsOutput(""); setAuditOutput({});
734
+ setMetaResult(null);
735
+ document.getElementById("result-files").hidden = true;
736
+ document.getElementById("audit-badge").hidden = true;
737
+ switchTab("exercice");
738
+ setProgress("running", "Soumission du job…", "0/" + files.length);
739
+
740
+ try {
741
+ const res = await fetch("/api/jobs", {
742
+ method: "POST",
743
+ headers: { "Content-Type": "application/json" },
744
+ body: JSON.stringify(payload),
745
+ });
746
+ if (!res.ok) {
747
+ const err = await res.json().catch(() => ({ error: res.statusText }));
748
+ throw new Error(err.error || `HTTP ${res.status}`);
749
+ }
750
+ currentJobId = (await res.json()).job_id;
751
+ poll();
752
+ } catch (e) {
753
+ setProgress("error", "Échec", "—");
754
+ setStatus("error", "Erreur : " + e.message);
755
+ document.getElementById("run-btn").disabled = false;
756
+ }
757
+ }
758
+
759
+ async function poll() {
760
+ if (!currentJobId) return;
761
+ try {
762
+ const res = await fetch(`/api/jobs/${currentJobId}`);
763
+ const data = await res.json();
764
+ jobResults = data.results || [];
765
+ if (data.status === "running") {
766
+ setProgress("running", data.step_label || "…", `${data.files_done}/${data.files_total}`);
767
+ // Affiche au fil de l'eau le dernier fichier terminé.
768
+ if (jobResults.length && activeResultIdx < jobResults.length) {
769
+ renderResultFiles(); showResult(Math.min(activeResultIdx, jobResults.length - 1));
770
+ }
771
+ pollTimer = setTimeout(poll, POLL_MS);
772
+ } else if (data.status === "done") {
773
+ const s = data.summary || {};
774
+ setProgress(s.rouges || s.erreurs ? "error" : "done", "Terminé", `${data.files_done}/${data.files_total}`);
775
+ const msg = `Terminé : ${s.verts ?? 0} VERT(S), ${s.rouges ?? 0} ROUGE(S), ${s.erreurs ?? 0} erreur(s) · ${s.cost_usd ?? 0} $`;
776
+ setStatus(s.rouges || s.erreurs ? "warn" : "done", msg);
777
+ activeResultIdx = 0;
778
+ renderResultFiles();
779
+ showResult(0);
780
+ document.getElementById("run-btn").disabled = false;
781
+ } else if (data.status === "error") {
782
+ setProgress("error", "Erreur", "—");
783
+ setStatus("error", "Erreur : " + (data.error || "inconnue"));
784
+ document.getElementById("run-btn").disabled = false;
785
+ }
786
+ } catch (e) {
787
+ setProgress("error", "Erreur de polling", "—");
788
+ setStatus("error", "Erreur de polling : " + e.message);
789
+ document.getElementById("run-btn").disabled = false;
790
+ }
791
+ }
792
+
793
+ function clearAll() {
794
+ if (pollTimer) clearTimeout(pollTimer);
795
+ currentJobId = null;
796
+ loadedFiles = []; jobResults = []; activeResultIdx = 0;
797
+ renderFileList();
798
+ document.getElementById("input").value = "";
799
+ setExerciseOutput(""); setAnalysisOutput(null); setNotionsOutput(""); setAuditOutput({});
800
+ setMetaResult(null);
801
+ document.getElementById("result-files").hidden = true;
802
+ document.getElementById("audit-badge").hidden = true;
803
+ setProgress("idle", "En attente", "—");
804
+ hideStatus();
805
+ document.getElementById("run-btn").disabled = false;
806
+ }
807
+
808
+ function copyActive() {
809
+ const text = currentPanelText();
810
+ if (!text) return;
811
+ navigator.clipboard.writeText(text).then(() => {
812
+ const btn = document.getElementById("copy-btn");
813
+ const old = btn.textContent;
814
+ btn.textContent = "Copié";
815
+ setTimeout(() => { btn.textContent = old; }, 1400);
816
+ });
817
+ }
818
+
819
+ function escapeHtml(s) {
820
+ return String(s)
821
+ .replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")
822
+ .replace(/"/g, "&quot;").replace(/'/g, "&#039;");
823
+ }
824
+ </script>
825
+
826
+ </body>
827
+ </html>
data/notions.xlsx ADDED
Binary file (74.6 kB). View file
 
requirements-deploy.txt ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Dépendances de DÉPLOIEMENT (slim) — pour Hugging Face Spaces / conteneur.
2
+ # Différence avec requirements.txt : on retire torch / sentence-transformers /
3
+ # langchain-huggingface (≈ 1 Go, inutiles avec l'embedding par défaut
4
+ # openai-3-small qui passe par l'API). On ajoute gunicorn (serveur WSGI).
5
+ flask>=3.0,<4.0
6
+ gunicorn>=21.0
7
+ python-dotenv>=1.0
8
+ requests>=2.31
9
+ openai>=1.40
10
+ langchain-core>=0.3
11
+ langchain-community>=0.3
12
+ langchain-openai>=0.2
13
+ faiss-cpu>=1.8
14
+ pandas>=2.0
15
+ openpyxl>=3.1
16
+ sympy>=1.12
17
+ numpy>=1.26
18
+ matplotlib>=3.8