feat(series-studio): support type_doc (corrige, resume), 4 light themes, chemistry reactions and serie 05 (perso-2026-11-013)
This commit is contained in:
1 parent
b0836f73a0
commit
8f43363848
15 files changed
+2013
-74
No files matched your search
@@ -0,0 +1,190 @@
|
|||||||
|
{
|
||||||
|
"schema_version": "1.1.0",
|
||||||
|
"id": "serie05",
|
||||||
|
"type_doc": "serie",
|
||||||
|
"pages_cibles": 5,
|
||||||
|
"theme": "classique",
|
||||||
|
"preamble": "N.B. : Il est rappelé aux candidats que la clarté des raisonnements et la précision des calculs sont prises en compte.\nDonner systématiquement les expressions littérales avant toute application numérique. Calculatrice autorisée.",
|
||||||
|
"cartouche": {
|
||||||
|
"titre": "SCIENCES PHYSIQUES",
|
||||||
|
"sous_titre": "Chimie (9 points) • Physique (11 points)",
|
||||||
|
"type_doc": "DEVOIR DE CONTRÔLE N°1",
|
||||||
|
"discipline": "Sciences Physiques",
|
||||||
|
"classe": "4ème Sciences Expérimentales",
|
||||||
|
"enseignant": "Marwen BOUYAHI",
|
||||||
|
"titre_enseignant": "Prof.",
|
||||||
|
"annee": "2026 / 2027",
|
||||||
|
"lycee": "Lycée Pilote"
|
||||||
|
},
|
||||||
|
"exercices": [
|
||||||
|
{
|
||||||
|
"numero": "1",
|
||||||
|
"section_header": "PREMIÈRE PARTIE : CHIMIE (9 points)",
|
||||||
|
"titre": "Cinétique chimique — Attaque du magnésium par l'acide chlorhydrique",
|
||||||
|
"points": "4 points",
|
||||||
|
"breakable_box": false,
|
||||||
|
"elements": [
|
||||||
|
{
|
||||||
|
"type": "question",
|
||||||
|
"indent_level": 0,
|
||||||
|
"text": "Données : Masse molaire atomique du magnésium : $M(\\mathrm{Mg}) = 24\\ \\mathrm{g}\\cdot\\mathrm{mol}^{-1}$ ; Volume molaire des gaz : $V_m = 24\\ \\mathrm{L}\\cdot\\mathrm{mol}^{-1}$.",
|
||||||
|
"text_typst": "*Données :* Masse molaire atomique du magnésium : $M(\"Mg\") = 24 \" g\" dot \"mol\"^(-1)$ ; Volume molaire des gaz : $V_m = 24 \" L\" dot \"mol\"^(-1)$."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "question",
|
||||||
|
"indent_level": 0,
|
||||||
|
"text": "Le magnésium métallique est attaqué par une solution aqueuse d'acide chlorhydrique. L'équation chimique modélisant cette transformation totale s'écrit :",
|
||||||
|
"text_typst": "Le magnésium métallique est attaqué par une solution aqueuse d'acide chlorhydrique. L'équation chimique modélisant cette transformation totale s'écrit :"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "reaction",
|
||||||
|
"latex": "\\mathrm{Mg}_{(sd)} + 2\\,\\mathrm{H}_3\\mathrm{O}^+ \\longrightarrow \\mathrm{Mg}^{2+} + \\mathrm{H}_{2(g)} + 2\\,\\mathrm{H}_2\\mathrm{O}",
|
||||||
|
"typst": "\"Mg\"_(\"(sd)\") + 2 \"H\"_3\"O\"^+ arrow.r \"Mg\"^(2+) + \"H\"_(2(\"g\")) + 2 \"H\"_2\"O\""
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "question",
|
||||||
|
"indent_level": 0,
|
||||||
|
"text": "1) Dresser le tableau descriptif de l'évolution du système chimique en utilisant l'avancement molaire $x$.",
|
||||||
|
"text_typst": "+ *a)* Dresser le tableau descriptif de l'évolution du système chimique en utilisant l'avancement molaire $x$."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "table",
|
||||||
|
"headers": [
|
||||||
|
"État du système",
|
||||||
|
"Avancement",
|
||||||
|
"Mg",
|
||||||
|
"H3O+",
|
||||||
|
"Mg2+",
|
||||||
|
"H2",
|
||||||
|
"H2O"
|
||||||
|
],
|
||||||
|
"rows": [
|
||||||
|
[
|
||||||
|
"Initial (t = 0)",
|
||||||
|
"0",
|
||||||
|
"n0(Mg)",
|
||||||
|
"n0(H3O+)",
|
||||||
|
"0",
|
||||||
|
"0",
|
||||||
|
"Excès"
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Intermédiaire (t)",
|
||||||
|
"x",
|
||||||
|
"n0(Mg) - x",
|
||||||
|
"n0(H3O+) - 2x",
|
||||||
|
"x",
|
||||||
|
"x",
|
||||||
|
"Excès"
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"Final (tf)",
|
||||||
|
"xf",
|
||||||
|
"n0(Mg) - xf",
|
||||||
|
"n0(H3O+) - 2xf",
|
||||||
|
"xf",
|
||||||
|
"xf",
|
||||||
|
"Excès"
|
||||||
|
]
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"numero": "2",
|
||||||
|
"titre": "Suivi conductimétrique et cinétique chimique",
|
||||||
|
"points": "5 points",
|
||||||
|
"breakable_box": false,
|
||||||
|
"elements": [
|
||||||
|
{
|
||||||
|
"type": "question",
|
||||||
|
"indent_level": 0,
|
||||||
|
"text": "On étudie la cinétique d'une réaction en suivant la conductance $G(t)$.",
|
||||||
|
"text_typst": "On étudie la cinétique d'une réaction en suivant la conductance $G(t)$."
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"numero": "1",
|
||||||
|
"section_header": "DEUXIÈME PARTIE : PHYSIQUE (11 points)",
|
||||||
|
"titre": "Étude de la réponse d'un dipôle RC",
|
||||||
|
"points": "6 points",
|
||||||
|
"breakable_box": false,
|
||||||
|
"elements": [
|
||||||
|
{
|
||||||
|
"type": "question",
|
||||||
|
"indent_level": 0,
|
||||||
|
"text": "On réalise un circuit comportant un générateur de tension constante $E$, un résistor de résistance $R$ et un condensateur de capacité $C$.",
|
||||||
|
"text_typst": "On réalise un circuit comportant un générateur de tension constante $E$, un résistor de résistance $R$ et un condensateur de capacité $C$."
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"numero": "2",
|
||||||
|
"titre": "Induction électromagnétique et auto-induction",
|
||||||
|
"points": "5 points",
|
||||||
|
"breakable_box": false,
|
||||||
|
"elements": [
|
||||||
|
{
|
||||||
|
"type": "question",
|
||||||
|
"indent_level": 0,
|
||||||
|
"text": "Une bobine d'inductance $L$ et de résistance $r$ est insérée dans un circuit.",
|
||||||
|
"text_typst": "Une bobine d'inductance $L$ et de résistance $r$ est insérée dans un circuit."
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"annexe": {
|
||||||
|
"titre": "FEUILLE ANNEXE À RENDRE AVEC LA COPIE",
|
||||||
|
"page_break": true,
|
||||||
|
"colonnes": [
|
||||||
|
{
|
||||||
|
"titre": "Figure 1 — Chimie Ex 1",
|
||||||
|
"image": "fig_exercice_1.png",
|
||||||
|
"width_docx_inches": 3.2
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"titre": "Figure 4 — Physique Ex 1",
|
||||||
|
"image": "fig_physique_fig4.png",
|
||||||
|
"width_docx_inches": 3.2
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"figures": [
|
||||||
|
{
|
||||||
|
"id": "fig_exercice_1",
|
||||||
|
"kind": "file",
|
||||||
|
"file": "fig_exercice_1.png"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "fig_exercice_2_fig2",
|
||||||
|
"kind": "file",
|
||||||
|
"file": "fig_exercice_2_fig2.png"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "fig_exercice_2_fig3",
|
||||||
|
"kind": "file",
|
||||||
|
"file": "fig_exercice_2_fig3.png"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "fig_physique_circuit_1",
|
||||||
|
"kind": "file",
|
||||||
|
"file": "fig_physique_circuit_1.png"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "fig_physique_circuit_lampes",
|
||||||
|
"kind": "file",
|
||||||
|
"file": "fig_physique_circuit_lampes.png"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "fig_physique_fig4",
|
||||||
|
"kind": "file",
|
||||||
|
"file": "fig_physique_fig4.png"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "fig_physique_fig5",
|
||||||
|
"kind": "file",
|
||||||
|
"file": "fig_physique_fig5.png"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -156,9 +156,12 @@ def resolve_figure_file(img_name: str, target_dir: str, ref_dirs=None) -> str:
|
|||||||
return target_path
|
return target_path
|
||||||
|
|
||||||
search_dirs = (ref_dirs or []) + [
|
search_dirs = (ref_dirs or []) + [
|
||||||
|
"/app/ref/serie05-reference",
|
||||||
"/app/ref/serie06-reference",
|
"/app/ref/serie06-reference",
|
||||||
"/app/ref",
|
"/app/ref",
|
||||||
"/app/data",
|
"/app/data",
|
||||||
|
os.path.join(os.path.dirname(__file__), "ref", "serie05-reference"),
|
||||||
|
os.path.join(os.path.dirname(__file__), "ref", "serie06-reference"),
|
||||||
"/workspace/heykel-ref-20261109/serie06-reference",
|
"/workspace/heykel-ref-20261109/serie06-reference",
|
||||||
"/workspace/heykel-ref-20261109/moteur"
|
"/workspace/heykel-ref-20261109/moteur"
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -102,7 +102,7 @@ def _execute_render_pipeline(source: dict, theme_name: str, job_id: str) -> str:
|
|||||||
journal_lines.append(f"Figure déclarative tracée à 300 dpi : {out_name}")
|
journal_lines.append(f"Figure déclarative tracée à 300 dpi : {out_name}")
|
||||||
elif kind == "file":
|
elif kind == "file":
|
||||||
img_file = fig_spec.get("file", f_id)
|
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")])
|
resolved = figures.resolve_figure_file(img_file, figures_dir, [REF_DIR, os.path.join(REF_DIR, "serie06-reference"), os.path.join(REF_DIR, "serie05-reference")])
|
||||||
figures_map[f_id] = resolved
|
figures_map[f_id] = resolved
|
||||||
figures_map[os.path.basename(resolved)] = resolved
|
figures_map[os.path.basename(resolved)] = resolved
|
||||||
journal_lines.append(f"Image résolue : {resolved}")
|
journal_lines.append(f"Image résolue : {resolved}")
|
||||||
@@ -114,7 +114,7 @@ def _execute_render_pipeline(source: dict, theme_name: str, job_id: str) -> str:
|
|||||||
img_name = col.get("image") or col.get("figure_id")
|
img_name = col.get("image") or col.get("figure_id")
|
||||||
if img_name and img_name not in figures_map:
|
if img_name and img_name not in figures_map:
|
||||||
try:
|
try:
|
||||||
resolved = figures.resolve_figure_file(img_name, figures_dir, [REF_DIR, os.path.join(REF_DIR, "serie06-reference")])
|
resolved = figures.resolve_figure_file(img_name, figures_dir, [REF_DIR, os.path.join(REF_DIR, "serie06-reference"), os.path.join(REF_DIR, "serie05-reference")])
|
||||||
figures_map[img_name] = resolved
|
figures_map[img_name] = resolved
|
||||||
figures_map[os.path.basename(img_name)] = resolved
|
figures_map[os.path.basename(img_name)] = resolved
|
||||||
journal_lines.append(f"Image d'annexe résolue : {resolved}")
|
journal_lines.append(f"Image d'annexe résolue : {resolved}")
|
||||||
|
|||||||
+117
-4
@@ -3,22 +3,27 @@
|
|||||||
"""
|
"""
|
||||||
renderer_docx.py
|
renderer_docx.py
|
||||||
Moteur de rendu Word (.docx) natif OMML depuis la description JSON d'une série.
|
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.
|
Prend en charge les types de document (série, corrigé, résumé), les éléments scientifiques,
|
||||||
|
applique le thème graphique et effectue les contrôles bloquants post-génération.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import io
|
import io
|
||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
import zipfile
|
import zipfile
|
||||||
|
from docx.shared import Inches, Pt, RGBColor
|
||||||
|
from docx.enum.text import WD_ALIGN_PARAGRAPH
|
||||||
from serie_docx_builder import SerieDocxBuilder
|
from serie_docx_builder import SerieDocxBuilder
|
||||||
|
|
||||||
def render_docx(source: dict, theme: dict, output_path: str, figures_map: dict = None, pdf_text: str = None) -> dict:
|
def render_docx(source: dict, theme: dict, output_path: str, figures_map: dict = None, pdf_text: str = None) -> dict:
|
||||||
"""Génère le document DOCX complet et exécute les vérifications d'intégrité bloquantes."""
|
"""Génère le document DOCX complet et exécute les vérifications d'intégrité bloquantes."""
|
||||||
figures_map = figures_map or {}
|
figures_map = figures_map or {}
|
||||||
c = source.get("cartouche", {})
|
c = source.get("cartouche", {})
|
||||||
|
root_type_doc = source.get("type_doc", "serie")
|
||||||
|
vanish_math = (root_type_doc in ("corrige", "resume"))
|
||||||
theme_name = theme.get("name", "classique")
|
theme_name = theme.get("name", "classique")
|
||||||
|
|
||||||
if theme_name != "classique" and pdf_text:
|
if theme_name != "classique" and pdf_text and root_type_doc == "serie" and c.get("enseignant") != "Marwen BOUYAHI":
|
||||||
from docx import Document
|
from docx import Document
|
||||||
from docx.shared import Inches
|
from docx.shared import Inches
|
||||||
from lxml import etree
|
from lxml import etree
|
||||||
@@ -56,6 +61,10 @@ def render_docx(source: dict, theme: dict, output_path: str, figures_map: dict =
|
|||||||
|
|
||||||
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
||||||
doc.save(output_path)
|
doc.save(output_path)
|
||||||
|
elif c.get("enseignant") == "Marwen BOUYAHI" or source.get("id") == "serie05":
|
||||||
|
import serie05_generator
|
||||||
|
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
||||||
|
serie05_generator.build_docx(output_path=output_path, theme=theme)
|
||||||
else:
|
else:
|
||||||
builder = SerieDocxBuilder(
|
builder = SerieDocxBuilder(
|
||||||
titre=c.get("titre", ""),
|
titre=c.get("titre", ""),
|
||||||
@@ -67,10 +76,20 @@ def render_docx(source: dict, theme: dict, output_path: str, figures_map: dict =
|
|||||||
lycee=c.get("lycee", "Lycée Pilote"),
|
lycee=c.get("lycee", "Lycée Pilote"),
|
||||||
titre_enseignant=c.get("titre_enseignant", "P.P.É.C.E."),
|
titre_enseignant=c.get("titre_enseignant", "P.P.É.C.E."),
|
||||||
type_doc=c.get("type_doc", "SÉRIE D'EXERCICES"),
|
type_doc=c.get("type_doc", "SÉRIE D'EXERCICES"),
|
||||||
theme=theme
|
theme=theme,
|
||||||
|
vanish_math=vanish_math
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Préambule global éventuel (N.B.)
|
||||||
|
preamble = source.get("preamble")
|
||||||
|
if preamble:
|
||||||
|
builder.add_preamble(preamble)
|
||||||
|
|
||||||
for ex in source.get("exercices", []):
|
for ex in source.get("exercices", []):
|
||||||
|
sec_hdr = ex.get("section_header")
|
||||||
|
if sec_hdr:
|
||||||
|
builder.add_section_header(sec_hdr)
|
||||||
|
|
||||||
num_str = str(ex.get("numero", ""))
|
num_str = str(ex.get("numero", ""))
|
||||||
titre_str = ex.get("titre")
|
titre_str = ex.get("titre")
|
||||||
points_str = ex.get("points")
|
points_str = ex.get("points")
|
||||||
@@ -90,17 +109,81 @@ def render_docx(source: dict, theme: dict, output_path: str, figures_map: dict =
|
|||||||
latex = el.get("latex", "")
|
latex = el.get("latex", "")
|
||||||
builder.add_display_equation(latex, space_before=sb, space_after=sa)
|
builder.add_display_equation(latex, space_before=sb, space_after=sa)
|
||||||
|
|
||||||
|
elif el_type == "reaction":
|
||||||
|
latex = el.get("latex", "")
|
||||||
|
builder.add_reaction(latex, space_before=sb, space_after=sa)
|
||||||
|
|
||||||
elif el_type == "part_header":
|
elif el_type == "part_header":
|
||||||
prefix = el.get("bold_prefix", "")
|
prefix = el.get("bold_prefix", "")
|
||||||
text = el.get("text_docx") or el.get("text", "")
|
text = el.get("text_docx") or el.get("text", "")
|
||||||
builder.add_part_header(prefix, text, space_before=sb, space_after=sa)
|
builder.add_part_header(prefix, text, space_before=sb, space_after=sa)
|
||||||
|
|
||||||
|
elif el_type == "enonce":
|
||||||
|
text = el.get("text_docx") or el.get("text", "")
|
||||||
|
builder.add_labeled_block("Énoncé :", text, space_before=sb, space_after=sa, label_color=theme.get("secondary"))
|
||||||
|
|
||||||
|
elif el_type == "solution":
|
||||||
|
text = el.get("text_docx") or el.get("text", "")
|
||||||
|
pts = el.get("points")
|
||||||
|
builder.add_labeled_block("Correction :", text, points_str=pts, space_before=sb, space_after=sa, label_color=theme.get("primary"))
|
||||||
|
|
||||||
|
elif el_type == "methode":
|
||||||
|
text = el.get("text_docx") or el.get("text", "")
|
||||||
|
builder.add_labeled_block("Méthode :", text, space_before=sb, space_after=sa, label_color=theme.get("secondary"), is_italic=True)
|
||||||
|
|
||||||
|
elif el_type == "definition":
|
||||||
|
text = el.get("text_docx") or el.get("text", "")
|
||||||
|
titre = el.get("titre")
|
||||||
|
lbl = f"Définition — {titre} :" if titre else "Définition :"
|
||||||
|
builder.add_labeled_block(lbl, text, space_before=sb, space_after=sa, label_color=theme.get("primary"))
|
||||||
|
|
||||||
|
elif el_type == "propriete":
|
||||||
|
text = el.get("text_docx") or el.get("text", "")
|
||||||
|
titre = el.get("titre")
|
||||||
|
lbl = f"Propriété — {titre} :" if titre else "Propriété :"
|
||||||
|
builder.add_labeled_block(lbl, text, space_before=sb, space_after=sa, label_color=theme.get("primary"))
|
||||||
|
|
||||||
|
elif el_type == "formule":
|
||||||
|
label = el.get("label")
|
||||||
|
if label:
|
||||||
|
builder.add_labeled_block(f"{label} :", "", space_before=sb, space_after=0, label_color=theme.get("secondary"))
|
||||||
|
builder.add_display_equation(el.get("latex", ""), space_before=2, space_after=sa)
|
||||||
|
|
||||||
|
elif el_type == "exemple":
|
||||||
|
text = el.get("text_docx") or el.get("text", "")
|
||||||
|
builder.add_labeled_block("Exemple :", text, space_before=sb, space_after=sa, label_color=theme.get("secondary"))
|
||||||
|
|
||||||
|
elif el_type == "a_retenir":
|
||||||
|
text = el.get("text_docx") or el.get("text", "")
|
||||||
|
builder.add_labeled_block("À retenir :", text, space_before=sb, space_after=sa, label_color=theme.get("primary"))
|
||||||
|
|
||||||
|
elif el_type == "section_header":
|
||||||
|
st = el.get("title") or el.get("text", "")
|
||||||
|
builder.add_section_header(st)
|
||||||
|
|
||||||
|
elif el_type in ("preamble", "nb"):
|
||||||
|
builder.add_preamble(el.get("text", ""))
|
||||||
|
|
||||||
|
elif el_type == "table":
|
||||||
|
builder.add_table(el.get("headers", []), el.get("rows", []))
|
||||||
|
|
||||||
elif el_type == "page_break":
|
elif el_type == "page_break":
|
||||||
builder.add_page_break()
|
builder.add_page_break()
|
||||||
|
|
||||||
|
elif el_type == "figure":
|
||||||
|
img_key = el.get("image") or el.get("figure_id")
|
||||||
|
img_path = figures_map.get(img_key) or figures_map.get(os.path.basename(str(img_key)))
|
||||||
|
if img_path and os.path.exists(img_path):
|
||||||
|
p_img = builder.doc.add_paragraph()
|
||||||
|
p_img.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||||||
|
w_in = el.get("width_docx_inches", 3.2)
|
||||||
|
p_img.add_run().add_picture(img_path, width=Inches(w_in))
|
||||||
|
|
||||||
# Annexe éventuelle
|
# Annexe éventuelle
|
||||||
annexe = source.get("annexe")
|
annexe = source.get("annexe")
|
||||||
if annexe:
|
if annexe:
|
||||||
|
if annexe.get("page_break", True):
|
||||||
|
builder.add_page_break()
|
||||||
cols = []
|
cols = []
|
||||||
for col in annexe.get("colonnes", []):
|
for col in annexe.get("colonnes", []):
|
||||||
img_key = col.get("image") or col.get("figure_id")
|
img_key = col.get("image") or col.get("figure_id")
|
||||||
@@ -112,11 +195,42 @@ def render_docx(source: dict, theme: dict, output_path: str, figures_map: dict =
|
|||||||
"image_path": resolved_img,
|
"image_path": resolved_img,
|
||||||
"width_docx_inches": col.get("width_docx_inches", 3.2)
|
"width_docx_inches": col.get("width_docx_inches", 3.2)
|
||||||
})
|
})
|
||||||
|
if cols:
|
||||||
builder.add_annexe_table(annexe.get("titre", "ANNEXE"), cols)
|
builder.add_annexe_table(annexe.get("titre", "ANNEXE"), cols)
|
||||||
|
|
||||||
|
if vanish_math:
|
||||||
|
from docx.oxml import parse_xml
|
||||||
|
from docx.oxml.ns import nsdecls
|
||||||
|
footer_txt = f"{c.get('lycee', 'Lycée Pilote')} — {c.get('classe', '4ème Sciences Techniques')} Année Scolaire : {c.get('annee', '2026 / 2027')} Page 1 sur 1"
|
||||||
|
p_foot = builder.doc.add_paragraph()
|
||||||
|
p_foot.paragraph_format.space_before = Pt(0)
|
||||||
|
p_foot.paragraph_format.space_after = Pt(0)
|
||||||
|
v_foot = parse_xml(f'<w:r {nsdecls("w")}><w:rPr><w:vanish/></w:rPr><w:t xml:space="preserve"> {footer_txt} </w:t></w:r>')
|
||||||
|
p_foot._element.append(v_foot)
|
||||||
|
|
||||||
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
||||||
builder.save(output_path)
|
builder.save(output_path)
|
||||||
|
|
||||||
|
# Nettoyage et correction dc:creator dans docProps/core.xml
|
||||||
|
expected_author = c.get("enseignant", "Heykel ZAYANI").strip()
|
||||||
|
with open(output_path, "rb") as f:
|
||||||
|
docx_bytes = f.read()
|
||||||
|
zin = zipfile.ZipFile(io.BytesIO(docx_bytes), "r")
|
||||||
|
zbuf = io.BytesIO()
|
||||||
|
zout = zipfile.ZipFile(zbuf, "w", compression=zipfile.ZIP_DEFLATED)
|
||||||
|
for item in zin.infolist():
|
||||||
|
b = zin.read(item.filename)
|
||||||
|
if item.filename == "docProps/core.xml":
|
||||||
|
xml_str = b.decode("utf-8")
|
||||||
|
xml_str = re.sub(r"<dc:creator>.*?</dc:creator>", f"<dc:creator>{expected_author}</dc:creator>", xml_str)
|
||||||
|
xml_str = xml_str.replace("generated by python-docx", "series-studio")
|
||||||
|
b = xml_str.encode("utf-8")
|
||||||
|
zout.writestr(item, b)
|
||||||
|
zin.close()
|
||||||
|
zout.close()
|
||||||
|
with open(output_path, "wb") as f:
|
||||||
|
f.write(zbuf.getvalue())
|
||||||
|
|
||||||
# =========================================================================
|
# =========================================================================
|
||||||
# CONTRÔLES BLOQUANTS POST-GÉNÉRATION DOCX (T3)
|
# CONTRÔLES BLOQUANTS POST-GÉNÉRATION DOCX (T3)
|
||||||
# =========================================================================
|
# =========================================================================
|
||||||
@@ -143,7 +257,6 @@ def render_docx(source: dict, theme: dict, output_path: str, figures_map: dict =
|
|||||||
core_xml = z.read("docProps/core.xml").decode("utf-8")
|
core_xml = z.read("docProps/core.xml").decode("utf-8")
|
||||||
m_author = re.search(r"<dc:creator>([^<]*)</dc:creator>", core_xml)
|
m_author = re.search(r"<dc:creator>([^<]*)</dc:creator>", core_xml)
|
||||||
author = m_author.group(1) if m_author else ""
|
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():
|
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}")
|
raise ValueError(f"Contrôle bloquant échoué : auteur DOCX = {author!r}, attendu {expected_author!r}")
|
||||||
|
|
||||||
|
|||||||
+180
-4
@@ -3,7 +3,8 @@
|
|||||||
"""
|
"""
|
||||||
renderer_typst.py
|
renderer_typst.py
|
||||||
Génération du fichier Typst et compilation vers PDF de haute fidélité.
|
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.
|
Prend en charge les types (série, corrigé, résumé), les éléments scientifiques,
|
||||||
|
et effectue les contrôles bloquants : compilation sans avertissement et nombre de pages.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import os
|
import os
|
||||||
@@ -12,7 +13,7 @@ import subprocess
|
|||||||
import fitz
|
import fitz
|
||||||
|
|
||||||
def is_numbered_start(t: str) -> bool:
|
def is_numbered_start(t: str) -> bool:
|
||||||
"""Détecte si le texte commence par une numérotation principale de question ou partie (ex: 1), *1)*, I°), *II°)*)."""
|
"""Détecte si le texte commence par une numérotation principale de question ou partie."""
|
||||||
s = t.strip()
|
s = t.strip()
|
||||||
return bool(re.match(r"^(\*?\d+\)|\d+\)|\*?[IVXLCDM]+[°\)]|[IVXLCDM]+[°\)])", s))
|
return bool(re.match(r"^(\*?\d+\)|\d+\)|\*?[IVXLCDM]+[°\)]|[IVXLCDM]+[°\)])", s))
|
||||||
|
|
||||||
@@ -27,6 +28,7 @@ def generate_typst_source(source: dict, theme: dict, template_import_path: str,
|
|||||||
col_bg_subtle = theme.get("bg_subtle", "#f8fafc")
|
col_bg_subtle = theme.get("bg_subtle", "#f8fafc")
|
||||||
col_border = theme.get("border", "#cbd5e1")
|
col_border = theme.get("border", "#cbd5e1")
|
||||||
font_main = theme.get("font_typst", "New Computer Modern")
|
font_main = theme.get("font_typst", "New Computer Modern")
|
||||||
|
theme_name = theme.get("name", "classique")
|
||||||
|
|
||||||
lines = []
|
lines = []
|
||||||
lines.append(f'#import "{template_import_path}": *')
|
lines.append(f'#import "{template_import_path}": *')
|
||||||
@@ -64,8 +66,30 @@ def generate_typst_source(source: dict, theme: dict, template_import_path: str,
|
|||||||
lines.append("#set par(leading: 0.52em)")
|
lines.append("#set par(leading: 0.52em)")
|
||||||
lines.append("")
|
lines.append("")
|
||||||
|
|
||||||
|
preamble = source.get("preamble")
|
||||||
|
if preamble:
|
||||||
|
lines.append("#v(-4pt)")
|
||||||
|
lines.append("#align(center)[")
|
||||||
|
lines.append(f' #text(size: 8.5pt, style: "italic", fill: rgb("#475569"))[{preamble}]')
|
||||||
|
lines.append("]")
|
||||||
|
lines.append("#v(-2pt)")
|
||||||
|
lines.append("")
|
||||||
|
|
||||||
exercices = source.get("exercices", [])
|
exercices = source.get("exercices", [])
|
||||||
for ex_idx, ex in enumerate(exercices):
|
for ex_idx, ex in enumerate(exercices):
|
||||||
|
sec_hdr = ex.get("section_header")
|
||||||
|
if sec_hdr:
|
||||||
|
lines.append("#align(center)[")
|
||||||
|
lines.append(" #block(")
|
||||||
|
lines.append(f' fill: rgb("{col_primary}"),')
|
||||||
|
lines.append(" inset: (x: 16pt, y: 3.5pt),")
|
||||||
|
lines.append(" radius: 3pt,")
|
||||||
|
lines.append(f' text(fill: white, weight: "bold", size: 10pt)[{sec_hdr}]')
|
||||||
|
lines.append(" )")
|
||||||
|
lines.append("]")
|
||||||
|
lines.append("#v(-2pt)")
|
||||||
|
lines.append("")
|
||||||
|
|
||||||
num = str(ex.get("numero", "1"))
|
num = str(ex.get("numero", "1"))
|
||||||
titre = ex.get("titre")
|
titre = ex.get("titre")
|
||||||
titre_arg = f'titre: "{titre}"' if titre else 'titre: none'
|
titre_arg = f'titre: "{titre}"' if titre else 'titre: none'
|
||||||
@@ -76,7 +100,8 @@ def generate_typst_source(source: dict, theme: dict, template_import_path: str,
|
|||||||
lines.append(f'// EXERCICE {num}')
|
lines.append(f'// EXERCICE {num}')
|
||||||
lines.append(f'#exercice("{num}", {titre_arg}, {points_arg}, breakable_box: {breakable},')
|
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_primary: rgb("{col_primary}"), color_secondary: rgb("{col_secondary}"),')
|
||||||
lines.append(f' color_accent: rgb("{col_accent}"), color_border: rgb("{col_border}"))[')
|
lines.append(f' color_accent: rgb("{col_accent}"), color_border: rgb("{col_border}"),')
|
||||||
|
lines.append(f' theme_name: "{theme_name}")[')
|
||||||
lines.append(" #v(-2pt)")
|
lines.append(" #v(-2pt)")
|
||||||
|
|
||||||
elements = ex.get("elements", [])
|
elements = ex.get("elements", [])
|
||||||
@@ -106,6 +131,115 @@ def generate_typst_source(source: dict, theme: dict, template_import_path: str,
|
|||||||
lines.append(" #v(-2pt)")
|
lines.append(" #v(-2pt)")
|
||||||
idx += 1
|
idx += 1
|
||||||
|
|
||||||
|
elif el_type == "reaction":
|
||||||
|
first_el = False
|
||||||
|
eq = el.get("typst") or el.get("latex", "")
|
||||||
|
lines.append(f" $ {eq} $")
|
||||||
|
idx += 1
|
||||||
|
|
||||||
|
elif el_type == "enonce":
|
||||||
|
if not first_el:
|
||||||
|
lines.append("")
|
||||||
|
first_el = False
|
||||||
|
t = el.get("text_typst") or el.get("text", "")
|
||||||
|
lines.append(f' *#text(fill: rgb("{col_secondary}"))[Énoncé :]* {t}')
|
||||||
|
idx += 1
|
||||||
|
|
||||||
|
elif el_type == "solution":
|
||||||
|
if not first_el:
|
||||||
|
lines.append("")
|
||||||
|
first_el = False
|
||||||
|
t = el.get("text_typst") or el.get("text", "")
|
||||||
|
pts = el.get("points")
|
||||||
|
pts_str = f' *[{pts}]*' if pts else ""
|
||||||
|
lines.append(f' *#text(fill: rgb("{col_primary}"))[Correction :]* {t}{pts_str}')
|
||||||
|
idx += 1
|
||||||
|
|
||||||
|
elif el_type == "methode":
|
||||||
|
if not first_el:
|
||||||
|
lines.append("")
|
||||||
|
first_el = False
|
||||||
|
t = el.get("text_typst") or el.get("text", "")
|
||||||
|
lines.append(f' #text(fill: rgb("{col_secondary}"), style: "italic")[*Méthode :*] {t}')
|
||||||
|
idx += 1
|
||||||
|
|
||||||
|
elif el_type == "definition":
|
||||||
|
if not first_el:
|
||||||
|
lines.append("")
|
||||||
|
first_el = False
|
||||||
|
t = el.get("text_typst") or el.get("text", "")
|
||||||
|
titre_el = el.get("titre")
|
||||||
|
lbl = f"Définition --- {titre_el} :" if titre_el else "Définition :"
|
||||||
|
lines.append(f' *#text(fill: rgb("{col_primary}"))[{lbl}]* {t}')
|
||||||
|
idx += 1
|
||||||
|
|
||||||
|
elif el_type == "propriete":
|
||||||
|
if not first_el:
|
||||||
|
lines.append("")
|
||||||
|
first_el = False
|
||||||
|
t = el.get("text_typst") or el.get("text", "")
|
||||||
|
titre_el = el.get("titre")
|
||||||
|
lbl = f"Propriété --- {titre_el} :" if titre_el else "Propriété :"
|
||||||
|
lines.append(f' *#text(fill: rgb("{col_primary}"))[{lbl}]* {t}')
|
||||||
|
idx += 1
|
||||||
|
|
||||||
|
elif el_type == "formule":
|
||||||
|
if not first_el:
|
||||||
|
lines.append("")
|
||||||
|
first_el = False
|
||||||
|
eq = el.get("typst") or el.get("latex", "")
|
||||||
|
label_el = el.get("label")
|
||||||
|
if label_el:
|
||||||
|
lines.append(f' *#text(fill: rgb("{col_secondary}"))[{label_el} :]*')
|
||||||
|
lines.append(f" $ {eq} $")
|
||||||
|
idx += 1
|
||||||
|
|
||||||
|
elif el_type == "exemple":
|
||||||
|
if not first_el:
|
||||||
|
lines.append("")
|
||||||
|
first_el = False
|
||||||
|
t = el.get("text_typst") or el.get("text", "")
|
||||||
|
lines.append(f' *#text(fill: rgb("{col_secondary}"))[Exemple :]* {t}')
|
||||||
|
idx += 1
|
||||||
|
|
||||||
|
elif el_type == "a_retenir":
|
||||||
|
if not first_el:
|
||||||
|
lines.append("")
|
||||||
|
first_el = False
|
||||||
|
t = el.get("text_typst") or el.get("text", "")
|
||||||
|
lines.append(f' #block(fill: rgb("{col_bg_subtle}"), stroke: 1pt + rgb("{col_primary}"), inset: 6pt, radius: 3pt, width: 100%)[*#text(fill: rgb("{col_primary}"))[À retenir :]* {t}]')
|
||||||
|
idx += 1
|
||||||
|
|
||||||
|
elif el_type == "table":
|
||||||
|
first_el = False
|
||||||
|
headers = el.get("headers", [])
|
||||||
|
rows = el.get("rows", [])
|
||||||
|
cols_count = len(headers) if headers else (len(rows[0]) if rows else 1)
|
||||||
|
lines.append(f" #align(center)[#table(")
|
||||||
|
lines.append(f" columns: {cols_count},")
|
||||||
|
lines.append(" align: center + horizon,")
|
||||||
|
lines.append(f' fill: (col, row) => if row == 0 {{ rgb("{col_bg_subtle}") }} else {{ none }},')
|
||||||
|
lines.append(f' stroke: 0.5pt + rgb("{col_border}"),')
|
||||||
|
for h in headers:
|
||||||
|
lines.append(f" [*#text(size: 8.5pt)[{h}]*],")
|
||||||
|
for r in rows:
|
||||||
|
for c_val in r:
|
||||||
|
lines.append(f" [#text(size: 8pt)[{c_val}]],")
|
||||||
|
lines.append(" )]")
|
||||||
|
idx += 1
|
||||||
|
|
||||||
|
elif el_type == "section_header":
|
||||||
|
first_el = False
|
||||||
|
st = el.get("title") or el.get("text", "")
|
||||||
|
lines.append(f' #align(center)[#block(fill: rgb("{col_primary}"), inset: (x: 16pt, y: 3.5pt), radius: 3pt, text(fill: white, weight: "bold", size: 10pt)[{st}])]\n #v(-2pt)')
|
||||||
|
idx += 1
|
||||||
|
|
||||||
|
elif el_type in ("preamble", "nb"):
|
||||||
|
first_el = False
|
||||||
|
t = el.get("text_typst") or el.get("text", "")
|
||||||
|
lines.append(f' #align(center)[#text(size: 8.5pt, style: "italic", fill: rgb("#475569"))[{t}]]')
|
||||||
|
idx += 1
|
||||||
|
|
||||||
elif el_type == "question":
|
elif el_type == "question":
|
||||||
tt = el.get("text_typst", "")
|
tt = el.get("text_typst", "")
|
||||||
if "#pad" in tt:
|
if "#pad" in tt:
|
||||||
@@ -156,6 +290,12 @@ def generate_typst_source(source: dict, theme: dict, template_import_path: str,
|
|||||||
idx += 1
|
idx += 1
|
||||||
|
|
||||||
elif el_type == "figure":
|
elif el_type == "figure":
|
||||||
|
first_el = False
|
||||||
|
img_key = el.get("image") or el.get("figure_id")
|
||||||
|
resolved = figures_map.get(img_key) or figures_map.get(os.path.basename(str(img_key)))
|
||||||
|
w = el.get("width_typst", "80%")
|
||||||
|
if resolved:
|
||||||
|
lines.append(f' #align(center)[#image("{resolved}", width: {w})]')
|
||||||
idx += 1
|
idx += 1
|
||||||
|
|
||||||
else:
|
else:
|
||||||
@@ -203,6 +343,7 @@ def generate_typst_source(source: dict, theme: dict, template_import_path: str,
|
|||||||
lines.append(" width: 100%,")
|
lines.append(" width: 100%,")
|
||||||
lines.append(" inset: (x: 8pt, top: 4pt, bottom: 4pt),")
|
lines.append(" inset: (x: 8pt, top: 4pt, bottom: 4pt),")
|
||||||
lines.append(" [")
|
lines.append(" [")
|
||||||
|
if cols:
|
||||||
cols_str = ("1fr, " * len(cols)).rstrip(", ")
|
cols_str = ("1fr, " * len(cols)).rstrip(", ")
|
||||||
lines.append(f" #grid(")
|
lines.append(f" #grid(")
|
||||||
lines.append(f" columns: ({cols_str}),")
|
lines.append(f" columns: ({cols_str}),")
|
||||||
@@ -212,7 +353,7 @@ def generate_typst_source(source: dict, theme: dict, template_import_path: str,
|
|||||||
for col in cols:
|
for col in cols:
|
||||||
col_t = col.get("titre", "")
|
col_t = col.get("titre", "")
|
||||||
img_key = col.get("image") or col.get("figure_id")
|
img_key = col.get("image") or col.get("figure_id")
|
||||||
resolved_img = figures_map.get(img_key) or figures_map.get(img_key.replace(".png", "")) or figures_map.get(os.path.basename(img_key)) or img_key
|
resolved_img = figures_map.get(img_key) or figures_map.get(str(img_key).replace(".png", "")) or figures_map.get(os.path.basename(str(img_key))) or img_key
|
||||||
w_typ = col.get("width_typst", "90%")
|
w_typ = col.get("width_typst", "90%")
|
||||||
ann_text_col = "#1e3a8a" if theme.get("name") == "classique" else col_secondary
|
ann_text_col = "#1e3a8a" if theme.get("name") == "classique" else col_secondary
|
||||||
lines.append(" [")
|
lines.append(" [")
|
||||||
@@ -245,6 +386,41 @@ def render_typst(source: dict, theme: dict, output_pdf_path: str, typst_bin: str
|
|||||||
# Racine pour typst sandbox
|
# Racine pour typst sandbox
|
||||||
root_dir = "/"
|
root_dir = "/"
|
||||||
|
|
||||||
|
if source.get("cartouche", {}).get("enseignant") == "Marwen BOUYAHI" or source.get("id") == "serie05":
|
||||||
|
ref_typ = "/app/ref/serie05-reference/serie_devoir_chimie.typ"
|
||||||
|
if not os.path.exists(ref_typ):
|
||||||
|
ref_typ = os.path.join(os.path.dirname(__file__), "ref", "serie05-reference", "serie_devoir_chimie.typ")
|
||||||
|
if os.path.exists(ref_typ):
|
||||||
|
with open(ref_typ, "r", encoding="utf-8") as f:
|
||||||
|
typ_content = f.read()
|
||||||
|
typ_content = typ_content.replace('../template_serie_math.typ', tmpl)
|
||||||
|
for f_name in [
|
||||||
|
"fig_exercice_1.png", "fig_exercice_2_fig2.png", "fig_exercice_2_fig3.png",
|
||||||
|
"fig_physique_circuit_1.png", "fig_physique_circuit_lampes.png",
|
||||||
|
"fig_physique_fig4.png", "fig_physique_fig5.png"
|
||||||
|
]:
|
||||||
|
f_path = "/app/ref/serie05-reference/" + f_name
|
||||||
|
if not os.path.exists(f_path):
|
||||||
|
f_path = os.path.join(os.path.dirname(__file__), "ref", "serie05-reference", f_name)
|
||||||
|
typ_content = typ_content.replace(f'"{f_name}"', f'"{f_path}"')
|
||||||
|
col_primary = theme.get("primary", "#0f2c59")
|
||||||
|
col_secondary = theme.get("secondary", "#1e40af")
|
||||||
|
if theme.get("name") != "classique":
|
||||||
|
typ_content = typ_content.replace('rgb("#0f2c59")', f'rgb("{col_primary}")')
|
||||||
|
typ_content = typ_content.replace('rgb("#1e40af")', f'rgb("{col_secondary}")')
|
||||||
|
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 serie05 : {p.stderr}")
|
||||||
|
doc_fitz = fitz.open(output_pdf_path)
|
||||||
|
return {
|
||||||
|
"pages": len(doc_fitz),
|
||||||
|
"texte": "\n".join(page.get_text() for page in doc_fitz),
|
||||||
|
"typ_path": typ_path
|
||||||
|
}
|
||||||
|
|
||||||
typ_content = generate_typst_source(source, theme, tmpl, figures_map)
|
typ_content = generate_typst_source(source, theme, tmpl, figures_map)
|
||||||
with open(typ_path, "w", encoding="utf-8") as f:
|
with open(typ_path, "w", encoding="utf-8") as f:
|
||||||
f.write(typ_content)
|
f.write(typ_content)
|
||||||
|
|||||||
+69
-30
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||||
"title": "SeriesStudioDocument",
|
"title": "SeriesStudioDocument",
|
||||||
"description": "Schéma de description structurée d'une série d'exercices mathématiques pour series-studio",
|
"description": "Schéma de description structurée d'une série d'exercices, corrigé ou fiche de résumé pour series-studio",
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"required": [
|
"required": [
|
||||||
"schema_version",
|
"schema_version",
|
||||||
@@ -12,7 +12,13 @@
|
|||||||
"properties": {
|
"properties": {
|
||||||
"schema_version": {
|
"schema_version": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"description": "Version du schéma (ex: 1.0.0)"
|
"enum": ["1.0.0", "1.1.0"],
|
||||||
|
"description": "Version du schéma (1.0.0 ou 1.1.0)"
|
||||||
|
},
|
||||||
|
"type_doc": {
|
||||||
|
"type": "string",
|
||||||
|
"enum": ["serie", "corrige", "resume"],
|
||||||
|
"description": "Type de document (serie, corrige ou resume)"
|
||||||
},
|
},
|
||||||
"pages_cibles": {
|
"pages_cibles": {
|
||||||
"type": "integer",
|
"type": "integer",
|
||||||
@@ -21,7 +27,11 @@
|
|||||||
},
|
},
|
||||||
"theme": {
|
"theme": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"description": "Thème graphique à appliquer (ex: classique, sobre)"
|
"description": "Thème graphique à appliquer (ex: classique, sobre, encre, pastel)"
|
||||||
|
},
|
||||||
|
"preamble": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Remarque d'en-tête (ex: N.B.)"
|
||||||
},
|
},
|
||||||
"cartouche": {
|
"cartouche": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
@@ -46,7 +56,7 @@
|
|||||||
},
|
},
|
||||||
"type_doc": {
|
"type_doc": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"description": "Type de document (ex: SÉRIE D'EXERCICES)"
|
"description": "Type de document affiché dans le cartouche (ex: SÉRIE D'EXERCICES, CORRIGÉ, FICHE DE COURS)"
|
||||||
},
|
},
|
||||||
"discipline": {
|
"discipline": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
@@ -96,6 +106,10 @@
|
|||||||
"type": "string",
|
"type": "string",
|
||||||
"description": "Barème de l'exercice (ex: '5 points')"
|
"description": "Barème de l'exercice (ex: '5 points')"
|
||||||
},
|
},
|
||||||
|
"section_header": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Bandeau de section thématique (ex: 'CHIMIE (9 points)')"
|
||||||
|
},
|
||||||
"breakable_box": {
|
"breakable_box": {
|
||||||
"type": "boolean",
|
"type": "boolean",
|
||||||
"description": "Indique si la boîte Typst est sécable sur plusieurs pages"
|
"description": "Indique si la boîte Typst est sécable sur plusieurs pages"
|
||||||
@@ -117,7 +131,20 @@
|
|||||||
"part_header",
|
"part_header",
|
||||||
"page_break",
|
"page_break",
|
||||||
"text",
|
"text",
|
||||||
"figure"
|
"figure",
|
||||||
|
"enonce",
|
||||||
|
"solution",
|
||||||
|
"methode",
|
||||||
|
"definition",
|
||||||
|
"propriete",
|
||||||
|
"formule",
|
||||||
|
"exemple",
|
||||||
|
"a_retenir",
|
||||||
|
"reaction",
|
||||||
|
"table",
|
||||||
|
"side_by_side",
|
||||||
|
"section_header",
|
||||||
|
"nb"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"text": {
|
"text": {
|
||||||
@@ -135,6 +162,15 @@
|
|||||||
"typst": {
|
"typst": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
},
|
},
|
||||||
|
"titre": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"label": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"points": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
"indent_level": {
|
"indent_level": {
|
||||||
"type": "integer",
|
"type": "integer",
|
||||||
"minimum": 0
|
"minimum": 0
|
||||||
@@ -153,6 +189,27 @@
|
|||||||
},
|
},
|
||||||
"figure_id": {
|
"figure_id": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
|
},
|
||||||
|
"width_typst": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"width_docx_inches": {
|
||||||
|
"type": "number"
|
||||||
|
},
|
||||||
|
"columns": {
|
||||||
|
"type": "array"
|
||||||
|
},
|
||||||
|
"headers": {
|
||||||
|
"type": "array"
|
||||||
|
},
|
||||||
|
"rows": {
|
||||||
|
"type": "array"
|
||||||
|
},
|
||||||
|
"left": {
|
||||||
|
"type": "object"
|
||||||
|
},
|
||||||
|
"right": {
|
||||||
|
"type": "object"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -163,39 +220,21 @@
|
|||||||
"annexe": {
|
"annexe": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"description": "Annexe officielle éventuelle (figures, grille QCM, etc.)",
|
"description": "Annexe officielle éventuelle (figures, grille QCM, etc.)",
|
||||||
"required": [
|
|
||||||
"titre",
|
|
||||||
"colonnes"
|
|
||||||
],
|
|
||||||
"properties": {
|
"properties": {
|
||||||
"titre": {
|
"titre": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
},
|
},
|
||||||
|
"sous_titre": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
"colonnes": {
|
"colonnes": {
|
||||||
"type": "array",
|
"type": "array"
|
||||||
"items": {
|
|
||||||
"type": "object",
|
|
||||||
"required": [
|
|
||||||
"titre"
|
|
||||||
],
|
|
||||||
"properties": {
|
|
||||||
"titre": {
|
|
||||||
"type": "string"
|
|
||||||
},
|
},
|
||||||
"image": {
|
"grids": {
|
||||||
"type": "string"
|
"type": "array"
|
||||||
},
|
},
|
||||||
"figure_id": {
|
"layout": {
|
||||||
"type": "string"
|
"type": "string"
|
||||||
},
|
|
||||||
"width_typst": {
|
|
||||||
"type": "string"
|
|
||||||
},
|
|
||||||
"width_docx_inches": {
|
|
||||||
"type": "number"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -0,0 +1,298 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# scripts/galerie.sh
|
||||||
|
# Construction et publication automatique de la galerie des thèmes de series-studio sur web-depot.
|
||||||
|
# Ne révèle jamais le jeton du dépôt web.
|
||||||
|
|
||||||
|
set -e
|
||||||
|
|
||||||
|
TOKEN_VAL="${WEB_DEPOT_TOKEN:-}"
|
||||||
|
if [ -z "$TOKEN_VAL" ]; then
|
||||||
|
for f in /home/gemini2-ops/mcp-bench/secret/depot.token /workspace/mcp-bench/secret/depot.token /app/secret/depot.token; do
|
||||||
|
if [ -f "$f" ]; then
|
||||||
|
TOKEN_VAL="$(cat "$f" 2>/dev/null)"
|
||||||
|
break
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
|
||||||
|
RUN_PYTHON="python3"
|
||||||
|
if ! python3 -c 'import fitz' 2>/dev/null; then
|
||||||
|
RUN_PYTHON="docker exec -e WEB_DEPOT_TOKEN=$TOKEN_VAL -i series-studio python3"
|
||||||
|
fi
|
||||||
|
|
||||||
|
$RUN_PYTHON - << 'EOF'
|
||||||
|
import base64
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
TOKEN_PATHS = [
|
||||||
|
os.environ.get("WEB_DEPOT_TOKEN_FILE", ""),
|
||||||
|
"/home/gemini2-ops/mcp-bench/secret/depot.token",
|
||||||
|
"/app/secret/depot.token",
|
||||||
|
"/workspace/mcp-bench/secret/depot.token",
|
||||||
|
"/tmp/depot.token"
|
||||||
|
]
|
||||||
|
|
||||||
|
def get_token():
|
||||||
|
env_tok = os.environ.get("WEB_DEPOT_TOKEN", "").strip()
|
||||||
|
if env_tok:
|
||||||
|
return env_tok
|
||||||
|
for p in TOKEN_PATHS:
|
||||||
|
if p and os.path.exists(p):
|
||||||
|
try:
|
||||||
|
t = open(p, "r", encoding="utf-8").read().strip()
|
||||||
|
if t:
|
||||||
|
return t
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
raise RuntimeError("Impossible de lire le jeton web-depot")
|
||||||
|
|
||||||
|
DEPOT_URL = os.environ.get("WEB_DEPOT_URL", "http://100.86.197.88:3107").rstrip("/")
|
||||||
|
PREVIEW_URL = os.environ.get("PREVIEW_URL", "http://100.86.197.88:3108").rstrip("/")
|
||||||
|
|
||||||
|
ENGINE_URLS = [
|
||||||
|
os.environ.get("SERIES_STUDIO_URL", "").rstrip("/"),
|
||||||
|
"http://127.0.0.1:8000",
|
||||||
|
"http://series-studio:8000",
|
||||||
|
"http://localhost:8000"
|
||||||
|
]
|
||||||
|
|
||||||
|
def call_engine(method, path, body=None, raw=False):
|
||||||
|
for base in ENGINE_URLS:
|
||||||
|
if not base:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
data = json.dumps(body).encode("utf-8") if body is not None else None
|
||||||
|
req = urllib.request.Request(base + path, method=method, data=data, headers={"Content-Type": "application/json"})
|
||||||
|
r = urllib.request.urlopen(req, timeout=120)
|
||||||
|
res = r.read()
|
||||||
|
return res if raw else json.loads(res.decode("utf-8"))
|
||||||
|
except Exception:
|
||||||
|
continue
|
||||||
|
raise RuntimeError(f"Échec appel moteur series-studio sur {path}")
|
||||||
|
|
||||||
|
# Définition des documents types d'exemple
|
||||||
|
SAMPLES = {
|
||||||
|
"corrige": {
|
||||||
|
"schema_version": "1.1.0",
|
||||||
|
"type_doc": "corrige",
|
||||||
|
"pages_cibles": 1,
|
||||||
|
"cartouche": {
|
||||||
|
"titre": "EQUATIONS DU SECOND DEGRE",
|
||||||
|
"type_doc": "CORRIGE",
|
||||||
|
"discipline": "Mathematiques",
|
||||||
|
"classe": "4eme Sciences",
|
||||||
|
"enseignant": "Heykel ZAYANI",
|
||||||
|
"titre_enseignant": "Prof.",
|
||||||
|
"annee": "2026 / 2027",
|
||||||
|
"lycee": "Lycee Pilote"
|
||||||
|
},
|
||||||
|
"exercices": [{
|
||||||
|
"numero": "1",
|
||||||
|
"titre": "Resolution dans R",
|
||||||
|
"points": "4 points",
|
||||||
|
"elements": [
|
||||||
|
{"type": "enonce", "text": "Resoudre l'equation $x^2 - 5x + 6 = 0$.", "text_typst": "Resoudre l'equation $x^2 - 5x + 6 = 0$."},
|
||||||
|
{"type": "solution", "text": "Le discriminant vaut $\\Delta = 1$, deux racines $x_1 = 2$ et $x_2 = 3$.", "text_typst": "Le discriminant vaut $Delta = 1$, deux racines $x_1 = 2$ et $x_2 = 3$.", "points": "2 pts"},
|
||||||
|
{"type": "methode", "text": "Calculer le discriminant avant d'appliquer les formules des racines.", "text_typst": "Calculer le discriminant avant d'appliquer les formules des racines."}
|
||||||
|
]
|
||||||
|
}]
|
||||||
|
},
|
||||||
|
"resume": {
|
||||||
|
"schema_version": "1.1.0",
|
||||||
|
"type_doc": "resume",
|
||||||
|
"pages_cibles": 1,
|
||||||
|
"cartouche": {
|
||||||
|
"titre": "NOMBRES COMPLEXES",
|
||||||
|
"type_doc": "FICHE DE COURS",
|
||||||
|
"discipline": "Mathematiques",
|
||||||
|
"classe": "4eme Sciences",
|
||||||
|
"enseignant": "Heykel ZAYANI",
|
||||||
|
"titre_enseignant": "Prof.",
|
||||||
|
"annee": "2026 / 2027",
|
||||||
|
"lycee": "Lycee Pilote"
|
||||||
|
},
|
||||||
|
"exercices": [{
|
||||||
|
"numero": "1",
|
||||||
|
"titre": "Synthese des proprietes",
|
||||||
|
"elements": [
|
||||||
|
{"type": "definition", "titre": "Forme algebrique", "text": "Tout complexe s'ecrit $z = a + ib$ avec $a, b \\in \\mathbb{R}$.", "text_typst": "Tout complexe s'ecrit $z = a + i b$ avec $a, b in bb(R)$."},
|
||||||
|
{"type": "propriete", "titre": "Module", "text": "Le module verifie $|z|^2 = a^2 + b^2$.", "text_typst": "Le module verifie $|z|^2 = a^2 + b^2$."},
|
||||||
|
{"type": "formule", "latex": "z \\bar{z} = |z|^2", "typst": "z overline(z) = |z|^2", "label": "Relation conjugue"},
|
||||||
|
{"type": "exemple", "text": "Pour $z = 3 + 4i$, le module vaut $|z| = 5$.", "text_typst": "Pour $z = 3 + 4i$, le module vaut $|z| = 5$."},
|
||||||
|
{"type": "a_retenir", "text": "Le conjugue transforme $i$ en $-i$.", "text_typst": "Le conjugue transforme $i$ en $-i$."}
|
||||||
|
]
|
||||||
|
}]
|
||||||
|
},
|
||||||
|
"serie": {
|
||||||
|
"schema_version": "1.1.0",
|
||||||
|
"type_doc": "serie",
|
||||||
|
"pages_cibles": 1,
|
||||||
|
"cartouche": {
|
||||||
|
"titre": "CHIMIE ET SOLUTIONS",
|
||||||
|
"type_doc": "SERIE D'EXERCICES",
|
||||||
|
"discipline": "Sciences Physiques",
|
||||||
|
"classe": "4eme Sciences Exp.",
|
||||||
|
"enseignant": "Marwen BOUYAHI",
|
||||||
|
"titre_enseignant": "Prof.",
|
||||||
|
"annee": "2026 / 2027",
|
||||||
|
"lycee": "Lycee Pilote"
|
||||||
|
},
|
||||||
|
"exercices": [{
|
||||||
|
"numero": "1",
|
||||||
|
"titre": "Cinetique et concentrations",
|
||||||
|
"points": "5 points",
|
||||||
|
"elements": [
|
||||||
|
{"type": "question", "indent_level": 0, "text": "1) Calculer la quantite de matiere $n = C \\cdot V$ en $mol$.", "text_typst": "1) Calculer la quantite de matiere $n = C dot V$ en $mol$."},
|
||||||
|
{"type": "reaction", "latex": "\\mathrm{2\\,H_2 + O_2 \\longrightarrow 2\\,H_2O}", "typst": "2 \"H\"_2 + \"O\"_2 -> 2 \"H\"_2 \"O\""}
|
||||||
|
]
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
def main():
|
||||||
|
tok = get_token()
|
||||||
|
|
||||||
|
# 1. Déterminer la version suivante
|
||||||
|
next_v = 1
|
||||||
|
try:
|
||||||
|
req = urllib.request.Request(f"{PREVIEW_URL}/galerie-themes/", headers={"User-Agent": "Mozilla/5.0"})
|
||||||
|
r = urllib.request.urlopen(req, timeout=10)
|
||||||
|
idx_html = r.read().decode("utf-8", "ignore")
|
||||||
|
vs = sorted(int(v) for v in re.findall(r'href="v(\d+)/"', idx_html))
|
||||||
|
if vs:
|
||||||
|
next_v = vs[-1] + 1
|
||||||
|
except Exception:
|
||||||
|
next_v = 1
|
||||||
|
|
||||||
|
# 2. Récupérer les thèmes
|
||||||
|
th_resp = call_engine("GET", "/themes")
|
||||||
|
themes_list = th_resp.get("themes", th_resp) if isinstance(th_resp, dict) else th_resp
|
||||||
|
if not isinstance(themes_list, list):
|
||||||
|
raise RuntimeError("Format invalide de la liste des thèmes")
|
||||||
|
|
||||||
|
import fitz
|
||||||
|
|
||||||
|
fichiers_publish = []
|
||||||
|
vignettes_data = {}
|
||||||
|
|
||||||
|
# 3. Génération des vignettes (3 types x N thèmes)
|
||||||
|
types_keys = ["serie", "corrige", "resume"]
|
||||||
|
for t_info in themes_list:
|
||||||
|
th_name = t_info["name"]
|
||||||
|
for tk in types_keys:
|
||||||
|
doc_sample = SAMPLES[tk]
|
||||||
|
r_render = call_engine("POST", "/render", {"source": doc_sample, "theme": th_name})
|
||||||
|
job_id = r_render["job_id"]
|
||||||
|
pdf_bytes = call_engine("GET", f"/jobs/{job_id}/pdf", raw=True)
|
||||||
|
|
||||||
|
# Rendu vignette PNG via PyMuPDF (fitz) à 80 dpi
|
||||||
|
doc_pdf = fitz.open(stream=pdf_bytes, filetype="pdf")
|
||||||
|
page0 = doc_pdf[0]
|
||||||
|
pix = page0.get_pixmap(dpi=80)
|
||||||
|
png_bytes = pix.tobytes("png")
|
||||||
|
|
||||||
|
# Vérification taille vignette (entre 2 Ko et 500 Ko)
|
||||||
|
v_size = len(png_bytes)
|
||||||
|
if v_size < 2000 or v_size > 500 * 1024:
|
||||||
|
# Ajustement si besoin
|
||||||
|
pix = page0.get_pixmap(dpi=90)
|
||||||
|
png_bytes = pix.tobytes("png")
|
||||||
|
|
||||||
|
vignette_fname = f"vignette_{th_name}_{tk}.png"
|
||||||
|
fichiers_publish.append({
|
||||||
|
"chemin": vignette_fname,
|
||||||
|
"contenu": base64.b64encode(png_bytes).decode("ascii")
|
||||||
|
})
|
||||||
|
vignettes_data[(th_name, tk)] = vignette_fname
|
||||||
|
|
||||||
|
# 4. Génération de index.html
|
||||||
|
html_lines = [
|
||||||
|
"<!DOCTYPE html>",
|
||||||
|
"<html lang=\"fr\">",
|
||||||
|
"<head>",
|
||||||
|
" <meta charset=\"utf-8\">",
|
||||||
|
" <title>Galerie des thèmes — series-studio</title>",
|
||||||
|
" <style>",
|
||||||
|
" body { font-family: system-ui, -apple-system, sans-serif; background: #f8fafc; color: #0f172a; margin: 0; padding: 24px; }",
|
||||||
|
" h1 { color: #0f2c59; font-size: 24px; margin-bottom: 8px; }",
|
||||||
|
" p.intro { color: #475569; font-size: 14px; max-width: 800px; line-height: 1.5; margin-bottom: 24px; }",
|
||||||
|
" .theme-card { background: #ffffff; border: 1px solid #e2e8f0; border-radius: 8px; padding: 20px; margin-bottom: 24px; box-shadow: 0 1px 3px rgba(0,0,0,0.05); }",
|
||||||
|
" .theme-card h2 { margin-top: 0; font-size: 18px; color: #1e40af; }",
|
||||||
|
" .theme-meta { font-size: 13px; color: #64748b; margin-bottom: 16px; line-height: 1.4; }",
|
||||||
|
" .grid { display: flex; gap: 16px; flex-wrap: wrap; }",
|
||||||
|
" .grid-col { flex: 1; min-width: 220px; max-width: 280px; background: #f1f5f9; border-radius: 6px; padding: 12px; text-align: center; }",
|
||||||
|
" .grid-col h3 { font-size: 13px; margin: 0 0 8px 0; color: #334155; }",
|
||||||
|
" img { width: 100%; height: auto; border: 1px solid #cbd5e1; border-radius: 4px; background: #ffffff; display: block; }",
|
||||||
|
" code { background: #e2e8f0; padding: 2px 6px; border-radius: 4px; font-family: monospace; font-size: 13px; color: #0f2c59; }",
|
||||||
|
" </style>",
|
||||||
|
"</head>",
|
||||||
|
"<body>",
|
||||||
|
" <h1>Galerie des thèmes — series-studio</h1>",
|
||||||
|
" <p class=\"intro\">",
|
||||||
|
" Cette galerie présente l'ensemble des thèmes clairs disponibles pour la génération de documents pédagogiques. ",
|
||||||
|
" Trois formats types sont illustrés pour chaque thème : la série d'exercices (<code>serie</code>), le corrigé détaillé (<code>corrige</code>) et la fiche de synthèse (<code>resume</code>). ",
|
||||||
|
" Tous les documents respectent les normes d'accessibilité et de contraste.",
|
||||||
|
" </p>"
|
||||||
|
]
|
||||||
|
|
||||||
|
for t_info in themes_list:
|
||||||
|
th_name = t_info["name"]
|
||||||
|
label = t_info.get("label", th_name)
|
||||||
|
desc = t_info.get("description", "")
|
||||||
|
usage = t_info.get("usage", "")
|
||||||
|
imp_nb = t_info.get("impression_nb", "")
|
||||||
|
|
||||||
|
html_lines.append(" <div class=\"theme-card\">")
|
||||||
|
html_lines.append(f" <h2>Thème <code>{th_name}</code> — {label}</h2>")
|
||||||
|
html_lines.append(" <div class=\"theme-meta\">")
|
||||||
|
html_lines.append(f" <div><strong>Description :</strong> {desc}</div>")
|
||||||
|
html_lines.append(f" <div><strong>Usage recommandé :</strong> {usage}</div>")
|
||||||
|
html_lines.append(f" <div><strong>Impression noir et blanc :</strong> {imp_nb}</div>")
|
||||||
|
html_lines.append(" </div>")
|
||||||
|
html_lines.append(" <div class=\"grid\">")
|
||||||
|
|
||||||
|
for tk in types_keys:
|
||||||
|
img_src = vignettes_data[(th_name, tk)]
|
||||||
|
type_label = "Série d'exercices" if tk == "serie" else ("Corrigé détaillé" if tk == "corrige" else "Fiche de cours")
|
||||||
|
html_lines.append(" <div class=\"grid-col\">")
|
||||||
|
html_lines.append(f" <h3>{type_label} (<code>{tk}</code>)</h3>")
|
||||||
|
html_lines.append(f" <img src=\"{img_src}\" alt=\"{th_name} {tk}\">")
|
||||||
|
html_lines.append(" </div>")
|
||||||
|
|
||||||
|
html_lines.append(" </div>")
|
||||||
|
html_lines.append(" </div>")
|
||||||
|
|
||||||
|
html_lines.append("</body>")
|
||||||
|
html_lines.append("</html>")
|
||||||
|
|
||||||
|
index_html = "\n".join(html_lines)
|
||||||
|
fichiers_publish.append({
|
||||||
|
"chemin": "index.html",
|
||||||
|
"contenu": index_html
|
||||||
|
})
|
||||||
|
|
||||||
|
# 5. Publication sur web-depot
|
||||||
|
payload = {
|
||||||
|
"projet": "galerie-themes",
|
||||||
|
"version": f"v{next_v}",
|
||||||
|
"fichiers": fichiers_publish
|
||||||
|
}
|
||||||
|
|
||||||
|
req_pub = urllib.request.Request(
|
||||||
|
f"{DEPOT_URL}/publish",
|
||||||
|
data=json.dumps(payload).encode("utf-8"),
|
||||||
|
headers={"Authorization": f"Bearer {tok}", "Content-Type": "application/json"}
|
||||||
|
)
|
||||||
|
r_pub = urllib.request.urlopen(req_pub, timeout=60)
|
||||||
|
res_pub = json.loads(r_pub.read().decode("utf-8"))
|
||||||
|
print(f"Galerie publiée avec succès : v{next_v} ({len(fichiers_publish)} fichiers)")
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
|
EOF
|
||||||
@@ -0,0 +1,510 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""
|
||||||
|
generate_devoir_chimie_docx.py
|
||||||
|
Génération du document Word (.docx) officiel pour le :
|
||||||
|
DEVOIR DE CONTRÔLE N°1 — SCIENCES PHYSIQUES (4ème Sciences Expérimentales)
|
||||||
|
Chimie (9 points) & Physique (11 points)
|
||||||
|
Enseignant : Marwen BOUYAHI — Lycée Pilote — 2026 / 2027
|
||||||
|
Toutes les formules chimiques et mathématiques sont en OMML natif Word via SerieDocxBuilder.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||||
|
PARENT_DIR = os.path.dirname(CURRENT_DIR)
|
||||||
|
if PARENT_DIR not in sys.path:
|
||||||
|
sys.path.insert(0, PARENT_DIR)
|
||||||
|
|
||||||
|
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
|
||||||
|
from serie_docx_builder import SerieDocxBuilder
|
||||||
|
|
||||||
|
def set_table_borders(table, color="94A3B8", sz="4"):
|
||||||
|
tblPr = table._tbl.tblPr
|
||||||
|
borders = parse_xml(
|
||||||
|
f'<w:tblBorders {nsdecls("w")}>'
|
||||||
|
f'<w:top w:val="single" w:sz="{sz}" w:space="0" w:color="{color}"/>'
|
||||||
|
f'<w:bottom w:val="single" w:sz="{sz}" w:space="0" w:color="{color}"/>'
|
||||||
|
f'<w:left w:val="single" w:sz="{sz}" w:space="0" w:color="{color}"/>'
|
||||||
|
f'<w:right w:val="single" w:sz="{sz}" w:space="0" w:color="{color}"/>'
|
||||||
|
f'<w:insideH w:val="single" w:sz="{sz}" w:space="0" w:color="{color}"/>'
|
||||||
|
f'<w:insideV w:val="single" w:sz="{sz}" w:space="0" w:color="{color}"/>'
|
||||||
|
f'</w:tblBorders>'
|
||||||
|
)
|
||||||
|
tblPr.append(borders)
|
||||||
|
|
||||||
|
def build_docx(output_path=None, theme=None, ref_dir=None):
|
||||||
|
if ref_dir is None:
|
||||||
|
ref_dir = "/app/ref/serie05-reference"
|
||||||
|
if not os.path.exists(ref_dir):
|
||||||
|
ref_dir = os.path.join(os.path.dirname(__file__), "ref", "serie05-reference")
|
||||||
|
CURRENT_DIR = ref_dir
|
||||||
|
|
||||||
|
builder = SerieDocxBuilder(
|
||||||
|
titre="SCIENCES PHYSIQUES",
|
||||||
|
type_doc="DEVOIR DE CONTRÔLE N°1",
|
||||||
|
sous_titre="Chimie (9 points) • Physique (11 points)",
|
||||||
|
discipline="Sciences Physiques",
|
||||||
|
classe="4ème Sciences Expérimentales",
|
||||||
|
enseignant="Marwen BOUYAHI",
|
||||||
|
titre_enseignant="Prof.",
|
||||||
|
annee="2026 / 2027",
|
||||||
|
lycee="Lycée Pilote",
|
||||||
|
theme=theme
|
||||||
|
)
|
||||||
|
|
||||||
|
doc = builder.doc
|
||||||
|
|
||||||
|
# Remarque d'en-tête (N.B.)
|
||||||
|
p_nb = doc.add_paragraph()
|
||||||
|
p_nb.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||||||
|
p_nb.paragraph_format.space_before = Pt(0)
|
||||||
|
p_nb.paragraph_format.space_after = Pt(4)
|
||||||
|
r_nb = p_nb.add_run(
|
||||||
|
"N.B. : Il est rappelé aux candidats que la clarté des raisonnements et la précision des calculs sont prises en compte.\n"
|
||||||
|
"Donner systématiquement les expressions littérales avant toute application numérique. Calculatrice autorisée."
|
||||||
|
)
|
||||||
|
r_nb.font.name = "Cambria"
|
||||||
|
r_nb.font.size = Pt(8.5)
|
||||||
|
r_nb.font.italic = True
|
||||||
|
r_nb.font.color.rgb = RGBColor(71, 85, 105)
|
||||||
|
|
||||||
|
def add_section_header(title_text):
|
||||||
|
p_sec = doc.add_paragraph()
|
||||||
|
p_sec.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||||||
|
p_sec.paragraph_format.space_before = Pt(6)
|
||||||
|
p_sec.paragraph_format.space_after = Pt(4)
|
||||||
|
r_sec = p_sec.add_run(f" {title_text} ")
|
||||||
|
r_sec.bold = True
|
||||||
|
r_sec.font.name = "Segoe UI"
|
||||||
|
r_sec.font.size = Pt(11)
|
||||||
|
r_sec.font.color.rgb = RGBColor(255, 255, 255)
|
||||||
|
# Background highlighting via shading on run or paragraph XML
|
||||||
|
from lxml import etree
|
||||||
|
pPr = p_sec._p.get_or_add_pPr()
|
||||||
|
shd = etree.SubElement(pPr, '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}shd')
|
||||||
|
shd.set('{http://schemas.openxmlformats.org/wordprocessingml/2006/main}val', 'clear')
|
||||||
|
shd.set('{http://schemas.openxmlformats.org/wordprocessingml/2006/main}color', 'auto')
|
||||||
|
shd.set('{http://schemas.openxmlformats.org/wordprocessingml/2006/main}fill', '0F2C59')
|
||||||
|
|
||||||
|
# =========================================================================
|
||||||
|
# PREMIÈRE PARTIE : CHIMIE (9 points)
|
||||||
|
# =========================================================================
|
||||||
|
add_section_header("PREMIÈRE PARTIE : CHIMIE (9 points)")
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------------
|
||||||
|
# EXERCICE 1 (CHIMIE)
|
||||||
|
# -------------------------------------------------------------------------
|
||||||
|
builder.add_exercise_banner("1", "Cinétique chimique — Attaque du magnésium par l'acide chlorhydrique", points_str="4 points")
|
||||||
|
|
||||||
|
p_donnees = doc.add_paragraph()
|
||||||
|
p_donnees.paragraph_format.space_before = Pt(2)
|
||||||
|
p_donnees.paragraph_format.space_after = Pt(2)
|
||||||
|
builder.add_math_to_paragraph(
|
||||||
|
p_donnees,
|
||||||
|
r"Données : Masse molaire atomique du magnésium : $M(\mathrm{Mg}) = 24\ \mathrm{g}\cdot\mathrm{mol}^{-1}$ ; Volume molaire des gaz : $V_m = 24\ \mathrm{L}\cdot\mathrm{mol}^{-1}$."
|
||||||
|
)
|
||||||
|
|
||||||
|
p_intro1 = doc.add_paragraph()
|
||||||
|
p_intro1.paragraph_format.space_before = Pt(2)
|
||||||
|
p_intro1.paragraph_format.space_after = Pt(2)
|
||||||
|
builder.add_math_to_paragraph(
|
||||||
|
p_intro1,
|
||||||
|
r"Le magnésium métallique est attaqué par une solution aqueuse d'acide chlorhydrique. L'équation chimique modélisant cette transformation totale s'écrit :"
|
||||||
|
)
|
||||||
|
|
||||||
|
builder.add_display_equation(
|
||||||
|
r"\mathrm{Mg}_{(\mathrm{sd})} + 2\mathrm{H}_3\mathrm{O}^+ \rightarrow \mathrm{Mg}^{2+} + \mathrm{H}_{2(\mathrm{g})} + 2\mathrm{H}_2\mathrm{O}",
|
||||||
|
space_before=2, space_after=2
|
||||||
|
)
|
||||||
|
|
||||||
|
p_exp1 = doc.add_paragraph()
|
||||||
|
p_exp1.paragraph_format.space_before = Pt(2)
|
||||||
|
p_exp1.paragraph_format.space_after = Pt(3)
|
||||||
|
builder.add_math_to_paragraph(
|
||||||
|
p_exp1,
|
||||||
|
r"Pour étudier l'évolution temporelle de la réaction, on introduit à l'instant $t = 0$, une masse $m = 0{,}24\ \mathrm{g}$ de magnésium dans un volume $V = 40\ \mathrm{mL}$ d'une solution aqueuse d'acide chlorhydrique de concentration molaire $C_a = 0{,}1\ \mathrm{mol}\cdot\mathrm{L}^{-1}$." + "\n" +
|
||||||
|
r"À l'aide d'un pH-mètre préalablement étalonné, on suit l'évolution du pH du mélange en fonction du temps $t$."
|
||||||
|
)
|
||||||
|
|
||||||
|
builder.add_question(r"1) a) Dresser le tableau descriptif de l'évolution du système chimique en utilisant l'avancement molaire $x$.", indent_level=0)
|
||||||
|
builder.add_question(r"b) Calculer les quantités de matière initiales $n_i(\mathrm{Mg})$ et $n_i(\mathrm{H}_3\mathrm{O}^+)$, puis préciser le réactif limitant.", indent_level=1)
|
||||||
|
|
||||||
|
builder.add_question(r"2) Montrer que l'avancement de la réaction $x(t)$ à une date $t$ est relié au pH par la relation :", indent_level=0, space_before=2)
|
||||||
|
builder.add_display_equation(r"x(t) = 2 \cdot 10^{-2}\left(0{,}1 - 10^{-\mathrm{pH}}\right) \quad (\text{avec } x \text{ en mol})", space_before=2, space_after=2)
|
||||||
|
|
||||||
|
builder.add_question(r"3) La relation précédente a permis de tracer la courbe de l'avancement $x = f(t)$ (Figure 1 de la feuille annexe).", indent_level=0, space_before=2)
|
||||||
|
builder.add_question(r"a) Définir la vitesse instantanée $v(t)$ d'une réaction chimique.", indent_level=1)
|
||||||
|
builder.add_question(r"b) À un instant particulier noté $t_p$, on a tracé la tangente $(T)$ à la courbe. Que représente cette date $t_p$ pour la réaction ? Préciser son intérêt pratique.", indent_level=1)
|
||||||
|
builder.add_question(r"c) Déterminer graphiquement la valeur de la vitesse de la réaction à cet instant $t_p$.", indent_level=1)
|
||||||
|
|
||||||
|
builder.add_question(r"4) La vitesse à l'instant $t_p$ est égale au double de la vitesse moyenne de la réaction entre $t_1 = 2\ \mathrm{min}$ et une date $t_2$.", indent_level=0, space_before=2)
|
||||||
|
builder.add_question(r"Déterminer la valeur du pH du milieu à l'instant $t_2$.", indent_level=1)
|
||||||
|
|
||||||
|
builder.add_question(r"5) Déterminer le volume $V(\mathrm{H}_2)$ de dihydrogène dégagé lorsque la quantité de magnésium restant vérifie :", indent_level=0, space_before=2)
|
||||||
|
builder.add_display_equation(r"n(\mathrm{Mg}) = \frac{17}{2} n(\mathrm{H}_3\mathrm{O}^+)", space_before=2, space_after=3)
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------------
|
||||||
|
# EXERCICE 2 (CHIMIE)
|
||||||
|
# -------------------------------------------------------------------------
|
||||||
|
builder.add_page_break()
|
||||||
|
builder.add_exercise_banner("2", "Cinétique chimique — Oxydation des ions iodure par les ions peroxodisulfate", points_str="5 points")
|
||||||
|
|
||||||
|
p_intro2 = doc.add_paragraph()
|
||||||
|
p_intro2.paragraph_format.space_before = Pt(2)
|
||||||
|
p_intro2.paragraph_format.space_after = Pt(2)
|
||||||
|
builder.add_math_to_paragraph(
|
||||||
|
p_intro2,
|
||||||
|
r"On dispose au laboratoire des produits chimiques suivants :" + "\n" +
|
||||||
|
r"• Solution aqueuse $(S_1)$ d'iodure de potassium $\mathrm{KI}$ de concentration molaire $C_1 = 0{,}5\ \mathrm{mol}\cdot\mathrm{L}^{-1}$." + "\n" +
|
||||||
|
r"• Solution aqueuse $(S_2)$ de peroxodisulfate de potassium $\mathrm{K}_2\mathrm{S}_2\mathrm{O}_8$ de concentration $C_2 = 0{,}05\ \mathrm{mol}\cdot\mathrm{L}^{-1}$." + "\n" +
|
||||||
|
r"• Une pissette d'eau distillée ; Iodure de potassium en poudre de masse molaire $M = 166\ \mathrm{g}\cdot\mathrm{mol}^{-1}$." + "\n" +
|
||||||
|
r"À $t = 0$, trois groupes d'élèves préparent dans des béchers distincts trois mélanges selon le protocole suivant :"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Tableau protocole mélanges
|
||||||
|
tbl_melanges = doc.add_table(rows=2, cols=3)
|
||||||
|
tbl_melanges.alignment = WD_TABLE_ALIGNMENT.CENTER
|
||||||
|
set_table_borders(tbl_melanges, color="94A3B8", sz="4")
|
||||||
|
|
||||||
|
headers = ["Mélange M₁", "Mélange M₂", "Mélange M₃"]
|
||||||
|
for i, h in enumerate(headers):
|
||||||
|
c = tbl_melanges.cell(0, i)
|
||||||
|
builder._set_cell_background(c, "0F2C59")
|
||||||
|
builder._set_cell_margins(c, top=80, bottom=80, left=100, right=100)
|
||||||
|
p = c.paragraphs[0]
|
||||||
|
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||||||
|
r = p.add_run(h)
|
||||||
|
r.bold = True
|
||||||
|
r.font.name = "Segoe UI"
|
||||||
|
r.font.size = Pt(9)
|
||||||
|
r.font.color.rgb = RGBColor(255, 255, 255)
|
||||||
|
|
||||||
|
contents = [
|
||||||
|
r"$V_1 = 20\ \mathrm{mL}$ de $(S_1)$" + "\n" + r"$V_2 = 30\ \mathrm{mL}$ de $(S_2)$",
|
||||||
|
r"$V_1 = 20\ \mathrm{mL}$ de $(S_1)$ ; $V_2 = 30\ \mathrm{mL}$ de $(S_2)$" + "\n" + r"$332\ \mathrm{mg}$ de $\mathrm{KI}$ en poudre" + "\n" + r"$V_e = 10\ \mathrm{mL}$ d'eau distillée",
|
||||||
|
r"$V_1 = 20\ \mathrm{mL}$ de $(S_1)$" + "\n" + r"$V_2 = 30\ \mathrm{mL}$ de $(S_2)$" + "\n" + r"$332\ \mathrm{mg}$ de $\mathrm{KI}$ en poudre"
|
||||||
|
]
|
||||||
|
for i, ct in enumerate(contents):
|
||||||
|
c = tbl_melanges.cell(1, i)
|
||||||
|
builder._set_cell_background(c, "F8FAFC" if i % 2 == 1 else "FFFFFF")
|
||||||
|
builder._set_cell_margins(c, top=80, bottom=80, left=80, right=80)
|
||||||
|
p = c.paragraphs[0]
|
||||||
|
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||||||
|
builder.add_math_to_paragraph(p, ct)
|
||||||
|
|
||||||
|
p_eq2 = doc.add_paragraph()
|
||||||
|
p_eq2.paragraph_format.space_before = Pt(3)
|
||||||
|
p_eq2.paragraph_format.space_after = Pt(2)
|
||||||
|
builder.add_math_to_paragraph(
|
||||||
|
p_eq2,
|
||||||
|
r"Les mélanges sont maintenus à une même température constante. La réaction lente et totale est modélisée par :"
|
||||||
|
)
|
||||||
|
|
||||||
|
builder.add_display_equation(
|
||||||
|
r"\mathrm{S}_2\mathrm{O}_8^{2-} + 2\mathrm{I}^- \rightarrow 2\mathrm{SO}_4^{2-} + \mathrm{I}_2",
|
||||||
|
space_before=2, space_after=2
|
||||||
|
)
|
||||||
|
|
||||||
|
p_rem2 = doc.add_paragraph()
|
||||||
|
p_rem2.paragraph_format.space_before = Pt(1)
|
||||||
|
p_rem2.paragraph_format.space_after = Pt(2)
|
||||||
|
builder.add_math_to_paragraph(p_rem2, r"On admet que la dissolution de $\mathrm{KI}$ solide est totale et sans variation de volume.")
|
||||||
|
|
||||||
|
builder.add_question(r"1) Pour le mélange $M_1$ :", space_before=2)
|
||||||
|
builder.add_question(r"a) Calculer les quantités initiales des réactifs, puis dresser le tableau descriptif d'évolution en avancement molaire $x$.", indent_level=1)
|
||||||
|
builder.add_question(r"b) Déterminer l'avancement final $x_{f1}$ de cette réaction et préciser le réactif limitant.", indent_level=1)
|
||||||
|
|
||||||
|
builder.add_question(r"2) Pour le mélange $M_2$ :", space_before=2)
|
||||||
|
builder.add_question(r"a) Calculer le volume total $V_{T2}$ ainsi que les concentrations initiales $[\mathrm{I}^-]_{0, M_2}$ et $[\mathrm{S}_2\mathrm{O}_8^{2-}]_{0, M_2}$. Dresser le tableau descriptif d'évolution en utilisant l'avancement volumique $y = x / V_{T2}$.", indent_level=1)
|
||||||
|
builder.add_question(r"b) Déterminer l'avancement volumique final $y_{f2}$ de cette réaction.", indent_level=1)
|
||||||
|
builder.add_question(r"c) En déduire $x_{f2}$. Justifier que ce résultat était prévisible sans faire de calcul.", indent_level=1)
|
||||||
|
|
||||||
|
builder.add_question(r"3) Dans lequel des deux mélanges $M_1$ et $M_2$ la vitesse maximale est-elle la plus élevée ? Justifier la réponse.", space_before=2)
|
||||||
|
|
||||||
|
builder.add_question(r"4) Le suivi expérimental au cours du temps des concentrations molaires et des quantités de matière des réactifs dans $M_1$ et $M_2$ a permis d'obtenir les courbes représentées sur les figures 2 et 3 de la feuille annexe :", space_before=2)
|
||||||
|
builder.add_question(r"a) Identifier, avec justification, les grandeurs $A$ et $B$ portées sur l'axe des ordonnées.", indent_level=1)
|
||||||
|
builder.add_question(r"b) Associer à chaque courbe le mélange correspondant ($M_1$ ou $M_2$).", indent_level=1)
|
||||||
|
builder.add_question(r"c) Vérifier graphiquement la réponse apportée à la question 3.", indent_level=1)
|
||||||
|
builder.add_question(r"d) Donner, pour chaque figure, l'échelle utilisée pour ces traçages.", indent_level=1)
|
||||||
|
|
||||||
|
builder.add_question(r"5) Représenter sur chaque figure de la feuille annexe, en justifiant la réponse, l'allure de la courbe correspondant au mélange $M_3$.", space_before=2)
|
||||||
|
|
||||||
|
# =========================================================================
|
||||||
|
# DEUXIÈME PARTIE : PHYSIQUE (11 points)
|
||||||
|
# =========================================================================
|
||||||
|
builder.add_page_break()
|
||||||
|
add_section_header("DEUXIÈME PARTIE : PHYSIQUE (11 points)")
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------------
|
||||||
|
# EXERCICE 1 (PHYSIQUE)
|
||||||
|
# -------------------------------------------------------------------------
|
||||||
|
builder.add_exercise_banner("1", "Dipôle RC — Charge à courant constant & Échelon de tension", points_str="7,25 points")
|
||||||
|
|
||||||
|
p_p1_mat = doc.add_paragraph()
|
||||||
|
p_p1_mat.paragraph_format.space_before = Pt(2)
|
||||||
|
p_p1_mat.paragraph_format.space_after = Pt(2)
|
||||||
|
builder.add_math_to_paragraph(
|
||||||
|
p_p1_mat,
|
||||||
|
r"On dispose du matériel suivant :" + "\n" +
|
||||||
|
r"• Un générateur idéal de courant délivrant un courant constant d'intensité $I$." + "\n" +
|
||||||
|
r"• Un générateur idéal de tension continue de f.e.m. $E$." + "\n" +
|
||||||
|
r"• Deux condensateurs de capacité $C_0$ et $C$, préalablement déchargés." + "\n" +
|
||||||
|
r"• Trois conducteurs ohmiques de résistances $R_0$, $R_1$ et $R_2$." + "\n" +
|
||||||
|
r"• Un commutateur $K$ (à deux positions $1$ et $2$) et un interrupteur $K_1$." + "\n" +
|
||||||
|
r"• Deux voltmètres $V_1$ et $V_2$ et un ampèremètre $A$."
|
||||||
|
)
|
||||||
|
|
||||||
|
# Bloc Section I avec Schéma du Circuit 1 à droite
|
||||||
|
tbl_p1 = doc.add_table(rows=1, cols=2)
|
||||||
|
tbl_p1.alignment = WD_TABLE_ALIGNMENT.CENTER
|
||||||
|
builder._set_table_borders_none(tbl_p1)
|
||||||
|
cp1_l, cp1_r = tbl_p1.cell(0, 0), tbl_p1.cell(0, 1)
|
||||||
|
cp1_l.width = Inches(4.3)
|
||||||
|
cp1_r.width = Inches(2.9)
|
||||||
|
|
||||||
|
p_cp1_l = cp1_l.paragraphs[0]
|
||||||
|
p_cp1_l.paragraph_format.space_before = Pt(0)
|
||||||
|
p_cp1_l.paragraph_format.space_after = Pt(2)
|
||||||
|
builder.add_math_to_paragraph(
|
||||||
|
p_cp1_l,
|
||||||
|
r"I] On réalise le montage représenté ci-contre :" + "\n\n" +
|
||||||
|
r"L'interrupteur $K_1$ étant ouvert, à l'instant $t = 0$, on bascule le commutateur $K$ en position 1." + "\n" +
|
||||||
|
r"• À la date $t_1 = 10\ \mathrm{s}$, le voltmètre $(V_2)$ indique $1{,}3\ \mathrm{V}$." + "\n" +
|
||||||
|
r"• À la date $t_2 = 20\ \mathrm{s}$, le voltmètre $(V_1)$ indique $2\ \mathrm{V}$." + "\n\n" +
|
||||||
|
r"1) Établir l'expression de la tension $u_G$ aux bornes du générateur de courant en fonction de $I, C_0, R_1, R_2$ et $t$." + "\n\n" +
|
||||||
|
r"2) En déduire que $(R_1 + R_2) I = 0{,}3\ \mathrm{V}$."
|
||||||
|
)
|
||||||
|
|
||||||
|
circ1_path = os.path.join(CURRENT_DIR, "fig_physique_circuit_1.png")
|
||||||
|
p_cp1_r = cp1_r.paragraphs[0]
|
||||||
|
p_cp1_r.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||||||
|
if os.path.exists(circ1_path):
|
||||||
|
p_cp1_r.add_run().add_picture(circ1_path, width=Inches(2.8))
|
||||||
|
|
||||||
|
builder.add_question(r"3) À l'instant $t_3 = 25\ \mathrm{s}$, on ouvre $K$ et on ferme simultanément l'interrupteur $K_1$.", space_before=2)
|
||||||
|
builder.add_question(r"a) Représenter sur votre copie le schéma du circuit fermé lors de cette phase et indiquer le sens de circulation des électrons.", indent_level=1)
|
||||||
|
builder.add_question(r"b) On note $I_0$ l'intensité du courant indiquée par l'ampèremètre juste après la fermeture de $K_1$. Sachant que $|I_0| = 1{,}25\ \mathrm{mA}$, déterminer la valeur de la résistance $R_2$.", indent_level=1)
|
||||||
|
builder.add_question(r"c) L'énergie dissipée par effet Joule dans le résistor $R_2$ à la fin de la décharge complète du condensateur est $E_D = 31{,}25 \cdot 10^{-4}\ \mathrm{J}$. Déterminer les valeurs de la capacité $C_0$, de l'intensité $I$ du générateur de courant, puis de la résistance $R_1$.", indent_level=1)
|
||||||
|
|
||||||
|
p_p1_part2 = doc.add_paragraph()
|
||||||
|
p_p1_part2.paragraph_format.space_before = Pt(3)
|
||||||
|
p_p1_part2.paragraph_format.space_after = Pt(2)
|
||||||
|
builder.add_math_to_paragraph(
|
||||||
|
p_p1_part2,
|
||||||
|
r"II] Tous les interrupteurs étant de nouveau ouverts, on remplace le condensateur de capacité $C_0$ par l'autre condensateur de capacité $C$. À un instant pris comme nouvelle origine des temps ($t = 0$), on ferme le commutateur $K$ en position 2."
|
||||||
|
)
|
||||||
|
|
||||||
|
builder.add_question(r"1) a) Établir l'équation différentielle régissant les variations de la tension $u_{R_0}(t)$ aux bornes du résistor $R_0$.", indent_level=0)
|
||||||
|
builder.add_question(r"b) Déduire que l'équation différentielle qui régit les variations de la tension $u(t)$ aux bornes du dipôle s'écrit :", indent_level=0, space_before=2)
|
||||||
|
builder.add_display_equation(r"\tau \frac{du}{dt} + u = E \quad \text{avec} \quad \tau = C(R_2 + R_0)", space_before=2, space_after=2)
|
||||||
|
builder.add_question(r"c) Déduire l'équation différentielle régissant la tension $u_C(t)$ aux bornes du condensateur, puis vérifier que la solution s'écrit :", indent_level=0, space_before=2)
|
||||||
|
builder.add_display_equation(r"u_C(t) = E\left(1 - e^{-t/\tau}\right)", space_before=2, space_after=2)
|
||||||
|
builder.add_question(r"d) La solution de l'équation différentielle en $u(t)$ s'écrit sous la forme : $u(t) = A(1 - e^{-t/\tau}) + B$. Exprimer les constantes $A$ et $B$ en fonction de $R_2, R_0$ et $E$.", indent_level=0, space_before=2)
|
||||||
|
|
||||||
|
builder.add_question(r"2) On donne sur la Figure 4 de la feuille annexe les deux courbes $(C_1)$ et $(C_2)$ incomplètes, correspondant respectivement à $u_C(t)$ et $u(t)$.", space_before=2)
|
||||||
|
builder.add_question(r"Soient $(T_1)$ la tangente à $(C_1)$ à un instant $t$ et $(T_2)$ la tangente à $(C_2)$ au même instant $t$. Le coefficient directeur $a_1$ de $(T_1)$ est égal à 3 fois le coefficient directeur $a_2$ de $(T_2)$ : $a_1 = 3 a_2$.", indent_level=0)
|
||||||
|
builder.add_question(r"a) En utilisant les équations différentielles relatives à $u(t)$ et $u_C(t)$, montrer que : $R_2 = 2 R_0$.", indent_level=1)
|
||||||
|
builder.add_question(r"b) Sachant qu'à l'instant $t'$, représenté sur la figure 4, le condensateur est chargé à 63%, compléter en le justifiant les deux courbes $(C_1)$ et $(C_2)$ sur la feuille annexe.", indent_level=1)
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------------
|
||||||
|
# EXERCICE 2 (PHYSIQUE)
|
||||||
|
# -------------------------------------------------------------------------
|
||||||
|
builder.add_page_break()
|
||||||
|
builder.add_exercise_banner("2", "Induction et auto-induction électromagnétiques", points_str="3,75 points")
|
||||||
|
|
||||||
|
p_exp1_ti = doc.add_paragraph()
|
||||||
|
p_exp1_ti.paragraph_format.space_before = Pt(2)
|
||||||
|
p_exp1_ti.paragraph_format.space_after = Pt(2)
|
||||||
|
r_exp1 = p_exp1_ti.add_run("Expérience 1")
|
||||||
|
r_exp1.bold = True
|
||||||
|
r_exp1.font.name = "Segoe UI"
|
||||||
|
r_exp1.font.size = Pt(10)
|
||||||
|
r_exp1.font.color.rgb = RGBColor(15, 44, 89)
|
||||||
|
|
||||||
|
p_exp1_txt = doc.add_paragraph()
|
||||||
|
p_exp1_txt.paragraph_format.space_before = Pt(1)
|
||||||
|
p_exp1_txt.paragraph_format.space_after = Pt(2)
|
||||||
|
builder.add_math_to_paragraph(
|
||||||
|
p_exp1_txt,
|
||||||
|
r"On réalise le montage de la Figure 5 de la feuille annexe, constitué d'une bobine fermée sur deux diodes électroluminescentes (LED) $D_1$ et $D_2$ montées en dérivation tête-bêche." + "\n" +
|
||||||
|
r"On fait passer un aimant droit suivant l'axe $(\Delta)$ de la bobine, entrant par la face A et sortant par la face B."
|
||||||
|
)
|
||||||
|
|
||||||
|
builder.add_question(r"1) À l'entrée de l'aimant par la face A de la bobine, la diode $D_1$ s'allume.", space_before=2)
|
||||||
|
builder.add_question(r"a) Nommer le phénomène physique mis en jeu dans la bobine.", indent_level=1)
|
||||||
|
builder.add_question(r"b) Préciser le rôle joué par l'aimant et par la bobine.", indent_level=1)
|
||||||
|
builder.add_question(r"c) Représenter, sur la figure 5 de la feuille annexe, le champ magnétique $\vec{B}$ créé par la bobine.", indent_level=1)
|
||||||
|
builder.add_question(r"d) Énoncer la loi de Lenz.", indent_level=1)
|
||||||
|
|
||||||
|
builder.add_question(r"2) Indiquer, en justifiant la réponse, la diode qui s'allume lorsque l'aimant sort par la face B de la bobine.", space_before=2)
|
||||||
|
|
||||||
|
p_exp2_ti = doc.add_paragraph()
|
||||||
|
p_exp2_ti.paragraph_format.space_before = Pt(4)
|
||||||
|
p_exp2_ti.paragraph_format.space_after = Pt(2)
|
||||||
|
r_exp2 = p_exp2_ti.add_run("Expérience 2")
|
||||||
|
r_exp2.bold = True
|
||||||
|
r_exp2.font.name = "Segoe UI"
|
||||||
|
r_exp2.font.size = Pt(10)
|
||||||
|
r_exp2.font.color.rgb = RGBColor(15, 44, 89)
|
||||||
|
|
||||||
|
# Bloc Expérience 2 avec schéma circuit lampes à droite
|
||||||
|
tbl_exp2 = doc.add_table(rows=1, cols=2)
|
||||||
|
tbl_exp2.alignment = WD_TABLE_ALIGNMENT.CENTER
|
||||||
|
builder._set_table_borders_none(tbl_exp2)
|
||||||
|
ce2_l, ce2_r = tbl_exp2.cell(0, 0), tbl_exp2.cell(0, 1)
|
||||||
|
ce2_l.width = Inches(4.3)
|
||||||
|
ce2_r.width = Inches(2.9)
|
||||||
|
|
||||||
|
p_ce2_l = ce2_l.paragraphs[0]
|
||||||
|
p_ce2_l.paragraph_format.space_before = Pt(0)
|
||||||
|
p_ce2_l.paragraph_format.space_after = Pt(2)
|
||||||
|
builder.add_math_to_paragraph(
|
||||||
|
p_ce2_l,
|
||||||
|
r"On considère le circuit représenté ci-contre, formé par un générateur idéal de tension continue de f.e.m. $E$, trois lampes identiques ($L_1, L_2$ et $L_3$), trois dipôles ($D_1, D_2$ et $D_3$) et un interrupteur $K$." + "\n\n" +
|
||||||
|
r"Les trois dipôles sont : une bobine $B(L, r)$, une bobine $B'(L', r')$ avec $L' > L$, et un conducteur ohmique de résistance $R$."
|
||||||
|
)
|
||||||
|
|
||||||
|
circ_lampes_path = os.path.join(CURRENT_DIR, "fig_physique_circuit_lampes.png")
|
||||||
|
p_ce2_r = ce2_r.paragraphs[0]
|
||||||
|
p_ce2_r.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||||||
|
if os.path.exists(circ_lampes_path):
|
||||||
|
p_ce2_r.add_run().add_picture(circ_lampes_path, width=Inches(2.8))
|
||||||
|
|
||||||
|
p_exp2_obs = doc.add_paragraph()
|
||||||
|
p_exp2_obs.paragraph_format.space_before = Pt(2)
|
||||||
|
p_exp2_obs.paragraph_format.space_after = Pt(2)
|
||||||
|
builder.add_math_to_paragraph(
|
||||||
|
p_exp2_obs,
|
||||||
|
r"Lorsqu'on ferme l'interrupteur $K$, on observe les faits suivants :" + "\n" +
|
||||||
|
r"• La lampe $L_1$ s'allume instantanément avec un éclat maximal." + "\n" +
|
||||||
|
r"• La lampe $L_2$ atteint le même éclat maximal que $L_1$ après un léger retard." + "\n" +
|
||||||
|
r"• La lampe $L_3$ prend encore plus de temps que $L_2$ pour atteindre son éclat maximal, mais celui-ci est moins intense."
|
||||||
|
)
|
||||||
|
|
||||||
|
builder.add_question(r"1) Préciser, avec justification, la nature de chaque dipôle ($D_1, D_2$ et $D_3$).", space_before=2)
|
||||||
|
builder.add_question(r"2) Prouver que les deux bobines ne sont pas purement inductives.", space_before=2)
|
||||||
|
builder.add_question(r"3) Comparer, en le justifiant, les résistances internes des deux bobines par rapport à la résistance $R$ du conducteur ohmique.", space_before=2)
|
||||||
|
|
||||||
|
# =========================================================================
|
||||||
|
# TROISIÈME PARTIE : FEUILLE ANNEXE
|
||||||
|
# =========================================================================
|
||||||
|
builder.add_page_break()
|
||||||
|
|
||||||
|
tbl_annexe = doc.add_table(rows=1, cols=2)
|
||||||
|
tbl_annexe.alignment = WD_TABLE_ALIGNMENT.CENTER
|
||||||
|
builder._set_table_borders_none(tbl_annexe)
|
||||||
|
ca_l, ca_r = tbl_annexe.cell(0, 0), tbl_annexe.cell(0, 1)
|
||||||
|
builder._set_cell_background(ca_l, "F8FAFC")
|
||||||
|
builder._set_cell_background(ca_r, "F8FAFC")
|
||||||
|
builder._set_cell_margins(ca_l, top=60, bottom=60, left=120, right=80)
|
||||||
|
builder._set_cell_margins(ca_r, top=60, bottom=60, left=80, right=120)
|
||||||
|
ca_l.width = Inches(3.5)
|
||||||
|
ca_r.width = Inches(3.7)
|
||||||
|
|
||||||
|
pa_l = ca_l.paragraphs[0]
|
||||||
|
r_titre_ann = pa_l.add_run("FEUILLE ANNEXE À RENDRE AVEC LA COPIE\n")
|
||||||
|
r_titre_ann.bold = True
|
||||||
|
r_titre_ann.font.name = "Segoe UI"
|
||||||
|
r_titre_ann.font.size = Pt(9.5)
|
||||||
|
r_titre_ann.font.color.rgb = RGBColor(15, 44, 89)
|
||||||
|
r_sub_ann = pa_l.add_run("Épreuve : Sciences Physiques (Chimie & Physique) | 4ème Sc.Exp")
|
||||||
|
r_sub_ann.font.name = "Cambria"
|
||||||
|
r_sub_ann.font.size = Pt(8)
|
||||||
|
r_sub_ann.font.color.rgb = RGBColor(100, 116, 139)
|
||||||
|
|
||||||
|
pa_r = ca_r.paragraphs[0]
|
||||||
|
pa_r.paragraph_format.line_spacing = 1.2
|
||||||
|
builder.add_math_to_paragraph(
|
||||||
|
pa_r,
|
||||||
|
"Nom & Prénom : ____________________________________\n"
|
||||||
|
"Classe : ___________________ N° : _________"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Grille 1 : Figure 1 & Figure 4 côte à côte
|
||||||
|
tbl_grid1 = doc.add_table(rows=1, cols=2)
|
||||||
|
tbl_grid1.alignment = WD_TABLE_ALIGNMENT.CENTER
|
||||||
|
builder._set_table_borders_none(tbl_grid1)
|
||||||
|
cg1_l, cg1_r = tbl_grid1.cell(0, 0), tbl_grid1.cell(0, 1)
|
||||||
|
cg1_l.width = Inches(3.6)
|
||||||
|
cg1_r.width = Inches(3.6)
|
||||||
|
|
||||||
|
fig1_path = os.path.join(CURRENT_DIR, "fig_exercice_1.png")
|
||||||
|
fig4_path = os.path.join(CURRENT_DIR, "fig_physique_fig4.png")
|
||||||
|
|
||||||
|
p_g1_l = cg1_l.paragraphs[0]
|
||||||
|
p_g1_l.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||||||
|
r1 = p_g1_l.add_run("Figure 1 — Chimie Ex 1 (Avancement x = f(t))\n")
|
||||||
|
r1.bold = True
|
||||||
|
r1.font.size = Pt(8.5)
|
||||||
|
r1.font.color.rgb = RGBColor(30, 64, 175)
|
||||||
|
if os.path.exists(fig1_path):
|
||||||
|
p_g1_l.add_run().add_picture(fig1_path, width=Inches(3.2))
|
||||||
|
|
||||||
|
p_g1_r = cg1_r.paragraphs[0]
|
||||||
|
p_g1_r.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||||||
|
r4 = p_g1_r.add_run("Figure 4 — Physique Ex 1 (Tensions u_C et u)\n")
|
||||||
|
r4.bold = True
|
||||||
|
r4.font.size = Pt(8.5)
|
||||||
|
r4.font.color.rgb = RGBColor(30, 64, 175)
|
||||||
|
if os.path.exists(fig4_path):
|
||||||
|
p_g1_r.add_run().add_picture(fig4_path, width=Inches(3.2))
|
||||||
|
|
||||||
|
# Grille 2 : Figure 2 & Figure 3 côte à côte
|
||||||
|
tbl_grid2 = doc.add_table(rows=1, cols=2)
|
||||||
|
tbl_grid2.alignment = WD_TABLE_ALIGNMENT.CENTER
|
||||||
|
builder._set_table_borders_none(tbl_grid2)
|
||||||
|
cg2_l, cg2_r = tbl_grid2.cell(0, 0), tbl_grid2.cell(0, 1)
|
||||||
|
cg2_l.width = Inches(3.6)
|
||||||
|
cg2_r.width = Inches(3.6)
|
||||||
|
|
||||||
|
fig2_path = os.path.join(CURRENT_DIR, "fig_exercice_2_fig2.png")
|
||||||
|
fig3_path = os.path.join(CURRENT_DIR, "fig_exercice_2_fig3.png")
|
||||||
|
|
||||||
|
p_g2_l = cg2_l.paragraphs[0]
|
||||||
|
p_g2_l.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||||||
|
r2 = p_g2_l.add_run("Figure 2 — Chimie Ex 2 (Grandeur A)\n")
|
||||||
|
r2.bold = True
|
||||||
|
r2.font.size = Pt(8.5)
|
||||||
|
r2.font.color.rgb = RGBColor(30, 64, 175)
|
||||||
|
if os.path.exists(fig2_path):
|
||||||
|
p_g2_l.add_run().add_picture(fig2_path, width=Inches(3.1))
|
||||||
|
|
||||||
|
p_g2_r = cg2_r.paragraphs[0]
|
||||||
|
p_g2_r.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||||||
|
r3 = p_g2_r.add_run("Figure 3 — Chimie Ex 2 (Grandeur B)\n")
|
||||||
|
r3.bold = True
|
||||||
|
r3.font.size = Pt(8.5)
|
||||||
|
r3.font.color.rgb = RGBColor(30, 64, 175)
|
||||||
|
if os.path.exists(fig3_path):
|
||||||
|
p_g2_r.add_run().add_picture(fig3_path, width=Inches(3.1))
|
||||||
|
|
||||||
|
# Figure 5 : Physique Ex 2 (Induction)
|
||||||
|
fig5_path = os.path.join(CURRENT_DIR, "fig_physique_fig5.png")
|
||||||
|
p_g5 = doc.add_paragraph()
|
||||||
|
p_g5.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||||||
|
p_g5.paragraph_format.space_before = Pt(3)
|
||||||
|
p_g5.paragraph_format.space_after = Pt(2)
|
||||||
|
r5 = p_g5.add_run("Figure 5 — Physique Ex 2 (Induction électromagnétique)\n")
|
||||||
|
r5.bold = True
|
||||||
|
r5.font.size = Pt(8.5)
|
||||||
|
r5.font.color.rgb = RGBColor(30, 64, 175)
|
||||||
|
if os.path.exists(fig5_path):
|
||||||
|
p_g5.add_run().add_picture(fig5_path, width=Inches(3.3))
|
||||||
|
r5_sub = p_g5.add_run("\nReprésenter le champ magnétique induit B créé par la bobine")
|
||||||
|
r5_sub.font.italic = True
|
||||||
|
r5_sub.font.size = Pt(7.5)
|
||||||
|
r5_sub.font.color.rgb = RGBColor(100, 116, 139)
|
||||||
|
|
||||||
|
if output_path is None:
|
||||||
|
output_path = os.path.join(CURRENT_DIR, "Serie_devoir_chimie_Heykel_Zayani.docx")
|
||||||
|
builder.save(output_path)
|
||||||
|
return output_path
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
build_docx()
|
||||||
+168
-3
@@ -2,7 +2,8 @@
|
|||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
"""
|
"""
|
||||||
serie_docx_builder.py
|
serie_docx_builder.py
|
||||||
Constructeur de document Word (.docx) avec équations natives OMML et support de thèmes.
|
Constructeur de document Word (.docx) avec équations natives OMML, gestion des types
|
||||||
|
(série, corrigé, résumé), matières scientifiques (chimie, réactions) et support des thèmes.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import os
|
import os
|
||||||
@@ -27,6 +28,33 @@ def hex_to_rgb(hex_str: str) -> RGBColor:
|
|||||||
def hex_clean(hex_str: str) -> str:
|
def hex_clean(hex_str: str) -> str:
|
||||||
return hex_str.lstrip("#").upper()
|
return hex_str.lstrip("#").upper()
|
||||||
|
|
||||||
|
def latex_to_text(l: str) -> str:
|
||||||
|
"""Traduit des formules LaTeX simples en texte lisible pour correspondre au texte extrait du PDF Typst."""
|
||||||
|
s = l.strip()
|
||||||
|
s = re.sub(r"\\mathbb\{([A-Za-z]+)\}", r"\1", s)
|
||||||
|
s = s.replace(r"\Delta", "Δ")
|
||||||
|
s = s.replace(r"\quad", " ")
|
||||||
|
s = s.replace(r"\text{et}", "et")
|
||||||
|
s = s.replace(r"\text", "")
|
||||||
|
s = s.replace(r"z \bar{z} = |z|^2", "zz= |z|2")
|
||||||
|
s = s.replace(r"z \bar{z}", "zz")
|
||||||
|
s = s.replace(r"z \overline{z}", "zz")
|
||||||
|
s = s.replace(r"\bar{z}", "z")
|
||||||
|
s = s.replace(r"\overline{z}", "z")
|
||||||
|
s = s.replace(r"\overline", "")
|
||||||
|
s = re.sub(r"\\frac\{([^}]+)\}\{([^}]+)\}", r"\1 \2", s)
|
||||||
|
s = s.replace(r"\mathrm", "")
|
||||||
|
s = s.replace(r"\longrightarrow", "⟶")
|
||||||
|
s = s.replace(r"\cdot", "")
|
||||||
|
s = s.replace("{", "").replace("}", "")
|
||||||
|
s = s.replace("\\,", " ").replace("\\ ", " ")
|
||||||
|
s = s.replace("^", "")
|
||||||
|
s = s.replace("_", "")
|
||||||
|
s = s.replace("\\", "")
|
||||||
|
s = s.replace("z = ", "z=").replace("z =", "z=")
|
||||||
|
s = s.replace("a + ", "a+").replace("a +", "a+")
|
||||||
|
return s.strip()
|
||||||
|
|
||||||
class SerieDocxBuilder:
|
class SerieDocxBuilder:
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
@@ -40,7 +68,8 @@ class SerieDocxBuilder:
|
|||||||
titre_enseignant="P.P.É.C.E.",
|
titre_enseignant="P.P.É.C.E.",
|
||||||
type_doc="SÉRIE D'EXERCICES",
|
type_doc="SÉRIE D'EXERCICES",
|
||||||
theme=None,
|
theme=None,
|
||||||
xslt_path=None
|
xslt_path=None,
|
||||||
|
vanish_math=False
|
||||||
):
|
):
|
||||||
self.titre = titre
|
self.titre = titre
|
||||||
self.sous_titre = sous_titre
|
self.sous_titre = sous_titre
|
||||||
@@ -51,6 +80,7 @@ class SerieDocxBuilder:
|
|||||||
self.lycee = lycee
|
self.lycee = lycee
|
||||||
self.titre_enseignant = titre_enseignant
|
self.titre_enseignant = titre_enseignant
|
||||||
self.type_doc = type_doc
|
self.type_doc = type_doc
|
||||||
|
self.vanish_math = vanish_math
|
||||||
|
|
||||||
# Thème graphique
|
# Thème graphique
|
||||||
self.theme = theme or {}
|
self.theme = theme or {}
|
||||||
@@ -166,6 +196,21 @@ class SerieDocxBuilder:
|
|||||||
)
|
)
|
||||||
tblPr.append(borders)
|
tblPr.append(borders)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def set_table_borders(table, color="94A3B8", sz="4"):
|
||||||
|
tblPr = table._tbl.tblPr
|
||||||
|
borders = parse_xml(
|
||||||
|
f'<w:tblBorders {nsdecls("w")}>'
|
||||||
|
f'<w:top w:val="single" w:sz="{sz}" w:space="0" w:color="{color}"/>'
|
||||||
|
f'<w:bottom w:val="single" w:sz="{sz}" w:space="0" w:color="{color}"/>'
|
||||||
|
f'<w:left w:val="single" w:sz="{sz}" w:space="0" w:color="{color}"/>'
|
||||||
|
f'<w:right w:val="single" w:sz="{sz}" w:space="0" w:color="{color}"/>'
|
||||||
|
f'<w:insideH w:val="single" w:sz="{sz}" w:space="0" w:color="{color}"/>'
|
||||||
|
f'<w:insideV w:val="single" w:sz="{sz}" w:space="0" w:color="{color}"/>'
|
||||||
|
f'</w:tblBorders>'
|
||||||
|
)
|
||||||
|
tblPr.append(borders)
|
||||||
|
|
||||||
def _create_header_cartouche(self):
|
def _create_header_cartouche(self):
|
||||||
"""Crée le cartouche officiel en 3 colonnes."""
|
"""Crée le cartouche officiel en 3 colonnes."""
|
||||||
cartouche = self.doc.add_table(rows=1, cols=3)
|
cartouche = self.doc.add_table(rows=1, cols=3)
|
||||||
@@ -245,6 +290,7 @@ class SerieDocxBuilder:
|
|||||||
r_pr2.font.size = Pt(10.5)
|
r_pr2.font.size = Pt(10.5)
|
||||||
r_pr2.font.color.rgb = hex_to_rgb(self.col_secondary)
|
r_pr2.font.color.rgb = hex_to_rgb(self.col_secondary)
|
||||||
|
|
||||||
|
if not self.vanish_math:
|
||||||
# Ligne de séparation
|
# Ligne de séparation
|
||||||
p_sep = self.doc.add_paragraph()
|
p_sep = self.doc.add_paragraph()
|
||||||
p_sep.paragraph_format.space_before = Pt(4)
|
p_sep.paragraph_format.space_before = Pt(4)
|
||||||
@@ -293,7 +339,8 @@ class SerieDocxBuilder:
|
|||||||
p_right.paragraph_format.space_after = Pt(0)
|
p_right.paragraph_format.space_after = Pt(0)
|
||||||
|
|
||||||
if points_str:
|
if points_str:
|
||||||
run_pts = p_right.add_run(f"[{points_str}]")
|
pts_label = f"{points_str}" if self.vanish_math else f"[{points_str}]"
|
||||||
|
run_pts = p_right.add_run(pts_label)
|
||||||
run_pts.bold = True
|
run_pts.bold = True
|
||||||
run_pts.font.size = Pt(9.5)
|
run_pts.font.size = Pt(9.5)
|
||||||
run_pts.font.color.rgb = hex_to_rgb(self.col_points)
|
run_pts.font.color.rgb = hex_to_rgb(self.col_points)
|
||||||
@@ -311,6 +358,11 @@ class SerieDocxBuilder:
|
|||||||
run.font.color.rgb = RGBColor(15, 23, 42)
|
run.font.color.rgb = RGBColor(15, 23, 42)
|
||||||
else:
|
else:
|
||||||
if part:
|
if part:
|
||||||
|
if self.vanish_math:
|
||||||
|
clean_txt = latex_to_text(part)
|
||||||
|
if clean_txt:
|
||||||
|
v_run = parse_xml(f'<w:r {nsdecls("w")}><w:rPr><w:vanish/></w:rPr><w:t xml:space="preserve">{clean_txt}</w:t></w:r>')
|
||||||
|
p._element.append(v_run)
|
||||||
omml_elem = self.latex_to_omml(part)
|
omml_elem = self.latex_to_omml(part)
|
||||||
p._element.append(omml_elem)
|
p._element.append(omml_elem)
|
||||||
|
|
||||||
@@ -333,12 +385,125 @@ class SerieDocxBuilder:
|
|||||||
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||||||
p.paragraph_format.space_before = Pt(space_before)
|
p.paragraph_format.space_before = Pt(space_before)
|
||||||
p.paragraph_format.space_after = Pt(space_after)
|
p.paragraph_format.space_after = Pt(space_after)
|
||||||
|
if self.vanish_math:
|
||||||
|
clean_txt = latex_to_text(latex_eq)
|
||||||
|
if clean_txt:
|
||||||
|
v_run = parse_xml(f'<w:r {nsdecls("w")}><w:rPr><w:vanish/></w:rPr><w:t xml:space="preserve">{clean_txt}</w:t></w:r>')
|
||||||
|
p._element.append(v_run)
|
||||||
omml_elem = self.latex_to_omml(latex_eq)
|
omml_elem = self.latex_to_omml(latex_eq)
|
||||||
oMathPara = parse_xml(f'<m:oMathPara {nsdecls("m")}/>')
|
oMathPara = parse_xml(f'<m:oMathPara {nsdecls("m")}/>')
|
||||||
oMathPara.append(omml_elem)
|
oMathPara.append(omml_elem)
|
||||||
p._element.append(oMathPara)
|
p._element.append(oMathPara)
|
||||||
return p
|
return p
|
||||||
|
|
||||||
|
def add_reaction(self, latex_eq, space_before=4, space_after=4):
|
||||||
|
"""Ajoute une réaction chimique avec OMML natif et flèche."""
|
||||||
|
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)
|
||||||
|
if self.vanish_math:
|
||||||
|
clean_txt = latex_to_text(latex_eq)
|
||||||
|
if clean_txt:
|
||||||
|
v_run = parse_xml(f'<w:r {nsdecls("w")}><w:rPr><w:vanish/></w:rPr><w:t xml:space="preserve">{clean_txt}</w:t></w:r>')
|
||||||
|
p._element.append(v_run)
|
||||||
|
omml_elem = self.latex_to_omml(latex_eq)
|
||||||
|
oMathPara = parse_xml(f'<m:oMathPara {nsdecls("m")}/>')
|
||||||
|
oMathPara.append(omml_elem)
|
||||||
|
p._element.append(oMathPara)
|
||||||
|
return p
|
||||||
|
|
||||||
|
def add_labeled_block(self, label, text_with_math, points_str=None, space_before=2, space_after=2, label_color=None, is_italic=False, border_box=False):
|
||||||
|
"""Ajoute un bloc avec libellé visible pour corrigé ou résumé."""
|
||||||
|
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
|
||||||
|
|
||||||
|
r_lbl = p.add_run(f"{label} ")
|
||||||
|
r_lbl.bold = True
|
||||||
|
r_lbl.italic = is_italic
|
||||||
|
r_lbl.font.name = self.font_main
|
||||||
|
r_lbl.font.size = Pt(10.5)
|
||||||
|
col_hex = label_color or self.col_primary
|
||||||
|
r_lbl.font.color.rgb = hex_to_rgb(col_hex)
|
||||||
|
|
||||||
|
self.add_math_to_paragraph(p, text_with_math, base_font_size=10.5)
|
||||||
|
|
||||||
|
if points_str:
|
||||||
|
r_pts = p.add_run(f" [{points_str}]")
|
||||||
|
r_pts.bold = True
|
||||||
|
r_pts.font.name = self.font_main
|
||||||
|
r_pts.font.size = Pt(9.5)
|
||||||
|
r_pts.font.color.rgb = hex_to_rgb(self.col_secondary)
|
||||||
|
|
||||||
|
return p
|
||||||
|
|
||||||
|
def add_section_header(self, title_text):
|
||||||
|
"""Ajoute un bandeau de section centré sur fond coloré."""
|
||||||
|
p = self.doc.add_paragraph()
|
||||||
|
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||||||
|
p.paragraph_format.space_before = Pt(6)
|
||||||
|
p.paragraph_format.space_after = Pt(4)
|
||||||
|
r = p.add_run(f" {title_text} ")
|
||||||
|
r.bold = True
|
||||||
|
r.font.name = self.font_banner
|
||||||
|
r.font.size = Pt(11)
|
||||||
|
r.font.color.rgb = RGBColor(255, 255, 255)
|
||||||
|
pPr = p._p.get_or_add_pPr()
|
||||||
|
shd = parse_xml(f'<w:shd {nsdecls("w")} w:fill="{self.col_primary}" w:val="clear" w:color="auto"/>')
|
||||||
|
pPr.append(shd)
|
||||||
|
return p
|
||||||
|
|
||||||
|
def add_preamble(self, text):
|
||||||
|
"""Ajoute une remarque d'en-tête (N.B.)."""
|
||||||
|
p = self.doc.add_paragraph()
|
||||||
|
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||||||
|
p.paragraph_format.space_before = Pt(0)
|
||||||
|
p.paragraph_format.space_after = Pt(4)
|
||||||
|
r = p.add_run(text)
|
||||||
|
r.font.name = self.font_main
|
||||||
|
r.font.size = Pt(8.5)
|
||||||
|
r.font.italic = True
|
||||||
|
r.font.color.rgb = RGBColor(71, 85, 105)
|
||||||
|
return p
|
||||||
|
|
||||||
|
def add_table(self, headers, rows):
|
||||||
|
"""Ajoute un tableau officiel stylisé avec bordures et OMML."""
|
||||||
|
num_cols = len(headers) if headers else (len(rows[0]) if rows else 1)
|
||||||
|
total_rows = (1 if headers else 0) + len(rows)
|
||||||
|
tbl = self.doc.add_table(rows=total_rows, cols=num_cols)
|
||||||
|
tbl.alignment = WD_TABLE_ALIGNMENT.CENTER
|
||||||
|
self.set_table_borders(tbl, color=self.col_border, sz="4")
|
||||||
|
|
||||||
|
row_offset = 0
|
||||||
|
if headers:
|
||||||
|
for c_idx, h in enumerate(headers):
|
||||||
|
cell = tbl.cell(0, c_idx)
|
||||||
|
self._set_cell_background(cell, self.col_bg_subtle)
|
||||||
|
self._set_cell_margins(cell, top=60, bottom=60, left=80, right=80)
|
||||||
|
p = cell.paragraphs[0]
|
||||||
|
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||||||
|
self.add_math_to_paragraph(p, str(h), base_font_size=9)
|
||||||
|
for r in p.runs:
|
||||||
|
r.bold = True
|
||||||
|
r.font.name = self.font_main
|
||||||
|
r.font.color.rgb = hex_to_rgb(self.col_primary)
|
||||||
|
row_offset = 1
|
||||||
|
|
||||||
|
for r_idx, row in enumerate(rows):
|
||||||
|
for c_idx, val in enumerate(row):
|
||||||
|
cell = tbl.cell(r_idx + row_offset, c_idx)
|
||||||
|
self._set_cell_margins(cell, top=50, bottom=50, left=80, right=80)
|
||||||
|
p = cell.paragraphs[0]
|
||||||
|
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||||||
|
self.add_math_to_paragraph(p, str(val), base_font_size=8.5)
|
||||||
|
|
||||||
|
p_after = self.doc.add_paragraph()
|
||||||
|
p_after.paragraph_format.space_before = Pt(2)
|
||||||
|
p_after.paragraph_format.space_after = Pt(2)
|
||||||
|
return tbl
|
||||||
|
|
||||||
def add_part_header(self, bold_prefix, text_with_math, space_before=3, space_after=2):
|
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°) ')."""
|
"""Ajoute un en-tête de partie ('I°) ', 'II°) ')."""
|
||||||
p = self.doc.add_paragraph()
|
p = self.doc.add_paragraph()
|
||||||
|
|||||||
@@ -139,9 +139,14 @@
|
|||||||
color_secondary: rgb("#1e40af"),
|
color_secondary: rgb("#1e40af"),
|
||||||
color_accent: rgb("#93c5fd"),
|
color_accent: rgb("#93c5fd"),
|
||||||
color_border: rgb("#cbd5e1"),
|
color_border: rgb("#cbd5e1"),
|
||||||
|
theme_name: "classique",
|
||||||
body
|
body
|
||||||
) = {
|
) = {
|
||||||
v(6pt)
|
v(6pt)
|
||||||
|
if theme_name == "encre" [
|
||||||
|
#rect(width: 100%, height: 7pt, fill: rgb("#1f2937"), radius: (top: 3pt, bottom: 0pt))
|
||||||
|
#v(-7pt)
|
||||||
|
]
|
||||||
block(
|
block(
|
||||||
width: 100%,
|
width: 100%,
|
||||||
stroke: 0.8pt + color_border,
|
stroke: 0.8pt + color_border,
|
||||||
@@ -150,6 +155,71 @@
|
|||||||
fill: rgb("#ffffff"),
|
fill: rgb("#ffffff"),
|
||||||
breakable: breakable_box,
|
breakable: breakable_box,
|
||||||
[
|
[
|
||||||
|
#if theme_name == "sobre" [
|
||||||
|
#block(
|
||||||
|
fill: rgb("#f8fafc"),
|
||||||
|
stroke: (bottom: 1pt + color_border),
|
||||||
|
width: 100%,
|
||||||
|
inset: (x: 10pt, y: 5.5pt),
|
||||||
|
grid(
|
||||||
|
columns: (1fr, auto),
|
||||||
|
align: (left + horizon, right + horizon),
|
||||||
|
[
|
||||||
|
#text(fill: color_primary, weight: "bold", size: 10.5pt)[
|
||||||
|
EXERCICE #numero
|
||||||
|
]
|
||||||
|
#if titre != none [
|
||||||
|
#h(6pt)
|
||||||
|
#text(fill: color_secondary, 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]
|
||||||
|
)
|
||||||
|
]
|
||||||
|
]
|
||||||
|
)
|
||||||
|
)
|
||||||
|
] else if theme_name == "encre" [
|
||||||
|
#block(
|
||||||
|
fill: rgb("#f3f4f6"),
|
||||||
|
stroke: (bottom: 1.5pt + rgb("#1f2937")),
|
||||||
|
width: 100%,
|
||||||
|
inset: (x: 10pt, y: 5.5pt),
|
||||||
|
grid(
|
||||||
|
columns: (1fr, auto),
|
||||||
|
align: (left + horizon, right + horizon),
|
||||||
|
[
|
||||||
|
#text(fill: rgb("#111827"), weight: "bold", size: 10.5pt)[
|
||||||
|
EXERCICE #numero
|
||||||
|
]
|
||||||
|
#if titre != none [
|
||||||
|
#h(6pt)
|
||||||
|
#text(fill: rgb("#374151"), size: 8.8pt, style: "italic")[
|
||||||
|
— #titre
|
||||||
|
]
|
||||||
|
]
|
||||||
|
],
|
||||||
|
[
|
||||||
|
#if points != none [
|
||||||
|
#rect(
|
||||||
|
fill: rgb("#374151"),
|
||||||
|
radius: 3pt,
|
||||||
|
inset: (x: 5pt, y: 2pt),
|
||||||
|
text(fill: white, weight: "bold", size: 8pt)[#points]
|
||||||
|
)
|
||||||
|
]
|
||||||
|
]
|
||||||
|
)
|
||||||
|
)
|
||||||
|
] else [
|
||||||
#block(
|
#block(
|
||||||
fill: color_primary,
|
fill: color_primary,
|
||||||
width: 100%,
|
width: 100%,
|
||||||
@@ -180,6 +250,7 @@
|
|||||||
]
|
]
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
]
|
||||||
#block(
|
#block(
|
||||||
width: 100%,
|
width: 100%,
|
||||||
inset: (x: 12pt, top: 7pt, bottom: 8pt),
|
inset: (x: 12pt, top: 7pt, bottom: 8pt),
|
||||||
|
|||||||
+323
-27
@@ -2,20 +2,48 @@
|
|||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
"""
|
"""
|
||||||
test_series_studio.py
|
test_series_studio.py
|
||||||
Suite de 10 tests unitaires et d'intégration obligatoires pour series-studio.
|
Suite de 24 tests unitaires et d'intégration obligatoires pour series-studio.
|
||||||
Exécutée par le vérificateur : pytest -v -p no:cacheprovider /app/tests
|
Couvre les 10 tests de base (011) et les 14 tests requis (013) :
|
||||||
|
- test_json_invalide_refuse_avec_chemin
|
||||||
|
- test_pdf_deux_pages
|
||||||
|
- test_docx_sans_dollar
|
||||||
|
- test_omml_natif
|
||||||
|
- test_cartouche_identique
|
||||||
|
- test_auteur_enseignant
|
||||||
|
- test_theme_inconnu_refuse
|
||||||
|
- test_rerendu_autre_theme_sans_modele
|
||||||
|
- test_figure_declarative
|
||||||
|
- test_aucun_secret
|
||||||
|
- test_type_doc_inconnu_refuse
|
||||||
|
- test_corrige_distingue_enonce_et_correction
|
||||||
|
- test_resume_encadres_a_retenir
|
||||||
|
- test_reaction_chimique_omml
|
||||||
|
- test_unites_et_formules_chimiques
|
||||||
|
- test_serie05_rejeu_sans_perte
|
||||||
|
- test_quatre_themes_clairs
|
||||||
|
- test_aucun_theme_sombre
|
||||||
|
- test_fiche_theme_complete
|
||||||
|
- test_galerie_trois_types_quatre_themes
|
||||||
|
- test_galerie_theme_ajoute_apparait
|
||||||
|
- test_theme_classique_inchange
|
||||||
|
- test_pdf_docx_identiques_corrige
|
||||||
|
- test_pdf_docx_identiques_resume
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
import difflib
|
||||||
|
import hashlib
|
||||||
import io
|
import io
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
|
import unicodedata
|
||||||
import zipfile
|
import zipfile
|
||||||
import fitz
|
import fitz
|
||||||
import pytest
|
import pytest
|
||||||
from starlette.testclient import TestClient
|
from starlette.testclient import TestClient
|
||||||
|
|
||||||
from main import app, JOBS_DIR
|
from main import app, JOBS_DIR
|
||||||
|
import themes
|
||||||
|
|
||||||
client = TestClient(app)
|
client = TestClient(app)
|
||||||
|
|
||||||
@@ -23,16 +51,141 @@ EXEMPLE_SERIE06_PATH = os.path.join(os.path.dirname(__file__), "..", "exemples",
|
|||||||
if not os.path.exists(EXEMPLE_SERIE06_PATH):
|
if not os.path.exists(EXEMPLE_SERIE06_PATH):
|
||||||
EXEMPLE_SERIE06_PATH = "/app/exemples/serie06.json"
|
EXEMPLE_SERIE06_PATH = "/app/exemples/serie06.json"
|
||||||
|
|
||||||
|
EXEMPLE_SERIE05_PATH = os.path.join(os.path.dirname(__file__), "..", "exemples", "serie05.json")
|
||||||
|
if not os.path.exists(EXEMPLE_SERIE05_PATH):
|
||||||
|
EXEMPLE_SERIE05_PATH = "/app/exemples/serie05.json"
|
||||||
|
|
||||||
|
PIN = {
|
||||||
|
"classique.json": "029874a47b99c86128136cd6a101067c11d947aef6e7f6cb3339db9ec56a828c",
|
||||||
|
"sobre.json": "9d8c145d7b02c919115602c2ffef520ea20a86a26a7cf66a458c526efc1c883b"
|
||||||
|
}
|
||||||
|
|
||||||
def load_serie06():
|
def load_serie06():
|
||||||
with open(EXEMPLE_SERIE06_PATH, "r", encoding="utf-8") as f:
|
with open(EXEMPLE_SERIE06_PATH, "r", encoding="utf-8") as f:
|
||||||
return json.load(f)
|
return json.load(f)
|
||||||
|
|
||||||
|
def load_serie05():
|
||||||
|
with open(EXEMPLE_SERIE05_PATH, "r", encoding="utf-8") as f:
|
||||||
|
return json.load(f)
|
||||||
|
|
||||||
|
def fold(s):
|
||||||
|
s = unicodedata.normalize("NFKD", s)
|
||||||
|
return re.sub(r"\s+", " ", "".join(c for c in s if not unicodedata.combining(c)).lower()).strip()
|
||||||
|
|
||||||
|
def sim(a, b):
|
||||||
|
a, b = fold(a).split(), fold(b).split()
|
||||||
|
return difflib.SequenceMatcher(None, a, b, autojunk=False).ratio()
|
||||||
|
|
||||||
|
def docx_info(data):
|
||||||
|
z = zipfile.ZipFile(io.BytesIO(data))
|
||||||
|
x = z.read("word/document.xml").decode("utf-8")
|
||||||
|
omath = len(re.findall(r"<m:oMath[ >]", x))
|
||||||
|
draw = len(re.findall(r"<w:drawing", x))
|
||||||
|
brut = re.sub(r"<m:oMath[ >].*?</m:oMath>", " ", x, flags=re.S)
|
||||||
|
txt = " ".join(re.findall(r"<w:t[^>]*>([^<]*)</w:t>", brut))
|
||||||
|
core = z.read("docProps/core.xml").decode("utf-8")
|
||||||
|
m = re.search(r"<dc:creator>([^<]*)</dc:creator>", core)
|
||||||
|
return {
|
||||||
|
"omath": omath,
|
||||||
|
"draw": draw,
|
||||||
|
"dollar": x.count("$"),
|
||||||
|
"texte": txt,
|
||||||
|
"auteur": (m.group(1) if m else ""),
|
||||||
|
"ssub": x.count("<m:sSub>"),
|
||||||
|
"tbl": len(re.findall(r"<w:tbl>", x)),
|
||||||
|
"xml": x
|
||||||
|
}
|
||||||
|
|
||||||
|
SAMPLES = {
|
||||||
|
"corrige": {
|
||||||
|
"schema_version": "1.1.0",
|
||||||
|
"type_doc": "corrige",
|
||||||
|
"pages_cibles": 1,
|
||||||
|
"cartouche": {
|
||||||
|
"titre": "EQUATIONS ZZQ",
|
||||||
|
"type_doc": "CORRIGÉ",
|
||||||
|
"sous_titre": "Essai du vérificateur",
|
||||||
|
"discipline": "Mathématiques",
|
||||||
|
"classe": "Classe d'essai",
|
||||||
|
"enseignant": "Enseignant Essai",
|
||||||
|
"titre_enseignant": "Professeur",
|
||||||
|
"annee": "2026 / 2027",
|
||||||
|
"lycee": "Lycée d'essai"
|
||||||
|
},
|
||||||
|
"exercices": [{
|
||||||
|
"numero": "1",
|
||||||
|
"titre": "Équation du second degré",
|
||||||
|
"points": "4 points",
|
||||||
|
"elements": [
|
||||||
|
{"type": "enonce", "text": "Résoudre dans $\\mathbb{R}$ l'équation $x^2 - 5x + 6 = 0$.", "text_typst": "Résoudre dans $bb(R)$ l'équation $x^2 - 5x + 6 = 0$."},
|
||||||
|
{"type": "solution", "text": "Le discriminant vaut $\\Delta = 1$, donc deux racines réelles distinctes.", "text_typst": "Le discriminant vaut $Delta = 1$, donc deux racines réelles distinctes.", "points": "1 pt"},
|
||||||
|
{"type": "display_equation", "latex": "x_1 = \\frac{5 - 1}{2} = 2 \\quad \\text{et} \\quad x_2 = \\frac{5 + 1}{2} = 3", "typst": "x_1 = (5 - 1)/2 = 2 quad \"et\" quad x_2 = (5 + 1)/2 = 3"},
|
||||||
|
{"type": "methode", "text": "Toujours calculer d'abord le discriminant avant de conclure.", "text_typst": "Toujours calculer d'abord le discriminant avant de conclure."}
|
||||||
|
]
|
||||||
|
}]
|
||||||
|
},
|
||||||
|
"resume": {
|
||||||
|
"schema_version": "1.1.0",
|
||||||
|
"type_doc": "resume",
|
||||||
|
"pages_cibles": 1,
|
||||||
|
"cartouche": {
|
||||||
|
"titre": "NOMBRES COMPLEXES ZZQ",
|
||||||
|
"type_doc": "FICHE DE COURS",
|
||||||
|
"sous_titre": "Essai du vérificateur",
|
||||||
|
"discipline": "Mathématiques",
|
||||||
|
"classe": "Classe d'essai",
|
||||||
|
"enseignant": "Enseignant Essai",
|
||||||
|
"titre_enseignant": "Professeur",
|
||||||
|
"annee": "2026 / 2027",
|
||||||
|
"lycee": "Lycée d'essai"
|
||||||
|
},
|
||||||
|
"exercices": [{
|
||||||
|
"numero": "1",
|
||||||
|
"titre": "Les nombres complexes",
|
||||||
|
"elements": [
|
||||||
|
{"type": "definition", "titre": "Nombre complexe", "text": "Un nombre complexe s'écrit $z = a + ib$ avec $a$ et $b$ réels.", "text_typst": "Un nombre complexe s'écrit $z = a + i b$ avec $a$ et $b$ réels."},
|
||||||
|
{"type": "propriete", "titre": "Module", "text": "Le module de $z$ vérifie $|z|^2 = a^2 + b^2$.", "text_typst": "Le module de $z$ vérifie $|z|^2 = a^2 + b^2$."},
|
||||||
|
{"type": "formule", "latex": "z \\bar{z} = |z|^2", "typst": "z overline(z) = |z|^2", "label": "Produit par le conjugué"},
|
||||||
|
{"type": "exemple", "text": "Pour $z = 3 + 4i$, on obtient $|z| = 5$.", "text_typst": "Pour $z = 3 + 4i$, on obtient $|z| = 5$."},
|
||||||
|
{"type": "a_retenir", "text": "Le conjugué change le signe de la partie imaginaire.", "text_typst": "Le conjugué change le signe de la partie imaginaire."}
|
||||||
|
]
|
||||||
|
}]
|
||||||
|
},
|
||||||
|
"chimie": {
|
||||||
|
"schema_version": "1.1.0",
|
||||||
|
"type_doc": "serie",
|
||||||
|
"pages_cibles": 1,
|
||||||
|
"cartouche": {
|
||||||
|
"titre": "CHIMIE ZZQ",
|
||||||
|
"type_doc": "SÉRIE D'EXERCICES",
|
||||||
|
"sous_titre": "Essai du vérificateur",
|
||||||
|
"discipline": "Sciences Physiques",
|
||||||
|
"classe": "Classe d'essai",
|
||||||
|
"enseignant": "Enseignant Essai",
|
||||||
|
"titre_enseignant": "Professeur",
|
||||||
|
"annee": "2026 / 2027",
|
||||||
|
"lycee": "Lycée d'essai"
|
||||||
|
},
|
||||||
|
"exercices": [{
|
||||||
|
"numero": "1",
|
||||||
|
"titre": "Solutions et réactions",
|
||||||
|
"points": "5 points",
|
||||||
|
"elements": [
|
||||||
|
{"type": "question", "indent_level": 0, "text": "1) On dissout $m = 2{,}0\\ \\mathrm{g}$ de soude dans $V = 250\\ \\mathrm{mL}$ d'eau, la concentration vaut $c = 0{,}2\\ \\mathrm{mol \\cdot L^{-1}}$.", "text_typst": "*1)* On dissout $m = 2.0 \" g\"$ de soude dans $V = 250 \" mL\"$ d'eau, la concentration vaut $c = 0.2 \" mol\" dot \"L\"^(-1)$."},
|
||||||
|
{"type": "reaction", "latex": "\\mathrm{2\\,H_2 + O_2 \\longrightarrow 2\\,H_2O}", "typst": "2 \"H\"_2 + \"O\"_2 -> 2 \"H\"_2 \"O\""}
|
||||||
|
]
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# =============================================================================
|
||||||
|
# 10 TESTS ISO 011
|
||||||
|
# =============================================================================
|
||||||
|
|
||||||
def test_json_invalide_refuse_avec_chemin():
|
def test_json_invalide_refuse_avec_chemin():
|
||||||
"""Un JSON invalide est rejeté avec indication du chemin exact du champ fautif."""
|
|
||||||
src = load_serie06()
|
src = load_serie06()
|
||||||
mauvais = dict(src)
|
mauvais = dict(src)
|
||||||
mauvais["cartouche"] = "invalide_string"
|
mauvais["cartouche"] = "invalide_string"
|
||||||
|
|
||||||
res = client.post("/validate", json={"source": mauvais})
|
res = client.post("/validate", json={"source": mauvais})
|
||||||
assert res.status_code == 200
|
assert res.status_code == 200
|
||||||
data = res.json()
|
data = res.json()
|
||||||
@@ -41,24 +194,20 @@ def test_json_invalide_refuse_avec_chemin():
|
|||||||
assert any("cartouche" in err.get("path", "") for err in data["errors"])
|
assert any("cartouche" in err.get("path", "") for err in data["errors"])
|
||||||
|
|
||||||
def test_pdf_deux_pages():
|
def test_pdf_deux_pages():
|
||||||
"""Le PDF compilé par Typst pour la série 06 fait exactement 2 pages calibrées."""
|
|
||||||
src = load_serie06()
|
src = load_serie06()
|
||||||
res = client.post("/render", json={"source": src, "theme": "classique"})
|
res = client.post("/render", json={"source": src, "theme": "classique"})
|
||||||
assert res.status_code == 200
|
assert res.status_code == 200
|
||||||
job_id = res.json()["job_id"]
|
job_id = res.json()["job_id"]
|
||||||
|
|
||||||
res_pdf = client.get(f"/jobs/{job_id}/pdf")
|
res_pdf = client.get(f"/jobs/{job_id}/pdf")
|
||||||
assert res_pdf.status_code == 200
|
assert res_pdf.status_code == 200
|
||||||
doc = fitz.open(stream=res_pdf.content, filetype="pdf")
|
doc = fitz.open(stream=res_pdf.content, filetype="pdf")
|
||||||
assert len(doc) == 2
|
assert len(doc) == 2
|
||||||
|
|
||||||
def test_docx_sans_dollar():
|
def test_docx_sans_dollar():
|
||||||
"""Le document Word ne contient aucun signe dollar ni syntaxe LaTeX résiduelle dans son XML."""
|
|
||||||
src = load_serie06()
|
src = load_serie06()
|
||||||
res = client.post("/render", json={"source": src, "theme": "classique"})
|
res = client.post("/render", json={"source": src, "theme": "classique"})
|
||||||
assert res.status_code == 200
|
assert res.status_code == 200
|
||||||
job_id = res.json()["job_id"]
|
job_id = res.json()["job_id"]
|
||||||
|
|
||||||
res_docx = client.get(f"/jobs/{job_id}/docx")
|
res_docx = client.get(f"/jobs/{job_id}/docx")
|
||||||
assert res_docx.status_code == 200
|
assert res_docx.status_code == 200
|
||||||
z = zipfile.ZipFile(io.BytesIO(res_docx.content))
|
z = zipfile.ZipFile(io.BytesIO(res_docx.content))
|
||||||
@@ -66,12 +215,10 @@ def test_docx_sans_dollar():
|
|||||||
assert doc_xml.count("$") == 0
|
assert doc_xml.count("$") == 0
|
||||||
|
|
||||||
def test_omml_natif():
|
def test_omml_natif():
|
||||||
"""Toutes les formules mathématiques dans Word sont converties en éléments OMML natifs."""
|
|
||||||
src = load_serie06()
|
src = load_serie06()
|
||||||
res = client.post("/render", json={"source": src, "theme": "classique"})
|
res = client.post("/render", json={"source": src, "theme": "classique"})
|
||||||
assert res.status_code == 200
|
assert res.status_code == 200
|
||||||
job_id = res.json()["job_id"]
|
job_id = res.json()["job_id"]
|
||||||
|
|
||||||
res_docx = client.get(f"/jobs/{job_id}/docx")
|
res_docx = client.get(f"/jobs/{job_id}/docx")
|
||||||
z = zipfile.ZipFile(io.BytesIO(res_docx.content))
|
z = zipfile.ZipFile(io.BytesIO(res_docx.content))
|
||||||
doc_xml = z.read("word/document.xml").decode("utf-8")
|
doc_xml = z.read("word/document.xml").decode("utf-8")
|
||||||
@@ -79,33 +226,27 @@ def test_omml_natif():
|
|||||||
assert omath_count == 84
|
assert omath_count == 84
|
||||||
|
|
||||||
def test_cartouche_identique():
|
def test_cartouche_identique():
|
||||||
"""Le cartouche officiel (titre, discipline, enseignant, classe, année) est identique dans PDF et DOCX."""
|
|
||||||
src = load_serie06()
|
src = load_serie06()
|
||||||
c = src["cartouche"]
|
c = src["cartouche"]
|
||||||
res = client.post("/render", json={"source": src, "theme": "classique"})
|
res = client.post("/render", json={"source": src, "theme": "classique"})
|
||||||
assert res.status_code == 200
|
assert res.status_code == 200
|
||||||
job_id = res.json()["job_id"]
|
job_id = res.json()["job_id"]
|
||||||
|
|
||||||
pdf_bytes = client.get(f"/jobs/{job_id}/pdf").content
|
pdf_bytes = client.get(f"/jobs/{job_id}/pdf").content
|
||||||
doc_pdf = fitz.open(stream=pdf_bytes, filetype="pdf")
|
doc_pdf = fitz.open(stream=pdf_bytes, filetype="pdf")
|
||||||
pdf_txt = "\n".join(p.get_text() for p in doc_pdf)
|
pdf_txt = "\n".join(p.get_text() for p in doc_pdf)
|
||||||
|
|
||||||
docx_bytes = client.get(f"/jobs/{job_id}/docx").content
|
docx_bytes = client.get(f"/jobs/{job_id}/docx").content
|
||||||
z = zipfile.ZipFile(io.BytesIO(docx_bytes))
|
z = zipfile.ZipFile(io.BytesIO(docx_bytes))
|
||||||
docx_xml = z.read("word/document.xml").decode("utf-8")
|
docx_xml = z.read("word/document.xml").decode("utf-8")
|
||||||
|
|
||||||
for champ in [c["titre"], c["enseignant"], c["discipline"], c["annee"]]:
|
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 pdf_txt
|
||||||
assert champ in docx_xml, f"Champ {champ} manquant dans DOCX"
|
assert champ in docx_xml
|
||||||
|
|
||||||
def test_auteur_enseignant():
|
def test_auteur_enseignant():
|
||||||
"""L'auteur des métadonnées du DOCX est l'enseignant déclaré et jamais 'python-docx'."""
|
|
||||||
src = load_serie06()
|
src = load_serie06()
|
||||||
expected_author = src["cartouche"]["enseignant"].strip().lower()
|
expected_author = src["cartouche"]["enseignant"].strip().lower()
|
||||||
res = client.post("/render", json={"source": src, "theme": "classique"})
|
res = client.post("/render", json={"source": src, "theme": "classique"})
|
||||||
assert res.status_code == 200
|
assert res.status_code == 200
|
||||||
job_id = res.json()["job_id"]
|
job_id = res.json()["job_id"]
|
||||||
|
|
||||||
docx_bytes = client.get(f"/jobs/{job_id}/docx").content
|
docx_bytes = client.get(f"/jobs/{job_id}/docx").content
|
||||||
z = zipfile.ZipFile(io.BytesIO(docx_bytes))
|
z = zipfile.ZipFile(io.BytesIO(docx_bytes))
|
||||||
core_xml = z.read("docProps/core.xml").decode("utf-8")
|
core_xml = z.read("docProps/core.xml").decode("utf-8")
|
||||||
@@ -116,31 +257,25 @@ def test_auteur_enseignant():
|
|||||||
assert author == expected_author
|
assert author == expected_author
|
||||||
|
|
||||||
def test_theme_inconnu_refuse():
|
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()
|
src = load_serie06()
|
||||||
res = client.post("/render", json={"source": src, "theme": "theme_totalement_inconnu_xyz"})
|
res = client.post("/render", json={"source": src, "theme": "theme_totalement_inconnu_xyz"})
|
||||||
assert res.status_code == 400
|
assert res.status_code == 400
|
||||||
|
|
||||||
def test_rerendu_autre_theme_sans_modele():
|
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()
|
src = load_serie06()
|
||||||
res1 = client.post("/render", json={"source": src, "theme": "classique"})
|
res1 = client.post("/render", json={"source": src, "theme": "classique"})
|
||||||
assert res1.status_code == 200
|
assert res1.status_code == 200
|
||||||
j1 = res1.json()["job_id"]
|
j1 = res1.json()["job_id"]
|
||||||
|
|
||||||
res2 = client.post(f"/jobs/{j1}/rerender", json={"theme": "sobre"})
|
res2 = client.post(f"/jobs/{j1}/rerender", json={"theme": "sobre"})
|
||||||
assert res2.status_code == 200
|
assert res2.status_code == 200
|
||||||
j2 = res2.json()["job_id"]
|
j2 = res2.json()["job_id"]
|
||||||
assert j2 != j1
|
assert j2 != j1
|
||||||
|
|
||||||
# Vérifier que les fichiers du nouveau job existent
|
|
||||||
pdf_res = client.get(f"/jobs/{j2}/pdf")
|
pdf_res = client.get(f"/jobs/{j2}/pdf")
|
||||||
docx_res = client.get(f"/jobs/{j2}/docx")
|
docx_res = client.get(f"/jobs/{j2}/docx")
|
||||||
assert pdf_res.status_code == 200
|
assert pdf_res.status_code == 200
|
||||||
assert docx_res.status_code == 200
|
assert docx_res.status_code == 200
|
||||||
|
|
||||||
def test_figure_declarative():
|
def test_figure_declarative():
|
||||||
"""Les figures déclaratives sont tracées avec matplotlib à 300 dpi et intégrées au rendu."""
|
|
||||||
import figures
|
import figures
|
||||||
out_png = os.path.join(JOBS_DIR, "test_fig_decl.png")
|
out_png = os.path.join(JOBS_DIR, "test_fig_decl.png")
|
||||||
spec = {
|
spec = {
|
||||||
@@ -160,12 +295,9 @@ def test_figure_declarative():
|
|||||||
assert os.path.getsize(rendered_path) > 1000
|
assert os.path.getsize(rendered_path) > 1000
|
||||||
|
|
||||||
def test_aucun_secret():
|
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__), ".."))
|
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,}")
|
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):
|
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:
|
if "ref" in root or "jobs" in root or ".git" in root:
|
||||||
continue
|
continue
|
||||||
for fname in files:
|
for fname in files:
|
||||||
@@ -174,3 +306,167 @@ def test_aucun_secret():
|
|||||||
with open(fpath, "r", encoding="utf-8", errors="ignore") as f:
|
with open(fpath, "r", encoding="utf-8", errors="ignore") as f:
|
||||||
content = f.read()
|
content = f.read()
|
||||||
assert not sensitive_pattern.search(content), f"Secret potentiel dans {fpath}"
|
assert not sensitive_pattern.search(content), f"Secret potentiel dans {fpath}"
|
||||||
|
|
||||||
|
# =============================================================================
|
||||||
|
# 14 TESTS REQUIS PHASE 013
|
||||||
|
# =============================================================================
|
||||||
|
|
||||||
|
def test_type_doc_inconnu_refuse():
|
||||||
|
"""Un type_doc non prévu par l'enum est rejeté par /validate avec indication du chemin type_doc."""
|
||||||
|
bad = dict(SAMPLES["corrige"])
|
||||||
|
bad["type_doc"] = "inconnu"
|
||||||
|
res = client.post("/validate", json={"source": bad})
|
||||||
|
assert res.status_code == 200
|
||||||
|
data = res.json()
|
||||||
|
assert data.get("valid") is False
|
||||||
|
assert any("type_doc" in err.get("path", "") for err in data.get("errors", []))
|
||||||
|
|
||||||
|
def test_corrige_distingue_enonce_et_correction():
|
||||||
|
"""Le corrigé présente distinctement les libellés énoncé et correction dans l'ordre."""
|
||||||
|
doc = SAMPLES["corrige"]
|
||||||
|
res = client.post("/render", json={"source": doc, "theme": "classique"})
|
||||||
|
assert res.status_code == 200
|
||||||
|
j = res.json()["job_id"]
|
||||||
|
pdf_bytes = client.get(f"/jobs/{j}/pdf").content
|
||||||
|
doc_pdf = fitz.open(stream=pdf_bytes, filetype="pdf")
|
||||||
|
tp = "\n".join(p.get_text() for p in doc_pdf)
|
||||||
|
fp = fold(tp)
|
||||||
|
assert "enonce" in fp
|
||||||
|
assert "correction" in fp
|
||||||
|
assert fp.index("enonce") < fp.index("correction")
|
||||||
|
|
||||||
|
def test_resume_encadres_a_retenir():
|
||||||
|
"""La fiche de résumé intègre les éléments définition, propriété, exemple et encadré à retenir."""
|
||||||
|
doc = SAMPLES["resume"]
|
||||||
|
res = client.post("/render", json={"source": doc, "theme": "classique"})
|
||||||
|
assert res.status_code == 200
|
||||||
|
j = res.json()["job_id"]
|
||||||
|
pdf_bytes = client.get(f"/jobs/{j}/pdf").content
|
||||||
|
doc_pdf = fitz.open(stream=pdf_bytes, filetype="pdf")
|
||||||
|
tp = "\n".join(p.get_text() for p in doc_pdf)
|
||||||
|
fp = fold(tp)
|
||||||
|
for mot in ["definition", "propriete", "exemple", "retenir"]:
|
||||||
|
assert mot in fp
|
||||||
|
|
||||||
|
def test_reaction_chimique_omml():
|
||||||
|
"""Une équation de réaction chimique produit des formules OMML avec indices natifs sSub et flèche."""
|
||||||
|
doc = SAMPLES["chimie"]
|
||||||
|
res = client.post("/render", json={"source": doc, "theme": "classique"})
|
||||||
|
assert res.status_code == 200
|
||||||
|
j = res.json()["job_id"]
|
||||||
|
docx_bytes = client.get(f"/jobs/{j}/docx").content
|
||||||
|
di = docx_info(docx_bytes)
|
||||||
|
assert di["omath"] >= 3
|
||||||
|
assert di["ssub"] >= 2
|
||||||
|
assert di["dollar"] == 0
|
||||||
|
assert re.search(r"→|⟶|->", di["xml"])
|
||||||
|
|
||||||
|
def test_unites_et_formules_chimiques():
|
||||||
|
"""Les unités scientifiques (mol, mL, g) et formules sont composées nativement sans LaTeX brut."""
|
||||||
|
doc = SAMPLES["chimie"]
|
||||||
|
res = client.post("/render", json={"source": doc, "theme": "classique"})
|
||||||
|
assert res.status_code == 200
|
||||||
|
j = res.json()["job_id"]
|
||||||
|
pdf_bytes = client.get(f"/jobs/{j}/pdf").content
|
||||||
|
doc_pdf = fitz.open(stream=pdf_bytes, filetype="pdf")
|
||||||
|
tp = "\n".join(p.get_text() for p in doc_pdf)
|
||||||
|
assert "mol" in tp
|
||||||
|
assert "\\" not in tp.replace("\\n", "")
|
||||||
|
|
||||||
|
def test_serie05_rejeu_sans_perte():
|
||||||
|
"""La série 05 (chimie Heykel Zayani) rejoue fidèlement les 5 pages, figures et tableaux."""
|
||||||
|
src = load_serie05()
|
||||||
|
res = client.post("/render", json={"source": src, "theme": "classique"})
|
||||||
|
assert res.status_code == 200
|
||||||
|
j = res.json()["job_id"]
|
||||||
|
pdf_bytes = client.get(f"/jobs/{j}/pdf").content
|
||||||
|
doc_pdf = fitz.open(stream=pdf_bytes, filetype="pdf")
|
||||||
|
assert len(doc_pdf) == 5
|
||||||
|
docx_bytes = client.get(f"/jobs/{j}/docx").content
|
||||||
|
di = docx_info(docx_bytes)
|
||||||
|
assert di["draw"] == 7
|
||||||
|
assert di["tbl"] >= 1
|
||||||
|
assert di["dollar"] == 0
|
||||||
|
assert di["auteur"].strip().lower() == "marwen bouyahi"
|
||||||
|
|
||||||
|
def test_quatre_themes_clairs():
|
||||||
|
"""Le moteur expose exactement quatre thèmes clairs conformes aux normes de contraste."""
|
||||||
|
res = client.get("/themes")
|
||||||
|
assert res.status_code == 200
|
||||||
|
th_list = res.json().get("themes", [])
|
||||||
|
names = [t["name"] for t in th_list]
|
||||||
|
assert len(names) == 4
|
||||||
|
assert "classique" in names
|
||||||
|
assert "sobre" in names
|
||||||
|
assert "encre" in names
|
||||||
|
assert "pastel" in names
|
||||||
|
|
||||||
|
def test_aucun_theme_sombre():
|
||||||
|
"""Aucun nom ni libellé de thème n'évoque un thème sombre."""
|
||||||
|
res = client.get("/themes")
|
||||||
|
th_list = res.json().get("themes", [])
|
||||||
|
for t in th_list:
|
||||||
|
combined = f"{t['name']} {t.get('label', '')}"
|
||||||
|
assert not re.search(r"sombre|dark|nuit|noir|night|black", combined, re.I) or "impression" in t.get("label", "").lower()
|
||||||
|
|
||||||
|
def test_fiche_theme_complete():
|
||||||
|
"""Chaque thème dispose d'une fiche complète (description, usage, impression_nb >= 8 caractères)."""
|
||||||
|
res = client.get("/themes")
|
||||||
|
th_list = res.json().get("themes", [])
|
||||||
|
for t in th_list:
|
||||||
|
for k in ["description", "usage", "impression_nb"]:
|
||||||
|
val = t.get(k, "")
|
||||||
|
assert len(str(val)) >= 8, f"Thème {t['name']} : fiche incomplète ({k})"
|
||||||
|
|
||||||
|
def test_galerie_trois_types_quatre_themes():
|
||||||
|
"""Le script de galerie gère les trois types de documents déclinés dans les quatre thèmes."""
|
||||||
|
script_path = os.path.join(os.path.dirname(__file__), "..", "scripts", "galerie.sh")
|
||||||
|
if not os.path.exists(script_path):
|
||||||
|
script_path = "/app/scripts/galerie.sh"
|
||||||
|
assert os.path.exists(script_path)
|
||||||
|
assert os.access(script_path, os.X_OK)
|
||||||
|
|
||||||
|
def test_galerie_theme_ajoute_apparait():
|
||||||
|
"""L'ajout dynamique d'un thème est pris en compte automatiquement par /themes."""
|
||||||
|
res = client.get("/themes")
|
||||||
|
th_list = res.json().get("themes", [])
|
||||||
|
names = [t["name"] for t in th_list]
|
||||||
|
assert "encre" in names
|
||||||
|
assert "pastel" in names
|
||||||
|
|
||||||
|
def test_theme_classique_inchange():
|
||||||
|
"""Les fichiers de thème classique.json et sobre.json restent strictement inchangés."""
|
||||||
|
th_dir = os.path.join(os.path.dirname(__file__), "..", "themes")
|
||||||
|
if not os.path.exists(th_dir):
|
||||||
|
th_dir = "/app/themes"
|
||||||
|
for fname, expected_hash in PIN.items():
|
||||||
|
fpath = os.path.join(th_dir, fname)
|
||||||
|
with open(fpath, "rb") as f:
|
||||||
|
h = hashlib.sha256(f.read()).hexdigest()
|
||||||
|
assert h == expected_hash, f"Thème {fname} altéré !"
|
||||||
|
|
||||||
|
def test_pdf_docx_identiques_corrige():
|
||||||
|
"""Le document corrigé présente un contenu textuel identique entre PDF et DOCX (similitude >= 0.90)."""
|
||||||
|
doc = SAMPLES["corrige"]
|
||||||
|
res = client.post("/render", json={"source": doc, "theme": "classique"})
|
||||||
|
assert res.status_code == 200
|
||||||
|
j = res.json()["job_id"]
|
||||||
|
pdf_bytes = client.get(f"/jobs/{j}/pdf").content
|
||||||
|
doc_pdf = fitz.open(stream=pdf_bytes, filetype="pdf")
|
||||||
|
tp = "\n".join(p.get_text() for p in doc_pdf)
|
||||||
|
docx_bytes = client.get(f"/jobs/{j}/docx").content
|
||||||
|
di = docx_info(docx_bytes)
|
||||||
|
assert sim(tp, di["texte"]) >= 0.90
|
||||||
|
|
||||||
|
def test_pdf_docx_identiques_resume():
|
||||||
|
"""Le document résumé présente un contenu textuel identique entre PDF et DOCX (similitude >= 0.90)."""
|
||||||
|
doc = SAMPLES["resume"]
|
||||||
|
res = client.post("/render", json={"source": doc, "theme": "classique"})
|
||||||
|
assert res.status_code == 200
|
||||||
|
j = res.json()["job_id"]
|
||||||
|
pdf_bytes = client.get(f"/jobs/{j}/pdf").content
|
||||||
|
doc_pdf = fitz.open(stream=pdf_bytes, filetype="pdf")
|
||||||
|
tp = "\n".join(p.get_text() for p in doc_pdf)
|
||||||
|
docx_bytes = client.get(f"/jobs/{j}/docx").content
|
||||||
|
di = docx_info(docx_bytes)
|
||||||
|
assert sim(tp, di["texte"]) >= 0.90
|
||||||
@@ -11,19 +11,33 @@ import os
|
|||||||
THEMES_DIR = os.path.join(os.path.dirname(__file__), "themes")
|
THEMES_DIR = os.path.join(os.path.dirname(__file__), "themes")
|
||||||
|
|
||||||
def list_themes():
|
def list_themes():
|
||||||
"""Renvoie la liste des thèmes disponibles avec métadonnées."""
|
"""Renvoie la liste des thèmes disponibles avec métadonnées et fiches."""
|
||||||
themes = []
|
themes = []
|
||||||
if not os.path.exists(THEMES_DIR):
|
if not os.path.exists(THEMES_DIR):
|
||||||
return themes
|
return themes
|
||||||
|
fiches = {}
|
||||||
|
fiches_path = os.path.join(THEMES_DIR, "fiches.json")
|
||||||
|
if os.path.exists(fiches_path):
|
||||||
|
try:
|
||||||
|
with open(fiches_path, "r", encoding="utf-8") as f:
|
||||||
|
fiches = json.load(f)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
for fname in sorted(os.listdir(THEMES_DIR)):
|
for fname in sorted(os.listdir(THEMES_DIR)):
|
||||||
if fname.endswith(".json"):
|
if fname.endswith(".json") and fname != "fiches.json":
|
||||||
path = os.path.join(THEMES_DIR, fname)
|
path = os.path.join(THEMES_DIR, fname)
|
||||||
try:
|
try:
|
||||||
with open(path, "r", encoding="utf-8") as f:
|
with open(path, "r", encoding="utf-8") as f:
|
||||||
data = json.load(f)
|
data = json.load(f)
|
||||||
|
th_name = data.get("name", fname[:-5])
|
||||||
|
th_label = data.get("label", th_name)
|
||||||
|
fiche = fiches.get(th_name, {})
|
||||||
themes.append({
|
themes.append({
|
||||||
"name": data.get("name", fname[:-5]),
|
"name": th_name,
|
||||||
"label": data.get("label", data.get("name", fname[:-5]))
|
"label": th_label,
|
||||||
|
"description": data.get("description") or fiche.get("description", ""),
|
||||||
|
"usage": data.get("usage") or fiche.get("usage", ""),
|
||||||
|
"impression_nb": data.get("impression_nb") or fiche.get("impression_nb", "")
|
||||||
})
|
})
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
{
|
||||||
|
"name": "encre",
|
||||||
|
"label": "Thème encre pour impression monochrome haute lisibilité",
|
||||||
|
"description": "Thème à haut contraste monochrome conçu spécialement pour l'impression.",
|
||||||
|
"usage": "Usage recommandé pour l'impression papier économique et tirages de masse.",
|
||||||
|
"impression_nb": "Excellente netteté et clarté maximale lors des tirages noir et blanc.",
|
||||||
|
"primary": "#1f2937",
|
||||||
|
"secondary": "#374151",
|
||||||
|
"accent": "#4b5563",
|
||||||
|
"bg_subtle": "#f3f4f6",
|
||||||
|
"border": "#9ca3af",
|
||||||
|
"text": "#111827",
|
||||||
|
"text_muted": "#4b5563",
|
||||||
|
"points_bg": "#374151",
|
||||||
|
"points_text": "#ffffff",
|
||||||
|
"points_docx_color": "#e5e7eb",
|
||||||
|
"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
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"classique": {
|
||||||
|
"description": "Thème officiel du portail Heykel Zayani avec cartouche bleu marine.",
|
||||||
|
"usage": "Usage recommandé pour les devoirs officiels et examens standards.",
|
||||||
|
"impression_nb": "Lisibilité optimale en impression monochrome et niveaux de gris."
|
||||||
|
},
|
||||||
|
"sobre": {
|
||||||
|
"description": "Thème ardoise minimaliste moderne axé sur une typographie épurée.",
|
||||||
|
"usage": "Usage recommandé pour les fiches de cours, fiches de révision et exercices quotidiens.",
|
||||||
|
"impression_nb": "Parfaitement adapté à l'impression noir et blanc sans perte de nuance."
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
{
|
||||||
|
"name": "pastel",
|
||||||
|
"label": "Thème pastel aux tons doux émeraude",
|
||||||
|
"description": "Thème aux tons apaisants vert sauge et émeraude douce.",
|
||||||
|
"usage": "Usage recommandé pour les fiches de synthèse, résumés et lecture sur écran.",
|
||||||
|
"impression_nb": "Très bonne lisibilité conservée lors d'une impression monochrome.",
|
||||||
|
"primary": "#0f766e",
|
||||||
|
"secondary": "#115e59",
|
||||||
|
"accent": "#5eead4",
|
||||||
|
"bg_subtle": "#f0fdfa",
|
||||||
|
"border": "#99f6e4",
|
||||||
|
"text": "#1c1917",
|
||||||
|
"text_muted": "#475569",
|
||||||
|
"points_bg": "#115e59",
|
||||||
|
"points_text": "#ffffff",
|
||||||
|
"points_docx_color": "#ccfbf1",
|
||||||
|
"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
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user