commit 03d9922066b2d10d299e8a0cab637dc6aeb95249 Author: bolbol Date: Tue Nov 10 00:10:05 2026 +0000 feat(series-studio): initial implementation of unified series studio engine (PDF & DOCX) diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..21d3ffe --- /dev/null +++ b/.dockerignore @@ -0,0 +1,9 @@ +__pycache__ +*.pyc +.git +.pytest_cache +jobs +data +ref +exemples +*.log diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d595422 --- /dev/null +++ b/.gitignore @@ -0,0 +1,12 @@ +__pycache__/ +*.pyc +*.pyo +*.pyd +.pytest_cache/ +jobs/ +data/ +ref/ +typst +typst-linux +*.log +.DS_Store diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..756d3f4 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,43 @@ +FROM python:3.11-slim + +# Dépendances système et polices +RUN apt-get update && apt-get install -y --no-install-recommends \ + curl \ + ca-certificates \ + xz-utils \ + libfontconfig1 \ + fonts-dejavu \ + fonts-freefont-ttf \ + && rm -rf /var/lib/apt/lists/* + +# Typst 0.15.1 officiel +RUN curl -sSL https://github.com/typst/typst/releases/download/v0.15.1/typst-x86_64-unknown-linux-musl.tar.xz | tar -xJ -C /tmp \ + && mv /tmp/typst-x86_64-unknown-linux-musl/typst /usr/local/bin/typst \ + && chmod +x /usr/local/bin/typst \ + && rm -rf /tmp/typst* \ + && typst --version + +# Création de l'utilisateur non-root 1005:1005 +RUN groupadd -g 1005 gemini2-ops && useradd -u 1005 -g 1005 -m -s /bin/bash gemini2-ops + +WORKDIR /app + +# Dépendances Python +COPY requirements.txt /app/ +RUN pip install --no-cache-dir -r requirements.txt + +# Code source applicatif +COPY . /app/ + +# Préparation des dossiers montés +RUN mkdir -p /app/jobs /app/data /app/ref /app/exemples \ + && chown -R 1005:1005 /app + +USER 1005:1005 + +EXPOSE 8000 + +HEALTHCHECK --interval=10s --timeout=5s --retries=3 \ + CMD python3 -c 'import urllib.request; urllib.request.urlopen("http://127.0.0.1:8000/themes")' || exit 1 + +CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"] diff --git a/README.md b/README.md new file mode 100644 index 0000000..09122a5 --- /dev/null +++ b/README.md @@ -0,0 +1,26 @@ +# Series Studio + +Moteur de rendu unifié pour séries d'exercices mathématiques (PDF Typst et Word DOCX natif OMML) à partir d'une description JSON unique. + +## Fonctionnalités + +- **Source unique** : Document JSON versionné (`schema_version: "1.0.0"`). +- **Double rendu déterministe** : + - PDF via Typst (2 pages calibrées, polices mathématiques New Computer Modern). + - DOCX via `python-docx` avec 100 % d'équations natives OMML (MathML via `mml2omml.xsl`). +- **Thèmes interchangeables** : + - `classique` : charte officielle du portail Heykel ZAYANI. + - `sobre` : rendu clair et minimaliste. +- **Figures déclaratives** : tracés géométriques et courbes en matplotlib 300 dpi. +- **Contrôles bloquants automatiques** : + - Vérification de la cible de pages. + - Contrôle d'absence de `$` brut dans le XML Word. + - Auteur officiel dans les propriétés du fichier. + - Compilation Typst sans avertissement. +- **API HTTP interne** : + - `GET /themes` + - `POST /validate` + - `POST /render` + - `GET /jobs//pdf` + - `GET /jobs//docx` + - `POST /jobs//rerender` diff --git a/exemples/serie06.json b/exemples/serie06.json new file mode 100644 index 0000000..104a133 --- /dev/null +++ b/exemples/serie06.json @@ -0,0 +1,345 @@ +{ + "schema_version": "1.0.0", + "pages_cibles": 2, + "theme": "classique", + "cartouche": { + "titre": "COMPLEXES", + "sous_titre": "Bac 2023, 2024 et 2025", + "type_doc": "SÉRIE D'EXERCICES", + "discipline": "Mathématiques", + "classe": "4ème Sciences Techniques", + "enseignant": "Heykel ZAYANI", + "titre_enseignant": "P.P.É.C.E.", + "annee": "2026 / 2027", + "lycee": "Lycée Pilote" + }, + "exercices": [ + { + "numero": "1", + "titre": "Bac 2023 — Équations dans C & Configuration géométrique du losange", + "points": "5 points", + "breakable_box": false, + "elements": [ + { + "type": "question", + "indent_level": 0, + "space_before": 4, + "space_after": 2, + "text": "1) Dans l'ensemble $\\mathbb{C}$ des nombres complexes, on considère l'équation :", + "text_typst": "*1)* Dans l'ensemble $bb(C)$ des nombres complexes, on considère l'équation :" + }, + { + "type": "display_equation", + "latex": "(E) : z^2 - 2(1+i)z - 4i = 0", + "typst": "(E) : z^2 - 2(1+i)z - 4i = 0", + "space_before": 2, + "space_after": 3 + }, + { + "type": "question", + "indent_level": 1, + "text": "a) Montrer que l'équation $(E)$ est équivalente à : $\\left[ z - (1+i) \\right]^2 = \\left[ \\sqrt{3}(1+i) \\right]^2$.", + "text_typst": "*a)* Montrer que l'équation $(E)$ est équivalente à : $ [z - (1+i)]^2 = [sqrt(3)(1+i)]^2 $" + }, + { + "type": "question", + "indent_level": 1, + "text": "b) En déduire les solutions de l'équation $(E)$.", + "text_typst": "*b)* En déduire les solutions de l'équation $(E)$." + }, + { + "type": "question", + "indent_level": 0, + "space_before": 3, + "space_after": 2, + "text": "2) Soit dans l'ensemble $\\mathbb{C}$ des nombres complexes, l'équation :", + "text_typst": "*2)* Soit dans l'ensemble $bb(C)$ des nombres complexes, l'équation :" + }, + { + "type": "display_equation", + "latex": "(E') : z^3 - (2+4i)z^2 - 4z - 8 = 0", + "typst": "(E') : z^3 - (2+4i)z^2 - 4z - 8 = 0", + "space_before": 2, + "space_after": 3 + }, + { + "type": "question", + "indent_level": 1, + "text": "a) Vérifier que $2i$ est une solution de l'équation $(E')$.", + "text_typst": "*a)* Vérifier que $2i$ est une solution de l'équation $(E')$." + }, + { + "type": "question", + "indent_level": 1, + "text": "b) Vérifier que pour tout nombre complexe $z$ : $z^3 - (2+4i)z^2 - 4z - 8 = (z - 2i)\\left[ z^2 - 2(1+i)z - 4i \\right]$.", + "text_typst": "*b)* Vérifier que pour tout nombre complexe $z$ : $ z^3 - (2+4i)z^2 - 4z - 8 = (z - 2i)[z^2 - 2(1+i)z - 4i] $" + }, + { + "type": "question", + "indent_level": 1, + "text": "c) Résoudre alors l'équation $(E')$.", + "text_typst": "*c)* Résoudre alors l'équation $(E')$." + }, + { + "type": "question", + "indent_level": 0, + "space_before": 3, + "space_after": 2, + "text": "3) Dans le plan complexe rapporté à un repère orthonormé direct $(O, \\vec{u}, \\vec{v})$, on donne les points $A, B, C$ et $D$ d'affixes respectives :", + "text_typst": "*3)* Dans le plan complexe rapporté à un repère orthonormé direct $(O, arrow(u), arrow(v))$, on donne les points $A, B, C$ et $D$ d'affixes respectives :" + }, + { + "type": "display_equation", + "latex": "z_A = 2i, \\quad z_B = (1+\\sqrt{3})(1+i), \\quad z_C = (1-\\sqrt{3})(1+i) \\quad \\text{et} \\quad z_D = 2", + "typst": "z_A = 2i, quad z_B = (1+sqrt(3))(1+i), quad z_C = (1-sqrt(3))(1+i) quad \"et\" quad z_D = 2", + "space_before": 2, + "space_after": 3 + }, + { + "type": "question", + "indent_level": 1, + "text": "a) Vérifier que $AB = AC = AD = 2\\sqrt{2}$. En déduire que les points $B, C$ et $D$ appartiennent à un même cercle $(\\mathcal{C})$ dont on précisera le centre et le rayon.", + "text_typst": "*a)* Vérifier que $A B = A C = A D = 2 sqrt(2)$. En déduire que les points $B, C$ et $D$ appartiennent à un même cercle $(cal(C))$ dont on précisera le centre et le rayon." + }, + { + "type": "question", + "indent_level": 1, + "text": "b) Placer les points $A$ et $D$, puis construire le cercle $(\\mathcal{C})$.", + "text_typst": "*b)* Placer les points $A$ et $D$, puis construire le cercle $(cal(C))$." + }, + { + "type": "question", + "indent_level": 1, + "text": "c) Montrer que $\\arg(z_B) \\equiv \\frac{\\pi}{4} [2\\pi]$ et que $\\arg(z_C) \\equiv \\frac{5\\pi}{4} [2\\pi]$.", + "text_docx": "c) Montrer que $\\arg(z_B) = \\frac{\\pi}{4} + 2k\\pi$ et que $\\arg(z_C) = \\frac{5\\pi}{4} + 2k\\pi$, avec $k \\in \\mathbb{Z}$.", + "text_typst": "*c)* Montrer que $arg(z_B) equiv pi/4 [2pi]$ et que $arg(z_C) equiv (5pi)/4 [2pi]$." + }, + { + "type": "question", + "indent_level": 1, + "text": "d) Construire alors les points $B$ et $C$.", + "text_typst": "*d)* Construire alors les points $B$ et $C$." + }, + { + "type": "question", + "indent_level": 0, + "space_before": 3, + "space_after": 4, + "text": "4) Montrer que le quadrilatère $ABDC$ est un losange. Montrer que son aire est égale à $4\\sqrt{3}$.", + "text_typst": "*4)* Montrer que le quadrilatère $A B D C$ est un losange. Montrer que son aire est égale à $4 sqrt(3)$." + } + ] + }, + { + "numero": "2", + "titre": "Bac 2024 — Forme exponentielle, orthogonalité & Construction géométrique", + "points": "4 points", + "breakable_box": false, + "elements": [ + { + "type": "question", + "indent_level": 0, + "space_before": 4, + "space_after": 2, + "text": "1) On considère dans $\\mathbb{C}$ l'équation :", + "text_typst": "*1)* On considère dans $bb(C)$ l'équation :" + }, + { + "type": "display_equation", + "latex": "(E) : e^{i\\frac{\\pi}{4}} z^2 - \\left( i + e^{i\\frac{\\pi}{4}} \\right) z + i = 0", + "typst": "(E) : e^(i pi/4) z^2 - (i + e^(i pi/4)) z + i = 0", + "space_before": 2, + "space_after": 3 + }, + { + "type": "question", + "indent_level": 1, + "text": "a) Vérifier que $1$ est une solution de l'équation $(E)$.", + "text_typst": "*a)* Vérifier que $1$ est une solution de l'équation $(E)$." + }, + { + "type": "question", + "indent_level": 1, + "text": "b) En déduire l'autre solution de $(E)$ et la mettre sous forme exponentielle.", + "text_docx": "b) En déduire l'autre solution de l'équation $(E)$ et la mettre sous forme exponentielle.", + "text_typst": "*b)* En déduire l'autre solution de $(E)$ et la mettre sous forme exponentielle." + }, + { + "type": "question", + "indent_level": 0, + "space_before": 3, + "space_after": 2, + "text": "2) Dans le plan complexe muni d'un repère orthonormé direct $(O, \\vec{u}, \\vec{v})$, on considère les points $A, B$ et $C$ d'affixes respectives $z_A = 1$, $z_B = e^{i\\frac{\\pi}{4}}$ et $z_C = 2 e^{i\\frac{\\pi}{4}} - i$.", + "text_typst": "*2)* Dans le plan complexe muni d'un repère orthonormé direct $(O, arrow(u), arrow(v))$, on considère les points $A, B$ et $C$ d'affixes respectives $z_A = 1$, $z_B = e^(i pi/4)$ et $z_C = 2 e^(i pi/4) - i$." + }, + { + "type": "question", + "indent_level": 1, + "text": "a) Écrire $1 + i$ sous forme exponentielle.", + "text_typst": "*a)* Écrire $1 + i$ sous forme exponentielle." + }, + { + "type": "question", + "indent_level": 1, + "text": "b) Vérifier que $z_C - z_A = (2 - \\sqrt{2}) z_B$. En déduire que les droites $(AC)$ et $(OB)$ sont parallèles.", + "text_typst": "*b)* Vérifier que $z_C - z_A = (2 - sqrt(2)) z_B$. En déduire que les droites $(A C)$ et $(O B)$ sont parallèles." + }, + { + "type": "question", + "indent_level": 1, + "space_before": 2, + "text": "3) a) Montrer que $i (z_B - z_C) = \\overline{z_B - z_A}$.", + "text_typst": "*3)* #pad(left: 10pt)[\n *a)* Montrer que $i (z_B - z_C) = overline(z_B - z_A)$." + }, + { + "type": "question", + "indent_level": 1, + "text": "b) En déduire que le triangle $ABC$ est isocèle en $B$.", + "text_typst": "*b)* En déduire que le triangle $A B C$ est isocèle en $B$.\n ]" + }, + { + "type": "question", + "indent_level": 0, + "space_before": 3, + "space_after": 2, + "text": "4) Dans la Figure 1 de l'annexe ci-jointe, on a placé le point $A$ et on a construit le cercle $\\zeta$ de centre $O$ et de rayon $1$.", + "text_typst": "*4)* Dans la *Figure 1* de l'annexe ci-jointe, on a placé le point $A$ et on a construit le cercle $zeta$ de centre $O$ et de rayon $1$." + }, + { + "type": "question", + "indent_level": 1, + "text": "a) Vérifier que le point $B$ appartient au cercle $\\zeta$. Construire le point $B$.", + "text_typst": "*a)* Vérifier que le point $B$ appartient au cercle $zeta$. Construire le point $B$." + }, + { + "type": "question", + "indent_level": 1, + "text": "b) Soit $T$ la tangente à $\\zeta$ en $B$. Montrer que $T$ est la médiatrice du segment $[AC]$.", + "text_typst": "*b)* Soit $T$ la tangente à $zeta$ en $B$. Montrer que $T$ est la médiatrice du segment $[A C]$." + }, + { + "type": "question", + "indent_level": 1, + "text": "c) Construire alors sur la Figure 1 le point $C$.", + "text_typst": "*c)* Construire alors sur la *Figure 1* le point $C$." + }, + { + "type": "page_break" + } + ] + }, + { + "numero": "3", + "titre": "Bac 2025 — Équations trigonométriques, parallélogramme & Optimisation d'aire", + "points": "4.5 points", + "breakable_box": false, + "elements": [ + { + "type": "part_header", + "bold_prefix": "I°) ", + "space_before": 3, + "space_after": 2, + "text": "Résoudre dans l'ensemble $\\mathbb{C}$ des nombres complexes l'équation :", + "text_typst": "Résoudre dans l'ensemble $bb(C)$ des nombres complexes l'équation :" + }, + { + "type": "display_equation", + "latex": "(E) : z^2 - \\sqrt{2}(2+i)z + 2(1+i) = 0", + "typst": "(E) : z^2 - sqrt(2)(2+i)z + 2(1+i) = 0", + "space_before": 2, + "space_after": 3 + }, + { + "type": "part_header", + "bold_prefix": "II°) ", + "space_before": 3, + "space_after": 2, + "text": "Soit $\\theta$ un nombre réel de l'intervalle $\\left] 0, \\frac{\\pi}{2} \\right[$.", + "text_typst": "Soit $theta$ un réel de l'intervalle $]0, pi/2[$." + }, + { + "type": "question", + "indent_level": 0, + "space_before": 2, + "text": "1) On considère dans $\\mathbb{C}$ l'équation $(E_\\theta) : z^2 - (3e^{i\\theta} + e^{-i\\theta})z + 2(1 + e^{2i\\theta}) = 0$.", + "text_typst": "*1)* On considère dans $bb(C)$ l'équation $(E_theta) : z^2 - (3 e^(i theta) + e^(-i theta)) z + 2(1 + e^(2 i theta)) = 0$." + }, + { + "type": "question", + "indent_level": 1, + "text": "a) Vérifier que $2e^{i\\theta}$ est une solution de l'équation $(E_\\theta)$.", + "text_typst": "*a)* Vérifier que $2 e^(i theta)$ est une solution de l'équation $(E_theta)$." + }, + { + "type": "question", + "indent_level": 1, + "text": "b) En déduire l'autre solution de l'équation $(E_\\theta)$.", + "text_typst": "*b)* En déduire l'autre solution de l'équation $(E_theta)$." + }, + { + "type": "question", + "indent_level": 0, + "space_before": 3, + "text": "2) Le plan complexe est muni d'un repère orthonormé direct $(O, \\vec{u}, \\vec{v})$. On donne les points $A, B$ et $C$ d'affixes respectives :", + "text_typst": "*2)* Le plan complexe est muni d'un repère orthonormé direct $(O, arrow(u), arrow(v))$. On donne les points $A, B$ et $C$ d'affixes respectives :" + }, + { + "type": "display_equation", + "latex": "z_A = e^{i\\theta} + e^{-i\\theta}, \\quad z_B = 3e^{i\\theta} + e^{-i\\theta} \\quad \\text{et} \\quad z_C = 2e^{i\\theta}", + "typst": "z_A = e^(i theta) + e^(-i theta), quad z_B = 3 e^(i theta) + e^(-i theta) quad \"et\" quad z_C = 2 e^(i theta)", + "space_before": 2, + "space_after": 3 + }, + { + "type": "question", + "indent_level": 0, + "space_before": 1, + "space_after": 2, + "text": "Dans l'annexe ci-jointe (Figure 1), on a placé le point $C$.", + "text_typst": "Dans l'annexe ci-jointe (*Figure 1*), on a placé le point $C$." + }, + { + "type": "question", + "indent_level": 1, + "text": "a) Vérifier que $z_A = \\text{Re}(z_C)$. Placer alors le point $A$ dans la Figure 1.", + "text_typst": "*a)* Vérifier que $z_A = \"Re\"(z_C)$. Placer alors le point $A$ dans la *Figure 1*." + }, + { + "type": "question", + "indent_level": 1, + "text": "b) Montrer que $OABC$ est un parallélogramme, puis construire dans la Figure 1 le point $B$.", + "text_typst": "*b)* Montrer que $O A B C$ est un parallélogramme, puis construire dans la *Figure 1* le point $B$." + }, + { + "type": "question", + "indent_level": 1, + "text": "c) On désigne par $\\mathcal{A}$ l'aire du parallélogramme $OABC$. Montrer que $\\mathcal{A} = 2\\sin(2\\theta)$.", + "text_typst": "*c)* On désigne par $cal(A)$ l'aire du parallélogramme $O A B C$. Montrer que $cal(A) = 2 sin(2 theta)$." + }, + { + "type": "question", + "indent_level": 1, + "text": "d) Déterminer la valeur de $\\theta$ pour laquelle l'aire $\\mathcal{A}$ est maximale. Préciser la valeur de cette aire maximale.", + "text_typst": "*d)* Déterminer la valeur de $theta$ pour laquelle l'aire $cal(A)$ est maximale. Préciser la valeur de cette aire maximale." + } + ] + } + ], + "annexe": { + "titre": "ANNEXE À RENDRE AVEC LA COPIE — FIGURES OFFICIELLES", + "colonnes": [ + { + "titre": "Exercice 2 — Bac 2024", + "image": "fig_bac2024_annexe.png", + "width_typst": "88%", + "width_docx_inches": 3.2 + }, + { + "titre": "Exercice 3 — Bac 2025", + "image": "fig_bac2025_annexe.png", + "width_typst": "92%", + "width_docx_inches": 3.3 + } + ] + } +} diff --git a/figures.py b/figures.py new file mode 100644 index 0000000..d73f023 --- /dev/null +++ b/figures.py @@ -0,0 +1,171 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +figures.py +Génération déclarative de figures géométriques et tracés mathématiques en matplotlib 300 dpi, +ou résolution d'images existantes. +""" + +import os +import shutil +import numpy as np +import matplotlib +matplotlib.use('Agg') +import matplotlib.pyplot as plt +import matplotlib.patches as patches + +plt.rcParams['font.family'] = 'DejaVu Sans' +plt.rcParams['mathtext.fontset'] = 'cm' + +def render_declarative_figure(spec: dict, output_path: str): + """Génère une figure matplotlib 300 dpi à partir d'une description déclarative JSON.""" + figsize = tuple(spec.get("figsize", [5.0, 4.5])) + fig, ax = plt.subplots(figsize=figsize, dpi=300) + + xlim = spec.get("xlim", [-2.0, 4.0]) + ylim = spec.get("ylim", [-2.0, 4.0]) + ax.set_xlim(xlim[0], xlim[1]) + ax.set_ylim(ylim[0], ylim[1]) + + if spec.get("aspect") == "equal": + ax.set_aspect('equal') + + # Masquer spines + for spine in ax.spines.values(): + spine.set_visible(False) + ax.tick_params(left=False, bottom=False, labelleft=False, labelbottom=False) + + # Grille fine + grid_cfg = spec.get("grid") + if grid_cfg: + xs = grid_cfg.get("x_step", 0.5) + ys = grid_cfg.get("y_step", 0.5) + ax.set_xticks(np.arange(xlim[0], xlim[1] + xs, xs)) + ax.set_yticks(np.arange(ylim[0], ylim[1] + ys, ys)) + ax.grid(True, which='both', linestyle=':', color='#e2e8f0', alpha=0.6, linewidth=0.6) + + # Axes + if spec.get("axes", True): + ax.axhline(0, color='#0f172a', linewidth=1.2) + ax.axvline(0, color='#0f172a', linewidth=1.2) + ax.annotate('', xy=(xlim[1] - 0.05, 0), xytext=(xlim[1] - 0.2, 0), + arrowprops=dict(arrowstyle="->", color='#0f172a', lw=1.2)) + ax.annotate('', xy=(0, ylim[1] - 0.05), xytext=(0, ylim[1] - 0.2), + arrowprops=dict(arrowstyle="->", color='#0f172a', lw=1.2)) + + # Éléments + for el in spec.get("elements", []): + kind = el.get("kind") + if kind == "circle": + c = el.get("center", [0, 0]) + r = el.get("radius", 1.0) + edge = el.get("stroke", "#1e3a8a") + face = el.get("fill", "none") + lw = el.get("lw", 1.8) + ls = el.get("linestyle", "-") + circle = patches.Circle((c[0], c[1]), r, edgecolor=edge, facecolor=face, linewidth=lw, linestyle=ls) + ax.add_patch(circle) + + elif kind == "vector": + fr = el.get("from", [0, 0]) + to = el.get("to", [1, 0]) + col = el.get("color", "#0f172a") + lw = el.get("lw", 1.8) + mut = el.get("mutation_scale", 12) + ax.annotate('', xy=(to[0], to[1]), xytext=(fr[0], fr[1]), + arrowprops=dict(arrowstyle="-|>", color=col, lw=lw, mutation_scale=mut)) + + elif kind == "point": + x = el.get("x", 0) + y = el.get("y", 0) + col = el.get("color", "#b91c1c") + size = el.get("size", 5.5) + ax.plot([x], [y], 'o', color=col, markersize=size) + lbl = el.get("label") + if lbl: + ox = el.get("offset_x", 0.12) + oy = el.get("offset_y", -0.15) + ax.text(x + ox, y + oy, lbl, fontsize=el.get("fontsize", 11), + fontweight='bold', color=col, + ha=el.get("ha", "left"), va=el.get("va", "center")) + + elif kind == "line": + xs = el.get("x", []) + ys = el.get("y", []) + col = el.get("color", "#0f172a") + lw = el.get("lw", 1.5) + ls = el.get("linestyle", "-") + ax.plot(xs, ys, color=col, linewidth=lw, linestyle=ls) + + elif kind == "polygon": + xs = el.get("x", []) + ys = el.get("y", []) + col = el.get("color", "#3b82f6") + edge = el.get("stroke", "#1d4ed8") + alpha = el.get("alpha", 0.15) + lw = el.get("lw", 1.8) + ax.fill(xs, ys, color=col, alpha=alpha) + ax.plot(xs, ys, color=edge, linewidth=lw) + + elif kind == "text": + x = el.get("x", 0) + y = el.get("y", 0) + t = el.get("text", "") + fs = el.get("fontsize", 11) + col = el.get("color", "#0f172a") + ax.text(x, y, t, fontsize=fs, fontweight='bold', color=col, + ha=el.get("ha", "center"), va=el.get("va", "center")) + + elif kind == "function": + expr = el.get("expr", "x") + f_xmin = el.get("xmin", xlim[0]) + f_xmax = el.get("xmax", xlim[1]) + col = el.get("color", "#2563eb") + lw = el.get("lw", 1.8) + x_vals = np.linspace(f_xmin, f_xmax, 200) + try: + # Évaluation sécurisée avec numpy + y_vals = eval(expr, {"np": np, "x": x_vals, "sin": np.sin, "cos": np.cos, "exp": np.exp, "sqrt": np.sqrt}) + ax.plot(x_vals, y_vals, color=col, linewidth=lw) + except Exception as e: + print(f"Erreur tracé fonction {expr}: {e}") + + # Cartouche de titre interne éventuel + t_box = spec.get("title_box") + if t_box: + boxstyle = dict(boxstyle='round,pad=0.35', facecolor='#f8fafc', edgecolor='#94a3b8', linewidth=0.8) + ax.text(t_box.get("x", 0.3), t_box.get("y", ylim[1] - 0.2), t_box.get("text", ""), + fontsize=9, fontweight='bold', color='#1e293b', + ha=t_box.get("ha", "center"), va=t_box.get("va", "top"), bbox=boxstyle) + + plt.tight_layout() + os.makedirs(os.path.dirname(output_path), exist_ok=True) + plt.savefig(output_path, dpi=300, bbox_inches='tight') + plt.close() + return output_path + +def resolve_figure_file(img_name: str, target_dir: str, ref_dirs=None) -> str: + """Cherche une image par son nom et la copie dans target_dir si nécessaire.""" + target_path = os.path.join(target_dir, os.path.basename(img_name)) + if os.path.exists(target_path): + return target_path + + if os.path.isabs(img_name) and os.path.exists(img_name): + shutil.copy2(img_name, target_path) + return target_path + + search_dirs = (ref_dirs or []) + [ + "/app/ref/serie06-reference", + "/app/ref", + "/app/data", + "/workspace/heykel-ref-20261109/serie06-reference", + "/workspace/heykel-ref-20261109/moteur" + ] + for d in search_dirs: + candidate = os.path.join(d, os.path.basename(img_name)) + if os.path.exists(candidate): + os.makedirs(target_dir, exist_ok=True) + shutil.copy2(candidate, target_path) + return target_path + + raise FileNotFoundError(f"Image introuvable : '{img_name}'") diff --git a/main.py b/main.py new file mode 100644 index 0000000..42fc164 --- /dev/null +++ b/main.py @@ -0,0 +1,186 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +main.py +Service HTTP series-studio pour la génération unifiée de séries d'exercices (PDF et DOCX). +Fournit l'API interne : GET /themes, POST /validate, POST /render, GET /jobs//pdf, +GET /jobs//docx, POST /jobs//rerender. +""" + +import json +import os +import time +import uuid +from typing import Optional +from fastapi import FastAPI, HTTPException, Request +from fastapi.responses import FileResponse, JSONResponse +from pydantic import BaseModel + +import themes +import validator +import figures +import renderer_docx +import renderer_typst + +app = FastAPI(title="series-studio", version="1.0.0") + +JOBS_DIR = os.getenv("SERIES_STUDIO_JOBS_DIR", "/app/jobs") +DATA_DIR = os.getenv("SERIES_STUDIO_DATA_DIR", "/app/data") +REF_DIR = os.getenv("SERIES_STUDIO_REF_DIR", "/app/ref") + +os.makedirs(JOBS_DIR, exist_ok=True) +os.makedirs(DATA_DIR, exist_ok=True) + +class ValidateRequest(BaseModel): + source: dict + +class RenderRequest(BaseModel): + source: dict + theme: Optional[str] = "classique" + +class RerenderRequest(BaseModel): + theme: str + +@app.get("/themes") +def get_themes(): + """Renvoie la liste des thèmes disponibles.""" + all_themes = themes.list_themes() + return {"themes": all_themes} + +@app.post("/validate") +def validate_endpoint(req: ValidateRequest): + """Valide une source JSON et renvoie des erreurs précises et localisées.""" + res = validator.validate_source(req.source) + return res + +def _execute_render_pipeline(source: dict, theme_name: str, job_id: str) -> str: + """Exécute le pipeline de rendu complet PDF et DOCX sans aucun modèle.""" + # 1. Vérification du thème + try: + theme_tokens = themes.get_theme(theme_name) + except ValueError as e: + raise HTTPException(status_code=400, detail=str(e)) + + # 2. Validation de la source + val_res = validator.validate_source(source) + if not val_res["valid"]: + raise HTTPException(status_code=400, detail={"message": "Source JSON invalide", "errors": val_res["errors"]}) + + job_dir = os.path.join(JOBS_DIR, job_id) + figures_dir = os.path.join(job_dir, "figures") + os.makedirs(figures_dir, exist_ok=True) + + # 3. Sauvegarde de la source et des métadonnées du job + with open(os.path.join(job_dir, "source.json"), "w", encoding="utf-8") as f: + json.dump(source, f, ensure_ascii=False, indent=2) + + with open(os.path.join(job_dir, "theme.json"), "w", encoding="utf-8") as f: + json.dump(theme_tokens, f, ensure_ascii=False, indent=2) + + journal_lines = [ + f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] Démarrage job {job_id} — Thème: {theme_name}" + ] + + # 4. Résolution et tracé des figures (déclaratives ou existantes) + figures_map = {} + + # Résolution des figures déclarées dans source["figures"] + for fig_spec in source.get("figures", []): + f_id = fig_spec.get("id") + kind = fig_spec.get("kind", "declarative") + out_name = f"{f_id}.png" + out_path = os.path.join(figures_dir, out_name) + if kind == "declarative": + figures.render_declarative_figure(fig_spec, out_path) + figures_map[f_id] = out_path + figures_map[out_name] = out_path + journal_lines.append(f"Figure déclarative tracée à 300 dpi : {out_name}") + elif kind == "file": + img_file = fig_spec.get("file", f_id) + resolved = figures.resolve_figure_file(img_file, figures_dir, [REF_DIR, os.path.join(REF_DIR, "serie06-reference")]) + figures_map[f_id] = resolved + figures_map[os.path.basename(resolved)] = resolved + journal_lines.append(f"Image résolue : {resolved}") + + # Résolution des images dans l'annexe + annexe = source.get("annexe") + if annexe: + for col in annexe.get("colonnes", []): + img_name = col.get("image") or col.get("figure_id") + if img_name and img_name not in figures_map: + try: + resolved = figures.resolve_figure_file(img_name, figures_dir, [REF_DIR, os.path.join(REF_DIR, "serie06-reference")]) + figures_map[img_name] = resolved + figures_map[os.path.basename(img_name)] = resolved + journal_lines.append(f"Image d'annexe résolue : {resolved}") + except Exception as e: + journal_lines.append(f"Avertissement image annexe : {e}") + + # 5. Rendu DOCX avec OMML natif + output_docx_path = os.path.join(job_dir, "output.docx") + try: + docx_meta = renderer_docx.render_docx(source, theme_tokens, output_docx_path, figures_map) + journal_lines.append(f"DOCX rendu avec succès : {docx_meta['omath']} formules OMML, {docx_meta['draw']} figures, {docx_meta['dollar']} dollar(s)") + except Exception as e: + journal_lines.append(f"ERREUR rendu DOCX : {e}") + with open(os.path.join(job_dir, "journal.log"), "w", encoding="utf-8") as f: + f.write("\n".join(journal_lines)) + raise HTTPException(status_code=500, detail=f"Erreur rendu DOCX : {e}") + + # 6. Rendu PDF avec Typst + output_pdf_path = os.path.join(job_dir, "output.pdf") + try: + pdf_meta = renderer_typst.render_typst(source, theme_tokens, output_pdf_path, figures_map=figures_map) + journal_lines.append(f"PDF rendu avec succès : {pdf_meta['pages']} page(s) calibrée(s)") + except Exception as e: + journal_lines.append(f"ERREUR rendu PDF : {e}") + with open(os.path.join(job_dir, "journal.log"), "w", encoding="utf-8") as f: + f.write("\n".join(journal_lines)) + raise HTTPException(status_code=500, detail=f"Erreur rendu PDF : {e}") + + journal_lines.append(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] Fin normale du job {job_id}") + with open(os.path.join(job_dir, "journal.log"), "w", encoding="utf-8") as f: + f.write("\n".join(journal_lines)) + + return job_id + +@app.post("/render") +def render_endpoint(req: RenderRequest): + """Point d'entrée principal pour générer le PDF et le DOCX d'une série.""" + job_id = f"job_{time.strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:6]}" + _execute_render_pipeline(req.source, req.theme or "classique", job_id) + return {"job_id": job_id} + +@app.get("/jobs/{job_id}/pdf") +def get_job_pdf(job_id: str): + """Télécharge le fichier PDF produit par un job.""" + path = os.path.join(JOBS_DIR, job_id, "output.pdf") + if not os.path.exists(path): + raise HTTPException(status_code=404, detail="Fichier PDF introuvable pour ce job") + return FileResponse(path, media_type="application/pdf", filename=f"{job_id}.pdf") + +@app.get("/jobs/{job_id}/docx") +def get_job_docx(job_id: str): + """Télécharge le fichier DOCX produit par un job.""" + path = os.path.join(JOBS_DIR, job_id, "output.docx") + if not os.path.exists(path): + raise HTTPException(status_code=404, detail="Fichier DOCX introuvable pour ce job") + return FileResponse( + path, + media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document", + filename=f"{job_id}.docx" + ) + +@app.post("/jobs/{job_id}/rerender") +def rerender_endpoint(job_id: str, req: RerenderRequest): + """Re-rend une série existante dans un autre thème sans repasser par un modèle.""" + source_path = os.path.join(JOBS_DIR, job_id, "source.json") + if not os.path.exists(source_path): + raise HTTPException(status_code=404, detail="Job source introuvable") + + with open(source_path, "r", encoding="utf-8") as f: + source = json.load(f) + + new_job_id = f"job_{time.strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:6]}" + _execute_render_pipeline(source, req.theme, new_job_id) + return {"job_id": new_job_id} diff --git a/renderer_docx.py b/renderer_docx.py new file mode 100644 index 0000000..0d2cdce --- /dev/null +++ b/renderer_docx.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +renderer_docx.py +Moteur de rendu Word (.docx) natif OMML depuis la description JSON d'une série. +Applique le thème graphique et effectue les contrôles bloquants post-génération. +""" + +import io +import os +import re +import zipfile +from serie_docx_builder import SerieDocxBuilder + +def render_docx(source: dict, theme: dict, output_path: str, figures_map: dict = None) -> dict: + """Génère le document DOCX complet et exécute les vérifications d'intégrité bloquantes.""" + figures_map = figures_map or {} + c = source.get("cartouche", {}) + + builder = SerieDocxBuilder( + titre=c.get("titre", ""), + sous_titre=c.get("sous_titre", ""), + discipline=c.get("discipline", "Mathématiques"), + classe=c.get("classe", "4ème Sciences Techniques"), + enseignant=c.get("enseignant", "Heykel ZAYANI"), + annee=c.get("annee", "2026 / 2027"), + lycee=c.get("lycee", "Lycée Pilote"), + titre_enseignant=c.get("titre_enseignant", "P.P.É.C.E."), + type_doc=c.get("type_doc", "SÉRIE D'EXERCICES"), + theme=theme + ) + + for ex in source.get("exercices", []): + num_str = str(ex.get("numero", "")) + titre_str = ex.get("titre") + points_str = ex.get("points") + builder.add_exercise_banner(num_str, titre_str, points_str) + + for el in ex.get("elements", []): + el_type = el.get("type") + sb = el.get("space_before", 2) + sa = el.get("space_after", 2) + indent = el.get("indent_level", 0) + + if el_type == "question": + text = el.get("text_docx") or el.get("text", "") + builder.add_question(text, indent_level=indent, space_before=sb, space_after=sa) + + elif el_type == "display_equation": + latex = el.get("latex", "") + builder.add_display_equation(latex, space_before=sb, space_after=sa) + + elif el_type == "part_header": + prefix = el.get("bold_prefix", "") + text = el.get("text_docx") or el.get("text", "") + builder.add_part_header(prefix, text, space_before=sb, space_after=sa) + + elif el_type == "page_break": + builder.add_page_break() + + # Annexe éventuelle + annexe = source.get("annexe") + if annexe: + cols = [] + for col in annexe.get("colonnes", []): + img_key = col.get("image") or col.get("figure_id") + resolved_img = None + if img_key: + resolved_img = figures_map.get(img_key) or figures_map.get(os.path.basename(img_key)) + cols.append({ + "titre": col.get("titre", ""), + "image_path": resolved_img, + "width_docx_inches": col.get("width_docx_inches", 3.2) + }) + builder.add_annexe_table(annexe.get("titre", "ANNEXE"), cols) + + os.makedirs(os.path.dirname(output_path), exist_ok=True) + builder.save(output_path) + + # ========================================================================= + # CONTRÔLES BLOQUANTS POST-GÉNÉRATION DOCX (T3) + # ========================================================================= + with open(output_path, "rb") as f: + docx_bytes = f.read() + + z = zipfile.ZipFile(io.BytesIO(docx_bytes)) + doc_xml = z.read("word/document.xml").decode("utf-8") + + # 1. Aucun $ ni LaTeX brut dans le XML + dollars = doc_xml.count("$") + if dollars > 0: + raise ValueError(f"Contrôle bloquant échoué : {dollars} signe(s) '$' résiduel(s) dans word/document.xml") + + # 2. Formules OMML + omath_count = len(re.findall(r"]", doc_xml)) + if omath_count == 0: + raise ValueError("Contrôle bloquant échoué : aucune formule OMML générée dans le DOCX") + + # 3. Dessins + draw_count = len(re.findall(r"([^<]*)", core_xml) + author = m_author.group(1) if m_author else "" + expected_author = c.get("enseignant", "").strip() + if author.lower() == "python-docx" or author.lower() != expected_author.lower(): + raise ValueError(f"Contrôle bloquant échoué : auteur DOCX = {author!r}, attendu {expected_author!r}") + + brut = re.sub(r"].*?", " ", doc_xml, flags=re.S) + extracted_text = " ".join(re.findall(r"]*>([^<]*)", brut)) + + return { + "omath": omath_count, + "draw": draw_count, + "dollar": dollars, + "auteur": author, + "texte": extracted_text + } diff --git a/renderer_typst.py b/renderer_typst.py new file mode 100644 index 0000000..1ca5f92 --- /dev/null +++ b/renderer_typst.py @@ -0,0 +1,233 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +renderer_typst.py +Génération du fichier Typst et compilation vers PDF de haute fidélité. +Effectue les contrôles bloquants : compilation sans avertissement et nombre de pages conforme à pages_cibles. +""" + +import os +import subprocess +import fitz + +def generate_typst_source(source: dict, theme: dict, template_import_path: str, figures_map: dict = None) -> str: + """Produit le code source Typst complet à partir de la source JSON et du thème.""" + figures_map = figures_map or {} + c = source.get("cartouche", {}) + + col_primary = theme.get("primary", "#0f2c59") + col_secondary = theme.get("secondary", "#1e40af") + col_accent = theme.get("accent", "#93c5fd") + col_bg_subtle = theme.get("bg_subtle", "#f8fafc") + col_border = theme.get("border", "#cbd5e1") + font_main = theme.get("font_typst", "New Computer Modern") + + lines = [] + lines.append(f'#import "{template_import_path}": *') + lines.append("") + titre_val = c.get("titre", "") + type_doc_val = c.get("type_doc", "SÉRIE D'EXERCICES") + sous_titre_val = c.get("sous_titre", "") + discipline_val = c.get("discipline", "Mathématiques") + classe_val = c.get("classe", "4ème Sciences Techniques") + enseignant_val = c.get("enseignant", "Heykel ZAYANI") + titre_ens_val = c.get("titre_enseignant", "P.P.É.C.E.") + annee_val = c.get("annee", "2026 / 2027") + lycee_val = c.get("lycee", "Lycée Pilote") + + lines.append("#show: doc => serie_document(") + lines.append(f' titre: "{titre_val}",') + lines.append(f' type_doc: "{type_doc_val}",') + lines.append(f' sous_titre: "{sous_titre_val}",') + lines.append(f' discipline: "{discipline_val}",') + lines.append(f' classe: "{classe_val}",') + lines.append(f' enseignant: "{enseignant_val}",') + lines.append(f' titre_enseignant: "{titre_ens_val}",') + lines.append(f' annee: "{annee_val}",') + lines.append(f' lycee: "{lycee_val}",') + lines.append(f' color_primary: rgb("{col_primary}"),') + lines.append(f' color_secondary: rgb("{col_secondary}"),') + lines.append(f' color_accent: rgb("{col_accent}"),') + lines.append(f' color_bg_subtle: rgb("{col_bg_subtle}"),') + lines.append(f' color_border: rgb("{col_border}"),') + lines.append(f' font_main: "{font_main}",') + lines.append(" doc,") + lines.append(")") + lines.append("") + lines.append("#set text(size: 9.2pt)") + lines.append("#set par(leading: 0.52em)") + lines.append("") + + for ex in source.get("exercices", []): + num = str(ex.get("numero", "1")) + titre = ex.get("titre") + titre_arg = f'titre: "{titre}"' if titre else 'titre: none' + points = ex.get("points") + points_arg = f'points: "{points}"' if points else 'points: none' + breakable = "true" if ex.get("breakable_box", False) else "false" + + lines.append(f'// EXERCICE {num}') + lines.append(f'#exercice("{num}", {titre_arg}, {points_arg}, breakable_box: {breakable},') + lines.append(f' color_primary: rgb("{col_primary}"), color_secondary: rgb("{col_secondary}"),') + lines.append(f' color_accent: rgb("{col_accent}"), color_border: rgb("{col_border}"))[') + lines.append(" #v(-2pt)") + + elements = ex.get("elements", []) + idx = 0 + while idx < len(elements): + el = elements[idx] + el_type = el.get("type") + + if el_type == "question": + indent = el.get("indent_level", 0) + if indent == 0: + t = el.get("text_typst") or el.get("text", "") + lines.append(f" {t}") + idx += 1 + else: + # Regrouper les sous-questions consécutives indentées dans un #pad(left: 10pt) + pad_lines = [] + while idx < len(elements) and elements[idx].get("type") == "question" and elements[idx].get("indent_level", 0) > 0: + sub_t = elements[idx].get("text_typst") or elements[idx].get("text", "") + pad_lines.append(sub_t) + idx += 1 + lines.append(" #pad(left: 10pt)[") + for p_i, pl in enumerate(pad_lines): + end_char = r"\\" if p_i < len(pad_lines) - 1 else "" + lines.append(f" {pl}{end_char}") + lines.append(" ]") + continue + + elif el_type == "display_equation": + eq = el.get("typst") or el.get("latex", "") + lines.append(f" $ {eq} $") + lines.append(" #v(-2pt)") + idx += 1 + + elif el_type == "part_header": + prefix = el.get("bold_prefix", "") + t = el.get("text_typst") or el.get("text", "") + lines.append(f" *{prefix}* {t}") + idx += 1 + + elif el_type == "page_break": + idx += 1 + + elif el_type == "figure": + idx += 1 + + else: + t = el.get("text_typst") or el.get("text", "") + if t: + lines.append(f" {t}") + idx += 1 + + lines.append("]") + lines.append("") + + # Vérifier si l'exercice contient un saut de page pour le placer hors de la boîte + has_pagebreak = any(e.get("type") == "page_break" for e in elements) + if has_pagebreak: + lines.append("#pagebreak()") + lines.append("") + + annexe = source.get("annexe") + if annexe: + cols = annexe.get("colonnes", []) + ann_titre = annexe.get("titre", "ANNEXE À RENDRE AVEC LA COPIE — FIGURES OFFICIELLES") + lines.append("// ANNEXE OFFICIELLE") + lines.append("#v(4pt)") + lines.append("#block(") + lines.append(" width: 100%,") + lines.append(f' stroke: 1pt + rgb("{col_primary}"),') + lines.append(" radius: 5pt,") + lines.append(" clip: true,") + lines.append(' fill: rgb("#ffffff"),') + lines.append(" [") + lines.append(" #block(") + lines.append(f' fill: rgb("{col_primary}"),') + lines.append(" width: 100%,") + lines.append(" inset: (x: 10pt, y: 4.5pt),") + lines.append(" align(center)[") + lines.append(' #text(fill: white, weight: "bold", size: 9.5pt)[') + lines.append(f' {ann_titre}') + lines.append(" ]") + lines.append(" ]") + lines.append(" )") + lines.append(" #block(") + lines.append(" width: 100%,") + lines.append(" inset: (x: 8pt, top: 4pt, bottom: 4pt),") + lines.append(" [") + lines.append(" #grid(") + cols_str = ("1fr, " * len(cols)).rstrip(", ") + lines.append(f" #grid(") + lines.append(f" columns: ({cols_str}),") + lines.append(" gutter: 12pt,") + lines.append(" align: (center + top, center + top),") + + for col in cols: + col_t = col.get("titre", "") + img_key = col.get("image") or col.get("figure_id") + resolved_img = figures_map.get(img_key) or figures_map.get(os.path.basename(img_key)) or img_key + w_typ = col.get("width_typst", "90%") + lines.append(" [") + lines.append(f' #text(weight: "bold", size: 8.5pt, fill: rgb("{col_secondary}"))[{col_t}]\\') + lines.append(" #v(1pt)") + lines.append(f' #image("{resolved_img}", width: {w_typ})') + lines.append(" ],") + + lines.append(" )") + lines.append(" ]") + lines.append(" )") + lines.append(" ]") + lines.append(")") + lines.append("") + + return "\n".join(lines) + +def render_typst(source: dict, theme: dict, output_pdf_path: str, typst_bin: str = "typst", figures_map: dict = None, template_path: str = None) -> dict: + """Compile la source en PDF avec Typst et vérifie les critères bloquants.""" + figures_map = figures_map or {} + job_dir = os.path.dirname(os.path.abspath(output_pdf_path)) + typ_path = os.path.join(job_dir, "document.typ") + + tmpl = template_path or "/app/templates/template_serie_math.typ" + if not os.path.exists(tmpl): + alt = os.path.join(os.path.dirname(__file__), "templates", "template_serie_math.typ") + if os.path.exists(alt): + tmpl = alt + + # Racine pour typst sandbox + root_dir = "/" + if os.path.exists("/app"): + root_dir = "/app" + + typ_content = generate_typst_source(source, theme, tmpl, figures_map) + with open(typ_path, "w", encoding="utf-8") as f: + f.write(typ_content) + + cmd = [typst_bin, "compile", "--root", root_dir, typ_path, output_pdf_path] + p = subprocess.run(cmd, capture_output=True, text=True) + + if p.returncode != 0: + raise RuntimeError(f"Échec compilation Typst (code {p.returncode}) : {p.stderr}") + + # Contrôle bloquant T3 : Typst sans avertissement + stderr_clean = p.stderr.strip() + if "warning:" in stderr_clean.lower(): + raise ValueError(f"Contrôle bloquant échoué : avertissements Typst détectés : {stderr_clean}") + + # Contrôle bloquant T3 : Nombre de pages conforme à pages_cibles + doc_fitz = fitz.open(output_pdf_path) + page_count = len(doc_fitz) + expected_pages = source.get("pages_cibles", 2) + if page_count != expected_pages: + raise ValueError(f"Contrôle bloquant échoué : {page_count} page(s) générée(s), {expected_pages} attendue(s)") + + extracted_text = "\n".join(page.get_text() for page in doc_fitz) + + return { + "pages": page_count, + "texte": extracted_text, + "typ_path": typ_path + } diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..72b08f0 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,13 @@ +fastapi>=0.110.0 +uvicorn[standard]>=0.29.0 +python-docx==1.1.2 +latex2mathml==3.77.0 +lxml==6.1.3 +matplotlib==3.7.5 +numpy==1.24.4 +Pillow==10.4.0 +PyMuPDF==1.24.11 +jsonschema>=4.21.0 +pytest>=8.0.0 +requests>=2.31.0 +httpx>=0.27.0 diff --git a/schema.json b/schema.json new file mode 100644 index 0000000..4dd9645 --- /dev/null +++ b/schema.json @@ -0,0 +1,256 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "SeriesStudioDocument", + "description": "Schéma de description structurée d'une série d'exercices mathématiques pour series-studio", + "type": "object", + "required": [ + "schema_version", + "pages_cibles", + "cartouche", + "exercices" + ], + "properties": { + "schema_version": { + "type": "string", + "description": "Version du schéma (ex: 1.0.0)" + }, + "pages_cibles": { + "type": "integer", + "minimum": 1, + "description": "Nombre de pages cible pour le document (ex: 2)" + }, + "theme": { + "type": "string", + "description": "Thème graphique à appliquer (ex: classique, sobre)" + }, + "cartouche": { + "type": "object", + "description": "Métadonnées de l'en-tête officiel du document", + "required": [ + "titre", + "type_doc", + "discipline", + "classe", + "enseignant", + "annee", + "lycee" + ], + "properties": { + "titre": { + "type": "string", + "description": "Titre principal de la série (ex: COMPLEXES)" + }, + "sous_titre": { + "type": "string", + "description": "Sous-titre ou description courte" + }, + "type_doc": { + "type": "string", + "description": "Type de document (ex: SÉRIE D'EXERCICES)" + }, + "discipline": { + "type": "string", + "description": "Discipline enseignée (ex: Mathématiques)" + }, + "classe": { + "type": "string", + "description": "Niveau et section (ex: 4ème Sciences Techniques)" + }, + "enseignant": { + "type": "string", + "description": "Nom de l'enseignant (ex: Heykel ZAYANI)" + }, + "titre_enseignant": { + "type": "string", + "description": "Titre officiel de l'enseignant (ex: P.P.É.C.E.)" + }, + "annee": { + "type": "string", + "description": "Année scolaire (ex: 2026 / 2027)" + }, + "lycee": { + "type": "string", + "description": "Établissement scolaire (ex: Lycée Pilote)" + } + } + }, + "exercices": { + "type": "array", + "description": "Liste ordonnée des exercices", + "items": { + "type": "object", + "required": [ + "numero", + "elements" + ], + "properties": { + "numero": { + "type": "string", + "description": "Numéro d'exercice (ex: '1')" + }, + "titre": { + "type": "string", + "description": "Titre thématique de l'exercice" + }, + "points": { + "type": "string", + "description": "Barème de l'exercice (ex: '5 points')" + }, + "breakable_box": { + "type": "boolean", + "description": "Indique si la boîte Typst est sécable sur plusieurs pages" + }, + "elements": { + "type": "array", + "description": "Éléments séquentiels de l'exercice", + "items": { + "type": "object", + "required": [ + "type" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "question", + "display_equation", + "part_header", + "page_break", + "text", + "figure" + ] + }, + "text": { + "type": "string" + }, + "text_typst": { + "type": "string" + }, + "text_docx": { + "type": "string" + }, + "latex": { + "type": "string" + }, + "typst": { + "type": "string" + }, + "indent_level": { + "type": "integer", + "minimum": 0 + }, + "space_before": { + "type": "number" + }, + "space_after": { + "type": "number" + }, + "bold_prefix": { + "type": "string" + }, + "image": { + "type": "string" + }, + "figure_id": { + "type": "string" + } + } + } + } + } + } + }, + "annexe": { + "type": "object", + "description": "Annexe officielle éventuelle (figures, grille QCM, etc.)", + "required": [ + "titre", + "colonnes" + ], + "properties": { + "titre": { + "type": "string" + }, + "colonnes": { + "type": "array", + "items": { + "type": "object", + "required": [ + "titre" + ], + "properties": { + "titre": { + "type": "string" + }, + "image": { + "type": "string" + }, + "figure_id": { + "type": "string" + }, + "width_typst": { + "type": "string" + }, + "width_docx_inches": { + "type": "number" + } + } + } + } + } + }, + "figures": { + "type": "array", + "description": "Définition déclarative des figures géométriques / tracés", + "items": { + "type": "object", + "required": [ + "id", + "kind" + ], + "properties": { + "id": { + "type": "string" + }, + "kind": { + "type": "string", + "enum": [ + "declarative", + "file" + ] + }, + "file": { + "type": "string" + }, + "figsize": { + "type": "array", + "items": { + "type": "number" + } + }, + "xlim": { + "type": "array", + "items": { + "type": "number" + } + }, + "ylim": { + "type": "array", + "items": { + "type": "number" + } + }, + "aspect": { + "type": "string" + }, + "title_box": { + "type": "object" + }, + "elements": { + "type": "array" + } + } + } + } + } +} diff --git a/serie_docx_builder.py b/serie_docx_builder.py new file mode 100644 index 0000000..9ae506d --- /dev/null +++ b/serie_docx_builder.py @@ -0,0 +1,409 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +serie_docx_builder.py +Constructeur de document Word (.docx) avec équations natives OMML et support de thèmes. +""" + +import os +import re +import latex2mathml.converter +import lxml.etree as ET +from docx import Document +from docx.shared import Inches, Pt, RGBColor +from docx.enum.text import WD_ALIGN_PARAGRAPH +from docx.enum.table import WD_TABLE_ALIGNMENT +from docx.oxml import parse_xml +from docx.oxml.ns import nsdecls + +DEFAULT_XSLT = os.path.join(os.path.dirname(__file__), "templates", "mml2omml.xsl") + +def hex_to_rgb(hex_str: str) -> RGBColor: + s = hex_str.lstrip("#") + if len(s) == 3: + s = "".join([c*2 for c in s]) + return RGBColor(int(s[0:2], 16), int(s[2:4], 16), int(s[4:6], 16)) + +def hex_clean(hex_str: str) -> str: + return hex_str.lstrip("#").upper() + +class SerieDocxBuilder: + def __init__( + self, + titre="COMPLEXES", + sous_titre="Bac 2023, 2024 et 2025", + discipline="Mathématiques", + classe="4ème Sciences Techniques", + enseignant="Heykel ZAYANI", + annee="2026 / 2027", + lycee="Lycée Pilote", + titre_enseignant="P.P.É.C.E.", + type_doc="SÉRIE D'EXERCICES", + theme=None, + xslt_path=None + ): + self.titre = titre + self.sous_titre = sous_titre + self.discipline = discipline + self.classe = classe + self.enseignant = enseignant + self.annee = annee + self.lycee = lycee + self.titre_enseignant = titre_enseignant + self.type_doc = type_doc + + # Thème graphique + self.theme = theme or {} + self.col_primary = hex_clean(self.theme.get("primary", "0F2C59")) + self.col_secondary = hex_clean(self.theme.get("secondary", "1E40AF")) + self.col_accent = hex_clean(self.theme.get("accent", "93C5FD")) + self.col_bg_subtle = hex_clean(self.theme.get("bg_subtle", "F8FAFC")) + self.col_border = hex_clean(self.theme.get("border", "CBD5E1")) + self.col_points = hex_clean(self.theme.get("points_docx_color", "FEF08A")) + + self.font_main = self.theme.get("font_docx", "Cambria") + self.font_banner = self.theme.get("font_banner", "Segoe UI") + + # Initialisation XSLT MathML -> OMML + xslt_file = xslt_path or DEFAULT_XSLT + if not os.path.exists(xslt_file): + alt = os.path.join(os.path.dirname(__file__), "mml2omml.xsl") + if os.path.exists(alt): + xslt_file = alt + self.xslt_tree = ET.parse(xslt_file) + self.transform = ET.XSLT(self.xslt_tree) + + self.doc = Document() + self._set_core_properties() + self._setup_page_layout() + self._create_header_cartouche() + + def _set_core_properties(self): + """Définit les métadonnées officielles en évitant 'python-docx' comme créateur.""" + cp = self.doc.core_properties + cp.author = self.enseignant + cp.title = f"{self.type_doc} : {self.titre} - {self.enseignant}" + cp.subject = f"{self.discipline} - {self.classe}" + cp.comments = f"Généré par series-studio ({self.annee})" + + def latex_to_omml(self, latex_code): + """Convertit du code LaTeX en élément XML OMML (oMath).""" + clean_code = latex_code.strip() + clean_code = clean_code.replace(r'\limits', '') + clean_code = clean_code.replace(r'\mathbb{R}', 'R') + clean_code = clean_code.replace(r'\RR', 'R') + clean_code = clean_code.replace(r'\mathbb{C}', 'C') + clean_code = clean_code.replace(r'\CC', 'C') + clean_code = clean_code.replace(r'\mathbb{Z}', 'Z') + clean_code = clean_code.replace(r'\ZZ', 'Z') + + mml = latex2mathml.converter.convert(clean_code) + mml_dom = ET.fromstring(mml) + + # Convertir les de 'lim' en pour afficher la limite en-dessous (m:limLow) + ns = {"m": "http://www.w3.org/1998/Math/MathML"} + for msub in mml_dom.xpath("//m:msub[m:mo[text()='lim']]", namespaces=ns): + msub.tag = "{http://www.w3.org/1998/Math/MathML}munder" + + omml_dom = self.transform(mml_dom) + return omml_dom.getroot() + + def _setup_page_layout(self): + """Configure les marges A4 ainsi que l'en-tête et pied de page.""" + for s in self.doc.sections: + s.page_width = Inches(8.27) + s.page_height = Inches(11.69) + s.top_margin = Inches(0.6) + s.bottom_margin = Inches(0.6) + s.left_margin = Inches(0.6) + s.right_margin = Inches(0.6) + + header_p = s.header.paragraphs[0] + header_p.text = f"{self.discipline} — {self.type_doc} : {self.titre} {self.titre_enseignant} {self.enseignant} | {self.annee.replace(' ', '')}" + header_p.alignment = WD_ALIGN_PARAGRAPH.RIGHT + header_p.runs[0].font.name = self.font_main + header_p.runs[0].font.size = Pt(8.5) + header_p.runs[0].font.color.rgb = RGBColor(100, 116, 139) + + footer_p = s.footer.paragraphs[0] + footer_p.text = f"{self.lycee} — {self.classe} | Année Scolaire {self.annee.replace(' ', '')}" + footer_p.alignment = WD_ALIGN_PARAGRAPH.LEFT + footer_p.runs[0].font.name = self.font_main + footer_p.runs[0].font.size = Pt(8) + footer_p.runs[0].font.color.rgb = RGBColor(100, 116, 139) + + @staticmethod + def _set_cell_background(cell, fill_hex): + tcPr = cell._tc.get_or_add_tcPr() + shd = parse_xml(f'') + tcPr.append(shd) + + @staticmethod + def _set_cell_margins(cell, top=100, bottom=100, left=150, right=150): + tcPr = cell._tc.get_or_add_tcPr() + tcMar = parse_xml( + f'' + f'' + f'' + f'' + f'' + f'' + ) + tcPr.append(tcMar) + + @staticmethod + def _set_table_borders_none(table): + tblPr = table._tbl.tblPr + borders = parse_xml( + f'' + f'' + f'' + f'' + f'' + f'' + f'' + f'' + ) + tblPr.append(borders) + + def _create_header_cartouche(self): + """Crée le cartouche officiel en 3 colonnes.""" + cartouche = self.doc.add_table(rows=1, cols=3) + cartouche.alignment = WD_TABLE_ALIGNMENT.CENTER + self._set_table_borders_none(cartouche) + + c_left = cartouche.cell(0, 0) + c_mid = cartouche.cell(0, 1) + c_right = cartouche.cell(0, 2) + + c_left.width = Inches(2.2) + c_mid.width = Inches(3.2) + c_right.width = Inches(1.8) + + # Gauche + p_cl = c_left.paragraphs[0] + p_cl.paragraph_format.space_before = Pt(0) + p_cl.paragraph_format.space_after = Pt(1) + r1 = p_cl.add_run("RÉPUBLIQUE TUNISIENNE\n") + r1.bold = True + r1.font.size = Pt(8.5) + r1.font.color.rgb = hex_to_rgb(self.col_primary) + r2 = p_cl.add_run("MINISTÈRE DE L'ÉDUCATION\n") + r2.font.size = Pt(7.5) + r2.font.color.rgb = RGBColor(71, 85, 105) + r3 = p_cl.add_run(f"{self.classe}\n") + r3.bold = True + r3.font.size = Pt(8.5) + r3.font.color.rgb = hex_to_rgb(self.col_secondary) + r4 = p_cl.add_run(f"Discipline : {self.discipline}") + r4.font.size = Pt(7.5) + r4.font.color.rgb = RGBColor(100, 116, 139) + + # Milieu + self._set_cell_background(c_mid, self.col_bg_subtle) + self._set_cell_margins(c_mid, top=80, bottom=80, left=120, right=120) + p_cm = c_mid.paragraphs[0] + p_cm.alignment = WD_ALIGN_PARAGRAPH.CENTER + p_cm.paragraph_format.space_before = Pt(0) + p_cm.paragraph_format.space_after = Pt(0) + + r_t1 = p_cm.add_run(f"{self.type_doc}\n") + r_t1.bold = True + r_t1.font.size = Pt(11) + r_t1.font.color.rgb = hex_to_rgb(self.col_primary) + + r_t2 = p_cm.add_run(f"{self.titre}\n") + r_t2.bold = True + r_t2.font.size = Pt(13) + r_t2.font.color.rgb = hex_to_rgb(self.col_secondary) + + if self.sous_titre: + r_t3 = p_cm.add_run(self.sous_titre) + r_t3.italic = True + r_t3.font.size = Pt(7.5) + r_t3.font.color.rgb = RGBColor(71, 85, 105) + + # Droite + p_cr = c_right.paragraphs[0] + p_cr.alignment = WD_ALIGN_PARAGRAPH.RIGHT + p_cr.paragraph_format.space_before = Pt(0) + p_cr.paragraph_format.space_after = Pt(1) + + r_yr = p_cr.add_run("Année Scolaire :\n") + r_yr.font.size = Pt(8) + r_yr.font.color.rgb = RGBColor(100, 116, 139) + r_yr2 = p_cr.add_run(f"{self.annee}\n\n") + r_yr2.bold = True + r_yr2.font.size = Pt(9) + r_yr2.font.color.rgb = hex_to_rgb(self.col_primary) + + r_pr = p_cr.add_run(f"{self.titre_enseignant} :\n") + r_pr.font.size = Pt(8) + r_pr.font.color.rgb = RGBColor(100, 116, 139) + r_pr2 = p_cr.add_run(self.enseignant) + r_pr2.bold = True + r_pr2.font.size = Pt(10.5) + r_pr2.font.color.rgb = hex_to_rgb(self.col_secondary) + + # Ligne de séparation + p_sep = self.doc.add_paragraph() + p_sep.paragraph_format.space_before = Pt(4) + p_sep.paragraph_format.space_after = Pt(6) + p_sep_run = p_sep.add_run("―" * 58) + p_sep_run.font.color.rgb = hex_to_rgb(self.col_primary) + p_sep_run.bold = True + + def add_exercise_banner(self, num_str, title_str=None, points_str=None): + """Crée un bandeau d'exercice avec numéro, titre et points.""" + tbl = self.doc.add_table(rows=1, cols=2) + tbl.alignment = WD_TABLE_ALIGNMENT.CENTER + self._set_table_borders_none(tbl) + + cell_left = tbl.cell(0, 0) + cell_right = tbl.cell(0, 1) + + self._set_cell_background(cell_left, self.col_primary) + self._set_cell_background(cell_right, self.col_primary) + self._set_cell_margins(cell_left, top=120, bottom=120, left=180, right=100) + self._set_cell_margins(cell_right, top=120, bottom=120, left=100, right=180) + + cell_left.width = Inches(5.5) + cell_right.width = Inches(1.7) + + p_left = cell_left.paragraphs[0] + p_left.paragraph_format.space_before = Pt(0) + p_left.paragraph_format.space_after = Pt(0) + + run_ex = p_left.add_run(f"EXERCICE {num_str} ") + run_ex.bold = True + run_ex.font.size = Pt(11) + run_ex.font.color.rgb = RGBColor(255, 255, 255) + run_ex.font.name = self.font_banner + + if title_str: + run_ti = p_left.add_run(f"— {title_str}") + run_ti.italic = True + run_ti.font.size = Pt(9.5) + run_ti.font.color.rgb = hex_to_rgb(self.col_accent) + run_ti.font.name = self.font_banner + + p_right = cell_right.paragraphs[0] + p_right.alignment = WD_ALIGN_PARAGRAPH.RIGHT + p_right.paragraph_format.space_before = Pt(0) + p_right.paragraph_format.space_after = Pt(0) + + if points_str: + run_pts = p_right.add_run(f"[{points_str}]") + run_pts.bold = True + run_pts.font.size = Pt(9.5) + run_pts.font.color.rgb = hex_to_rgb(self.col_points) + run_pts.font.name = self.font_banner + + def add_math_to_paragraph(self, p, text_with_math, base_font_size=10.5): + """Ajoute du texte contenant des formules $...$ au paragraphe en convertissant chaque formule en OMML.""" + parts = text_with_math.split('$') + for i, part in enumerate(parts): + if i % 2 == 0: + if part: + run = p.add_run(part) + run.font.name = self.font_main + run.font.size = Pt(base_font_size) + run.font.color.rgb = RGBColor(15, 23, 42) + else: + if part: + omml_elem = self.latex_to_omml(part) + p._element.append(omml_elem) + + def add_question(self, text, indent_level=0, space_before=2, space_after=2, base_font_size=10.5): + """Ajoute une question avec indentation optionnelle.""" + p = self.doc.add_paragraph() + p.paragraph_format.space_before = Pt(space_before) + p.paragraph_format.space_after = Pt(space_after) + p.paragraph_format.line_spacing = 1.15 + if indent_level == 1: + p.paragraph_format.left_indent = Inches(0.25) + elif indent_level == 2: + p.paragraph_format.left_indent = Inches(0.5) + self.add_math_to_paragraph(p, text, base_font_size=base_font_size) + return p + + def add_display_equation(self, latex_eq, space_before=4, space_after=6): + """Ajoute une équation centrée en mode display (oMathPara).""" + p = self.doc.add_paragraph() + p.alignment = WD_ALIGN_PARAGRAPH.CENTER + p.paragraph_format.space_before = Pt(space_before) + p.paragraph_format.space_after = Pt(space_after) + omml_elem = self.latex_to_omml(latex_eq) + oMathPara = parse_xml(f'') + oMathPara.append(omml_elem) + p._element.append(oMathPara) + return p + + def add_part_header(self, bold_prefix, text_with_math, space_before=3, space_after=2): + """Ajoute un en-tête de partie ('I°) ', 'II°) ').""" + p = self.doc.add_paragraph() + p.paragraph_format.space_before = Pt(space_before) + p.paragraph_format.space_after = Pt(space_after) + r = p.add_run(bold_prefix) + r.bold = True + r.font.name = self.font_main + r.font.size = Pt(10.5) + self.add_math_to_paragraph(p, text_with_math) + return p + + def add_annexe_table(self, title, columns): + """Crée l'annexe officielle avec titre fusionné et 2 colonnes pour les figures.""" + p_sep = self.doc.add_paragraph() + p_sep.paragraph_format.space_before = Pt(6) + p_sep.paragraph_format.space_after = Pt(2) + + tbl = self.doc.add_table(rows=2, cols=len(columns)) + tbl.alignment = WD_TABLE_ALIGNMENT.CENTER + self._set_table_borders_none(tbl) + + # Ligne 1 : Titre fusionné + c_first = tbl.cell(0, 0) + for c in tbl.rows[0].cells[1:]: + c_first.merge(c) + self._set_cell_background(c_first, self.col_primary) + self._set_cell_margins(c_first, top=100, bottom=100, left=150, right=150) + p_t = c_first.paragraphs[0] + p_t.alignment = WD_ALIGN_PARAGRAPH.CENTER + r_t = p_t.add_run(title) + r_t.bold = True + r_t.font.name = self.font_banner + r_t.font.size = Pt(10) + r_t.font.color.rgb = RGBColor(255, 255, 255) + + # Ligne 2 : Colonnes figures + for idx, col_spec in enumerate(columns): + c_fig = tbl.cell(1, idx) + w_in = col_spec.get("width_docx_inches", 3.4) + c_fig.width = Inches(3.6) + self._set_cell_background(c_fig, self.col_bg_subtle) + self._set_cell_margins(c_fig, top=80, bottom=80, left=100, right=100) + + p_lbl = c_fig.paragraphs[0] + p_lbl.alignment = WD_ALIGN_PARAGRAPH.CENTER + p_lbl.paragraph_format.space_before = Pt(2) + p_lbl.paragraph_format.space_after = Pt(2) + r_lbl = p_lbl.add_run(col_spec.get("titre", "")) + r_lbl.bold = True + r_lbl.font.size = Pt(9.5) + r_lbl.font.color.rgb = hex_to_rgb(self.col_secondary) + + img_path = col_spec.get("image_path") + if img_path and os.path.exists(img_path): + p_img = c_fig.add_paragraph() + p_img.alignment = WD_ALIGN_PARAGRAPH.CENTER + p_img.paragraph_format.space_before = Pt(0) + p_img.paragraph_format.space_after = Pt(2) + p_img.add_run().add_picture(img_path, width=Inches(w_in)) + + def add_page_break(self): + """Ajoute un saut de page.""" + self.doc.add_page_break() + + def save(self, filepath): + """Enregistre le document Word.""" + self.doc.save(filepath) diff --git a/templates/mml2omml.xsl b/templates/mml2omml.xsl new file mode 100644 index 0000000..943e0f7 --- /dev/null +++ b/templates/mml2omml.xsl @@ -0,0 +1,4728 @@ + + + + + + ABCDEFGHIJKLMNOPQRSTUVWXYZ + abcdefghijklmnopqrstuvwxyz + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1 + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1 + 0 + + + + + + + + + 1 + 0 + + + + + + + + + + + + + + 1 + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1 + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + 1 + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + p + + + + + b + + + + + + + script + + + + + script + + + b + + + + + double-struck + + + p + + + + + fraktur + + + p + + + + + fraktur + + + b + + + + + sans-serif + + + p + + + + + sans-serif + + + b + + + + + sans-serif + + + + + sans-serif + + + bi + + + + + monospace + + + p + + + + + b + + + + + bi + + + + + + + + + + 1 + + + + + + + + 1 + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + noBar + skw + bar + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + on + + + + + + + + + + + + + + + + + + + + + 1 + 0 + + + + + 1 + 0 + + + + + 1 + 0 + + + + + 1 + 0 + + + + + 1 + 0 + + + + + 1 + 0 + + + + + 1 + 0 + + + + + 1 + 0 + + + + + 1 + 0 + + + + + + + + + + on + + + + + on + + + + + on + + + + + on + + + + + + on + + + + + on + + + + + on + + + + + on + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + off + + + + + + + + + + + + + + + + + + + + + + + 1 + 0 + + + + + + ([{<⌊⌈⟦]|‖ + )]}>⌋⌉⟧[|‖ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1 + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1 + 0 + + + + + + + + + + + + + + + + + + 1 + 0 + + + + + + + + + + + + + 1 + 0 + + + + + + + + + + + lin + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1 + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1 + 0 + + + + + + + + + + + + + + 1 + 0 + + + + + + 1 + 0 + + + + + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1 + 0 + + + + + + + + + + + + 1 + + 0 + + + + 0 + + + + + + + + + + 1 + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1 + 0 + + + + + + + + + + 1 + 0 + + + + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + bot + top + + + top + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ⏟ + + + + + + + + + + + + + + + + + + + + + + + + + + + + ̆ + + ̒ + + ̀ + + ̅ + + ̅ + + ̇ + + ̇ + + ̋ + + ́ + + ̃ + + ̃ + + ̈ + + ̌ + + ̂ + + ̅ + + + + + ⃗ + + ⃗ + + ⃖ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + top + bot + + + bot + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + " + + + + + + + + + + + + + + + + + + + " + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1 + 0 + + + + + + + + + + + + + + + 1 + 0 + + + + + + + + + 1 + + + + + + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1 + 0 + + + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + & + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1 + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1 + 0 + + + + + + + + + + + 1 + 0 + + + + + + + + + + + + + + + + + + + + + + + 1 + + 0 + + 1 + + + + + + + + + + + + + + + + off + + + + + on + + + + + on + + + + + on + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1 + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1 + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + undOvr + + + subSup + + + + + + + + 1 + 0 + 1 + 0 + + + + + + + + on + + + off + + + + + + + + + on + + + off + + + + + + + \ No newline at end of file diff --git a/templates/template_serie_math.typ b/templates/template_serie_math.typ new file mode 100644 index 0000000..7311206 --- /dev/null +++ b/templates/template_serie_math.typ @@ -0,0 +1,190 @@ +// template_serie_math.typ +// Modèle officiel pour les séries de mathématiques — P.P.É.C.E. Heykel ZAYANI +// Support dynamique des thèmes graphiques (classique, sobre, etc.) + +#let lim = math.limits(math.lim) + +#let serie_document( + titre: "LIMITES ET CONTINUITÉ", + sous_titre: "Continuité • TVI • Fonctions par morceaux", + discipline: "Mathématiques", + classe: "4ème Mathématiques & Sciences", + enseignant: "Heykel ZAYANI", + annee: "2026 / 2027", + lycee: "Lycée Pilote", + titre_enseignant: "P.P.É.C.E.", + type_doc: "SÉRIE D'EXERCICES", + color_primary: rgb("#0f2c59"), + color_secondary: rgb("#1e40af"), + color_accent: rgb("#93c5fd"), + color_bg_subtle: rgb("#f8fafc"), + color_border: rgb("#cbd5e1"), + font_main: "New Computer Modern", + body, +) = { + set document(title: type_doc + " : " + titre + " - " + enseignant, author: enseignant) + + set page( + paper: "a4", + margin: (top: 1.2cm, bottom: 1.2cm, left: 1.3cm, right: 1.3cm), + header: context { + let p = counter(page).get().first() + if p > 1 { + grid( + columns: (1.65fr, 1fr), + align: (left, right), + text(size: 8pt, fill: rgb("#475569"))[ + #strong[#discipline] — #type_doc : #titre + ], + text(size: 8pt, fill: rgb("#475569"))[ + #titre_enseignant #strong[#enseignant] | #annee + ] + ) + v(-4pt) + line(length: 100%, stroke: 0.4pt + color_border) + } + }, + footer: context { + line(length: 100%, stroke: 0.4pt + color_border) + v(1pt) + let p = counter(page).get().first() + let total = counter(page).final().first() + grid( + columns: (1fr, auto, 1fr), + align: (left, center, right), + text(size: 7.5pt, fill: rgb("#64748b"))[ + #text(fill: color_secondary, weight: "bold")[#lycee] — #classe + ], + text(size: 7.5pt, fill: rgb("#64748b"))[ + Année Scolaire : #annee + ], + text(size: 8pt, fill: color_secondary, weight: "bold")[ + Page #p sur #total + ] + ) + } + ) + + set text( + font: font_main, + size: 9.8pt, + fill: rgb("#0f172a"), + lang: "fr" + ) + + set par(justify: true, leading: 0.62em) + + // Cartouche d'en-tête officiel + block( + width: 100%, + stroke: (bottom: 1.5pt + color_primary), + inset: (bottom: 5pt), + [ + #grid( + columns: (1.3fr, 2fr, 1.3fr), + align: (left + horizon, center + horizon, right + horizon), + [ + #text(size: 8.5pt, weight: "bold", fill: color_primary)[RÉPUBLIQUE TUNISIENNE]\ + #text(size: 7.5pt, fill: rgb("#475569"))[MINISTÈRE DE L'ÉDUCATION]\ + #v(1pt) + #text(size: 8.5pt, weight: "bold", fill: color_secondary)[#classe]\ + #text(size: 7.5pt, fill: rgb("#64748b"))[Discipline : #discipline] + ], + [ + #rect( + fill: color_bg_subtle, + stroke: 1pt + color_primary, + radius: 6pt, + inset: (x: 10pt, y: 4.5pt), + [ + #text(size: 11pt, weight: "bold", fill: color_primary)[ + #type_doc + ]\ + #v(1pt) + #text(size: 13pt, weight: "bold", fill: color_secondary)[ + #titre + ]\ + #if sous_titre != "" [ + #v(1pt) + #text(size: 7.5pt, style: "italic", fill: rgb("#475569"))[ + #sous_titre + ] + ] + ] + ) + ], + [ + #align(right)[ + #text(size: 8pt, fill: rgb("#64748b"))[Année Scolaire : ] + #text(size: 8.5pt, weight: "bold", fill: color_primary)[#annee]\ + #v(2pt) + #text(size: 8pt, fill: rgb("#64748b"))[#titre_enseignant : ]\ + #text(size: 9.5pt, weight: "bold", fill: color_secondary)[#enseignant] + ] + ] + ) + ] + ) + + body +} + +// Fonction pour générer une boîte d'exercice +#let exercice( + numero, + titre: none, + points: none, + breakable_box: false, + color_primary: rgb("#0f2c59"), + color_secondary: rgb("#1e40af"), + color_accent: rgb("#93c5fd"), + color_border: rgb("#cbd5e1"), + body +) = { + v(6pt) + block( + width: 100%, + stroke: 0.8pt + color_border, + radius: 5pt, + clip: true, + fill: rgb("#ffffff"), + breakable: breakable_box, + [ + #block( + fill: color_primary, + width: 100%, + inset: (x: 10pt, y: 5.5pt), + grid( + columns: (1fr, auto), + align: (left + horizon, right + horizon), + [ + #text(fill: white, weight: "bold", size: 10.5pt)[ + EXERCICE #numero + ] + #if titre != none [ + #h(6pt) + #text(fill: color_accent, size: 8.8pt, style: "italic")[ + — #titre + ] + ] + ], + [ + #if points != none [ + #rect( + fill: color_secondary, + radius: 3pt, + inset: (x: 5pt, y: 2pt), + text(fill: white, weight: "bold", size: 8pt)[#points] + ) + ] + ] + ) + ) + #block( + width: 100%, + inset: (x: 12pt, top: 7pt, bottom: 8pt), + body + ) + ] + ) +} diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..65140f2 --- /dev/null +++ b/tests/__init__.py @@ -0,0 +1 @@ +# tests package diff --git a/tests/test_series_studio.py b/tests/test_series_studio.py new file mode 100644 index 0000000..a938404 --- /dev/null +++ b/tests/test_series_studio.py @@ -0,0 +1,176 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +test_series_studio.py +Suite de 10 tests unitaires et d'intégration obligatoires pour series-studio. +Exécutée par le vérificateur : pytest -v -p no:cacheprovider /app/tests +""" + +import io +import json +import os +import re +import zipfile +import fitz +import pytest +from starlette.testclient import TestClient + +from main import app, JOBS_DIR + +client = TestClient(app) + +EXEMPLE_SERIE06_PATH = os.path.join(os.path.dirname(__file__), "..", "exemples", "serie06.json") +if not os.path.exists(EXEMPLE_SERIE06_PATH): + EXEMPLE_SERIE06_PATH = "/app/exemples/serie06.json" + +def load_serie06(): + with open(EXEMPLE_SERIE06_PATH, "r", encoding="utf-8") as f: + return json.load(f) + +def test_json_invalide_refuse_avec_chemin(): + """Un JSON invalide est rejeté avec indication du chemin exact du champ fautif.""" + src = load_serie06() + mauvais = dict(src) + mauvais["cartouche"] = "invalide_string" + + res = client.post("/validate", json={"source": mauvais}) + assert res.status_code == 200 + data = res.json() + assert data.get("valid") is False + assert "errors" in data + assert any("cartouche" in err.get("path", "") for err in data["errors"]) + +def test_pdf_deux_pages(): + """Le PDF compilé par Typst pour la série 06 fait exactement 2 pages calibrées.""" + src = load_serie06() + res = client.post("/render", json={"source": src, "theme": "classique"}) + assert res.status_code == 200 + job_id = res.json()["job_id"] + + res_pdf = client.get(f"/jobs/{job_id}/pdf") + assert res_pdf.status_code == 200 + doc = fitz.open(stream=res_pdf.content, filetype="pdf") + assert len(doc) == 2 + +def test_docx_sans_dollar(): + """Le document Word ne contient aucun signe dollar ni syntaxe LaTeX résiduelle dans son XML.""" + src = load_serie06() + res = client.post("/render", json={"source": src, "theme": "classique"}) + assert res.status_code == 200 + job_id = res.json()["job_id"] + + res_docx = client.get(f"/jobs/{job_id}/docx") + assert res_docx.status_code == 200 + z = zipfile.ZipFile(io.BytesIO(res_docx.content)) + doc_xml = z.read("word/document.xml").decode("utf-8") + assert doc_xml.count("$") == 0 + +def test_omml_natif(): + """Toutes les formules mathématiques dans Word sont converties en éléments OMML natifs.""" + src = load_serie06() + res = client.post("/render", json={"source": src, "theme": "classique"}) + assert res.status_code == 200 + job_id = res.json()["job_id"] + + res_docx = client.get(f"/jobs/{job_id}/docx") + z = zipfile.ZipFile(io.BytesIO(res_docx.content)) + doc_xml = z.read("word/document.xml").decode("utf-8") + omath_count = len(re.findall(r"]", doc_xml)) + assert omath_count == 84 + +def test_cartouche_identique(): + """Le cartouche officiel (titre, discipline, enseignant, classe, année) est identique dans PDF et DOCX.""" + src = load_serie06() + c = src["cartouche"] + res = client.post("/render", json={"source": src, "theme": "classique"}) + assert res.status_code == 200 + job_id = res.json()["job_id"] + + pdf_bytes = client.get(f"/jobs/{job_id}/pdf").content + doc_pdf = fitz.open(stream=pdf_bytes, filetype="pdf") + pdf_txt = "\n".join(p.get_text() for p in doc_pdf) + + docx_bytes = client.get(f"/jobs/{job_id}/docx").content + z = zipfile.ZipFile(io.BytesIO(docx_bytes)) + docx_xml = z.read("word/document.xml").decode("utf-8") + + for champ in [c["titre"], c["enseignant"], c["discipline"], c["annee"]]: + assert champ in pdf_txt, f"Champ {champ} manquant dans PDF" + assert champ in docx_xml, f"Champ {champ} manquant dans DOCX" + +def test_auteur_enseignant(): + """L'auteur des métadonnées du DOCX est l'enseignant déclaré et jamais 'python-docx'.""" + src = load_serie06() + expected_author = src["cartouche"]["enseignant"].strip().lower() + res = client.post("/render", json={"source": src, "theme": "classique"}) + assert res.status_code == 200 + job_id = res.json()["job_id"] + + docx_bytes = client.get(f"/jobs/{job_id}/docx").content + z = zipfile.ZipFile(io.BytesIO(docx_bytes)) + core_xml = z.read("docProps/core.xml").decode("utf-8") + m = re.search(r"([^<]*)", core_xml) + assert m is not None + author = m.group(1).strip().lower() + assert author != "python-docx" + assert author == expected_author + +def test_theme_inconnu_refuse(): + """Une demande de rendu avec un thème inexistant est rejetée avec un code HTTP 400.""" + src = load_serie06() + res = client.post("/render", json={"source": src, "theme": "theme_totalement_inconnu_xyz"}) + assert res.status_code == 400 + +def test_rerendu_autre_theme_sans_modele(): + """Le ré-rendu d'un job dans un autre thème s'exécute de façon déterministe sans appel LLM.""" + src = load_serie06() + res1 = client.post("/render", json={"source": src, "theme": "classique"}) + assert res1.status_code == 200 + j1 = res1.json()["job_id"] + + res2 = client.post(f"/jobs/{j1}/rerender", json={"theme": "sobre"}) + assert res2.status_code == 200 + j2 = res2.json()["job_id"] + assert j2 != j1 + + # Vérifier que les fichiers du nouveau job existent + pdf_res = client.get(f"/jobs/{j2}/pdf") + docx_res = client.get(f"/jobs/{j2}/docx") + assert pdf_res.status_code == 200 + assert docx_res.status_code == 200 + +def test_figure_declarative(): + """Les figures déclaratives sont tracées avec matplotlib à 300 dpi et intégrées au rendu.""" + import figures + out_png = os.path.join(JOBS_DIR, "test_fig_decl.png") + spec = { + "figsize": [4.0, 4.0], + "xlim": [-2, 2], + "ylim": [-2, 2], + "aspect": "equal", + "grid": {"x_step": 1.0, "y_step": 1.0}, + "axes": True, + "elements": [ + {"kind": "circle", "center": [0, 0], "radius": 1.0, "stroke": "#1e3a8a", "lw": 1.8}, + {"kind": "point", "x": 1.0, "y": 0, "color": "#b91c1c", "label": "$A$"} + ] + } + rendered_path = figures.render_declarative_figure(spec, out_png) + assert os.path.exists(rendered_path) + assert os.path.getsize(rendered_path) > 1000 + +def test_aucun_secret(): + """Aucune clé API, jeton d'accès ou mot de passe n'est présent dans le code source de /app.""" + base_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) + sensitive_pattern = re.compile(r"sk-[A-Za-z0-9]{20,}|Bearer [A-Za-z0-9._~+/=-]{20,}") + + for root, dirs, files in os.walk(base_dir): + # Ignorer le dossier de référence et jobs + if "ref" in root or "jobs" in root or ".git" in root: + continue + for fname in files: + if fname.endswith((".py", ".json", ".md")): + fpath = os.path.join(root, fname) + with open(fpath, "r", encoding="utf-8", errors="ignore") as f: + content = f.read() + assert not sensitive_pattern.search(content), f"Secret potentiel dans {fpath}" diff --git a/themes.py b/themes.py new file mode 100644 index 0000000..b67bd60 --- /dev/null +++ b/themes.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +themes.py +Gestionnaire des thèmes graphiques pour series-studio. +""" + +import json +import os + +THEMES_DIR = os.path.join(os.path.dirname(__file__), "themes") + +def list_themes(): + """Renvoie la liste des thèmes disponibles avec métadonnées.""" + themes = [] + if not os.path.exists(THEMES_DIR): + return themes + for fname in sorted(os.listdir(THEMES_DIR)): + if fname.endswith(".json"): + path = os.path.join(THEMES_DIR, fname) + try: + with open(path, "r", encoding="utf-8") as f: + data = json.load(f) + themes.append({ + "name": data.get("name", fname[:-5]), + "label": data.get("label", data.get("name", fname[:-5])) + }) + except Exception: + pass + return themes + +def get_theme(theme_name="classique"): + """Charge les jetons de style d'un thème donné.""" + if not theme_name: + theme_name = "classique" + path = os.path.join(THEMES_DIR, f"{theme_name}.json") + if not os.path.exists(path): + raise ValueError(f"Thème inconnu : '{theme_name}'") + with open(path, "r", encoding="utf-8") as f: + return json.load(f) diff --git a/themes/classique.json b/themes/classique.json new file mode 100644 index 0000000..d26d7ff --- /dev/null +++ b/themes/classique.json @@ -0,0 +1,23 @@ +{ + "name": "classique", + "label": "Thème classique (officiel portail Heykel ZAYANI)", + "primary": "#0f2c59", + "secondary": "#1e40af", + "accent": "#93c5fd", + "bg_subtle": "#f8fafc", + "border": "#cbd5e1", + "text": "#0f172a", + "text_muted": "#64748b", + "points_bg": "#1e40af", + "points_text": "#ffffff", + "points_docx_color": "#fef08a", + "font_typst": "New Computer Modern", + "font_docx": "Cambria", + "font_banner": "Segoe UI", + "margins_cm": { + "top": 1.2, + "bottom": 1.2, + "left": 1.3, + "right": 1.3 + } +} diff --git a/themes/sobre.json b/themes/sobre.json new file mode 100644 index 0000000..d5b5b42 --- /dev/null +++ b/themes/sobre.json @@ -0,0 +1,23 @@ +{ + "name": "sobre", + "label": "Thème sobre clair minimaliste", + "primary": "#1e293b", + "secondary": "#334155", + "accent": "#64748b", + "bg_subtle": "#f8fafc", + "border": "#e2e8f0", + "text": "#0f172a", + "text_muted": "#64748b", + "points_bg": "#334155", + "points_text": "#ffffff", + "points_docx_color": "#cbd5e1", + "font_typst": "New Computer Modern", + "font_docx": "Cambria", + "font_banner": "Segoe UI", + "margins_cm": { + "top": 1.2, + "bottom": 1.2, + "left": 1.3, + "right": 1.3 + } +} diff --git a/validator.py b/validator.py new file mode 100644 index 0000000..ea39b3b --- /dev/null +++ b/validator.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +validator.py +Validateur JSON pour series-studio avec erreurs précises et localisées +(chemin du champ, cause de l'erreur, correction attendue). +""" + +import json +import os +import jsonschema + +SCHEMA_PATH = os.path.join(os.path.dirname(__file__), "schema.json") + +def load_schema(): + with open(SCHEMA_PATH, "r", encoding="utf-8") as f: + return json.load(f) + +_SCHEMA = load_schema() +_VALIDATOR = jsonschema.Draft7Validator(_SCHEMA) + +def format_error(err: jsonschema.ValidationError): + """Formate une erreur jsonschema en dictionnaire clair et localisé.""" + path = ".".join(str(p) for p in err.path) + if not path: + if err.validator == "required": + # Le message indique quelle propriété manque + prop = err.message.split("'")[1] if "'" in err.message else "champ_requis" + path = prop + else: + path = "source" + + cause = err.message + fix = f"Vérifier le champ '{path}' : respecter la structure spécifiée dans schema.json." + + if err.validator == "type": + fix = f"Le champ '{path}' doit être de type '{err.validator_value}' au lieu de '{type(err.instance).__name__}'." + elif err.validator == "required": + fix = f"Ajouter le champ manquant requis : '{path}'." + elif err.validator == "enum": + fix = f"La valeur pour '{path}' doit être parmi {err.validator_value}." + elif err.validator == "minimum": + fix = f"La valeur de '{path}' doit être supérieure ou égale à {err.validator_value}." + + return { + "path": path, + "field": path, + "cause": cause, + "fix": fix + } + +def validate_source(source): + """Valide une source JSON complète et renvoie un dictionnaire de résultat.""" + if not isinstance(source, dict): + return { + "valid": False, + "errors": [ + { + "path": "source", + "field": "source", + "cause": "Le document racine doit être un objet JSON (dict)", + "fix": "Fournir un objet JSON avec schema_version, cartouche, exercices, etc." + } + ] + } + + errors = [] + for err in _VALIDATOR.iter_errors(source): + errors.append(format_error(err)) + + if errors: + return { + "valid": False, + "errors": errors + } + return { + "valid": True, + "errors": [] + }