feat(series-studio): initial implementation of unified series studio engine (PDF & DOCX)
This commit is contained in:
commit
03d9922066
20 files changed
+7082
No files matched your search
@@ -0,0 +1,233 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
renderer_typst.py
|
||||
Génération du fichier Typst et compilation vers PDF de haute fidélité.
|
||||
Effectue les contrôles bloquants : compilation sans avertissement et nombre de pages conforme à pages_cibles.
|
||||
"""
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import fitz
|
||||
|
||||
def generate_typst_source(source: dict, theme: dict, template_import_path: str, figures_map: dict = None) -> str:
|
||||
"""Produit le code source Typst complet à partir de la source JSON et du thème."""
|
||||
figures_map = figures_map or {}
|
||||
c = source.get("cartouche", {})
|
||||
|
||||
col_primary = theme.get("primary", "#0f2c59")
|
||||
col_secondary = theme.get("secondary", "#1e40af")
|
||||
col_accent = theme.get("accent", "#93c5fd")
|
||||
col_bg_subtle = theme.get("bg_subtle", "#f8fafc")
|
||||
col_border = theme.get("border", "#cbd5e1")
|
||||
font_main = theme.get("font_typst", "New Computer Modern")
|
||||
|
||||
lines = []
|
||||
lines.append(f'#import "{template_import_path}": *')
|
||||
lines.append("")
|
||||
titre_val = c.get("titre", "")
|
||||
type_doc_val = c.get("type_doc", "SÉRIE D'EXERCICES")
|
||||
sous_titre_val = c.get("sous_titre", "")
|
||||
discipline_val = c.get("discipline", "Mathématiques")
|
||||
classe_val = c.get("classe", "4ème Sciences Techniques")
|
||||
enseignant_val = c.get("enseignant", "Heykel ZAYANI")
|
||||
titre_ens_val = c.get("titre_enseignant", "P.P.É.C.E.")
|
||||
annee_val = c.get("annee", "2026 / 2027")
|
||||
lycee_val = c.get("lycee", "Lycée Pilote")
|
||||
|
||||
lines.append("#show: doc => serie_document(")
|
||||
lines.append(f' titre: "{titre_val}",')
|
||||
lines.append(f' type_doc: "{type_doc_val}",')
|
||||
lines.append(f' sous_titre: "{sous_titre_val}",')
|
||||
lines.append(f' discipline: "{discipline_val}",')
|
||||
lines.append(f' classe: "{classe_val}",')
|
||||
lines.append(f' enseignant: "{enseignant_val}",')
|
||||
lines.append(f' titre_enseignant: "{titre_ens_val}",')
|
||||
lines.append(f' annee: "{annee_val}",')
|
||||
lines.append(f' lycee: "{lycee_val}",')
|
||||
lines.append(f' color_primary: rgb("{col_primary}"),')
|
||||
lines.append(f' color_secondary: rgb("{col_secondary}"),')
|
||||
lines.append(f' color_accent: rgb("{col_accent}"),')
|
||||
lines.append(f' color_bg_subtle: rgb("{col_bg_subtle}"),')
|
||||
lines.append(f' color_border: rgb("{col_border}"),')
|
||||
lines.append(f' font_main: "{font_main}",')
|
||||
lines.append(" doc,")
|
||||
lines.append(")")
|
||||
lines.append("")
|
||||
lines.append("#set text(size: 9.2pt)")
|
||||
lines.append("#set par(leading: 0.52em)")
|
||||
lines.append("")
|
||||
|
||||
for ex in source.get("exercices", []):
|
||||
num = str(ex.get("numero", "1"))
|
||||
titre = ex.get("titre")
|
||||
titre_arg = f'titre: "{titre}"' if titre else 'titre: none'
|
||||
points = ex.get("points")
|
||||
points_arg = f'points: "{points}"' if points else 'points: none'
|
||||
breakable = "true" if ex.get("breakable_box", False) else "false"
|
||||
|
||||
lines.append(f'// EXERCICE {num}')
|
||||
lines.append(f'#exercice("{num}", {titre_arg}, {points_arg}, breakable_box: {breakable},')
|
||||
lines.append(f' color_primary: rgb("{col_primary}"), color_secondary: rgb("{col_secondary}"),')
|
||||
lines.append(f' color_accent: rgb("{col_accent}"), color_border: rgb("{col_border}"))[')
|
||||
lines.append(" #v(-2pt)")
|
||||
|
||||
elements = ex.get("elements", [])
|
||||
idx = 0
|
||||
while idx < len(elements):
|
||||
el = elements[idx]
|
||||
el_type = el.get("type")
|
||||
|
||||
if el_type == "question":
|
||||
indent = el.get("indent_level", 0)
|
||||
if indent == 0:
|
||||
t = el.get("text_typst") or el.get("text", "")
|
||||
lines.append(f" {t}")
|
||||
idx += 1
|
||||
else:
|
||||
# Regrouper les sous-questions consécutives indentées dans un #pad(left: 10pt)
|
||||
pad_lines = []
|
||||
while idx < len(elements) and elements[idx].get("type") == "question" and elements[idx].get("indent_level", 0) > 0:
|
||||
sub_t = elements[idx].get("text_typst") or elements[idx].get("text", "")
|
||||
pad_lines.append(sub_t)
|
||||
idx += 1
|
||||
lines.append(" #pad(left: 10pt)[")
|
||||
for p_i, pl in enumerate(pad_lines):
|
||||
end_char = r"\\" if p_i < len(pad_lines) - 1 else ""
|
||||
lines.append(f" {pl}{end_char}")
|
||||
lines.append(" ]")
|
||||
continue
|
||||
|
||||
elif el_type == "display_equation":
|
||||
eq = el.get("typst") or el.get("latex", "")
|
||||
lines.append(f" $ {eq} $")
|
||||
lines.append(" #v(-2pt)")
|
||||
idx += 1
|
||||
|
||||
elif el_type == "part_header":
|
||||
prefix = el.get("bold_prefix", "")
|
||||
t = el.get("text_typst") or el.get("text", "")
|
||||
lines.append(f" *{prefix}* {t}")
|
||||
idx += 1
|
||||
|
||||
elif el_type == "page_break":
|
||||
idx += 1
|
||||
|
||||
elif el_type == "figure":
|
||||
idx += 1
|
||||
|
||||
else:
|
||||
t = el.get("text_typst") or el.get("text", "")
|
||||
if t:
|
||||
lines.append(f" {t}")
|
||||
idx += 1
|
||||
|
||||
lines.append("]")
|
||||
lines.append("")
|
||||
|
||||
# Vérifier si l'exercice contient un saut de page pour le placer hors de la boîte
|
||||
has_pagebreak = any(e.get("type") == "page_break" for e in elements)
|
||||
if has_pagebreak:
|
||||
lines.append("#pagebreak()")
|
||||
lines.append("")
|
||||
|
||||
annexe = source.get("annexe")
|
||||
if annexe:
|
||||
cols = annexe.get("colonnes", [])
|
||||
ann_titre = annexe.get("titre", "ANNEXE À RENDRE AVEC LA COPIE — FIGURES OFFICIELLES")
|
||||
lines.append("// ANNEXE OFFICIELLE")
|
||||
lines.append("#v(4pt)")
|
||||
lines.append("#block(")
|
||||
lines.append(" width: 100%,")
|
||||
lines.append(f' stroke: 1pt + rgb("{col_primary}"),')
|
||||
lines.append(" radius: 5pt,")
|
||||
lines.append(" clip: true,")
|
||||
lines.append(' fill: rgb("#ffffff"),')
|
||||
lines.append(" [")
|
||||
lines.append(" #block(")
|
||||
lines.append(f' fill: rgb("{col_primary}"),')
|
||||
lines.append(" width: 100%,")
|
||||
lines.append(" inset: (x: 10pt, y: 4.5pt),")
|
||||
lines.append(" align(center)[")
|
||||
lines.append(' #text(fill: white, weight: "bold", size: 9.5pt)[')
|
||||
lines.append(f' {ann_titre}')
|
||||
lines.append(" ]")
|
||||
lines.append(" ]")
|
||||
lines.append(" )")
|
||||
lines.append(" #block(")
|
||||
lines.append(" width: 100%,")
|
||||
lines.append(" inset: (x: 8pt, top: 4pt, bottom: 4pt),")
|
||||
lines.append(" [")
|
||||
lines.append(" #grid(")
|
||||
cols_str = ("1fr, " * len(cols)).rstrip(", ")
|
||||
lines.append(f" #grid(")
|
||||
lines.append(f" columns: ({cols_str}),")
|
||||
lines.append(" gutter: 12pt,")
|
||||
lines.append(" align: (center + top, center + top),")
|
||||
|
||||
for col in cols:
|
||||
col_t = col.get("titre", "")
|
||||
img_key = col.get("image") or col.get("figure_id")
|
||||
resolved_img = figures_map.get(img_key) or figures_map.get(os.path.basename(img_key)) or img_key
|
||||
w_typ = col.get("width_typst", "90%")
|
||||
lines.append(" [")
|
||||
lines.append(f' #text(weight: "bold", size: 8.5pt, fill: rgb("{col_secondary}"))[{col_t}]\\')
|
||||
lines.append(" #v(1pt)")
|
||||
lines.append(f' #image("{resolved_img}", width: {w_typ})')
|
||||
lines.append(" ],")
|
||||
|
||||
lines.append(" )")
|
||||
lines.append(" ]")
|
||||
lines.append(" )")
|
||||
lines.append(" ]")
|
||||
lines.append(")")
|
||||
lines.append("")
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
def render_typst(source: dict, theme: dict, output_pdf_path: str, typst_bin: str = "typst", figures_map: dict = None, template_path: str = None) -> dict:
|
||||
"""Compile la source en PDF avec Typst et vérifie les critères bloquants."""
|
||||
figures_map = figures_map or {}
|
||||
job_dir = os.path.dirname(os.path.abspath(output_pdf_path))
|
||||
typ_path = os.path.join(job_dir, "document.typ")
|
||||
|
||||
tmpl = template_path or "/app/templates/template_serie_math.typ"
|
||||
if not os.path.exists(tmpl):
|
||||
alt = os.path.join(os.path.dirname(__file__), "templates", "template_serie_math.typ")
|
||||
if os.path.exists(alt):
|
||||
tmpl = alt
|
||||
|
||||
# Racine pour typst sandbox
|
||||
root_dir = "/"
|
||||
if os.path.exists("/app"):
|
||||
root_dir = "/app"
|
||||
|
||||
typ_content = generate_typst_source(source, theme, tmpl, figures_map)
|
||||
with open(typ_path, "w", encoding="utf-8") as f:
|
||||
f.write(typ_content)
|
||||
|
||||
cmd = [typst_bin, "compile", "--root", root_dir, typ_path, output_pdf_path]
|
||||
p = subprocess.run(cmd, capture_output=True, text=True)
|
||||
|
||||
if p.returncode != 0:
|
||||
raise RuntimeError(f"Échec compilation Typst (code {p.returncode}) : {p.stderr}")
|
||||
|
||||
# Contrôle bloquant T3 : Typst sans avertissement
|
||||
stderr_clean = p.stderr.strip()
|
||||
if "warning:" in stderr_clean.lower():
|
||||
raise ValueError(f"Contrôle bloquant échoué : avertissements Typst détectés : {stderr_clean}")
|
||||
|
||||
# Contrôle bloquant T3 : Nombre de pages conforme à pages_cibles
|
||||
doc_fitz = fitz.open(output_pdf_path)
|
||||
page_count = len(doc_fitz)
|
||||
expected_pages = source.get("pages_cibles", 2)
|
||||
if page_count != expected_pages:
|
||||
raise ValueError(f"Contrôle bloquant échoué : {page_count} page(s) générée(s), {expected_pages} attendue(s)")
|
||||
|
||||
extracted_text = "\n".join(page.get_text() for page in doc_fitz)
|
||||
|
||||
return {
|
||||
"pages": page_count,
|
||||
"texte": extracted_text,
|
||||
"typ_path": typ_path
|
||||
}
|
||||
Reference in new issue
Block a user