models report eda: the exploratory notebook run on a build's file, rendered with Quarto and kept as an MLflow run of the notebook's experiment

This commit is contained in:
2026-11-06 00:28:47 -06:00
parent 761b5b03bc
commit 15ffeb3efe
7 changed files with 341 additions and 7 deletions
+1
View File
@@ -21,6 +21,7 @@ WebApi.
| `pipelines/cohort_build.py` | Builds a cohort: all patients → index date → A1 → … → An → study population. Lists the steps, gives each rule its own nodes and runs them. `python -m models cohorts build cacu cohorte_vigilancia --manifest target/manifest.json [--graph]` shows the attrition or the Mermaid diagram; it stores nothing. |
| `pipelines/export_cohort.py` | Exports a build to its Parquet file. `python -m models cohorts export cacu cohorte_vigilancia [--build N]` writes the kit's build once; `--source dbt --manifest target/manifest.json` builds it from dbt's rules into `dbt/<n>.parquet` and writes only when its rows change. The timeline comes from dbt's view `<domain>_linea_de_tiempo`. |
| `steps/risks.py`, `pipelines/store_risks.py` | Stores an estimate file as a batch of risks in the domain's database (`evaluacion_riesgo_lote`, `evaluacion_riesgo`), through `cohorte_repository`: one preliminary risk per member at the model's horizon, with the version's MLflow keys. Storing the same estimate again adds nothing. A batch points to a kit build (`armado_id`), so estimates of dbt builds are refused. `python -m models store cacu cin2_logistic --input file.parquet`, or `run … --estimate --store --output file.parquet`. |
| `steps/report.py`, `io/rendering.py`, `pipelines/report_eda.py` | A model's exploratory notebook as an MLflow report: `python -m models report eda cacu cin2_logistic [--source kit\|dbt] [--build N] [--notebook path] [--kernel name]` runs `notebooks/<scenario>/01_eda.ipynb` on the build's file (`COHORT_FILE`), renders it with Quarto to one HTML page, and logs the page and the notebook without outputs as a run of the experiment `<domain>-<scenario>/<notebook>`, tagged with the notebook's content hash and the build's file. The same notebook and file are reported once. Needs Quarto (`QUARTO_BIN`) and a Python with Jupyter (`QUARTO_PYTHON`). |
| `cacu/cin2_logistic/` | CaCu's CIN2+ prototype: the probability of a CIN2+ biopsy within `outcome_window_months` (provisional, 12) of the index cytology, from the index sample's Bethesda, HPV and HPV 16/18 results; no clinical validation. Its steps (`model.py`, Hamilton nodes), driver (`train.py`) and settings (`model.toml`); it only reads the build's Parquet file. Train with `python -m models train cacu cin2_logistic [--source kit|dbt] [--build N] [--environment dev|prod]`; estimate with `python -m models estimate cacu cin2_logistic --output file.parquet [--build N] [--version N]` (`estimate.py`), by default with the version holding the `produccion` alias. `python -m models run cacu cin2_logistic [--export] [--train] [--promote] [--estimate --output file.parquet]` runs only the steps named, in that order, and repeats none already done. |
| `cacu/`, `cama/`, `tea/` | Un paquete por dominio, con sus escenarios y sus cuadernos (`notebooks/`, fuera del paquete instalado). |
| `ocr.py` | Los trabajos de OCR (`OCR_JOBS`): resultados de VPH, grado CIN y grado histológico desde los PDF guardados (VAR-01..09). |
+36
View File
@@ -94,6 +94,29 @@ def _store(args: argparse.Namespace) -> int:
return _store_step(args, args.input)
def _report_eda(args: argparse.Namespace) -> int:
"""Runs the model's exploratory notebook on a build's file and keeps the rendered page as an MLflow report."""
from pathlib import Path
from models.io.rendering import RenderError
from models.pipelines.report_eda import report_eda
if not (model := _model_module(args, "model")) or not (path := _cohort_file(args, model)):
return 1
notebook = Path(args.notebook) if args.notebook else (
Path(model.__file__).parents[1] / "notebooks" / args.scenario / "01_eda.ipynb")
if not notebook.exists():
print(f"no notebook at {notebook}", file=sys.stderr)
return 1
try:
run_id, written = report_eda(notebook, path, args.domain, args.scenario, kernel=args.kernel)
except RenderError as error:
print(error, file=sys.stderr)
return 1
print(f"{'reported' if written else 'already reported'}: run {run_id}, {notebook.name} on {path}")
return 0
def _estimate(args: argparse.Namespace) -> int:
"""Scores the build's file with a registered version and writes the output file."""
if not (model := _model_module(args, "model")) or not (path := _cohort_file(args, model)):
@@ -286,6 +309,19 @@ def build_parser() -> argparse.ArgumentParser:
estimate.add_argument("--version", help="the model version; the one in production by default")
estimate.set_defaults(run=_estimate)
report = commands.add_parser("report", help="notebooks run on a build's file and kept as MLflow reports")
report.set_defaults(run=lambda args: _show_help(report))
reports = report.add_subparsers(dest="action", metavar="<report>")
eda = reports.add_parser("eda", help="render the exploratory notebook with Quarto and log it to MLflow")
eda.add_argument("domain", choices=["cacu", "cama", "tea"])
eda.add_argument("scenario", help="the model's folder, e.g. cin2_logistic")
eda.add_argument("--notebook", help="the notebook; the scenario's notebooks/<scenario>/01_eda.ipynb by default")
eda.add_argument("--build", "--armado", dest="armado", type=int,
help="the build's number: a kit build's armado_id, or a dbt build's; the latest exported by default")
eda.add_argument("--source", choices=["kit", "dbt"], default="dbt", help="whose builds: the kit's or dbt's rules'")
eda.add_argument("--kernel", help="the Jupyter kernel to run it with; the notebook's own by default")
eda.set_defaults(run=_report_eda)
store = commands.add_parser("store", help="store an estimate file as a batch of risks in the domain's database")
store.add_argument("domain", choices=["cacu", "cama", "tea"])
store.add_argument("scenario", help="the model's folder, e.g. cin2_logistic")
+49
View File
@@ -0,0 +1,49 @@
"""Renders a notebook to a self-contained HTML page with Quarto, running it first.
`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 json
import os
import shutil
import subprocess
import tempfile
from pathlib import Path
QUARTO_ENV = "QUARTO_BIN"
class RenderError(RuntimeError):
"""Quarto failed: a cell raised, the kernel is missing, or Quarto isn't installed."""
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
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`, and writes the page to `output`."""
command = quarto()
if kernel:
notebook = {**notebook, "metadata": {**notebook.get("metadata", {}),
"kernelspec": {"name": kernel, "display_name": kernel, "language": "python"}}}
with tempfile.TemporaryDirectory(prefix="render-") as folder:
source = Path(folder) / f"{name}.ipynb"
source.write_text(json.dumps(notebook, ensure_ascii=False))
done = subprocess.run([command, "render", source.name, "--execute", "--to", "html", "-M", "embed-resources:true"],
cwd=folder, env={**os.environ, **(env or {})}, 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:]}")
output.parent.mkdir(parents=True, exist_ok=True)
shutil.move(page, output)
return output
+38 -7
View File
@@ -11,6 +11,9 @@ process never interfere.
`MLFLOW_ARTIFACT_ROOT`, when set, is where new experiments keep their
artifacts (MLflow's own default is `./mlruns`, relative to the working directory).
Reports are runs too: `record_report` keeps a rendered notebook and its source as artifacts, in an experiment of
their own, and `find_run` finds one already made from the same inputs.
A run that logs a model (`log_model`) registers `runs:/<run_id>/model`, tagged
with its `modelo_sha`: the hash of the stored artifact, which identifies the exact
model that produced a risk. Which code trained it is recorded apart: every run is
@@ -29,7 +32,7 @@ import mlflow.pyfunc
from core.governance.enums import ArtifactKind, Environment
from mlflow import MlflowClient
from models.io.lineage import ARMADO_TAG, DOMAINS, MODEL_SHA_TAG, code_version, model_sha, registered_name
from models.io.lineage import ARMADO_TAG, DOMAINS, MODEL_SHA_TAG, code_version, matches, model_sha, registered_name
from models.io.storage import ReadOnlyRepository, resolve_repository
ARTIFACT_ROOT_ENV = "MLFLOW_ARTIFACT_ROOT"
@@ -70,6 +73,39 @@ def log_artifact_file(client: MlflowClient, run_id: str, kind: str, path: str |
client.log_dict(run_id, metadata, f"{kind}/{Path(path).name}.meta.json")
def experiment_id(client: MlflowClient, name: str) -> str:
"""The experiment `name`, created if it doesn't exist, under `MLFLOW_ARTIFACT_ROOT` when that's set."""
experiment = client.get_experiment_by_name(name)
if experiment:
return experiment.experiment_id
root = os.environ.get(ARTIFACT_ROOT_ENV)
return client.create_experiment(name, artifact_location=str(Path(root) / name) if root else None)
def find_run(client: MlflowClient, experiment: str, expected: dict[str, str]) -> str | None:
"""The newest finished run of `experiment` whose tags hold every expected value, or `None`."""
found = client.get_experiment_by_name(experiment)
if found is None:
return None
for run in client.search_runs([found.experiment_id], order_by=["attributes.start_time DESC"]):
if run.info.status == "FINISHED" and matches(run.data.tags, expected):
return run.info.run_id
return None
def record_report(client: MlflowClient, experiment: str, tags: dict[str, str], files: dict[str, Path]) -> str:
"""A finished run of `experiment` with `tags`, the code version, and each file logged under its kind's folder."""
run = client.create_run(experiment_id(client, experiment), tags={**code_version(), **tags})
try:
for kind, path in files.items():
log_artifact_file(client, run.info.run_id, kind, path)
except Exception:
client.set_terminated(run.info.run_id, "FAILED")
raise
client.set_terminated(run.info.run_id, "FINISHED")
return run.info.run_id
class TrainingRun:
"""One instance per training execution, wrapping one MLflow run. PROD
runs name the cohort build they were trained on, so their metrics trace
@@ -112,12 +148,7 @@ class TrainingRun:
self.client.set_tag(self.run_id, tag, value)
def _experiment_id(self) -> str:
name = registered_name(self.domain, self.scenario)
experiment = self.client.get_experiment_by_name(name)
if experiment:
return experiment.experiment_id
root = os.environ.get(ARTIFACT_ROOT_ENV)
return self.client.create_experiment(name, artifact_location=str(Path(root) / name) if root else None)
return experiment_id(self.client, registered_name(self.domain, self.scenario))
def repository(self, entity: str) -> ReadOnlyRepository:
"""ML-04: read-only access to `persistance.<domain>.<entity>_repository`."""
+48
View File
@@ -0,0 +1,48 @@
"""An exploratory notebook as an MLflow report: run on a build's file, rendered with Quarto, kept as artifacts.
Each notebook is an experiment, `<domain>-<scenario>/<notebook>` (`cacu-cin2_logistic/01_eda`), and each report a run
in it, tagged with the notebook's content hash and the build's file (`models.io.lineage.cohort_reference`). Its
artifacts are the rendered page (`report/`) and the notebook without outputs (`notebook/`). A notebook and a file that
were already reported together are not rendered again.
The notebook reads the build's file from `COHORT_FILE`, set here, and the database and cohort folder from the
environment it inherits.
"""
import json
import tempfile
from pathlib import Path
from mlflow import MlflowClient
from models.io.lineage import cohort_reference, file_sha256, registered_name
from models.io.rendering import render_notebook
from models.io.storage import read_metadata
from models.io.tracking import find_run, record_report
from models.steps.report import notebook_sha256, without_outputs
COHORT_FILE_ENV = "COHORT_FILE"
NOTEBOOK_TAG, NOTEBOOK_SHA_TAG, REPORT_TAG = "notebook", "notebook.sha256", "report"
def report_experiment(domain: str, scenario: str, notebook: Path) -> str:
return f"{registered_name(domain, scenario)}/{notebook.stem}"
def report_eda(notebook_path: str | Path, cohort_path: str | Path, domain: str, scenario: str,
kernel: str | None = None) -> tuple[str, bool]:
"""Returns the report's run id and whether it was rendered now."""
notebook_path, cohort_path = Path(notebook_path), Path(cohort_path)
notebook = json.loads(notebook_path.read_text())
experiment = report_experiment(domain, scenario, notebook_path)
tags = {REPORT_TAG: "eda", NOTEBOOK_TAG: notebook_path.name, NOTEBOOK_SHA_TAG: notebook_sha256(notebook),
**cohort_reference(read_metadata(cohort_path), file_sha256(cohort_path))}
client = MlflowClient()
if existing := find_run(client, experiment, tags):
return existing, False
with tempfile.TemporaryDirectory(prefix="report-") as folder:
page = render_notebook(notebook, notebook_path.stem, Path(folder) / f"{notebook_path.stem}.html",
env={COHORT_FILE_ENV: str(cohort_path.resolve())}, kernel=kernel)
source = Path(folder) / notebook_path.name
source.write_text(json.dumps(without_outputs(notebook), ensure_ascii=False, indent=1))
return record_report(client, experiment, tags, {"report": page, "notebook": source}), True
+21
View File
@@ -0,0 +1,21 @@
"""What identifies a notebook's content: its cells' sources, without outputs or execution counts."""
import copy
import hashlib
import json
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()
+148
View File
@@ -0,0 +1,148 @@
"""What this module covers: an exploratory notebook as an MLflow report (`models.steps.report`, `models.io.rendering`,
`models.io.tracking.find_run`/`record_report`, `models.pipelines.report_eda`) and `models report eda`: the content hash,
rendering with the build's file in the environment, one run per notebook and file, and its artifacts.
Fixtures: `fake_quarto`, a stand-in `quarto` (through `QUARTO_BIN`) that writes a page naming the kernel and the
`COHORT_FILE` it was given, or fails when the notebook says so; `notebook`, a two-cell notebook with outputs;
`cohort`, a dbt build's file with its metadata; `mlflow_tracking` (conftest), a SQLite-backed MLflow.
"""
import json
import os
import stat
import sys
from pathlib import Path
import pyarrow as pa
import pyarrow.parquet as pq
import pytest
from mlflow import MlflowClient
from models.__main__ import main
from models.io.rendering import RenderError, render_notebook
from models.pipelines.report_eda import report_eda
from models.steps.report import notebook_sha256, without_outputs
FAKE = '''#!{python}
import json, os, pathlib, sys
source = pathlib.Path(sys.argv[2])
notebook = json.loads(source.read_text())
if "fail" in json.dumps(notebook["cells"]):
sys.exit("a cell raised")
kernel = notebook["metadata"]["kernelspec"]["name"]
source.with_suffix(".html").write_text(f"<html>kernel={{kernel}} cohort={{os.environ.get('COHORT_FILE')}}</html>")
'''
@pytest.fixture
def fake_quarto(tmp_path, monkeypatch):
path = tmp_path / "quarto"
path.write_text(FAKE.format(python=sys.executable))
path.chmod(path.stat().st_mode | stat.S_IEXEC)
monkeypatch.setenv("QUARTO_BIN", str(path))
return path
def _notebook(source="print(1)"):
return {"cells": [{"cell_type": "markdown", "metadata": {}, "source": ["# EDA"]},
{"cell_type": "code", "metadata": {}, "execution_count": 3, "source": [source],
"outputs": [{"output_type": "stream", "name": "stdout", "text": ["1\n"]}]}],
"metadata": {"kernelspec": {"name": "isssteleon-webapi", "display_name": "k", "language": "python"}},
"nbformat": 4, "nbformat_minor": 5}
@pytest.fixture
def notebook(tmp_path):
path = tmp_path / "notebooks" / "01_eda.ipynb"
path.parent.mkdir()
path.write_text(json.dumps(_notebook()))
return path
def _cohort(path, build):
path.parent.mkdir(parents=True, exist_ok=True)
table = pa.table({"pac_id": [1, 2]})
pq.write_table(table.replace_schema_metadata({"url": "cacu/cohorte_vigilancia", "producer": "dbt", "build": str(build)}), path)
return path
@pytest.fixture
def cohort(tmp_path):
return _cohort(tmp_path / "cohorts" / "dbt" / "1.parquet", 1)
def test_the_hash_follows_the_sources_not_the_outputs():
"""Pins down: running a notebook again (new outputs, counts) keeps its hash; editing a cell changes it. Fails if
outputs enter the hash, which would make every rendering a new report."""
ran_again = _notebook()
ran_again["cells"][1].update(outputs=[], execution_count=9)
assert notebook_sha256(ran_again) == notebook_sha256(_notebook())
assert notebook_sha256(_notebook("print(2)")) != notebook_sha256(_notebook())
assert without_outputs(_notebook())["cells"][1]["outputs"] == []
def test_rendering_gets_the_environment_and_the_kernel(fake_quarto, tmp_path):
"""Pins down: the page is rendered with the extra environment (the build's file) and with `kernel` when given.
Fails if either is lost on the way to Quarto."""
page = render_notebook(_notebook(), "01_eda", tmp_path / "out" / "01_eda.html", env={"COHORT_FILE": "/x.parquet"},
kernel="models")
assert page.read_text() == "<html>kernel=models cohort=/x.parquet</html>"
def test_a_failing_notebook_or_missing_quarto_is_a_render_error(fake_quarto, tmp_path, monkeypatch):
"""Pins down: a cell that raises, and Quarto not being installed, end as `RenderError` with the reason. Fails if a
broken report is logged or the error is a bare `FileNotFoundError`."""
with pytest.raises(RenderError, match="a cell raised"):
render_notebook(_notebook("fail"), "01_eda", tmp_path / "page.html")
monkeypatch.setenv("QUARTO_BIN", "")
monkeypatch.setenv("PATH", str(tmp_path / "empty"))
with pytest.raises(RenderError, match="isn't installed"):
render_notebook(_notebook(), "01_eda", tmp_path / "page.html")
def test_a_report_is_a_run_of_the_notebooks_experiment_with_its_page(fake_quarto, notebook, cohort, mlflow_tracking):
"""Pins down: the run is in `<domain>-<scenario>/<notebook>`, tagged with the notebook's hash and the build's file,
and holds the page (rendered on that file) and the notebook without outputs. Fails if the page or the source is
missing, or the run can't be traced to its inputs."""
run_id, written = report_eda(notebook, cohort, "cacu", "cin2_logistic")
client = MlflowClient()
run = client.get_run(run_id)
assert written and client.get_experiment(run.info.experiment_id).name == "cacu-cin2_logistic/01_eda"
assert run.data.tags["notebook.sha256"] == notebook_sha256(_notebook())
assert (run.data.tags["cohort.source"], run.data.tags["cohort.build"]) == ("dbt", "1")
assert sorted(a.path for a in client.list_artifacts(run_id)) == ["notebook", "report"]
page = Path(client.download_artifacts(run_id, "report/01_eda.html")).read_text()
assert str(cohort.resolve()) in page
source = json.loads(Path(client.download_artifacts(run_id, "notebook/01_eda.ipynb")).read_text())
assert source["cells"][1]["outputs"] == []
def test_the_same_notebook_and_file_are_reported_once(fake_quarto, notebook, cohort, mlflow_tracking, tmp_path):
"""Pins down: reporting again reuses the run; an edited notebook or another build's file makes a new one. Fails if
the check ignores either input, or renders every time."""
first, _ = report_eda(notebook, cohort, "cacu", "cin2_logistic")
again, written = report_eda(notebook, cohort, "cacu", "cin2_logistic")
other_build, _ = report_eda(notebook, _cohort(tmp_path / "cohorts" / "dbt" / "2.parquet", 2), "cacu", "cin2_logistic")
notebook.write_text(json.dumps(_notebook("print(2)")))
edited, _ = report_eda(notebook, cohort, "cacu", "cin2_logistic")
assert again == first and not written
assert len({first, other_build, edited}) == 3
def test_the_command_reports_on_the_latest_dbt_build(fake_quarto, notebook, tmp_path, monkeypatch, mlflow_tracking, capsys):
"""Pins down: `models report eda` takes dbt's latest exported build by default and the notebook given. Fails if it
reads the kit's builds by default, or ignores `--notebook`."""
folder = tmp_path / "cohorts" / "cacu" / "cohorte_vigilancia" / "dbt"
_cohort(folder / "1.parquet", 1)
_cohort(folder / "2.parquet", 2)
monkeypatch.setenv("COHORTS_DIR", str(tmp_path / "cohorts"))
assert main(["report", "eda", "cacu", "cin2_logistic", "--notebook", str(notebook)]) == 0
assert "reported" in capsys.readouterr().out
run = MlflowClient().search_runs([MlflowClient().get_experiment_by_name("cacu-cin2_logistic/01_eda").experiment_id])[0]
assert run.data.tags["cohort.build"] == "2"