Files
models/models/reports/rendering.py
T
edgar e8c264e571 Subgroup reports for CaCu's survival and PIM scenarios, as version files and as notebooks in the code
Every CaCu PIM scenario (cin2_pim, post-colposcopy, post-treatment) and the survival scenario now keep, per
combination of their covariates, the model against its empirical estimate, with the methods each used:

- PIM (models/cacu/cin2_pim/report.py): Turnbull's interval-censored estimate (prevalent = mass at 0, free in (l, r],
  unknown baseline in [0, r]; ported from bayes-pim chapter 24) with a bootstrap band, against the mixture refitted on
  every coded member with a delta-method band over the likelihood (inverse numerical Hessian, numerical gradient of
  CR(t), log scale); E/O at each horizon with log(E/O) taken as normal.
- Survival (models/cacu/survival/report.py): Kaplan-Meier with Greenwood's band against the SEER pipeline's own
  subgroup points and bootstrap interval (survival_curves.sv_sub_weights and sv_sub_points, called as they are).

A version keeps the record as analisis/subgrupos.json and a self-contained Plotly page as reportes/subgrupos.html
(TrainingRun.log_report; the saver publishes a dataflow's `reports`). The same drawing is a notebook in the code,
models/cacu/{cin2_pim,survival}/notebooks/reporte_subgrupos.ipynb: chart names and computed results only, a
`parameters` cell, `#| echo: false` cells. models.reports.templates lists those notebooks with the scenarios each serves
and reads one by id, for the WebApi's /governance/notebook-templates. The Jupyter renderer now drops the code of
`#| echo: false` cells, as Quarto does.

plotly>=5.18 joins the `survival-curves` extra (installed by the WebApi) and the dev group.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-21 22:41:04 -06:00

186 lines
7.7 KiB
Python

"""Runs a notebook, renders it to a self-contained HTML page, and identifies its content by its cells' sources, without
outputs or execution counts.
Two renderers, one class each in `RENDERERS`: `quarto`, and `jupyter`, which runs the cells with `nbclient` and
exports the page with `nbconvert` (the `notebooks` extra), so it needs nothing outside Python. `NOTEBOOK_RENDERER`
picks one; otherwise Quarto when it's installed, else Jupyter.
`QUARTO_BIN` names the `quarto` executable when it isn't on the `PATH`. Quarto runs notebooks through a Python that has
Jupyter (`nbformat`, `nbclient`); under `uv run` the first one on the `PATH` is this package's, which doesn't, so
`QUARTO_PYTHON` names one that does. The notebook runs with the kernel its metadata
names, or `kernel` if given, in the environment given: that's how a report points the notebook at a database, a
cohort folder and a build's file. Quarto writes next to its input, so the notebook is copied to a temporary folder
first and the source folder is left untouched.
"""
import copy
import hashlib
import json
import os
import shutil
import subprocess
import tempfile
from abc import ABC, abstractmethod
from pathlib import Path
QUARTO_ENV = "QUARTO_BIN"
RENDERER_ENV = "NOTEBOOK_RENDERER"
# Seconds a single cell may run under the Jupyter renderer.
CELL_TIMEOUT_ENV = "NOTEBOOK_CELL_TIMEOUT"
CELL_TIMEOUT = 1800
class RenderError(RuntimeError):
"""The notebook couldn't be run: a cell raised, the kernel is missing, or the renderer isn't installed. `page` is
the page of the cells that did run, when the renderer could still make one."""
def __init__(self, message: str, page: str | None = None):
super().__init__(message)
self.page = page
class NotebookRenderer(ABC):
name: str
@classmethod
@abstractmethod
def available(cls) -> bool: ...
@abstractmethod
def render(self, notebook: dict, name: str, folder: Path, env: dict[str, str]) -> str:
"""Runs `notebook` in `folder` with exactly `env` as its environment and returns the page's HTML."""
RENDERERS: dict[str, type[NotebookRenderer]] = {}
def register_renderer(cls: type[NotebookRenderer]) -> type[NotebookRenderer]:
RENDERERS[cls.name] = cls
return cls
def quarto() -> str:
found = os.environ.get(QUARTO_ENV) or shutil.which("quarto")
if not found:
raise RenderError(f"quarto isn't installed: put it on the PATH or set {QUARTO_ENV}")
return found
@register_renderer
class QuartoRenderer(NotebookRenderer):
name = "quarto"
@classmethod
def available(cls) -> bool:
return bool(os.environ.get(QUARTO_ENV) or shutil.which("quarto"))
def render(self, notebook: dict, name: str, folder: Path, env: dict[str, str]) -> str:
source = folder / f"{name}.ipynb"
source.write_text(json.dumps(notebook, ensure_ascii=False))
done = subprocess.run([quarto(), "render", source.name, "--execute", "--to", "html", "-M", "embed-resources:true"],
cwd=folder, env=env, capture_output=True, text=True)
page = source.with_suffix(".html")
if done.returncode or not page.exists():
raise RenderError(f"quarto couldn't render {name}: {(done.stderr or done.stdout)[-2000:]}")
return page.read_text()
HIDE_INPUT_TAG = "remove_input" # what a `#| echo: false` cell gets before the page is exported
@register_renderer
class JupyterRenderer(NotebookRenderer):
"""The kernel is the one the notebook names, which must be installed beside this package (`python3` is this
package's own interpreter once `ipykernel` is installed)."""
name = "jupyter"
@classmethod
def available(cls) -> bool:
try:
import nbclient # noqa: F401
import nbconvert # noqa: F401
except ImportError:
return False
return True
def render(self, notebook: dict, name: str, folder: Path, env: dict[str, str]) -> str:
import nbformat
from nbclient import NotebookClient
from nbclient.exceptions import CellExecutionError, DeadKernelError
from nbconvert import HTMLExporter
node = nbformat.reads(json.dumps(notebook), as_version=4)
kernel = node.metadata.get("kernelspec", {}).get("name") or "python3"
timeout = int(os.environ.get(CELL_TIMEOUT_ENV, CELL_TIMEOUT))
client = NotebookClient(node, timeout=timeout, kernel_name=kernel, resources={"metadata": {"path": str(folder)}})
try:
client.execute(env=env, cwd=str(folder))
except (CellExecutionError, DeadKernelError, TimeoutError) as error:
raise RenderError(f"{name}: {str(error)[-2000:]}", page=self._page(HTMLExporter, node)) from error
except Exception as error:
raise RenderError(f"{name}: el kernel {kernel!r} no pudo correr el notebook: {error}") from error
return self._page(HTMLExporter, node)
@staticmethod
def _page(exporter, node) -> str:
"""The page, without the code of the cells that ask for it as Quarto does (`#| echo: false`), so a notebook
renders the same with either renderer."""
from nbconvert.preprocessors import TagRemovePreprocessor
for cell in node.cells:
if cell.cell_type == "code" and any(line.replace(" ", "") == "#|echo:false" for line in cell.source.splitlines()):
tags = cell.metadata.setdefault("tags", [])
if HIDE_INPUT_TAG not in tags:
tags.append(HIDE_INPUT_TAG)
page = exporter(embed_images=True)
page.register_preprocessor(TagRemovePreprocessor(remove_input_tags={HIDE_INPUT_TAG}, enabled=True), enabled=True)
body, _ = page.from_notebook_node(node)
return body
def renderer() -> NotebookRenderer:
"""The renderer `NOTEBOOK_RENDERER` names; otherwise Quarto if installed, else Jupyter."""
if chosen := os.environ.get(RENDERER_ENV):
if chosen not in RENDERERS:
raise RenderError(f"{RENDERER_ENV}={chosen!r}: use one of {sorted(RENDERERS)}")
return RENDERERS[chosen]()
for cls in RENDERERS.values():
if cls.available():
return cls()
raise RenderError(f"no notebook renderer is installed: install quarto or the 'notebooks' extra ({sorted(RENDERERS)})")
def with_kernel(notebook: dict, kernel: str | None) -> dict:
if not kernel:
return notebook
return {**notebook, "metadata": {**notebook.get("metadata", {}),
"kernelspec": {"name": kernel, "display_name": kernel, "language": "python"}}}
def render_notebook(notebook: dict, name: str, output: Path, *, env: dict[str, str] | None = None,
kernel: str | None = None) -> Path:
"""Runs and renders `notebook` (its JSON) as `name`, with this process's environment plus `env`, and writes the
page to `output`."""
with tempfile.TemporaryDirectory(prefix="render-") as folder:
page = renderer().render(with_kernel(notebook, kernel), name, Path(folder), {**os.environ, **(env or {})})
output.parent.mkdir(parents=True, exist_ok=True)
output.write_text(page)
return output
def without_outputs(notebook: dict) -> dict:
"""The notebook as written: code cells keep their source and lose their outputs."""
cleared = copy.deepcopy(notebook)
for cell in cleared["cells"]:
if cell["cell_type"] == "code":
cell["outputs"], cell["execution_count"] = [], None
return cleared
def notebook_sha256(notebook: dict) -> str:
"""Changes when a cell's type or source changes, not when the notebook is run again."""
cells = [[cell["cell_type"], "".join(cell["source"]) if isinstance(cell["source"], list) else cell["source"]]
for cell in notebook["cells"]]
return hashlib.sha256(json.dumps(cells, ensure_ascii=False).encode()).hexdigest()