410 lines
16 KiB
Python
410 lines
16 KiB
Python
#!/usr/bin/env python3
|
|
# -*- coding: utf-8 -*-
|
|
"""
|
|
serie_docx_builder.py
|
|
Constructeur de document Word (.docx) avec équations natives OMML et support de thèmes.
|
|
"""
|
|
|
|
import os
|
|
import re
|
|
import latex2mathml.converter
|
|
import lxml.etree as ET
|
|
from docx import Document
|
|
from docx.shared import Inches, Pt, RGBColor
|
|
from docx.enum.text import WD_ALIGN_PARAGRAPH
|
|
from docx.enum.table import WD_TABLE_ALIGNMENT
|
|
from docx.oxml import parse_xml
|
|
from docx.oxml.ns import nsdecls
|
|
|
|
DEFAULT_XSLT = os.path.join(os.path.dirname(__file__), "templates", "mml2omml.xsl")
|
|
|
|
def hex_to_rgb(hex_str: str) -> RGBColor:
|
|
s = hex_str.lstrip("#")
|
|
if len(s) == 3:
|
|
s = "".join([c*2 for c in s])
|
|
return RGBColor(int(s[0:2], 16), int(s[2:4], 16), int(s[4:6], 16))
|
|
|
|
def hex_clean(hex_str: str) -> str:
|
|
return hex_str.lstrip("#").upper()
|
|
|
|
class SerieDocxBuilder:
|
|
def __init__(
|
|
self,
|
|
titre="COMPLEXES",
|
|
sous_titre="Bac 2023, 2024 et 2025",
|
|
discipline="Mathématiques",
|
|
classe="4ème Sciences Techniques",
|
|
enseignant="Heykel ZAYANI",
|
|
annee="2026 / 2027",
|
|
lycee="Lycée Pilote",
|
|
titre_enseignant="P.P.É.C.E.",
|
|
type_doc="SÉRIE D'EXERCICES",
|
|
theme=None,
|
|
xslt_path=None
|
|
):
|
|
self.titre = titre
|
|
self.sous_titre = sous_titre
|
|
self.discipline = discipline
|
|
self.classe = classe
|
|
self.enseignant = enseignant
|
|
self.annee = annee
|
|
self.lycee = lycee
|
|
self.titre_enseignant = titre_enseignant
|
|
self.type_doc = type_doc
|
|
|
|
# Thème graphique
|
|
self.theme = theme or {}
|
|
self.col_primary = hex_clean(self.theme.get("primary", "0F2C59"))
|
|
self.col_secondary = hex_clean(self.theme.get("secondary", "1E40AF"))
|
|
self.col_accent = hex_clean(self.theme.get("accent", "93C5FD"))
|
|
self.col_bg_subtle = hex_clean(self.theme.get("bg_subtle", "F8FAFC"))
|
|
self.col_border = hex_clean(self.theme.get("border", "CBD5E1"))
|
|
self.col_points = hex_clean(self.theme.get("points_docx_color", "FEF08A"))
|
|
|
|
self.font_main = self.theme.get("font_docx", "Cambria")
|
|
self.font_banner = self.theme.get("font_banner", "Segoe UI")
|
|
|
|
# Initialisation XSLT MathML -> OMML
|
|
xslt_file = xslt_path or DEFAULT_XSLT
|
|
if not os.path.exists(xslt_file):
|
|
alt = os.path.join(os.path.dirname(__file__), "mml2omml.xsl")
|
|
if os.path.exists(alt):
|
|
xslt_file = alt
|
|
self.xslt_tree = ET.parse(xslt_file)
|
|
self.transform = ET.XSLT(self.xslt_tree)
|
|
|
|
self.doc = Document()
|
|
self._set_core_properties()
|
|
self._setup_page_layout()
|
|
self._create_header_cartouche()
|
|
|
|
def _set_core_properties(self):
|
|
"""Définit les métadonnées officielles en évitant 'python-docx' comme créateur."""
|
|
cp = self.doc.core_properties
|
|
cp.author = self.enseignant
|
|
cp.title = f"{self.type_doc} : {self.titre} - {self.enseignant}"
|
|
cp.subject = f"{self.discipline} - {self.classe}"
|
|
cp.comments = f"Généré par series-studio ({self.annee})"
|
|
|
|
def latex_to_omml(self, latex_code):
|
|
"""Convertit du code LaTeX en élément XML OMML (oMath)."""
|
|
clean_code = latex_code.strip()
|
|
clean_code = clean_code.replace(r'\limits', '')
|
|
clean_code = clean_code.replace(r'\mathbb{R}', 'R')
|
|
clean_code = clean_code.replace(r'\RR', 'R')
|
|
clean_code = clean_code.replace(r'\mathbb{C}', 'C')
|
|
clean_code = clean_code.replace(r'\CC', 'C')
|
|
clean_code = clean_code.replace(r'\mathbb{Z}', 'Z')
|
|
clean_code = clean_code.replace(r'\ZZ', 'Z')
|
|
|
|
mml = latex2mathml.converter.convert(clean_code)
|
|
mml_dom = ET.fromstring(mml)
|
|
|
|
# Convertir les <msub> de 'lim' en <munder> pour afficher la limite en-dessous (m:limLow)
|
|
ns = {"m": "http://www.w3.org/1998/Math/MathML"}
|
|
for msub in mml_dom.xpath("//m:msub[m:mo[text()='lim']]", namespaces=ns):
|
|
msub.tag = "{http://www.w3.org/1998/Math/MathML}munder"
|
|
|
|
omml_dom = self.transform(mml_dom)
|
|
return omml_dom.getroot()
|
|
|
|
def _setup_page_layout(self):
|
|
"""Configure les marges A4 ainsi que l'en-tête et pied de page."""
|
|
for s in self.doc.sections:
|
|
s.page_width = Inches(8.27)
|
|
s.page_height = Inches(11.69)
|
|
s.top_margin = Inches(0.6)
|
|
s.bottom_margin = Inches(0.6)
|
|
s.left_margin = Inches(0.6)
|
|
s.right_margin = Inches(0.6)
|
|
|
|
header_p = s.header.paragraphs[0]
|
|
header_p.text = f"{self.discipline} — {self.type_doc} : {self.titre} {self.titre_enseignant} {self.enseignant} | {self.annee.replace(' ', '')}"
|
|
header_p.alignment = WD_ALIGN_PARAGRAPH.RIGHT
|
|
header_p.runs[0].font.name = self.font_main
|
|
header_p.runs[0].font.size = Pt(8.5)
|
|
header_p.runs[0].font.color.rgb = RGBColor(100, 116, 139)
|
|
|
|
footer_p = s.footer.paragraphs[0]
|
|
footer_p.text = f"{self.lycee} — {self.classe} | Année Scolaire {self.annee.replace(' ', '')}"
|
|
footer_p.alignment = WD_ALIGN_PARAGRAPH.LEFT
|
|
footer_p.runs[0].font.name = self.font_main
|
|
footer_p.runs[0].font.size = Pt(8)
|
|
footer_p.runs[0].font.color.rgb = RGBColor(100, 116, 139)
|
|
|
|
@staticmethod
|
|
def _set_cell_background(cell, fill_hex):
|
|
tcPr = cell._tc.get_or_add_tcPr()
|
|
shd = parse_xml(f'<w:shd {nsdecls("w")} w:fill="{fill_hex}"/>')
|
|
tcPr.append(shd)
|
|
|
|
@staticmethod
|
|
def _set_cell_margins(cell, top=100, bottom=100, left=150, right=150):
|
|
tcPr = cell._tc.get_or_add_tcPr()
|
|
tcMar = parse_xml(
|
|
f'<w:tcMar {nsdecls("w")}>'
|
|
f'<w:top w:w="{top}" w:type="dxa"/>'
|
|
f'<w:bottom w:w="{bottom}" w:type="dxa"/>'
|
|
f'<w:left w:w="{left}" w:type="dxa"/>'
|
|
f'<w:right w:w="{right}" w:type="dxa"/>'
|
|
f'</w:tcMar>'
|
|
)
|
|
tcPr.append(tcMar)
|
|
|
|
@staticmethod
|
|
def _set_table_borders_none(table):
|
|
tblPr = table._tbl.tblPr
|
|
borders = parse_xml(
|
|
f'<w:tblBorders {nsdecls("w")}>'
|
|
f'<w:top w:val="none" w:sz="0" w:space="0" w:color="auto"/>'
|
|
f'<w:bottom w:val="none" w:sz="0" w:space="0" w:color="auto"/>'
|
|
f'<w:left w:val="none" w:sz="0" w:space="0" w:color="auto"/>'
|
|
f'<w:right w:val="none" w:sz="0" w:space="0" w:color="auto"/>'
|
|
f'<w:insideH w:val="none" w:sz="0" w:space="0" w:color="auto"/>'
|
|
f'<w:insideV w:val="none" w:sz="0" w:space="0" w:color="auto"/>'
|
|
f'</w:tblBorders>'
|
|
)
|
|
tblPr.append(borders)
|
|
|
|
def _create_header_cartouche(self):
|
|
"""Crée le cartouche officiel en 3 colonnes."""
|
|
cartouche = self.doc.add_table(rows=1, cols=3)
|
|
cartouche.alignment = WD_TABLE_ALIGNMENT.CENTER
|
|
self._set_table_borders_none(cartouche)
|
|
|
|
c_left = cartouche.cell(0, 0)
|
|
c_mid = cartouche.cell(0, 1)
|
|
c_right = cartouche.cell(0, 2)
|
|
|
|
c_left.width = Inches(2.2)
|
|
c_mid.width = Inches(3.2)
|
|
c_right.width = Inches(1.8)
|
|
|
|
# Gauche
|
|
p_cl = c_left.paragraphs[0]
|
|
p_cl.paragraph_format.space_before = Pt(0)
|
|
p_cl.paragraph_format.space_after = Pt(1)
|
|
r1 = p_cl.add_run("RÉPUBLIQUE TUNISIENNE\n")
|
|
r1.bold = True
|
|
r1.font.size = Pt(8.5)
|
|
r1.font.color.rgb = hex_to_rgb(self.col_primary)
|
|
r2 = p_cl.add_run("MINISTÈRE DE L'ÉDUCATION\n")
|
|
r2.font.size = Pt(7.5)
|
|
r2.font.color.rgb = RGBColor(71, 85, 105)
|
|
r3 = p_cl.add_run(f"{self.classe}\n")
|
|
r3.bold = True
|
|
r3.font.size = Pt(8.5)
|
|
r3.font.color.rgb = hex_to_rgb(self.col_secondary)
|
|
r4 = p_cl.add_run(f"Discipline : {self.discipline}")
|
|
r4.font.size = Pt(7.5)
|
|
r4.font.color.rgb = RGBColor(100, 116, 139)
|
|
|
|
# Milieu
|
|
self._set_cell_background(c_mid, self.col_bg_subtle)
|
|
self._set_cell_margins(c_mid, top=80, bottom=80, left=120, right=120)
|
|
p_cm = c_mid.paragraphs[0]
|
|
p_cm.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
|
p_cm.paragraph_format.space_before = Pt(0)
|
|
p_cm.paragraph_format.space_after = Pt(0)
|
|
|
|
r_t1 = p_cm.add_run(f"{self.type_doc}\n")
|
|
r_t1.bold = True
|
|
r_t1.font.size = Pt(11)
|
|
r_t1.font.color.rgb = hex_to_rgb(self.col_primary)
|
|
|
|
r_t2 = p_cm.add_run(f"{self.titre}\n")
|
|
r_t2.bold = True
|
|
r_t2.font.size = Pt(13)
|
|
r_t2.font.color.rgb = hex_to_rgb(self.col_secondary)
|
|
|
|
if self.sous_titre:
|
|
r_t3 = p_cm.add_run(self.sous_titre)
|
|
r_t3.italic = True
|
|
r_t3.font.size = Pt(7.5)
|
|
r_t3.font.color.rgb = RGBColor(71, 85, 105)
|
|
|
|
# Droite
|
|
p_cr = c_right.paragraphs[0]
|
|
p_cr.alignment = WD_ALIGN_PARAGRAPH.RIGHT
|
|
p_cr.paragraph_format.space_before = Pt(0)
|
|
p_cr.paragraph_format.space_after = Pt(1)
|
|
|
|
r_yr = p_cr.add_run("Année Scolaire :\n")
|
|
r_yr.font.size = Pt(8)
|
|
r_yr.font.color.rgb = RGBColor(100, 116, 139)
|
|
r_yr2 = p_cr.add_run(f"{self.annee}\n\n")
|
|
r_yr2.bold = True
|
|
r_yr2.font.size = Pt(9)
|
|
r_yr2.font.color.rgb = hex_to_rgb(self.col_primary)
|
|
|
|
r_pr = p_cr.add_run(f"{self.titre_enseignant} :\n")
|
|
r_pr.font.size = Pt(8)
|
|
r_pr.font.color.rgb = RGBColor(100, 116, 139)
|
|
r_pr2 = p_cr.add_run(self.enseignant)
|
|
r_pr2.bold = True
|
|
r_pr2.font.size = Pt(10.5)
|
|
r_pr2.font.color.rgb = hex_to_rgb(self.col_secondary)
|
|
|
|
# Ligne de séparation
|
|
p_sep = self.doc.add_paragraph()
|
|
p_sep.paragraph_format.space_before = Pt(4)
|
|
p_sep.paragraph_format.space_after = Pt(6)
|
|
p_sep_run = p_sep.add_run("―" * 58)
|
|
p_sep_run.font.color.rgb = hex_to_rgb(self.col_primary)
|
|
p_sep_run.bold = True
|
|
|
|
def add_exercise_banner(self, num_str, title_str=None, points_str=None):
|
|
"""Crée un bandeau d'exercice avec numéro, titre et points."""
|
|
tbl = self.doc.add_table(rows=1, cols=2)
|
|
tbl.alignment = WD_TABLE_ALIGNMENT.CENTER
|
|
self._set_table_borders_none(tbl)
|
|
|
|
cell_left = tbl.cell(0, 0)
|
|
cell_right = tbl.cell(0, 1)
|
|
|
|
self._set_cell_background(cell_left, self.col_primary)
|
|
self._set_cell_background(cell_right, self.col_primary)
|
|
self._set_cell_margins(cell_left, top=120, bottom=120, left=180, right=100)
|
|
self._set_cell_margins(cell_right, top=120, bottom=120, left=100, right=180)
|
|
|
|
cell_left.width = Inches(5.5)
|
|
cell_right.width = Inches(1.7)
|
|
|
|
p_left = cell_left.paragraphs[0]
|
|
p_left.paragraph_format.space_before = Pt(0)
|
|
p_left.paragraph_format.space_after = Pt(0)
|
|
|
|
run_ex = p_left.add_run(f"EXERCICE {num_str} ")
|
|
run_ex.bold = True
|
|
run_ex.font.size = Pt(11)
|
|
run_ex.font.color.rgb = RGBColor(255, 255, 255)
|
|
run_ex.font.name = self.font_banner
|
|
|
|
if title_str:
|
|
run_ti = p_left.add_run(f"— {title_str}")
|
|
run_ti.italic = True
|
|
run_ti.font.size = Pt(9.5)
|
|
run_ti.font.color.rgb = hex_to_rgb(self.col_accent)
|
|
run_ti.font.name = self.font_banner
|
|
|
|
p_right = cell_right.paragraphs[0]
|
|
p_right.alignment = WD_ALIGN_PARAGRAPH.RIGHT
|
|
p_right.paragraph_format.space_before = Pt(0)
|
|
p_right.paragraph_format.space_after = Pt(0)
|
|
|
|
if points_str:
|
|
run_pts = p_right.add_run(f"[{points_str}]")
|
|
run_pts.bold = True
|
|
run_pts.font.size = Pt(9.5)
|
|
run_pts.font.color.rgb = hex_to_rgb(self.col_points)
|
|
run_pts.font.name = self.font_banner
|
|
|
|
def add_math_to_paragraph(self, p, text_with_math, base_font_size=10.5):
|
|
"""Ajoute du texte contenant des formules $...$ au paragraphe en convertissant chaque formule en OMML."""
|
|
parts = text_with_math.split('$')
|
|
for i, part in enumerate(parts):
|
|
if i % 2 == 0:
|
|
if part:
|
|
run = p.add_run(part)
|
|
run.font.name = self.font_main
|
|
run.font.size = Pt(base_font_size)
|
|
run.font.color.rgb = RGBColor(15, 23, 42)
|
|
else:
|
|
if part:
|
|
omml_elem = self.latex_to_omml(part)
|
|
p._element.append(omml_elem)
|
|
|
|
def add_question(self, text, indent_level=0, space_before=2, space_after=2, base_font_size=10.5):
|
|
"""Ajoute une question avec indentation optionnelle."""
|
|
p = self.doc.add_paragraph()
|
|
p.paragraph_format.space_before = Pt(space_before)
|
|
p.paragraph_format.space_after = Pt(space_after)
|
|
p.paragraph_format.line_spacing = 1.15
|
|
if indent_level == 1:
|
|
p.paragraph_format.left_indent = Inches(0.25)
|
|
elif indent_level == 2:
|
|
p.paragraph_format.left_indent = Inches(0.5)
|
|
self.add_math_to_paragraph(p, text, base_font_size=base_font_size)
|
|
return p
|
|
|
|
def add_display_equation(self, latex_eq, space_before=4, space_after=6):
|
|
"""Ajoute une équation centrée en mode display (oMathPara)."""
|
|
p = self.doc.add_paragraph()
|
|
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
|
p.paragraph_format.space_before = Pt(space_before)
|
|
p.paragraph_format.space_after = Pt(space_after)
|
|
omml_elem = self.latex_to_omml(latex_eq)
|
|
oMathPara = parse_xml(f'<m:oMathPara {nsdecls("m")}/>')
|
|
oMathPara.append(omml_elem)
|
|
p._element.append(oMathPara)
|
|
return p
|
|
|
|
def add_part_header(self, bold_prefix, text_with_math, space_before=3, space_after=2):
|
|
"""Ajoute un en-tête de partie ('I°) ', 'II°) ')."""
|
|
p = self.doc.add_paragraph()
|
|
p.paragraph_format.space_before = Pt(space_before)
|
|
p.paragraph_format.space_after = Pt(space_after)
|
|
r = p.add_run(bold_prefix)
|
|
r.bold = True
|
|
r.font.name = self.font_main
|
|
r.font.size = Pt(10.5)
|
|
self.add_math_to_paragraph(p, text_with_math)
|
|
return p
|
|
|
|
def add_annexe_table(self, title, columns):
|
|
"""Crée l'annexe officielle avec titre fusionné et 2 colonnes pour les figures."""
|
|
p_sep = self.doc.add_paragraph()
|
|
p_sep.paragraph_format.space_before = Pt(6)
|
|
p_sep.paragraph_format.space_after = Pt(2)
|
|
|
|
tbl = self.doc.add_table(rows=2, cols=len(columns))
|
|
tbl.alignment = WD_TABLE_ALIGNMENT.CENTER
|
|
self._set_table_borders_none(tbl)
|
|
|
|
# Ligne 1 : Titre fusionné
|
|
c_first = tbl.cell(0, 0)
|
|
for c in tbl.rows[0].cells[1:]:
|
|
c_first.merge(c)
|
|
self._set_cell_background(c_first, self.col_primary)
|
|
self._set_cell_margins(c_first, top=100, bottom=100, left=150, right=150)
|
|
p_t = c_first.paragraphs[0]
|
|
p_t.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
|
r_t = p_t.add_run(title)
|
|
r_t.bold = True
|
|
r_t.font.name = self.font_banner
|
|
r_t.font.size = Pt(10)
|
|
r_t.font.color.rgb = RGBColor(255, 255, 255)
|
|
|
|
# Ligne 2 : Colonnes figures
|
|
for idx, col_spec in enumerate(columns):
|
|
c_fig = tbl.cell(1, idx)
|
|
w_in = col_spec.get("width_docx_inches", 3.4)
|
|
c_fig.width = Inches(3.6)
|
|
self._set_cell_background(c_fig, self.col_bg_subtle)
|
|
self._set_cell_margins(c_fig, top=80, bottom=80, left=100, right=100)
|
|
|
|
p_lbl = c_fig.paragraphs[0]
|
|
p_lbl.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
|
p_lbl.paragraph_format.space_before = Pt(2)
|
|
p_lbl.paragraph_format.space_after = Pt(2)
|
|
r_lbl = p_lbl.add_run(col_spec.get("titre", ""))
|
|
r_lbl.bold = True
|
|
r_lbl.font.size = Pt(9.5)
|
|
r_lbl.font.color.rgb = hex_to_rgb(self.col_secondary)
|
|
|
|
img_path = col_spec.get("image_path")
|
|
if img_path and os.path.exists(img_path):
|
|
p_img = c_fig.add_paragraph()
|
|
p_img.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
|
p_img.paragraph_format.space_before = Pt(0)
|
|
p_img.paragraph_format.space_after = Pt(2)
|
|
p_img.add_run().add_picture(img_path, width=Inches(w_in))
|
|
|
|
def add_page_break(self):
|
|
"""Ajoute un saut de page."""
|
|
self.doc.add_page_break()
|
|
|
|
def save(self, filepath):
|
|
"""Enregistre le document Word."""
|
|
self.doc.save(filepath)
|