import re
import os
import yaml
import markdown
from bs4 import BeautifulSoup
from latex2mathml.converter import convert as latex_to_mathml
from .utils.fiche_utils import render_fiche_markdown
import pypandoc
import streamlit as st
from .utils.dynamic import (
build_dynamic_sections,
build_ivc_sections,
build_ihh_sections,
build_isg_sections,
build_production_sections,
build_minerai_sections
)
# === Fonctions de transformation ===
def remplacer_latex_par_mathml(markdown_text):
def remplacer_bloc_display(match):
formule_latex = match.group(1).strip()
try:
mathml = latex_to_mathml(formule_latex, display='block')
return f'
{mathml}
'
except Exception as e:
return f"Erreur LaTeX block: {e}"
def remplacer_bloc_inline(match):
formule_latex = match.group(1).strip()
try:
mathml = latex_to_mathml(formule_latex, display='inline')
return f'{mathml}'
except Exception as e:
return f"Erreur LaTeX inline: {e}"
markdown_text = re.sub(r"\$\$(.*?)\$\$", remplacer_bloc_display, markdown_text, flags=re.DOTALL)
markdown_text = re.sub(r"(?', f'{bloc_titre}
']
for bloc in sections_n1:
if bloc["titre"] and bloc["titre"] != bloc_titre:
html_output.append(f"{bloc['titre']}
")
if bloc["intro"]:
intro_md = remplacer_latex_par_mathml("\n".join(bloc["intro"]))
html_intro = markdown_to_html_rgaa(intro_md)
html_output.append(html_intro)
for sous_titre, contenu in bloc["sections_n2"].items():
contenu_md = remplacer_latex_par_mathml("\n".join(contenu))
contenu_html = markdown_to_html_rgaa(contenu_md, caption_text=sous_titre)
html_output.append(f"{sous_titre}
{contenu_html} ")
html_output.append("")
return html_output
def generer_fiche(md_source, dossier, nom_fichier, seuils):
front_match = re.match(r"(?s)^---\n(.*?)\n---\n", md_source)
context = yaml.safe_load(front_match.group(1)) if front_match else {}
type_fiche = context.get("type_fiche")
if type_fiche == "indice":
indice = context.get("indice_court")
if indice == "ICS":
md_source = build_dynamic_sections(md_source)
elif indice == "IVC":
md_source = build_ivc_sections(md_source)
elif indice == "IHH":
md_source = build_ihh_sections(md_source)
elif indice == "ISG":
md_source = build_isg_sections(md_source)
elif type_fiche in ["assemblage", "fabrication"]:
md_source = build_production_sections(md_source)
elif type_fiche == "minerai":
md_source = build_minerai_sections(md_source)
contenu_md = render_fiche_markdown(md_source, seuils, license_path="assets/licence.md")
md_path = os.path.join("Fiches", dossier, nom_fichier)
os.makedirs(os.path.dirname(md_path), exist_ok=True)
with open(md_path, "w", encoding="utf-8") as f:
f.write(contenu_md)
# Génération automatique du PDF
pdf_dir = os.path.join("static", "Fiches", dossier)
os.makedirs(pdf_dir, exist_ok=True)
# Construire le chemin PDF correspondant (même nom que .md, mais .pdf)
nom_pdf = os.path.splitext(nom_fichier)[0] + ".pdf"
pdf_path = os.path.join(pdf_dir, nom_pdf)
try:
pypandoc.convert_file(
md_path,
to="pdf",
outputfile=pdf_path,
extra_args=["--pdf-engine=xelatex", "-V", "geometry:margin=2cm"]
)
except Exception as e:
st.error(f"[ERREUR] Génération PDF échouée pour {md_path}: {e}")
html_output = rendu_html(contenu_md)
html_dir = os.path.join("HTML", dossier)
os.makedirs(html_dir, exist_ok=True)
html_path = os.path.join(html_dir, os.path.splitext(nom_fichier)[0] + ".html")
with open(html_path, "w", encoding="utf-8") as f:
f.write("\n".join(html_output))
return html_path