#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ serie_docx_builder.py 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 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() 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: 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, vanish_math=False ): 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 self.vanish_math = vanish_math # Thème graphique self.theme = theme or {} self.col_primary = hex_clean(self.theme.get("primary", "0F2C59")) self.col_secondary = hex_clean(self.theme.get("secondary", "1E40AF")) self.col_accent = hex_clean(self.theme.get("accent", "93C5FD")) self.col_bg_subtle = hex_clean(self.theme.get("bg_subtle", "F8FAFC")) self.col_border = hex_clean(self.theme.get("border", "CBD5E1")) self.col_points = hex_clean(self.theme.get("points_docx_color", "FEF08A")) self.font_main = self.theme.get("font_docx", "Cambria") self.font_banner = self.theme.get("font_banner", "Segoe UI") # Initialisation XSLT MathML -> OMML xslt_file = xslt_path or DEFAULT_XSLT if not os.path.exists(xslt_file): alt = os.path.join(os.path.dirname(__file__), "mml2omml.xsl") if os.path.exists(alt): xslt_file = alt self.xslt_tree = ET.parse(xslt_file) self.transform = ET.XSLT(self.xslt_tree) self.doc = Document() self._set_core_properties() self._setup_page_layout() self._create_header_cartouche() def _set_core_properties(self): """Définit les métadonnées officielles en évitant 'python-docx' comme créateur.""" cp = self.doc.core_properties cp.author = self.enseignant cp.title = f"{self.type_doc} : {self.titre} - {self.enseignant}" cp.subject = f"{self.discipline} - {self.classe}" cp.comments = f"Généré par series-studio ({self.annee})" def latex_to_omml(self, latex_code): """Convertit du code LaTeX en élément XML OMML (oMath).""" clean_code = latex_code.strip() clean_code = clean_code.replace(r'\limits', '') clean_code = clean_code.replace(r'\mathbb{R}', 'R') clean_code = clean_code.replace(r'\RR', 'R') clean_code = clean_code.replace(r'\mathbb{C}', 'C') clean_code = clean_code.replace(r'\CC', 'C') clean_code = clean_code.replace(r'\mathbb{Z}', 'Z') clean_code = clean_code.replace(r'\ZZ', 'Z') mml = latex2mathml.converter.convert(clean_code) mml_dom = ET.fromstring(mml) # Convertir les de 'lim' en pour afficher la limite en-dessous (m:limLow) ns = {"m": "http://www.w3.org/1998/Math/MathML"} for msub in mml_dom.xpath("//m:msub[m:mo[text()='lim']]", namespaces=ns): msub.tag = "{http://www.w3.org/1998/Math/MathML}munder" omml_dom = self.transform(mml_dom) return omml_dom.getroot() def _setup_page_layout(self): """Configure les marges A4 ainsi que l'en-tête et pied de page.""" for s in self.doc.sections: s.page_width = Inches(8.27) s.page_height = Inches(11.69) s.top_margin = Inches(0.6) s.bottom_margin = Inches(0.6) s.left_margin = Inches(0.6) s.right_margin = Inches(0.6) header_p = s.header.paragraphs[0] header_p.text = f"{self.discipline} — {self.type_doc} : {self.titre} {self.titre_enseignant} {self.enseignant} | {self.annee.replace(' ', '')}" header_p.alignment = WD_ALIGN_PARAGRAPH.RIGHT header_p.runs[0].font.name = self.font_main header_p.runs[0].font.size = Pt(8.5) header_p.runs[0].font.color.rgb = RGBColor(100, 116, 139) footer_p = s.footer.paragraphs[0] footer_p.text = f"{self.lycee} — {self.classe} | Année Scolaire {self.annee.replace(' ', '')}" footer_p.alignment = WD_ALIGN_PARAGRAPH.LEFT footer_p.runs[0].font.name = self.font_main footer_p.runs[0].font.size = Pt(8) footer_p.runs[0].font.color.rgb = RGBColor(100, 116, 139) @staticmethod def _set_cell_background(cell, fill_hex): tcPr = cell._tc.get_or_add_tcPr() shd = parse_xml(f'') tcPr.append(shd) @staticmethod def _set_cell_margins(cell, top=100, bottom=100, left=150, right=150): tcPr = cell._tc.get_or_add_tcPr() tcMar = parse_xml( f'' f'' f'' f'' f'' f'' ) tcPr.append(tcMar) @staticmethod def _set_table_borders_none(table): tblPr = table._tbl.tblPr borders = parse_xml( f'' f'' f'' f'' f'' f'' f'' f'' ) tblPr.append(borders) @staticmethod def set_table_borders(table, color="94A3B8", sz="4"): tblPr = table._tbl.tblPr borders = parse_xml( f'' f'' f'' f'' f'' f'' f'' f'' ) tblPr.append(borders) def _create_header_cartouche(self): """Crée le cartouche officiel en 3 colonnes.""" cartouche = self.doc.add_table(rows=1, cols=3) cartouche.alignment = WD_TABLE_ALIGNMENT.CENTER self._set_table_borders_none(cartouche) c_left = cartouche.cell(0, 0) c_mid = cartouche.cell(0, 1) c_right = cartouche.cell(0, 2) c_left.width = Inches(2.2) c_mid.width = Inches(3.2) c_right.width = Inches(1.8) # Gauche p_cl = c_left.paragraphs[0] p_cl.paragraph_format.space_before = Pt(0) p_cl.paragraph_format.space_after = Pt(1) r1 = p_cl.add_run("RÉPUBLIQUE TUNISIENNE\n") r1.bold = True r1.font.size = Pt(8.5) r1.font.color.rgb = hex_to_rgb(self.col_primary) r2 = p_cl.add_run("MINISTÈRE DE L'ÉDUCATION\n") r2.font.size = Pt(7.5) r2.font.color.rgb = RGBColor(71, 85, 105) r3 = p_cl.add_run(f"{self.classe}\n") r3.bold = True r3.font.size = Pt(8.5) r3.font.color.rgb = hex_to_rgb(self.col_secondary) r4 = p_cl.add_run(f"Discipline : {self.discipline}") r4.font.size = Pt(7.5) r4.font.color.rgb = RGBColor(100, 116, 139) # Milieu self._set_cell_background(c_mid, self.col_bg_subtle) self._set_cell_margins(c_mid, top=80, bottom=80, left=120, right=120) p_cm = c_mid.paragraphs[0] p_cm.alignment = WD_ALIGN_PARAGRAPH.CENTER p_cm.paragraph_format.space_before = Pt(0) p_cm.paragraph_format.space_after = Pt(0) r_t1 = p_cm.add_run(f"{self.type_doc}\n") r_t1.bold = True r_t1.font.size = Pt(11) r_t1.font.color.rgb = hex_to_rgb(self.col_primary) r_t2 = p_cm.add_run(f"{self.titre}\n") r_t2.bold = True r_t2.font.size = Pt(13) r_t2.font.color.rgb = hex_to_rgb(self.col_secondary) if self.sous_titre: r_t3 = p_cm.add_run(self.sous_titre) r_t3.italic = True r_t3.font.size = Pt(7.5) r_t3.font.color.rgb = RGBColor(71, 85, 105) # Droite p_cr = c_right.paragraphs[0] p_cr.alignment = WD_ALIGN_PARAGRAPH.RIGHT p_cr.paragraph_format.space_before = Pt(0) p_cr.paragraph_format.space_after = Pt(1) r_yr = p_cr.add_run("Année Scolaire :\n") r_yr.font.size = Pt(8) r_yr.font.color.rgb = RGBColor(100, 116, 139) r_yr2 = p_cr.add_run(f"{self.annee}\n\n") r_yr2.bold = True r_yr2.font.size = Pt(9) r_yr2.font.color.rgb = hex_to_rgb(self.col_primary) r_pr = p_cr.add_run(f"{self.titre_enseignant} :\n") r_pr.font.size = Pt(8) r_pr.font.color.rgb = RGBColor(100, 116, 139) r_pr2 = p_cr.add_run(self.enseignant) r_pr2.bold = True r_pr2.font.size = Pt(10.5) r_pr2.font.color.rgb = hex_to_rgb(self.col_secondary) if not self.vanish_math: # 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: 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.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: if self.vanish_math: clean_txt = latex_to_text(part) if clean_txt: v_run = parse_xml(f'{clean_txt}') p._element.append(v_run) 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) if self.vanish_math: clean_txt = latex_to_text(latex_eq) if clean_txt: v_run = parse_xml(f'{clean_txt}') p._element.append(v_run) omml_elem = self.latex_to_omml(latex_eq) oMathPara = parse_xml(f'') oMathPara.append(omml_elem) p._element.append(oMathPara) 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'{clean_txt}') p._element.append(v_run) omml_elem = self.latex_to_omml(latex_eq) oMathPara = parse_xml(f'') 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'') 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): """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)