Files
models/models/reports/eda.py
T

48 lines
2.5 KiB
Python

"""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.storage.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 registered_name
from models.io.storage import cohort_reference, file_sha256, read_metadata
from models.io.tracking import find_run, record_report
from models.reports.rendering import notebook_sha256, render_notebook, 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