models cohorts list and show: a cohort's builds from both sources, and one build's file, hash and lineage

This commit is contained in:
2026-11-06 00:40:50 -06:00
parent 15ffeb3efe
commit 71e77f0c7e
4 changed files with 195 additions and 0 deletions
+60
View File
@@ -259,6 +259,53 @@ def _cohort_export(args: argparse.Namespace) -> int:
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}").cohorte_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}").cohorte_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")
@@ -290,6 +337,19 @@ def build_parser() -> argparse.ArgumentParser:
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")
+39
View File
@@ -6,6 +6,7 @@ beside them, numbered in order, so a lookup of the kit's builds never picks one
repository is used, so a model folder reading its cohort file never loads the database layer.
"""
import hashlib
import importlib
import json
import os
@@ -64,6 +65,44 @@ def find_cohort_file(root: Path, url: str, armado_id: int | None = None) -> Path
return path
def list_builds(root: Path, url: str, cohorts=None) -> list[dict]:
"""One row per build of the cohort, newest first within each source: dbt's builds from their files' metadata, and,
with `cohorts` (the domain's `cohorte_repository`), the kit's builds and whether each has its file. Without
`cohorts` only files are read, never the database."""
rows = []
for number in reversed(_numbers(dbt_build_path(root, url, 0).parent)):
path = dbt_build_path(root, url, number)
lineage = read_metadata(path)
rows.append({"source": "dbt", "build": number, "datos_as_of": lineage.get("datos_as_of"),
"n_members": lineage.get("n_members"), "created": lineage.get("built_at"), "file": str(path)})
for build in (cohorts.builds(url) if cohorts is not None else []):
path = cohort_path(root, url, build.armado_id)
rows.append({"source": "kit", "build": build.armado_id, "datos_as_of": build.datos_as_of.isoformat(),
"n_members": str(build.n_miembros), "created": build.armado_en.isoformat(),
"file": str(path) if path.exists() else None})
return rows
def describe_build(root: Path, url: str, source: str, build: int, cohorts=None) -> dict:
"""One build: its file and hash, and its lineage with the parameters, rules and attrition decoded. A kit build
without a file is described from `cohorts` (the domain's `cohorte_repository`). `LookupError` if there's no such
build."""
path = dbt_build_path(root, url, build) if source == "dbt" else cohort_path(root, url, build)
if path.exists():
lineage = read_metadata(path)
for key in ("parametros", "rules", "attrition"):
if lineage.get(key):
lineage[key] = json.loads(lineage[key])
digest = hashlib.sha256(path.read_bytes()).hexdigest()
return {"source": source, "build": build, "file": str(path), "file_sha256": digest, "lineage": lineage}
stored = cohorts.build(build) if source == "kit" and cohorts is not None else None
if stored is None or stored.url != url:
raise LookupError(f"no {source} build {build} of {url}")
return {"source": "kit", "build": build, "file": None, "file_sha256": None,
"lineage": {"url": stored.url, "version": stored.version, "datos_as_of": stored.datos_as_of.isoformat(),
"n_members": str(stored.n_miembros), "huella": stored.huella, "armado_en": stored.armado_en.isoformat()}}
def read_cohort(path: str | Path) -> pd.DataFrame:
"""The build's rows, after checking the file's schema without reading them."""
schema = pq.read_schema(path)