integration layer; merge work on indicators from forks with existing ingestion pipeline

This commit is contained in:
Roberto Treviño Cervantes
2026-10-23 00:00:13 -06:00
parent 73547f2bb1
commit cbb3b9c7b6
21 changed files with 1644 additions and 10 deletions
+35 -7
View File
@@ -1,17 +1,45 @@
import importlib
from abc import ABC, abstractmethod
from typing import Any
from typing import Any, ClassVar, Iterator
from persistance.repository import Repository
def resolve_repository(domain: str, entity: str) -> Repository:
"""`entity` is the repository's name in `persistance.<domain>` without
the suffix, e.g. `"paciente"`, `"citologia_cervical"`."""
module = importlib.import_module(f"persistance.{domain}")
try:
return getattr(module, f"{entity}_repository")
except AttributeError as exc:
raise ValueError(f"persistance.{domain} has no {entity}_repository") from exc
class ScreeningModel(ABC):
"""Standard train()/predict() interface every screening model implements,
regardless of which of the three data marts (CaCu/CaMa/TEA) it targets.
"""Common train()/predict() interface for the CaCu, CaMa and TEA models.
Implementations are free to pull their own data straight from
`persistance.<domain>` — the same standard repository API WebApi uses —
or accept already-fetched rows from a caller; `data` is intentionally
untyped at this scaffolding stage.
Data is read through the same `persistance.<domain>.<entity>_repository`
objects WebApi writes with, so anything loaded through the import flow
is visible here. `train` may also be given rows fetched by the caller.
"""
domain: ClassVar[str]
def repository(self, entity: str) -> Repository:
return resolve_repository(self.domain, entity)
def dataset(self, entity: str, *, batch_size: int = 500, **filters) -> Iterator[dict[str, Any]]:
"""Every row of `entity` as plain dicts, paged through the
repository so a large table is never loaded in one go."""
repository = self.repository(entity)
offset = 0
while True:
page = repository.list(limit=batch_size, offset=offset, **filters)
yield from (row.model_dump() for row in page)
if len(page) < batch_size:
return
offset += batch_size
@abstractmethod
def train(self, data: Any = None) -> None:
"""Fit the model, optionally on `data` passed in by the caller."""
+3 -1
View File
@@ -9,9 +9,11 @@ class CaCuModel(ScreeningModel):
Can pull its own training data straight from `persistance.cacu`'s
repositories (`paciente_repository`, `citologia_cervical_repository`,
`biopsia_cervical_repository`, ...) or be handed already-fetched rows.
No real model yet — this is interface scaffolding only.
No real model yet; this is interface scaffolding only.
"""
domain = "cacu"
def train(self, data: Any = None) -> None:
raise NotImplementedError("CaCu training is not implemented yet.")
+3 -1
View File
@@ -9,9 +9,11 @@ class CaMaModel(ScreeningModel):
Can pull its own training data straight from `persistance.cama`'s
repositories (`paciente_repository`, `mastografia_repository`,
`biopsia_mama_repository`, ...) or be handed already-fetched rows.
No real model yet — this is interface scaffolding only.
No real model yet; this is interface scaffolding only.
"""
domain = "cama"
def train(self, data: Any = None) -> None:
raise NotImplementedError("CaMa training is not implemented yet.")
+196
View File
@@ -0,0 +1,196 @@
"""Cohort construction, versioning and exclusion tracking (EL-01..EL-07,
TRIPOD+AI 20a). A `CohortBuilder` turns a domain's clinical episodes into a
frozen, hashed cohort (`CohortVersion` + `CohortMember`) that training
reads instead of the live tables, which may change later.
- `build()` (training time, EL-04a) applies every `ExclusionCriterion`,
logs each exclusion with its reason (EL-05) and the per-criterion counts
(EL-07).
- `evaluate_applicability()` (production, EL-04b) checks one new row
against the criteria marked `applicable_in_production` only; criteria
that need future follow-up are never among them. It writes nothing.
"""
import hashlib
import json
from dataclasses import dataclass
from typing import Any, Callable, Sequence
from models.base import resolve_repository
from persistance.governance import (
cohort_exclusion_count_repository,
cohort_exclusion_repository,
cohort_member_repository,
cohort_version_repository,
)
from core.governance.models import CohortExclusion, CohortExclusionCount, CohortMember, CohortVersion
@dataclass
class ExclusionCriterion:
code: str
reason_code: str
predicate: Callable[[dict[str, Any]], bool]
"""Returns True when the row should be EXCLUDED."""
applicable_in_production: bool = False
"""EL-04b: whether this criterion is also checked on new rows in
production. Leave False for criteria that depend on future follow-up,
which can only be evaluated when building the training table."""
def compute_version_hash(*, criteria_version: str, criterion_codes: Sequence[str], episode_ids: Sequence[int]) -> str:
"""EL-02/EL-03: deterministic hash of the criteria version, the
criterion codes applied and the source episode ids. A change in any of
them, such as new patients or a longer analysis period, yields a new
version."""
payload = json.dumps(
{
"criteria_version": criteria_version,
"criterion_codes": sorted(criterion_codes),
"episode_ids": sorted(episode_ids),
},
sort_keys=True,
)
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
class CohortBuilder:
"""Builds the cohort for one clinical scenario (one model per scenario,
one cohort table per model). Subclasses set `criteria` and may override
`fetch_episodes` (EL-01)."""
domain: str
scenario: str
criteria_version: str
criteria: Sequence[ExclusionCriterion] = ()
def fetch_episodes(self) -> list[dict[str, Any]]:
"""Episode rows as plain dicts (EL-01). The default pages through
`persistance.<domain>.episodio_clinico_repository`; override it when
a scenario needs extra joins to build its features."""
repository = resolve_repository(self.domain, "episodio_clinico")
episodes: list[dict[str, Any]] = []
offset = 0
while True:
page = repository.list(limit=500, offset=offset)
episodes.extend(row.model_dump() for row in page)
if len(page) < 500:
break
offset += 500
return episodes
def build(self, *, description: str | None = None) -> CohortVersion:
episodes = self.fetch_episodes()
n_source = len(episodes)
excluded_ids: set[int] = set()
exclusion_rows: list[CohortExclusion] = []
exclusion_counts: dict[tuple[str, str], int] = {}
for episode in episodes:
episode_id = episode.get("episodio_id")
for criterion in self.criteria:
if episode_id in excluded_ids:
break
if criterion.predicate(episode):
excluded_ids.add(episode_id)
exclusion_rows.append(
CohortExclusion(
cohort_version_id=0, # filled in once the CohortVersion exists
pac_id_hospital=episode.get("pac_id_hospital", ""),
episodio_id=episode_id,
criterion_code=criterion.code,
reason_code=criterion.reason_code,
)
)
key = (criterion.code, criterion.reason_code)
exclusion_counts[key] = exclusion_counts.get(key, 0) + 1
included = [e for e in episodes if e.get("episodio_id") not in excluded_ids]
version_hash = compute_version_hash(
criteria_version=self.criteria_version,
criterion_codes=[c.code for c in self.criteria],
episode_ids=[e.get("episodio_id") for e in episodes if e.get("episodio_id") is not None],
)
cohort_version = cohort_version_repository.create(
CohortVersion(
domain=self.domain,
scenario=self.scenario,
criteria_version=self.criteria_version,
version_hash=version_hash,
source_table=f"{self.domain}.episodioclinico",
description=description,
n_source=n_source,
n_included=len(included),
)
)
for row in exclusion_rows:
row.cohort_version_id = cohort_version.cohort_version_id
if exclusion_rows:
with cohort_exclusion_repository.open_session() as session:
for row in exclusion_rows:
session.add(row)
session.commit()
if exclusion_counts:
with cohort_exclusion_count_repository.open_session() as session:
for (criterion_code, reason_code), count in exclusion_counts.items():
session.add(
CohortExclusionCount(
cohort_version_id=cohort_version.cohort_version_id,
criterion_code=criterion_code,
reason_code=reason_code,
count=count,
)
)
session.commit()
if included:
with cohort_member_repository.open_session() as session:
for episode in included:
session.add(
CohortMember(
cohort_version_id=cohort_version.cohort_version_id,
pac_id_hospital=episode.get("pac_id_hospital", ""),
episodio_id=episode.get("episodio_id"),
feature_snapshot=json.dumps(episode, default=str, sort_keys=True),
)
)
session.commit()
return cohort_version
def evaluate_applicability(self, row: dict[str, Any]) -> bool:
"""EL-04b: production gate. Returns False if any criterion marked
`applicable_in_production` would exclude the row. Writes nothing;
exclusion logs belong to the training-time build (EL-04a)."""
return not any(c.predicate(row) for c in self.criteria if c.applicable_in_production)
COHORT_BUILDERS: dict[tuple[str, str], type[CohortBuilder]] = {}
def register_cohort_builder(cls: type[CohortBuilder]) -> type[CohortBuilder]:
"""Registers a scenario's builder so the API can list and run it:
@register_cohort_builder
class TamizajeCaCu(CohortBuilder):
domain, scenario, criteria_version = "cacu", "tamizaje", "v1"
criteria = [ExclusionCriterion("EDAD", "fuera_de_rango", lambda e: ..., applicable_in_production=True)]
"""
COHORT_BUILDERS[(cls.domain, cls.scenario)] = cls
return cls
def describe_builder(cls: type[CohortBuilder]) -> dict[str, Any]:
return {
"domain": cls.domain,
"scenario": cls.scenario,
"criteria_version": cls.criteria_version,
"criteria": [
{"code": c.code, "reason_code": c.reason_code, "applicable_in_production": c.applicable_in_production}
for c in cls.criteria
],
}
+33
View File
@@ -0,0 +1,33 @@
"""ONNX checkpoint inspection (ML-01b, MLD-03).
Writing/storing a checkpoint is `models.training.TrainingRun.log_artifact`,
which hands it to MLflow directly — nothing here manages storage paths.
`onnx` is an optional dependency (`models[export]`); without it
`inspect_onnx_metadata` returns `{"available": False}`.
"""
from pathlib import Path
from typing import Any
def inspect_onnx_metadata(path: str | Path) -> dict[str, Any]:
"""IR version, opsets, producer and graph inputs/outputs of a checkpoint.
`{"available": False}` when the optional `onnx` package isn't installed;
`ValueError` when it is and the file isn't a valid ONNX model."""
try:
import onnx
except ImportError:
return {"available": False, "reason": "el paquete 'onnx' no está instalado (extra 'export')"}
try:
model = onnx.load(str(path))
except Exception as exc:
raise ValueError(f"no es un modelo ONNX válido: {exc}") from exc
return {
"available": True,
"ir_version": model.ir_version,
"producer_name": model.producer_name,
"producer_version": model.producer_version,
"opset_imports": [{"domain": o.domain, "version": o.version} for o in model.opset_import],
"graph_inputs": [i.name for i in model.graph.input],
"graph_outputs": [o.name for o in model.graph.output],
}
+266
View File
@@ -0,0 +1,266 @@
"""Extraction of results from the PDF reports stored with each study
(VAR-01..09, VARM-01..05).
Each `OcrJob` says which table, which stored PDF and which result columns
an extraction fills; `OCR_JOBS` lists them all. Adding a job is adding an
`OcrExtractor` (usually a `ReportOcrExtractor` with its `fields`) and an
entry in `OCR_JOBS`.
Extraction method (VAR-04, VARM-05): the PDF's text layer is read with
pdfplumber; pages without one are recognized with Tesseract 5's LSTM engine
(Smith, R. "An Overview of the Tesseract OCR Engine", ICDAR 2007). Values
are then located by caption matching tolerant to OCR errors, and by
lexicon matching over the narrative with NegEx-style negation handling
(Chapman, W. et al. "A Simple Algorithm for Identifying Negated Findings and
Diseases in Discharge Summaries", J Biomed Inform 34(5), 2001). Every
value carries a 0..1 confidence: caption match quality x parse quality x
Tesseract's word confidence.
"""
import json
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Any, ClassVar
from core.cacu.enums import GRADO_CIN_ALIAS, GradoCIN, ResultadoVPH
from core.cama.enums import GradoHistologicoMama
from core.ocr import OcrEstatus
from extraction import FieldKind, FieldSpec, read_document
from extraction.nlp import RecordExtractor, SegmentLine
from extraction.nlp.vocabulary import CLINICAL_TERMS, labels_for
from extraction.ocr import TesseractOcr
from models.base import resolve_repository
from persistance.repository import Repository
# Below this confidence a value is stored but flagged for manual review.
REVIEW_THRESHOLD = 0.8
@dataclass
class OcrExtractionResult:
"""VAR-03/VARM-04a: the values plus their confidence and provenance."""
values: dict[str, Any]
confianza: float
estatus: OcrEstatus
requiere_revision: bool
metodo_principal: str
metodo_alternativo: str | None = None
quality_validation: str | None = None
@dataclass
class OcrColumnSpec:
"""The columns of one extraction on its table: the stored PDF, the
five traceability columns, and extractor result key -> result column."""
blob_field: str
confianza_field: str
estatus_field: str
requiere_revision_field: str
metodo_principal_field: str
metodo_alternativo_field: str
result_field_map: dict[str, str] = field(default_factory=dict)
class OcrExtractor(ABC):
@abstractmethod
def extract(self, pdf_blob: bytes) -> OcrExtractionResult:
"""Reads `pdf_blob`. A document that can be read but where nothing
is found returns estatus FALLIDO with requiere_revision; an
unreadable one may raise, and the driver records FALLIDO."""
class ReportOcrExtractor(OcrExtractor):
"""Reads a report and looks for `fields` (result key -> FieldSpec)."""
fields: ClassVar[dict[str, FieldSpec]]
def extract(self, pdf_blob: bytes) -> OcrExtractionResult:
document = read_document("reporte.pdf", pdf_blob)
lines = [SegmentLine(document.name, page.number, line) for page in document.pages for line in page.lines]
found = RecordExtractor(list(self.fields.values())).extract(lines)
by_key = {key: found[spec.name] for key, spec in self.fields.items() if spec.name in found}
sources = {page.source for page in document.pages}
principal = "pdf-texto" if "text" in sources else TesseractOcr().name
alternativo = TesseractOcr().name if sources == {"text", "ocr"} else None
evidence = {key: value.to_dict() for key, value in by_key.items()}
missing = [key for key in self.fields if key not in by_key]
if missing:
evidence["faltantes"] = missing
if not by_key:
return OcrExtractionResult({}, 0.0, OcrEstatus.FALLIDO, True, principal, alternativo, json.dumps(evidence, ensure_ascii=False))
confianza = round(min(value.confidence for value in by_key.values()) * len(by_key) / len(self.fields), 3)
return OcrExtractionResult(
values={key: value.value for key, value in by_key.items()},
confianza=confianza,
estatus=OcrEstatus.REALIZADO,
requiere_revision=bool(missing) or confianza < REVIEW_THRESHOLD,
metodo_principal=principal,
metodo_alternativo=alternativo,
quality_validation=json.dumps(evidence, ensure_ascii=False, default=str),
)
def choice_field(column: str, values: dict[str, Any], **options) -> FieldSpec:
return FieldSpec(column, FieldKind.CHOICE, labels=labels_for(column), choices={**values, **CLINICAL_TERMS.get(column, {})}, **options)
class VphOcrExtractor(ReportOcrExtractor):
"""VAR-01: VPH result and genotypes 16/18 from `cit_vph_pdf_blob`."""
fields = {
"resultado": choice_field("cit_vph_resultado", {m.value: m.value for m in ResultadoVPH}, scan_free_text=True),
"genotipo_16": choice_field("cit_vph_genotipo_16", {}),
"genotipo_18": choice_field("cit_vph_genotipo_18", {}),
}
class CinGradoOcrExtractor(ReportOcrExtractor):
"""VAR-02: CIN grade from the cervical biopsy report `bx_pdf_blob`."""
fields = {"grado": choice_field("bx_cin_grado", {**{m.value: m.value for m in GradoCIN}, **GRADO_CIN_ALIAS}, scan_free_text=True)}
class GradoHistologicoOcrExtractor(ReportOcrExtractor):
"""VARM-03: histological grade from the breast biopsy report `bx_pdf_blob`."""
fields = {
"grado": choice_field(
"bx_grado_histologico",
{m.value.replace("_", " "): m.value for m in GradoHistologicoMama},
scan_free_text=True,
)
}
def _ocr_columns(prefix: str, blob_field: str, results: dict[str, str]) -> OcrColumnSpec:
return OcrColumnSpec(
blob_field=blob_field,
confianza_field=f"{prefix}_ocr_confianza",
estatus_field=f"{prefix}_ocr_estatus",
requiere_revision_field=f"{prefix}_ocr_requiere_revision",
metodo_principal_field=f"{prefix}_ocr_metodo_principal",
metodo_alternativo_field=f"{prefix}_ocr_metodo_alternativo",
result_field_map=results,
)
CIT_VPH_COLUMNS = _ocr_columns(
"cit_vph",
"cit_vph_pdf_blob",
{"resultado": "cit_vph_resultado", "genotipo_16": "cit_vph_genotipo_16", "genotipo_18": "cit_vph_genotipo_18"},
)
BX_CIN_COLUMNS = _ocr_columns("bx", "bx_pdf_blob", {"grado": "bx_cin_grado"})
BX_GRADO_HISTOLOGICO_COLUMNS = _ocr_columns("bx", "bx_pdf_blob", {"grado": "bx_grado_histologico"})
@dataclass(frozen=True)
class OcrJob:
domain: str
entity: str # repository name in persistance.<domain>, without `_repository`
label: str
columns: OcrColumnSpec
extractor: type[OcrExtractor]
@property
def repository(self) -> Repository:
"""Resolved on use, so it follows whatever database URL is active."""
return resolve_repository(self.domain, self.entity)
OCR_JOBS: dict[tuple[str, str], OcrJob] = {
(job.domain, job.entity): job
for job in (
OcrJob("cacu", "citologia_cervical", "CaCu · Resultado de VPH (citología cervical)", CIT_VPH_COLUMNS, VphOcrExtractor),
OcrJob("cacu", "biopsia_cervical", "CaCu · Grado CIN (biopsia cervical)", BX_CIN_COLUMNS, CinGradoOcrExtractor),
OcrJob("cama", "biopsia_mama", "CaMa · Grado histológico (biopsia de mama)", BX_GRADO_HISTOLOGICO_COLUMNS, GradoHistologicoOcrExtractor),
)
}
@dataclass
class OcrRunSummary:
processed: int = 0
skipped_already_done: int = 0
failed: int = 0
needs_review: int = 0
def run_pending_extractions(
repository: Repository,
spec: OcrColumnSpec,
extractor: OcrExtractor,
*,
domain: str,
entity: str,
governance_repository: Repository | None = None,
source_description: str | None = None,
limit: int = 500,
) -> OcrRunSummary:
"""VAR-09: rows whose status is already REALIZADO are skipped, so the
persisted result is what prevents duplicate runs. A failing row is
stored as FALLIDO and the batch continues. With `governance_repository`,
every processed row is logged as an `ExtractionRun` (VAR-07/08)."""
from core.governance.enums import EstatusExtraccion
from core.governance.models import ExtractionRun
summary = OcrRunSummary()
pk_name = next(iter(repository.model.__table__.primary_key.columns)).name
candidates = repository.list(limit=limit)
with repository.open_session() as session:
for row in candidates:
pk_value = getattr(row, pk_name)
tracked = session.get(repository.model, pk_value)
if tracked is None or getattr(tracked, spec.blob_field, None) is None:
continue
if getattr(tracked, spec.estatus_field, None) == OcrEstatus.REALIZADO:
summary.skipped_already_done += 1
continue
started_at = datetime.now(timezone.utc)
try:
result = extractor.extract(getattr(tracked, spec.blob_field))
except NotImplementedError:
raise
except Exception as exc: # noqa: BLE001 -- one unreadable report must not stop the batch
result = OcrExtractionResult({}, 0.0, OcrEstatus.FALLIDO, True, type(extractor).__name__, None, f"error: {exc}")
for result_key, column in spec.result_field_map.items():
if result_key in result.values:
setattr(tracked, column, result.values[result_key])
setattr(tracked, spec.confianza_field, result.confianza)
setattr(tracked, spec.estatus_field, OcrEstatus(result.estatus).value)
setattr(tracked, spec.requiere_revision_field, result.requiere_revision)
setattr(tracked, spec.metodo_principal_field, result.metodo_principal)
setattr(tracked, spec.metodo_alternativo_field, result.metodo_alternativo)
session.add(tracked)
if result.estatus == OcrEstatus.FALLIDO:
summary.failed += 1
else:
summary.processed += 1
if result.requiere_revision:
summary.needs_review += 1
if governance_repository is not None:
governance_repository.create(
ExtractionRun(
domain=domain,
entity=entity,
entity_pk=str(pk_value),
column_extracted=",".join(spec.result_field_map.values()),
source_description=source_description,
source_started_at=started_at,
source_ended_at=datetime.now(timezone.utc),
transform_description=f"{type(extractor).__name__}: {result.metodo_principal}"
+ (f" + {result.metodo_alternativo}" if result.metodo_alternativo else ""),
quality_validation=result.quality_validation,
estatus=(
EstatusExtraccion.COMPLETADA if result.estatus == OcrEstatus.REALIZADO else EstatusExtraccion.FALLIDA
).value,
)
)
session.commit()
return summary
+128
View File
@@ -0,0 +1,128 @@
"""MLD-4/MLD-5: every prediction is stored with the MLflow model version that
produced it. WebApi's `/predict` routes go through `PredictionService`
rather than calling `model.predict(...)` directly.
"""
import hashlib
import json
from dataclasses import dataclass
from typing import Any
from mlflow import MlflowException
from core.governance.models import ModelPrediction
from models.base import ScreeningModel
from models.cohort import CohortBuilder
from models.registry import PRODUCTION_ALIAS, registered_name, registry
from persistance.governance import model_prediction_repository
@dataclass
class Interpretability:
"""MLD-03: campos mínimos que toda estimación debe poder reportar para
interpretabilidad clínica. Todos opcionales: cada modelo llena los que
apliquen a su método (p. ej. odds_ratio en una regresión logística,
hazard_ratio en un modelo de supervivencia)."""
odds_ratio: float | None = None
hazard_ratio: float | None = None
probabilidad_acumulada: float | None = None
def to_json(self) -> str:
return json.dumps(
{
"odds_ratio": self.odds_ratio,
"hazard_ratio": self.hazard_ratio,
"probabilidad_acumulada": self.probabilidad_acumulada,
}
)
class ApplicabilityRejected(Exception):
"""Raised when the EL-04b applicability gate rejects a row. Callers
should report it as a client error (4xx), not a server error."""
class PredictionService:
"""Runs a `ScreeningModel` and records its predictions against the
MLflow version holding the `produccion` alias for `(domain, scenario)`.
If `cohort_builder` is given, each row is checked with
`evaluate_applicability` (EL-04b). Inapplicable rows are still scored
but stored with `applicability_passed=False`, unless
`reject_inapplicable` is set.
"""
def __init__(
self,
model: ScreeningModel,
*,
domain: str,
scenario: str,
cohort_builder: CohortBuilder | None = None,
reject_inapplicable: bool = False,
):
self.model = model
self.domain = domain
self.scenario = scenario
self.cohort_builder = cohort_builder
self.reject_inapplicable = reject_inapplicable
def active_model_version(self):
"""The MLflow model version currently holding the `produccion`
alias for this (domain, scenario), or `None`."""
name = registered_name(self.domain, self.scenario)
try:
return registry.client.get_model_version_by_alias(name, PRODUCTION_ALIAS)
except MlflowException:
return None
def predict_and_record(
self,
data: Any,
*,
pac_id_hospital: str,
episodio_id: int | None = None,
interpretability: Interpretability | None = None,
) -> ModelPrediction:
"""Scores `data` and stores the result (MLD-5) tagged with the active
MLflow model version (MLD-4). `NotImplementedError` from the model is
propagated unchanged; WebApi maps it to 501.
"""
applicability_passed = True
if self.cohort_builder is not None:
row = data if isinstance(data, dict) else {}
applicability_passed = self.cohort_builder.evaluate_applicability(row)
if not applicability_passed and self.reject_inapplicable:
raise ApplicabilityRejected(
f"la fila de {pac_id_hospital} no cumple los criterios de aplicabilidad de producción (EL-04b)"
)
# Predict before looking up the version so an unimplemented model
# surfaces as NotImplementedError even with no ModelVersion seeded.
output = self.model.predict(data)
model_version = self.active_model_version()
if model_version is None:
raise RuntimeError(
f"no hay una versión en producción para ({self.domain}, {self.scenario}) en MLflow — "
"promueve una con models.registry.registry.promote antes de predecir"
)
input_hash = hashlib.sha256(json.dumps(data, default=str, sort_keys=True).encode("utf-8")).hexdigest()
prediction = model_prediction_repository.create(
ModelPrediction(
mlflow_run_id=model_version.run_id,
modelo_nombre=model_version.name,
modelo_version=str(model_version.version),
domain=self.domain,
pac_id_hospital=pac_id_hospital,
episodio_id=episodio_id,
input_hash=input_hash,
output=json.dumps(output, default=str),
prediccion=str(output) if not isinstance(output, (dict, list)) else None,
confianza=output.get("confianza") if isinstance(output, dict) else None,
interpretability=interpretability.to_json() if interpretability else None,
applicability_passed=applicability_passed,
)
)
return prediction
+253
View File
@@ -0,0 +1,253 @@
"""Model registry: a thin layer over MLflow's own registry (ML-01b, ML-02,
ML-03, MLD-01, MLD-01b, MLD-03, MLD-4), adding only what MLflow doesn't know
about on its own — the promotion checks tied to our cohort versioning and
validation-report convention.
Training, versioning, artifact storage and stage live in MLflow itself
(`MLFLOW_TRACKING_URI`, the usual MLflow env var). A registered model is
named `<domain>-<scenario>`; "production" is the `produccion` alias on one
of its versions — never stored here, read from MLflow on every call.
`models.cohort`'s own `CohorteArmadoBase`/`EvaluacionRiesgoLoteBase` reference
MLflow the same way: by `mlflow_run_id`, never by copying its rows.
"""
from dataclasses import asdict, dataclass
from typing import Any
from mlflow import MlflowException, MlflowClient
from core.governance.enums import Environment
from persistance.governance import cohort_exclusion_count_repository, cohort_version_repository, model_prediction_repository
REPORT_TAGS = ("technical_validation_report_uri", "clinical_validation_report_uri", "interpretability_report_uri")
PRODUCTION_ALIAS = "produccion"
@dataclass(frozen=True)
class PromotionCheck:
code: str
requirement: str
passed: bool
detail: str = ""
class PromotionBlocked(Exception):
def __init__(self, checks: list[PromotionCheck]):
self.checks = checks
failed = ", ".join(f"{c.code} ({c.requirement})" for c in checks if not c.passed)
super().__init__(f"la versión no cumple: {failed}")
def registered_name(domain: str, scenario: str) -> str:
return f"{domain}-{scenario}"
class ModelRegistry:
"""`registry` below is a module-level singleton, so `client` is resolved
fresh on every access instead of cached at construction time — otherwise
it would permanently bind to whatever `MLFLOW_TRACKING_URI` was set at
import time, ignoring any later change (every test sets its own)."""
def __init__(self, client: MlflowClient | None = None):
self._client = client
@property
def client(self) -> MlflowClient:
return self._client or MlflowClient()
# -- reading --------------------------------------------------------------
def get(self, domain: str, scenario: str, version: str):
try:
return self.client.get_model_version(registered_name(domain, scenario), version)
except MlflowException as exc:
raise LookupError(f"no existe la versión {version} de ({domain}, {scenario})") from exc
def versions(self, domain: str | None = None, scenario: str | None = None) -> list[dict[str, Any]]:
"""Every version, newest first. `scenario` needs `domain`; `domain`
alone matches every scenario of that domain (MLflow's own
`search_registered_models` LIKE filter); neither matches everything."""
if domain and scenario:
names = [registered_name(domain, scenario)]
elif domain:
names = [m.name for m in self.client.search_registered_models(filter_string=f"name LIKE '{domain}-%'")]
else:
return [self._describe(mv) for mv in self.client.search_model_versions()]
return [self._describe(mv) for name in names for mv in self.client.search_model_versions(f"name='{name}'")]
def _status(self, mv) -> str:
try:
production = self.client.get_model_version_by_alias(mv.name, PRODUCTION_ALIAS)
if str(production.version) == str(mv.version):
return "produccion"
except MlflowException:
pass
if mv.tags.get("retirada_en"):
return "retirada"
return "candidata" if mv.tags.get("environment") == Environment.PROD.value else "desarrollo"
def status(self, domain: str, scenario: str, version: str) -> str:
return self._status(self.get(domain, scenario, version))
# -- registering --------------------------------------------------------------
def register(
self,
*,
domain: str,
scenario: str,
environment: Environment | str,
cohort_version_id: int | None = None,
metrics: dict[str, Any] | None = None,
hyperparameters: dict[str, Any] | None = None,
**reports: str | None,
) -> str:
"""For training code that runs elsewhere and reports over the API.
In-process training uses `models.training.TrainingRun` directly."""
from models.training import TrainingRun
run = TrainingRun(domain=domain, scenario=scenario, environment=environment, cohort_version_id=cohort_version_id)
return run.finish(metrics=metrics, hyperparameters=hyperparameters, **reports)
def attach_reports(self, domain: str, scenario: str, version: str, **reports: str | None) -> None:
"""MLD-01/01b/03 documents are usually written after training."""
unknown = set(reports) - set(REPORT_TAGS)
if unknown:
raise ValueError(f"campos desconocidos: {sorted(unknown)}")
name = registered_name(domain, scenario)
for tag, uri in reports.items():
self.client.set_model_version_tag(name, version, tag, uri or "")
def add_artifact(self, domain: str, scenario: str, version: str, *, kind, filename: str, data: bytes) -> None:
"""Logs an artifact file to the run behind an already-registered
version (ML-01a/b) — e.g. a checkpoint exported after training.
An `ONNX_CHECKPOINT` is parsed first, so a corrupt export is
rejected (400) instead of silently stored."""
import tempfile
from pathlib import Path
from core.governance.enums import ArtifactKind
from models.export import inspect_onnx_metadata
mv = self.get(domain, scenario, version)
kind_value = kind.value if hasattr(kind, "value") else str(kind)
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / filename
path.write_bytes(data)
if kind_value == ArtifactKind.ONNX_CHECKPOINT.value:
inspect_onnx_metadata(path) # raises ValueError on an invalid checkpoint
self.client.log_artifact(mv.run_id, str(path), artifact_path=kind_value)
def _describe(self, mv) -> dict[str, Any]:
run = self.client.get_run(mv.run_id)
return {
"name": mv.name,
"version": str(mv.version),
"run_id": mv.run_id,
"tags": dict(mv.tags),
"metrics": dict(run.data.metrics),
"created_at": _iso(mv.creation_timestamp),
"status": self._status(mv),
}
def describe(self, domain: str, scenario: str, version: str) -> dict[str, Any]:
return self._describe(self.get(domain, scenario, version))
def lineage(self, domain: str, scenario: str, version: str) -> dict[str, Any]:
"""Everything a version came from and produced: its cohort (hash and
exclusion counts), logged artifacts and predictions."""
mv = self.get(domain, scenario, version)
cohort_version_id = mv.tags.get("cohort_version_id")
cohort = cohort_version_repository.get(int(cohort_version_id)) if cohort_version_id else None
exclusions = (
cohort_exclusion_count_repository.list(limit=500, cohort_version_id=cohort.cohort_version_id) if cohort else []
)
return {
"model_version": self.describe(domain, scenario, version),
"cohort_version": cohort.model_dump() if cohort else None,
"cohort_exclusions": [count.model_dump() for count in exclusions],
"artifacts": [a.path for a in self.client.list_artifacts(mv.run_id)],
"predictions": model_prediction_repository.count(modelo_nombre=mv.name, modelo_version=str(version)),
"checks": [asdict(check) for check in self.checks(domain, scenario, version)],
}
# -- promotion --------------------------------------------------------------------
def checks(self, domain: str, scenario: str, version: str) -> list[PromotionCheck]:
mv = self.get(domain, scenario, version)
run = self.client.get_run(mv.run_id)
cohort_version_id = mv.tags.get("cohort_version_id")
cohort = cohort_version_repository.get(int(cohort_version_id)) if cohort_version_id else None
metrics = run.data.metrics
artifacts = self.client.list_artifacts(mv.run_id)
return [
PromotionCheck("ML-02", "versión etiquetada para producción", mv.tags.get("environment") == Environment.PROD.value, mv.tags.get("environment", "")),
PromotionCheck(
"ML-03",
"enlazada a la versión de cohorte con la que se entrenó",
cohort is not None,
f"hash {cohort.version_hash[:12]}" if cohort else "sin cohorte",
),
PromotionCheck("MLD-01", "métricas de desempeño registradas", bool(metrics), ", ".join(sorted(metrics))),
PromotionCheck("MLD-01", "reporte de pruebas técnicas", bool(mv.tags.get("technical_validation_report_uri")), mv.tags.get("technical_validation_report_uri", "")),
PromotionCheck("MLD-01b", "validación clínica documentada", bool(mv.tags.get("clinical_validation_report_uri")), mv.tags.get("clinical_validation_report_uri", "")),
PromotionCheck("MLD-03", "reporte de interpretabilidad (pesos, OR/HR)", bool(mv.tags.get("interpretability_report_uri")), mv.tags.get("interpretability_report_uri", "")),
PromotionCheck("ML-01b", "artefactos registrados en la corrida", bool(artifacts), f"{len(artifacts)} artefacto(s)"),
]
def promote(self, domain: str, scenario: str, version: str):
"""Makes this the production version of its scenario, tagging the
previous one `retirada_en`. Promotion is always a manual step
(MLD-01/01b)."""
checks = self.checks(domain, scenario, version)
if not all(check.passed for check in checks):
raise PromotionBlocked(checks)
name = registered_name(domain, scenario)
try:
previous = self.client.get_model_version_by_alias(name, PRODUCTION_ALIAS)
if str(previous.version) != str(version):
self.client.set_model_version_tag(name, previous.version, "retirada_en", _now_iso())
except MlflowException:
pass
self.client.set_registered_model_alias(name, PRODUCTION_ALIAS, version)
self.client.set_model_version_tag(name, version, "promovida_en", _now_iso())
return self.get(domain, scenario, version)
def retire(self, domain: str, scenario: str, version: str):
"""Withdraws a version from production; its scenario has no active
model until another one is promoted, so predictions stop (503)."""
name = registered_name(domain, scenario)
try:
active = self.client.get_model_version_by_alias(name, PRODUCTION_ALIAS)
except MlflowException:
active = None
if active is None or str(active.version) != str(version):
raise ValueError("la versión no está en producción")
self.client.delete_registered_model_alias(name, PRODUCTION_ALIAS)
self.client.set_model_version_tag(name, version, "retirada_en", _now_iso())
return self.get(domain, scenario, version)
def compare(self, domain: str, scenario: str, a: str, b: str) -> dict[str, Any]:
"""Metric-by-metric difference (b - a) between two versions."""
ma = self.client.get_run(self.get(domain, scenario, a).run_id).data.metrics
mb = self.client.get_run(self.get(domain, scenario, b).run_id).data.metrics
rows = []
for name in sorted(set(ma) | set(mb)):
va, vb = ma.get(name), mb.get(name)
delta = vb - va if va is not None and vb is not None else None
rows.append({"metric": name, "a": va, "b": vb, "delta": delta})
return {"a": self.describe(domain, scenario, a), "b": self.describe(domain, scenario, b), "metrics": rows}
def _now_iso() -> str:
from datetime import datetime, timezone
return datetime.now(timezone.utc).isoformat()
def _iso(epoch_millis: int) -> str:
from datetime import datetime, timezone
return datetime.fromtimestamp(epoch_millis / 1000, tz=timezone.utc).isoformat()
registry = ModelRegistry()
+3 -1
View File
@@ -8,10 +8,12 @@ class TeaModel(ScreeningModel):
Can pull its own training data straight from `persistance.tea`'s
repositories (`pacientes_repository`, `evaluacion_psicologica_repository`,
...) or be handed already-fetched rows. No real model yet — this is
...) or be handed already-fetched rows. No real model yet; this is
interface scaffolding only.
"""
domain = "tea"
def train(self, data: Any = None) -> None:
raise NotImplementedError("TEA training is not implemented yet.")
+135
View File
@@ -0,0 +1,135 @@
"""Bookkeeping around a training run (ML-01..ML-05).
Does not train anything. It opens an MLflow run, records which cohort
version fed it (ML-03), the artifacts it produced (ML-01a/b), keeps data
access read-only (ML-04) and tags the run as dev or prod (ML-02). MLflow
itself owns run tracking, metrics and artifact storage — this class only
adds the project-specific tags `finish()` needs for `models.registry`'s
promotion checks.
Uses `MlflowClient`'s run-scoped methods (`log_metric(run_id, ...)`, not the
fluent `mlflow.log_metric(...)`) rather than MLflow's global active-run
stack, so an unfinished run from one `TrainingRun` can never block another
one started elsewhere in the same process.
"""
import json
from pathlib import Path
from typing import Any
from mlflow import MlflowClient, MlflowException
from core.governance.enums import ArtifactKind, Environment
from models.base import resolve_repository
from models.registry import REPORT_TAGS, registered_name
from persistance.repository import Repository
class ReadOnlyRepository:
"""ML-04: read-only view of a `Repository` exposing `get`/`list`/`count`.
Write methods raise `PermissionError` so a training routine cannot
modify clinical data."""
_WRITE_METHODS = {"create", "bulk_upsert", "open_session"}
def __init__(self, repository: Repository):
self._repository = repository
self.model = repository.model
def get(self, id_):
return self._repository.get(id_)
def list(self, *, limit: int = 100, offset: int = 0, **filters):
return self._repository.list(limit=limit, offset=offset, **filters)
def count(self, **filters) -> int:
return self._repository.count(**filters)
def __getattr__(self, name: str):
if name in self._WRITE_METHODS:
raise PermissionError(
f"ML-04: un TrainingRun solo tiene permiso de lectura — '{name}' no está disponible en ReadOnlyRepository."
)
raise AttributeError(name)
class TrainingRun:
"""One instance per training execution, wrapping one MLflow run. PROD
runs require `cohort_version_id` so their metrics can be traced to the
data that produced them (ML-03); dev runs may omit it.
"""
def __init__(
self,
*,
domain: str,
scenario: str,
environment: Environment | str,
cohort_version_id: int | None = None,
):
environment = Environment(environment)
if environment is Environment.PROD and cohort_version_id is None:
raise ValueError("ML-03: una corrida PROD debe enlazar un cohort_version_id.")
self.domain = domain
self.scenario = scenario
self.environment = environment
self.cohort_version_id = cohort_version_id
self.client = MlflowClient()
experiment_id = self._experiment_id()
run = self.client.create_run(
experiment_id,
tags={"domain": domain, "scenario": scenario, "environment": environment.value},
)
self.run_id = run.info.run_id
if cohort_version_id is not None:
self.client.set_tag(self.run_id, "cohort_version_id", str(cohort_version_id))
def _experiment_id(self) -> str:
name = registered_name(self.domain, self.scenario)
experiment = self.client.get_experiment_by_name(name)
return experiment.experiment_id if experiment else self.client.create_experiment(name)
def repository(self, entity: str) -> ReadOnlyRepository:
"""ML-04: read-only access to `persistance.<domain>.<entity>_repository`."""
return ReadOnlyRepository(resolve_repository(self.domain, entity))
def log_artifact(self, kind: ArtifactKind | str, path: str | Path, *, metadata: dict[str, Any] | None = None) -> None:
"""ML-01a/ML-01b: logs an artifact file to the run, under a folder
named for its kind."""
kind = ArtifactKind(kind)
self.client.log_artifact(self.run_id, str(path), artifact_path=kind.value)
if metadata:
self.client.log_dict(self.run_id, metadata, f"{kind.value}/{Path(path).name}.meta.json")
def finish(
self,
*,
metrics: dict[str, Any] | None = None,
hyperparameters: dict[str, Any] | None = None,
**reports: str | None,
) -> str:
"""Logs metrics/params to the run, registers it as a new version of
`<domain>-<scenario>` tagged with `models.registry`'s promotion
inputs (environment, cohort link, report URIs), and returns the new
version string. Call once, after training (and artifact logging)
completes."""
unknown = set(reports) - set(REPORT_TAGS)
if unknown:
raise ValueError(f"campos desconocidos: {sorted(unknown)}")
for key, value in (metrics or {}).items():
self.client.log_metric(self.run_id, key, value)
for key, value in (hyperparameters or {}).items():
self.client.log_param(self.run_id, key, value if isinstance(value, (str, int, float, bool)) else json.dumps(value, default=str))
name = registered_name(self.domain, self.scenario)
try:
self.client.create_registered_model(name)
except MlflowException:
pass
version_tags = {"domain": self.domain, "scenario": self.scenario, "environment": self.environment.value}
if self.cohort_version_id is not None:
version_tags["cohort_version_id"] = str(self.cohort_version_id)
version_tags.update({key: uri for key, uri in reports.items() if uri})
model_version = self.client.create_model_version(name, source=f"runs:/{self.run_id}", run_id=self.run_id, tags=version_tags)
self.client.set_terminated(self.run_id)
return str(model_version.version)