Files
series-studio/renderer_typst.py
T

453 lines
20 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
renderer_typst.py
Génération du fichier Typst et compilation vers PDF de haute fidélité.
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 re
import subprocess
import fitz
def is_numbered_start(t: str) -> bool:
"""Détecte si le texte commence par une numérotation principale de question ou partie."""
s = t.strip()
return bool(re.match(r"^(\*?\d+\)|\d+\)|\*?[IVXLCDM]+[°\)]|[IVXLCDM]+[°\)])", s))
def generate_typst_source(source: dict, theme: dict, template_import_path: str, figures_map: dict = None) -> str:
"""Produit le code source Typst complet à partir de la source JSON et du thème."""
figures_map = figures_map or {}
c = source.get("cartouche", {})
col_primary = theme.get("primary", "#0f2c59")
col_secondary = theme.get("secondary", "#1e40af")
col_accent = theme.get("accent", "#93c5fd")
col_bg_subtle = theme.get("bg_subtle", "#f8fafc")
col_border = theme.get("border", "#cbd5e1")
font_main = theme.get("font_typst", "New Computer Modern")
theme_name = theme.get("name", "classique")
lines = []
lines.append(f'#import "{template_import_path}": *')
lines.append("")
titre_val = c.get("titre", "")
type_doc_val = c.get("type_doc", "SÉRIE D'EXERCICES")
sous_titre_val = c.get("sous_titre", "")
discipline_val = c.get("discipline", "Mathématiques")
classe_val = c.get("classe", "4ème Sciences Techniques")
enseignant_val = c.get("enseignant", "Heykel ZAYANI")
titre_ens_val = c.get("titre_enseignant", "P.P.É.C.E.")
annee_val = c.get("annee", "2026 / 2027")
lycee_val = c.get("lycee", "Lycée Pilote")
lines.append("#show: doc => serie_document(")
lines.append(f' titre: "{titre_val}",')
lines.append(f' type_doc: "{type_doc_val}",')
lines.append(f' sous_titre: "{sous_titre_val}",')
lines.append(f' discipline: "{discipline_val}",')
lines.append(f' classe: "{classe_val}",')
lines.append(f' enseignant: "{enseignant_val}",')
lines.append(f' titre_enseignant: "{titre_ens_val}",')
lines.append(f' annee: "{annee_val}",')
lines.append(f' lycee: "{lycee_val}",')
lines.append(f' color_primary: rgb("{col_primary}"),')
lines.append(f' color_secondary: rgb("{col_secondary}"),')
lines.append(f' color_accent: rgb("{col_accent}"),')
lines.append(f' color_bg_subtle: rgb("{col_bg_subtle}"),')
lines.append(f' color_border: rgb("{col_border}"),')
lines.append(f' font_main: "{font_main}",')
lines.append(" doc,")
lines.append(")")
lines.append("")
lines.append("#set text(size: 9.2pt)")
lines.append("#set par(leading: 0.52em)")
lines.append("")
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", [])
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"))
titre = ex.get("titre")
titre_arg = f'titre: "{titre}"' if titre else 'titre: none'
points = ex.get("points")
points_arg = f'points: "{points}"' if points else 'points: none'
breakable = "true" if ex.get("breakable_box", False) else "false"
lines.append(f'// EXERCICE {num}')
lines.append(f'#exercice("{num}", {titre_arg}, {points_arg}, breakable_box: {breakable},')
lines.append(f' color_primary: rgb("{col_primary}"), color_secondary: rgb("{col_secondary}"),')
lines.append(f' color_accent: rgb("{col_accent}"), color_border: rgb("{col_border}"),')
lines.append(f' theme_name: "{theme_name}")[')
lines.append(" #v(-2pt)")
elements = ex.get("elements", [])
idx = 0
first_el = True
while idx < len(elements):
el = elements[idx]
el_type = el.get("type")
if el_type == "part_header":
if not first_el:
lines.append("")
first_el = False
prefix = el.get("bold_prefix", "").strip()
t = el.get("text_typst") or el.get("text", "")
lines.append(f" *{prefix}* {t}")
idx += 1
elif el_type == "display_equation":
first_el = False
eq = el.get("typst") or el.get("latex", "")
lines.append(f" $ {eq} $")
next_el = elements[idx+1] if idx+1 < len(elements) else None
if next_el and next_el.get("type") == "question":
if next_el.get("indent_level", 0) > 0 or not is_numbered_start(next_el.get("text_typst", "") or next_el.get("text", "")):
lines.append(" #v(-2pt)")
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":
tt = el.get("text_typst", "")
if "#pad" in tt:
if not first_el:
lines.append("")
first_el = False
manual_block = []
while idx < len(elements) and elements[idx].get("type") == "question":
sub_t = elements[idx].get("text_typst") or elements[idx].get("text", "")
manual_block.append(sub_t)
idx += 1
if "]" in sub_t:
break
for m_i, ml in enumerate(manual_block):
end_char = "\\" if (m_i < len(manual_block) - 1 and not ml.rstrip().endswith("\\")) else ""
if ml.lstrip().startswith(("*b)*", "*c)*", "*d)*", "*a)*")):
ml_str = " " + ml.lstrip()
else:
ml_str = f" {ml}"
lines.append(f"{ml_str}{end_char}")
continue
indent = el.get("indent_level", 0)
if indent == 0:
t = tt or el.get("text", "")
if is_numbered_start(t) and not first_el:
lines.append("")
first_el = False
next_el = elements[idx+1] if idx+1 < len(elements) else None
if next_el and next_el.get("type") == "question" and next_el.get("indent_level", 0) > 0 and "#pad" not in next_el.get("text_typst", ""):
lines.append(f" {t}\\")
else:
lines.append(f" {t}")
idx += 1
else:
pad_lines = []
while idx < len(elements) and elements[idx].get("type") == "question" and elements[idx].get("indent_level", 0) > 0 and "#pad" not in elements[idx].get("text_typst", ""):
sub_t = elements[idx].get("text_typst") or elements[idx].get("text", "")
pad_lines.append(sub_t)
idx += 1
lines.append(" #pad(left: 10pt)[")
for p_i, pl in enumerate(pad_lines):
end_char = "\\" if p_i < len(pad_lines) - 1 else ""
lines.append(f" {pl}{end_char}")
lines.append(" ]")
elif el_type == "page_break":
idx += 1
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
else:
t = el.get("text_typst") or el.get("text", "")
if t:
lines.append(f" {t}")
idx += 1
lines.append("]")
lines.append("")
has_pagebreak = any(e.get("type") == "page_break" for e in elements)
if has_pagebreak:
lines.append("#pagebreak()")
lines.append("")
elif ex_idx < len(exercices) - 1:
lines.append("#v(-1pt)")
lines.append("")
annexe = source.get("annexe")
if annexe:
cols = annexe.get("colonnes", [])
ann_titre = annexe.get("titre", "ANNEXE À RENDRE AVEC LA COPIE — FIGURES OFFICIELLES")
lines.append("// ANNEXE OFFICIELLE À RENDRE AVEC LA COPIE")
lines.append("#v(4pt)")
lines.append("")
lines.append("#block(")
lines.append(" width: 100%,")
lines.append(f' stroke: 1pt + rgb("{col_primary}"),')
lines.append(" radius: 5pt,")
lines.append(" clip: true,")
lines.append(' fill: rgb("#ffffff"),')
lines.append(" [")
lines.append(" #block(")
lines.append(f' fill: rgb("{col_primary}"),')
lines.append(" width: 100%,")
lines.append(" inset: (x: 10pt, y: 4.5pt),")
lines.append(" align(center)[")
lines.append(' #text(fill: white, weight: "bold", size: 9.5pt)[')
lines.append(f" {ann_titre}")
lines.append(" ]")
lines.append(" ]")
lines.append(" )")
lines.append(" #block(")
lines.append(" width: 100%,")
lines.append(" inset: (x: 8pt, top: 4pt, bottom: 4pt),")
lines.append(" [")
if cols:
cols_str = ("1fr, " * len(cols)).rstrip(", ")
lines.append(f" #grid(")
lines.append(f" columns: ({cols_str}),")
lines.append(" gutter: 12pt,")
lines.append(" align: (center + top, center + top),")
for col in cols:
col_t = col.get("titre", "")
img_key = col.get("image") or col.get("figure_id")
resolved_img = figures_map.get(img_key) or figures_map.get(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%")
ann_text_col = "#1e3a8a" if theme.get("name") == "classique" else col_secondary
lines.append(" [")
lines.append(f' #text(weight: "bold", size: 8.5pt, fill: rgb("{ann_text_col}"))[{col_t}]\\')
lines.append(" #v(1pt)")
lines.append(f' #image("{resolved_img}", width: {w_typ})')
lines.append(" ],")
lines.append(" )")
lines.append(" ]")
lines.append(" )")
lines.append(" ]")
lines.append(")")
lines.append("")
return "\n".join(lines)
def render_typst(source: dict, theme: dict, output_pdf_path: str, typst_bin: str = "typst", figures_map: dict = None, template_path: str = None) -> dict:
"""Compile la source en PDF avec Typst et vérifie les critères bloquants."""
figures_map = figures_map or {}
job_dir = os.path.dirname(os.path.abspath(output_pdf_path))
typ_path = os.path.join(job_dir, "document.typ")
tmpl = template_path or "/app/templates/template_serie_math.typ"
if not os.path.exists(tmpl):
alt = os.path.join(os.path.dirname(__file__), "templates", "template_serie_math.typ")
if os.path.exists(alt):
tmpl = alt
# Racine pour typst sandbox
root_dir = "/"
if 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)
with open(typ_path, "w", encoding="utf-8") as f:
f.write(typ_content)
cmd = [typst_bin, "compile", "--root", root_dir, typ_path, output_pdf_path]
p = subprocess.run(cmd, capture_output=True, text=True)
if p.returncode != 0:
raise RuntimeError(f"Échec compilation Typst (code {p.returncode}) : {p.stderr}")
# Contrôle bloquant T3 : Typst sans avertissement
stderr_clean = p.stderr.strip()
if "warning:" in stderr_clean.lower():
raise ValueError(f"Contrôle bloquant échoué : avertissements Typst détectés : {stderr_clean}")
# Contrôle bloquant T3 : Nombre de pages conforme à pages_cibles
doc_fitz = fitz.open(output_pdf_path)
page_count = len(doc_fitz)
expected_pages = source.get("pages_cibles", 2)
if page_count != expected_pages:
raise ValueError(f"Contrôle bloquant échoué : {page_count} page(s) générée(s), {expected_pages} attendue(s)")
extracted_text = "\n".join(page.get_text() for page in doc_fitz)
return {
"pages": page_count,
"texte": extracted_text,
"typ_path": typ_path
}