Files
models/models/__main__.py
T

417 lines
21 KiB
Python

"""The package's command line: `python -m models <command>`.
Each area adds its subcommands to `build_parser`. Heavy imports (MLflow, the kit) belong inside the
command that needs them, so `--help` stays immediate.
"""
import argparse
import sys
from collections.abc import Sequence
def _show_help(parser: argparse.ArgumentParser) -> int:
"""A command without actions yet shows its help and fails, rather than appearing to have run."""
parser.print_help()
return 2
def _model_module(args: argparse.Namespace, name: str):
"""A module of the model's folder; `None` and a message on stderr if there's no such model."""
from importlib import import_module
package = f"models.{args.domain}.{args.scenario}"
try:
return import_module(f"{package}.{name}")
except ModuleNotFoundError as error:
if not (error.name or "").startswith(package):
raise
print(f"no such model: {args.domain}/{args.scenario}", file=sys.stderr)
return None
def _cohort_file(args: argparse.Namespace, model):
"""The build's exported file; `None` and a message on stderr if it's missing."""
from persistance.settings import settings
from models.io.storage import cohorts_root, dbt_build_path, find_cohort_file, latest_dbt_build
url = model.SETTINGS["cohort"]
command = f"python -m models cohorts export {url.replace('/', ' ')}" + (" --source dbt" if args.source == "dbt" else "")
try:
root = cohorts_root(getattr(settings, f"{args.domain}_database_url"))
if args.source == "kit":
return find_cohort_file(root, url, args.armado)
if args.armado is not None:
if not (path := dbt_build_path(root, url, args.armado)).exists():
raise FileNotFoundError(f"dbt build {args.armado} of {url} isn't exported: no {path}")
return path
if not (latest := latest_dbt_build(root, url)):
raise FileNotFoundError(f"no exported dbt builds of {url} under {root}")
return latest[1]
except (FileNotFoundError, ValueError) as error:
print(f"{error}: export it with `{command}`", file=sys.stderr)
return None
def _train(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
"""Trains the model on the build's file, always as a new version."""
if args.environment == "prod" and args.armado is None:
parser.error("a prod run names its cohort build: --build (ML-03)")
if not (model := _model_module(args, "model")) or not (trainer := _model_module(args, "train")):
return 1
if not (path := _cohort_file(args, model)):
return 1
print(f"{args.domain}/{args.scenario} version {trainer.train(path, args.environment.upper())}, from {path}")
return 0
def _estimate_step(args: argparse.Namespace, path) -> int:
estimator = _model_module(args, "estimate")
if not estimator:
return 1
try:
resolved, written = estimator.estimate(path, args.output, args.version)
except LookupError as error:
print(error, file=sys.stderr)
return 1
print(f"{'estimated' if written else 'already estimated'}: version {resolved.version}, from {path}, to {args.output}")
return 0
def _store_step(args: argparse.Namespace, estimate_path) -> int:
from models.pipelines.store_risks import store_estimate
try:
batch, written = store_estimate(estimate_path, args.domain)
except (LookupError, ValueError, FileNotFoundError) as error:
print(error, file=sys.stderr)
return 1
print(f"{'stored' if written else 'already stored'}: batch {batch}, from {estimate_path}")
return 0
def _store(args: argparse.Namespace) -> int:
"""Stores an estimate file as a batch of risks in the domain's database."""
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)):
return 1
return _estimate_step(args, path)
def _promote_step(args: argparse.Namespace, version: str) -> int:
from mlflow import MlflowException
from models.io.registry import PRODUCTION_ALIAS, registered_name, registry
name = registered_name(args.domain, args.scenario)
try:
current = registry.client.get_model_version_by_alias(name, PRODUCTION_ALIAS).version
except MlflowException:
current = None
if str(current) == str(version):
print(f"already in production: version {version}")
return 0
registry.client.set_registered_model_alias(name, PRODUCTION_ALIAS, version)
print(f"in production: version {version}")
return 0
def _run(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
"""Runs the steps asked for, in their order. A step whose result already exists is a no-op."""
if not (args.export or args.train or args.promote or args.estimate or args.store):
parser.error("name at least one step: --export, --train, --promote, --estimate, --store")
if (args.estimate or args.store) and not args.output:
parser.error("--estimate and --store need --output")
if args.train and args.environment == "prod" and args.armado is None and not (args.export and args.source == "dbt"):
parser.error("a prod run names its cohort build: --build (ML-03)")
if args.export and args.source == "dbt" and not args.manifest:
parser.error("--export with --source dbt needs --manifest")
if args.export and args.source == "dbt" and args.armado is not None:
parser.error("a dbt build is numbered when it's exported: --build can't go with --export --source dbt")
if args.train and args.version:
parser.error("--version names an existing version: it can't go with --train")
if not (model := _model_module(args, "model")):
return 1
if args.export:
cohort = model.SETTINGS["cohort"].split("/", 1)[1]
export = argparse.Namespace(domain=args.domain, cohort=cohort, source=args.source, build=args.armado,
manifest=args.manifest)
if args.source == "dbt":
export.build = None
if code := _cohort_export(export):
return code
if not (args.train or args.promote or args.estimate):
return _store_step(args, args.output) if args.store else 0
if not (path := _cohort_file(args, model)):
return 1
version = args.version
if args.train or (args.promote and not version):
if not (trainer := _model_module(args, "train")):
return 1
environment = args.environment.upper()
version = trainer.find_trained(path, environment)
if args.train and version:
print(f"already trained: version {version}, from {path}")
elif args.train:
version = trainer.train(path, environment)
print(f"trained: version {version}, from {path}")
elif not version:
print(f"no {environment} version trained on {path}: use --train or --version", file=sys.stderr)
return 1
if args.promote and (code := _promote_step(args, version)):
return code
if args.estimate and (code := _estimate_step(args, path)):
return code
return _store_step(args, args.output) if args.store else 0
def _cohort_build(args: argparse.Namespace) -> int:
"""Runs the cohort's rules and shows its attrition, or only its graph. Stores nothing."""
from sqlalchemy.exc import DBAPIError
from importlib import import_module
from models.io.contracts import CohortDefinitionError
from models.io.storage import read_queries
from models.pipelines.cohort_build import build_cohort, build_driver, mermaid
url = f"{args.domain}/{args.cohort}"
try:
queries = read_queries(args.manifest, url)
if args.graph:
print(mermaid(build_driver(queries).graph))
return 0
built = build_cohort(queries, import_module(f"persistance.{args.domain}").dbt_query_repository)
except (FileNotFoundError, CohortDefinitionError) as error:
print(error, file=sys.stderr)
return 1
except DBAPIError as error:
print(f"a query of {url} failed ({error.orig}): is `{args.domain}_linea_de_tiempo` created? "
f"Run `dbt run --select {args.domain}_linea_de_tiempo` in Transformation", file=sys.stderr)
return 1
print(built.attrition.to_string(index=False))
print(f"{url}: {len(built.study_population)} members, not stored")
return 0
def _cohort_export(args: argparse.Namespace) -> int:
"""Exports a build to its Parquet file: the kit's stored build, or one built now from dbt's rules."""
from importlib import import_module
from persistance.edges.dbt import DbtRelationError
from persistance.settings import settings
from sqlalchemy.exc import DBAPIError
from models.io.contracts import CohortDefinitionError
from models.io.storage import read_queries
from models.io.storage import cohorts_root
from models.pipelines.export_cohort import export_dbt_build, export_kit_build
url = f"{args.domain}/{args.cohort}"
repositories = import_module(f"persistance.{args.domain}")
timeline = repositories.timeline_repository
try:
root = cohorts_root(getattr(settings, f"{args.domain}_database_url"))
if args.source == "dbt":
queries = read_queries(args.manifest, url)
path, outcome = export_dbt_build(queries, repositories.dbt_query_repository, timeline, root, args.domain)
else:
path, outcome = export_kit_build(repositories.cohort_repository, timeline, root, args.domain, url, args.build)
except PermissionError as error:
print(f"{error}: the data folder is read-only, set COHORTS_DIR", file=sys.stderr)
return 1
except DBAPIError as error:
print(f"a query of {url} failed ({error.orig}): is `{args.domain}_linea_de_tiempo` created? "
f"Run `dbt run --select {args.domain}_linea_de_tiempo` in Transformation", file=sys.stderr)
return 1
except (FileNotFoundError, LookupError, ValueError, DbtRelationError) as error:
print(error, file=sys.stderr)
return 1
print(f"{outcome}: {path}")
return 0
def _cohort_list(args: argparse.Namespace) -> int:
"""Prints the cohort's builds: dbt's from their files, the kit's from the database."""
from importlib import import_module
from persistance.settings import settings
from models.io.storage import cohorts_root, list_builds
url = f"{args.domain}/{args.cohort}"
try:
root = cohorts_root(getattr(settings, f"{args.domain}_database_url"))
except ValueError as error:
print(error, file=sys.stderr)
return 1
cohorts = None if args.source == "dbt" else import_module(f"persistance.{args.domain}").cohort_repository
rows = [row for row in list_builds(root, url, cohorts) if args.source in (None, row["source"])]
if not rows:
print(f"{url}: no builds", file=sys.stderr)
return 1
print(f"{'source':<6} {'build':>5} {'datos_as_of':<11} {'members':>7} {'created':<25} file")
for row in rows:
print(f"{row['source']:<6} {row['build']:>5} {row['datos_as_of'] or '':<11} {row['n_members'] or '':>7} "
f"{(row['created'] or '')[:25]:<25} {row['file'] or '(not exported)'}")
return 0
def _cohort_show(args: argparse.Namespace) -> int:
"""Prints one build's file, hash and lineage as JSON."""
import json
from importlib import import_module
from persistance.settings import settings
from models.io.storage import cohorts_root, describe_build
url = f"{args.domain}/{args.cohort}"
try:
root = cohorts_root(getattr(settings, f"{args.domain}_database_url"))
cohorts = import_module(f"persistance.{args.domain}").cohort_repository if args.source == "kit" else None
described = describe_build(root, url, args.source, args.build, cohorts)
except (ValueError, LookupError) as error:
print(error, file=sys.stderr)
return 1
print(json.dumps(described, indent=2, ensure_ascii=False))
return 0
def _cohort_export_checked(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
if args.source == "dbt" and not args.manifest:
parser.error("--source dbt needs --manifest")
if args.source == "dbt" and args.build is not None:
parser.error("--build names a kit build: it can't go with --source dbt")
return _cohort_export(args)
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(prog="python -m models", description="Commands of the screening models.")
commands = parser.add_subparsers(dest="command", metavar="<command>", required=True)
cohorts = commands.add_parser("cohorts", help="the cohort builds and their Parquet files")
cohorts.set_defaults(run=lambda args: _show_help(cohorts))
actions = cohorts.add_subparsers(dest="action", metavar="<action>")
build = actions.add_parser("build", help="run a cohort's rules and show its attrition; stores nothing")
build.add_argument("domain", choices=["cacu", "cama", "tea"])
build.add_argument("cohort", help="the cohort without its domain, e.g. cohorte_vigilancia")
build.add_argument("--manifest", required=True, help="the manifest.json `dbt compile` wrote")
build.add_argument("--graph", action="store_true", help="print the chain as a Mermaid diagram without running it")
build.set_defaults(run=_cohort_build)
export = actions.add_parser("export", help="export a build to its Parquet file, once")
export.add_argument("domain", choices=["cacu", "cama", "tea"])
export.add_argument("cohort", help="the cohort without its domain, e.g. cohorte_vigilancia")
export.add_argument("--source", choices=["kit", "dbt"], default="kit",
help="the kit's stored build, or one built now from dbt's rules")
export.add_argument("--build", type=int, help="the kit build's armado_id; the cohort's latest by default")
export.add_argument("--manifest", help="the manifest.json `dbt compile` wrote; needed with --source dbt")
export.set_defaults(run=lambda args: _cohort_export_checked(export, args))
listing = actions.add_parser("list", help="the cohort's builds, from both sources, and whether each has its file")
listing.add_argument("domain", choices=["cacu", "cama", "tea"])
listing.add_argument("cohort", help="the cohort without its domain, e.g. cohorte_vigilancia")
listing.add_argument("--source", choices=["kit", "dbt"], help="only one source's builds; dbt's read no database")
listing.set_defaults(run=_cohort_list)
show = actions.add_parser("show", help="one build's file, hash, parameters, rules and attrition")
show.add_argument("domain", choices=["cacu", "cama", "tea"])
show.add_argument("cohort", help="the cohort without its domain, e.g. cohorte_vigilancia")
show.add_argument("--source", choices=["kit", "dbt"], default="dbt", help="whose build: the kit's or dbt's rules'")
show.add_argument("--build", type=int, required=True, help="the build's number")
show.set_defaults(run=_cohort_show)
train = commands.add_parser("train", help="train a model on a cohort build's file and register a version")
train.add_argument("domain", choices=["cacu", "cama", "tea"])
train.add_argument("scenario", help="the model's folder, e.g. cin2_logistic")
train.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")
train.add_argument("--source", choices=["kit", "dbt"], default="kit", help="whose builds: the kit's or dbt's rules'")
train.add_argument("--environment", choices=["dev", "prod"], default="dev")
train.set_defaults(run=lambda args: _train(train, args))
estimate = commands.add_parser("estimate", help="score a cohort build's file with a registered version")
estimate.add_argument("domain", choices=["cacu", "cama", "tea"])
estimate.add_argument("scenario", help="the model's folder, e.g. cin2_logistic")
estimate.add_argument("--output", required=True, help="the Parquet file to write")
estimate.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")
estimate.add_argument("--source", choices=["kit", "dbt"], default="kit", help="whose builds: the kit's or dbt's rules'")
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")
store.add_argument("--input", required=True, help="the Parquet file `estimate` wrote")
store.set_defaults(run=_store)
run = commands.add_parser("run", help="run the pipeline's steps you name; those already done are no-ops")
run.add_argument("domain", choices=["cacu", "cama", "tea"])
run.add_argument("scenario", help="the model's folder, e.g. cin2_logistic")
run.add_argument("--export", action="store_true", help="export the build to its Parquet file")
run.add_argument("--train", action="store_true", help="train, unless a version from this file, code and environment exists")
run.add_argument("--promote", action="store_true", help="set the production alias on that version, or on --version")
run.add_argument("--estimate", action="store_true", help="score the build with --version, or the one in production")
run.add_argument("--store", action="store_true", help="store the estimate in --output as a batch of risks")
run.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")
run.add_argument("--source", choices=["kit", "dbt"], default="kit", help="whose builds: the kit's or dbt's rules'")
run.add_argument("--version", help="an existing model version, for --promote and --estimate")
run.add_argument("--environment", choices=["dev", "prod"], default="dev")
run.add_argument("--output", help="the Parquet file --estimate writes and --store reads")
run.add_argument("--manifest", help="the manifest.json `dbt compile` wrote; needed with --export --source dbt")
run.set_defaults(run=lambda args: _run(run, args))
return parser
def main(argv: Sequence[str] | None = None) -> int:
args = build_parser().parse_args(argv)
return args.run(args)
if __name__ == "__main__":
sys.exit(main())