158 lines
7.4 KiB
Python
158 lines
7.4 KiB
Python
#!/usr/bin/env python3
|
||
"""Les cahiers du formateur : les notes de chaque diaporama, en PDF, à garder à côté de soi.
|
||
|
||
BigBlueButton n'affiche pas les notes du présentateur. Le cahier les rend lisibles sur un
|
||
second écran ou sur papier, diapositive par diapositive, dans l'ordre du diaporama.
|
||
|
||
Il se DÉRIVE des sources (`module-NN/deck.json` et `module-NN/slides/*.html`) : une diapositive
|
||
modifiée se reporte au cahier en le régénérant, jamais en le retouchant.
|
||
|
||
python3 promo/formation/cahiers.py # les treize cahiers et le cahier complet
|
||
python3 promo/formation/cahiers.py --module 7 # un seul
|
||
python3 promo/formation/cahiers.py --vers /chemin # ailleurs que promo/formation/cahiers/
|
||
|
||
Le PDF est produit par LibreOffice (`soffice --headless`), sans réseau.
|
||
"""
|
||
import argparse
|
||
import html
|
||
import json
|
||
import re
|
||
import subprocess
|
||
import sys
|
||
import tempfile
|
||
from pathlib import Path
|
||
|
||
ICI = Path(__file__).resolve().parent
|
||
|
||
# Les adresses des diaporamas, telles que les tient `docs/conception/schemas-flux.md`.
|
||
REGISTRE = ICI.parent.parent / "docs" / "conception" / "schemas-flux.md"
|
||
|
||
STYLE = """
|
||
@page { size: A4; margin: 18mm 18mm 20mm 18mm; }
|
||
body { font-family: 'DejaVu Sans', 'Liberation Sans', sans-serif; font-size: 10.5pt;
|
||
line-height: 1.45; color: #1a1d26; }
|
||
h1 { font-family: 'DejaVu Serif', serif; font-size: 22pt; font-weight: normal; margin: 0 0 2pt 0; }
|
||
.sur { font-size: 8.5pt; letter-spacing: 1.5pt; text-transform: uppercase; color: #0a6b78; margin: 0; }
|
||
.avant { border: 1pt solid #c9cfdc; background: #f3f5fa; padding: 8pt 10pt; margin: 10pt 0 6pt 0; }
|
||
h2 { font-family: 'DejaVu Serif', serif; font-size: 13pt; font-weight: normal; color: #0a6b78;
|
||
border-bottom: 1pt solid #c9cfdc; margin: 16pt 0 4pt 0; padding-bottom: 2pt; }
|
||
.tete { margin: 12pt 0 3pt 0; page-break-after: avoid; }
|
||
.titre { font-weight: bold; font-size: 11pt; }
|
||
.num { color: #0a6b78; font-weight: bold; font-size: 11pt; }
|
||
.oeil { font-size: 8.5pt; color: #5a6785; }
|
||
.anim { font-size: 8.5pt; color: #7a3e8f; }
|
||
.notes { margin: 0; text-align: justify; }
|
||
"""
|
||
|
||
|
||
def texte(fragment: str) -> str:
|
||
"""Le texte lisible d'un fragment HTML, sans balises ni blancs superflus."""
|
||
t = html.unescape(re.sub(r"<[^>]+>", " ", fragment))
|
||
return re.sub(r"\s+", " ", t).strip()
|
||
|
||
|
||
def adresses() -> dict[int, str]:
|
||
"""Module -> adresse du diaporama, lues dans le registre (rien n'est recopié ici)."""
|
||
if not REGISTRE.exists():
|
||
return {}
|
||
trouve = re.findall(r"^\| (\d+) \| \[[^\]]+\]\((https://claude\.ai/artifact/[^)]+)\)",
|
||
REGISTRE.read_text(encoding="utf-8"), re.M)
|
||
return {int(n): u for n, u in trouve}
|
||
|
||
|
||
def lire_module(dossier: Path) -> dict:
|
||
deck = json.loads((dossier / "deck.json").read_text(encoding="utf-8"))
|
||
debuts = {v["start"]: v["description"] for v in deck.get("sections", {}).values()}
|
||
dias = []
|
||
for rang, ident in enumerate(deck["order"], 1):
|
||
s = (dossier / "slides" / f"{ident}.html").read_text(encoding="utf-8")
|
||
notes = re.search(r"<aside>(.*?)</aside>", s, re.S)
|
||
corps = re.sub(r"<aside>.*?</aside>", "", s, flags=re.S)
|
||
titre = re.search(r"<h[12][^>]*>(.*?)</h[12]>", corps, re.S)
|
||
oeil = re.search(r'<p style="font-size:2[48]px;letter-spacing:[34]px;text-transform:uppercase[^"]*">(.*?)</p>',
|
||
corps, re.S)
|
||
clics = len(set(re.findall(r'data-build-in="\w+ (\d+)', corps)))
|
||
dias.append({
|
||
"rang": rang,
|
||
"titre": texte(titre.group(1)) if titre else ident,
|
||
"oeil": texte(oeil.group(1)) if oeil else "",
|
||
"notes": texte(notes.group(1)) if notes else "",
|
||
"clics": clics,
|
||
"section": debuts.get(ident, ""),
|
||
})
|
||
titre = deck["title"].split("—", 1)[-1].strip()
|
||
return {"numero": int(dossier.name.split("-")[1]), "titre": titre, "dias": dias}
|
||
|
||
|
||
def html_module(m: dict, url: str, saut: bool) -> str:
|
||
animees = [d for d in m["dias"] if d["clics"]]
|
||
o = ['<div>',
|
||
'<p class="sur"' + (' style="page-break-before: always"' if saut else '') + '>Set-OPS · cahier du formateur</p>',
|
||
f'<h1>{html.escape(m["titre"])}</h1>',
|
||
]
|
||
avant = [f'<b>{len(m["dias"])} diapositives.</b> Les notes ci-dessous sont celles du diaporama, '
|
||
'dans son ordre.']
|
||
if url:
|
||
avant.append(f'Diaporama : {html.escape(url)}')
|
||
if animees:
|
||
liste = ", ".join(f'{d["rang"]} ({d["clics"]} clics)' for d in animees)
|
||
avant.append(f'<b>Diapositives animées :</b> {liste}. Dans BigBlueButton, un PDF les montre '
|
||
'dans leur état final ; pour les dérouler, partager l’écran avec le diaporama '
|
||
'ouvert en mode Présentation.')
|
||
o.append('<p class="avant">' + '<br>'.join(avant) + '</p>')
|
||
for d in m["dias"]:
|
||
if d["section"]:
|
||
o.append(f'<h2>{html.escape(d["section"])}</h2>')
|
||
tete = [f'<span class="num">{d["rang"]:02d}</span><span class="titre"> · {html.escape(d["titre"])}</span>']
|
||
if d["oeil"]:
|
||
tete.append(f'<span class="oeil">{html.escape(d["oeil"])}</span>')
|
||
if d["clics"]:
|
||
tete.append(f'<span class="anim">Animée : {d["clics"]} clics — les notes suivent les clics.</span>')
|
||
o.append('<p class="tete">' + '<br>'.join(tete) + '</p>')
|
||
o.append(f'<p class="notes">{html.escape(d["notes"]) or "(pas de notes)"}</p>')
|
||
o.append('</div>')
|
||
return "\n".join(o)
|
||
|
||
|
||
def page(titre: str, corps: str) -> str:
|
||
return (f'<!doctype html><html lang="fr"><head><meta charset="utf-8"><title>{html.escape(titre)}</title>'
|
||
f'<style>{STYLE}</style></head><body>\n{corps}\n</body></html>\n')
|
||
|
||
|
||
def en_pdf(source: Path, vers: Path) -> None:
|
||
r = subprocess.run(["soffice", "--headless", "--infilter=HTML (StarWriter)",
|
||
"--convert-to", "pdf:writer_pdf_Export",
|
||
"--outdir", str(vers), str(source)], capture_output=True, text=True)
|
||
if r.returncode != 0 or not (vers / (source.stem + ".pdf")).exists():
|
||
sys.exit(f"LibreOffice n'a pas produit {source.stem}.pdf :\n{r.stderr or r.stdout}")
|
||
|
||
|
||
def main() -> None:
|
||
p = argparse.ArgumentParser(description=__doc__.split("\n")[0])
|
||
p.add_argument("--module", type=int, help="un seul module (0 à 12)")
|
||
p.add_argument("--vers", type=Path, default=ICI / "cahiers", help="dossier des PDF")
|
||
a = p.parse_args()
|
||
modules = [lire_module(d) for d in sorted(ICI.glob("module-[0-9][0-9]"))]
|
||
if a.module is not None:
|
||
modules = [m for m in modules if m["numero"] == a.module]
|
||
if not modules:
|
||
sys.exit(f"Aucun module {a.module}.")
|
||
urls = adresses()
|
||
a.vers.mkdir(parents=True, exist_ok=True)
|
||
with tempfile.TemporaryDirectory() as tmp:
|
||
t = Path(tmp)
|
||
for m in modules:
|
||
nom = f"cahier-module-{m['numero']:02d}"
|
||
(t / f"{nom}.html").write_text(page(m["titre"], html_module(m, urls.get(m["numero"], ""), False)),
|
||
encoding="utf-8")
|
||
en_pdf(t / f"{nom}.html", a.vers)
|
||
print(f" {a.vers / (nom + '.pdf')}")
|
||
if a.module is None:
|
||
corps = "\n".join(html_module(m, urls.get(m["numero"], ""), i > 0) for i, m in enumerate(modules))
|
||
(t / "cahier-complet.html").write_text(page("Cahier du formateur — Set-OPS", corps), encoding="utf-8")
|
||
en_pdf(t / "cahier-complet.html", a.vers)
|
||
print(f" {a.vers / 'cahier-complet.pdf'}")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|