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
+6
View File
@@ -6,3 +6,9 @@ __pycache__/
*.egg-info/
.env
uv.lock
# MLflow's own default local stores, used only when MLFLOW_TRACKING_URI
# isn't set (dev/tests point it elsewhere, e.g. a tmp_path file store).
mlflow.db
mlruns/
mlartifacts/
+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)
+13
View File
@@ -5,10 +5,21 @@ description = "train()/predict() interfaces for the CaCu, CaMa and TEA screening
requires-python = ">=3.11"
dependencies = [
"persistance",
"extraction",
"mlflow>=2.9",
]
[project.optional-dependencies]
# Only needed to read back a checkpoint's own metadata (opset, producer) in
# models.export.inspect_onnx_metadata — writing/logging a checkpoint never
# requires it, see that module's docstring.
export = [
"onnx>=1.15",
]
[tool.uv.sources]
persistance = { path = "../Persistance", editable = true }
extraction = { path = "../Extraction", editable = true }
[build-system]
requires = ["hatchling"]
@@ -20,4 +31,6 @@ packages = ["models"]
[dependency-groups]
dev = [
"pytest>=8.0.0",
"onnx>=1.15",
"reportlab>=4.0",
]
+85
View File
@@ -0,0 +1,85 @@
import pytest
def _wire(monkeypatch, tmp_path, domain: str, base_module: str, base_class: str):
import importlib
from persistance import db as persistance_db
from persistance import settings as persistance_settings
monkeypatch.setattr(persistance_settings.settings, f"{domain}_database_url", f"sqlite:///{tmp_path / f'{domain}.db'}")
engine = getattr(persistance_db, f"get_{domain}_engine")
engine.cache_clear()
importlib.import_module(f"core.{domain}.models")
base = getattr(importlib.import_module(base_module), base_class)
base.metadata.create_all(engine())
return engine
@pytest.fixture
def governance_db(tmp_path, monkeypatch):
engine = _wire(monkeypatch, tmp_path, "governance", "core.governance.base", "GovernanceModel")
yield
engine.cache_clear()
@pytest.fixture
def cacu_db(tmp_path, monkeypatch):
engine = _wire(monkeypatch, tmp_path, "cacu", "core.cacu.base", "CaCuModel")
yield
engine.cache_clear()
@pytest.fixture
def mlflow_tracking(tmp_path, monkeypatch):
"""A local, SQLite-backed MLflow tracking URI — no server, no network,
isolated per test (MLflow's own default local backend; the older plain
file store is deprecated as of MLflow 3). Also `chdir`s into `tmp_path`:
an experiment with no explicit `artifact_location` falls back to
`./mlruns` relative to the CWD, and production never sets one either
(the real MLflow server picks it, e.g. S3) — so this is purely test
isolation, not something `models.training` should set itself."""
import mlflow
uri = f"sqlite:///{tmp_path / 'mlflow.db'}"
monkeypatch.setenv("MLFLOW_TRACKING_URI", uri)
mlflow.set_tracking_uri(uri)
monkeypatch.chdir(tmp_path)
yield
@pytest.fixture
def production_ready(governance_db, mlflow_tracking):
"""Factory: registers a PROD version that passes every promotion check,
returns (domain, scenario, version)."""
from core.governance.enums import ArtifactKind, Environment
from core.governance.models import CohortVersion
from models.registry import registry
from persistance.governance import cohort_version_repository
def make(tag: str, *, domain: str = "cacu", scenario: str = "tamizaje", metrics: dict | None = None):
cohort = cohort_version_repository.create(
CohortVersion(
domain=domain, scenario=scenario, criteria_version="v1", version_hash=f"hash-{tag}",
source_table=f"{domain}.episodioclinico", n_source=10, n_included=8,
)
)
version = registry.register(
domain=domain, scenario=scenario, environment=Environment.PROD,
cohort_version_id=cohort.cohort_version_id, metrics=metrics or {"auc": 0.8},
technical_validation_report_uri="docs/tecnica.pdf", clinical_validation_report_uri="docs/clinica.pdf",
interpretability_report_uri="docs/interpretabilidad.html",
)
registry.add_artifact(domain, scenario, version, kind=ArtifactKind.ONNX_CHECKPOINT, filename="model.onnx", data=tiny_onnx())
return domain, scenario, version
return make
def tiny_onnx() -> bytes:
import onnx.helper
node = onnx.helper.make_node("Identity", ["x"], ["y"])
x = onnx.helper.make_tensor_value_info("x", onnx.TensorProto.FLOAT, [1])
y = onnx.helper.make_tensor_value_info("y", onnx.TensorProto.FLOAT, [1])
return onnx.helper.make_model(onnx.helper.make_graph([node], "tiny", [x], [y]), producer_name="pytest").SerializeToString()
+79
View File
@@ -0,0 +1,79 @@
from datetime import date
import pytest
from models.cohort import CohortBuilder, ExclusionCriterion, compute_version_hash
def _seed_episodes():
from core.cacu.episodio_clinico.enums import TipoEpisodio
from core.cacu.models import EpisodioClinico
from persistance.cacu import episodio_clinico_repository
for i, year in enumerate([2018, 2019, 2021, 2022, 2023]):
episodio_clinico_repository.create(
EpisodioClinico(
pac_id_hospital=f"H-{i}",
tipo_episodio=TipoEpisodio.TAMIZAJE,
evento_fecha=date(year, 6, 1),
)
)
class FechaVentanaCohortBuilder(CohortBuilder):
domain = "cacu"
scenario = "tamizaje_test"
criteria_version = "v1"
criteria = [
ExclusionCriterion(
code="FECHA_FUERA_DE_VENTANA",
reason_code="ANTES_2020",
predicate=lambda e: e["evento_fecha"] < date(2020, 1, 1),
applicable_in_production=True,
),
]
def test_build_excludes_and_materializes_counts(cacu_db, governance_db):
_seed_episodes()
builder = FechaVentanaCohortBuilder()
cohort_version = builder.build(description="ventana >= 2020")
assert cohort_version.n_source == 5
assert cohort_version.n_included == 3
assert cohort_version.version_hash
from persistance.governance import cohort_exclusion_count_repository, cohort_exclusion_repository, cohort_member_repository
members = cohort_member_repository.list(cohort_version_id=cohort_version.cohort_version_id)
assert len(members) == 3
exclusions = cohort_exclusion_repository.list(cohort_version_id=cohort_version.cohort_version_id)
assert len(exclusions) == 2
assert {e.reason_code for e in exclusions} == {"ANTES_2020"}
counts = cohort_exclusion_count_repository.list(cohort_version_id=cohort_version.cohort_version_id)
assert len(counts) == 1
assert counts[0].count == 2
assert counts[0].criterion_code == "FECHA_FUERA_DE_VENTANA"
def test_version_hash_is_deterministic_and_order_independent():
hash_a = compute_version_hash(criteria_version="v1", criterion_codes=["X", "Y"], episode_ids=[3, 1, 2])
hash_b = compute_version_hash(criteria_version="v1", criterion_codes=["Y", "X"], episode_ids=[1, 2, 3])
hash_c = compute_version_hash(criteria_version="v2", criterion_codes=["X", "Y"], episode_ids=[1, 2, 3])
assert hash_a == hash_b
assert hash_a != hash_c
assert len(hash_a) == 64
def test_evaluate_applicability_uses_only_production_applicable_criteria():
builder = FechaVentanaCohortBuilder()
old_row = {"evento_fecha": date(2018, 1, 1)}
recent_row = {"evento_fecha": date(2023, 1, 1)}
assert builder.evaluate_applicability(old_row) is False
assert builder.evaluate_applicability(recent_row) is True
+27
View File
@@ -0,0 +1,27 @@
"""`models` reads through Persistance's Repository, the same path WebApi
uses, against a temporary SQLite database."""
import pytest
def test_dataset_pages_through_every_row(cacu_db):
from datetime import date
from core.cacu.models import Paciente
from models.cacu import CaCuModel
model = CaCuModel()
repository = model.repository("paciente")
for i in range(7):
repository.create(Paciente(pac_id_hospital=f"M-{i}", pac_sexo="Femenino", pac_fecha_nacimiento=date(1990, 1, 1)))
rows = list(model.dataset("paciente", batch_size=3))
assert [r["pac_id_hospital"] for r in rows] == [f"M-{i}" for i in range(7)]
assert list(model.dataset("paciente", pac_id_hospital="M-3"))[0]["pac_sexo"] == "Femenino"
def test_unknown_entity_is_a_clear_error():
from models.tea import TeaModel
with pytest.raises(ValueError, match="no nope_repository"):
TeaModel().repository("nope")
+44
View File
@@ -0,0 +1,44 @@
import onnx
import onnx.helper
from models.export import inspect_onnx_metadata
def _tiny_onnx_bytes() -> bytes:
node = onnx.helper.make_node("Identity", ["x"], ["y"])
x = onnx.helper.make_tensor_value_info("x", onnx.TensorProto.FLOAT, [1])
y = onnx.helper.make_tensor_value_info("y", onnx.TensorProto.FLOAT, [1])
graph = onnx.helper.make_graph([node], "tiny", [x], [y])
model = onnx.helper.make_model(graph, producer_name="pytest-fixture")
return model.SerializeToString()
def test_inspect_onnx_metadata_reads_producer_and_io(tmp_path):
path = tmp_path / "model.onnx"
path.write_bytes(_tiny_onnx_bytes())
metadata = inspect_onnx_metadata(path)
assert metadata["available"] is True
assert metadata["producer_name"] == "pytest-fixture"
assert metadata["graph_inputs"] == ["x"]
assert metadata["graph_outputs"] == ["y"]
def test_inspect_onnx_metadata_without_onnx_available(monkeypatch, tmp_path):
import builtins
real_import = builtins.__import__
def fake_import(name, *args, **kwargs):
if name == "onnx":
raise ImportError("onnx not installed")
return real_import(name, *args, **kwargs)
monkeypatch.setattr(builtins, "__import__", fake_import)
path = tmp_path / "model.onnx"
path.write_bytes(b"irrelevant")
assert inspect_onnx_metadata(path) == {
"available": False,
"reason": "el paquete 'onnx' no está instalado (extra 'export')",
}
+97
View File
@@ -0,0 +1,97 @@
from datetime import date
import pytest
from core.ocr import OcrEstatus
from models.ocr import CIT_VPH_COLUMNS, OcrExtractionResult, OcrExtractor, run_pending_extractions
class StubVphExtractor(OcrExtractor):
def extract(self, pdf_blob: bytes) -> OcrExtractionResult:
return OcrExtractionResult(
values={"resultado": "POSITIVO", "genotipo_16": 1, "genotipo_18": 0},
confianza=0.92,
estatus=OcrEstatus.REALIZADO,
requiere_revision=False,
metodo_principal="stub-v1",
)
class AlwaysFailsExtractor(OcrExtractor):
def extract(self, pdf_blob: bytes) -> OcrExtractionResult:
raise RuntimeError("boom")
def _make_cacu_citologia_repo():
from core.cacu.models import CitologiaCervical
from persistance.cacu import citologia_cervical_repository
return citologia_cervical_repository, CitologiaCervical
def test_run_pending_extractions_populates_result_and_metadata(cacu_db):
repo, CitologiaCervical = _make_cacu_citologia_repo()
repo.create(
CitologiaCervical(
pac_id_hospital="H-1",
cit_vph_pdf_blob=b"%PDF-fake",
)
)
summary = run_pending_extractions(repo, CIT_VPH_COLUMNS, StubVphExtractor(), domain="cacu", entity="citologiacervical")
assert summary.processed == 1
assert summary.skipped_already_done == 0
row = repo.list()[0]
assert row.cit_vph_resultado == "POSITIVO"
assert row.cit_vph_genotipo_16 == 1
assert row.cit_vph_ocr_estatus == OcrEstatus.REALIZADO
assert row.cit_vph_ocr_requiere_revision is False
assert row.cit_vph_ocr_metodo_principal == "stub-v1"
def test_run_pending_extractions_is_idempotent(cacu_db):
repo, CitologiaCervical = _make_cacu_citologia_repo()
repo.create(CitologiaCervical(pac_id_hospital="H-1", cit_vph_pdf_blob=b"%PDF-fake"))
first = run_pending_extractions(repo, CIT_VPH_COLUMNS, StubVphExtractor(), domain="cacu", entity="citologiacervical")
second = run_pending_extractions(repo, CIT_VPH_COLUMNS, StubVphExtractor(), domain="cacu", entity="citologiacervical")
assert first.processed == 1
assert second.processed == 0
assert second.skipped_already_done == 1
def test_run_pending_extractions_persists_failure_instead_of_crashing(cacu_db):
repo, CitologiaCervical = _make_cacu_citologia_repo()
repo.create(CitologiaCervical(pac_id_hospital="H-1", cit_vph_pdf_blob=b"%PDF-fake"))
summary = run_pending_extractions(repo, CIT_VPH_COLUMNS, AlwaysFailsExtractor(), domain="cacu", entity="citologiacervical")
assert summary.failed == 1
row = repo.list()[0]
assert row.cit_vph_ocr_estatus == OcrEstatus.FALLIDO
assert row.cit_vph_ocr_requiere_revision is True
def test_run_pending_extractions_logs_to_governance(cacu_db, governance_db):
from persistance.governance import extraction_run_repository
repo, CitologiaCervical = _make_cacu_citologia_repo()
repo.create(CitologiaCervical(pac_id_hospital="H-1", cit_vph_pdf_blob=b"%PDF-fake"))
run_pending_extractions(
repo,
CIT_VPH_COLUMNS,
StubVphExtractor(),
domain="cacu",
entity="citologiacervical",
governance_repository=extraction_run_repository,
source_description="HIS export 2026-09-01",
)
runs = extraction_run_repository.list()
assert len(runs) == 1
assert runs[0].domain == "cacu"
assert runs[0].source_description == "HIS export 2026-09-01"
+40
View File
@@ -0,0 +1,40 @@
from core.ocr import OcrEstatus
from extraction.testing import scanned_pdf, text_pdf
from models.ocr import CinGradoOcrExtractor, GradoHistologicoOcrExtractor, VphOcrExtractor
def test_cin_grade_from_narrative_diagnosis():
report = text_pdf(
[
[
"REPORTE DE ESTUDIO HISTOPATOLOGICO",
"Descripción microscópica: epitelio escamoso con atipia en el tercio inferior.",
"No se observa carcinoma invasor.",
"DIAGNÓSTICO:",
"Lesión intraepitelial escamosa de bajo grado (NIC I) asociada a VPH.",
]
]
)
result = CinGradoOcrExtractor().extract(report)
assert result.values == {"grado": "LIEBG"}
assert result.estatus is OcrEstatus.REALIZADO
def test_breast_histological_grade_prefers_in_situ_over_its_prefix():
report = text_pdf([["Diagnóstico: CARCINOMA DUCTAL IN SITU de alto grado nuclear."]])
assert GradoHistologicoOcrExtractor().extract(report).values == {"grado": "CARCINOMA_IN_SITU"}
def test_scanned_vph_report_uses_tesseract_and_reports_confidence():
report = scanned_pdf([["Resultado VPH: NEGATIVO", "Genotipo 16: NO DETECTADO", "Genotipo 18: NO DETECTADO"]])
result = VphOcrExtractor().extract(report)
assert result.values == {"resultado": "NEGATIVO", "genotipo_16": 0, "genotipo_18": 0}
assert result.metodo_principal.startswith("tesseract")
assert 0 < result.confianza <= 1
def test_missing_fields_require_review_and_empty_reports_fail():
partial = VphOcrExtractor().extract(text_pdf([["VPH alto riesgo: POSITIVO"]]))
assert partial.estatus is OcrEstatus.REALIZADO and partial.requiere_revision
empty = VphOcrExtractor().extract(text_pdf([["Hoja sin resultados de laboratorio"]]))
assert empty.estatus is OcrEstatus.FALLIDO and empty.requiere_revision
+77
View File
@@ -0,0 +1,77 @@
import json
import pytest
from models.base import ScreeningModel
from models.cohort import CohortBuilder, ExclusionCriterion
from models.prediction import ApplicabilityRejected, Interpretability, PredictionService
from models.registry import registry
class StubModel(ScreeningModel):
domain = "cacu"
def train(self, data=None):
raise NotImplementedError
def predict(self, data):
return {"label": "positivo", "confianza": 0.73}
class AlwaysRejectCohortBuilder(CohortBuilder):
domain = "cacu"
scenario = "tamizaje"
criteria_version = "v1"
criteria = [ExclusionCriterion(code="X", reason_code="siempre", predicate=lambda e: True, applicable_in_production=True)]
def _promote_a_version(production_ready):
domain, scenario, version = production_ready("v1-prod")
return registry.promote(domain, scenario, version)
def test_predict_and_record_persists_prediction_tagged_with_active_version(production_ready):
version = _promote_a_version(production_ready)
service = PredictionService(StubModel(), domain="cacu", scenario="tamizaje")
prediction = service.predict_and_record(
{"edad": 40},
pac_id_hospital="H-1",
interpretability=Interpretability(odds_ratio=1.8),
)
assert prediction.mlflow_run_id == version.run_id
assert prediction.modelo_version == str(version.version)
assert prediction.applicability_passed is True
assert json.loads(prediction.output)["label"] == "positivo"
assert json.loads(prediction.interpretability)["odds_ratio"] == 1.8
def test_predict_without_active_version_raises(governance_db, mlflow_tracking):
service = PredictionService(StubModel(), domain="cacu", scenario="tamizaje")
with pytest.raises(RuntimeError, match="no hay una versión en producción"):
service.predict_and_record({"edad": 40}, pac_id_hospital="H-1")
def test_applicability_gate_flags_but_does_not_block_by_default(production_ready):
_promote_a_version(production_ready)
service = PredictionService(
StubModel(), domain="cacu", scenario="tamizaje", cohort_builder=AlwaysRejectCohortBuilder()
)
prediction = service.predict_and_record({"edad": 40}, pac_id_hospital="H-1")
assert prediction.applicability_passed is False
def test_applicability_gate_can_reject_outright(production_ready):
_promote_a_version(production_ready)
service = PredictionService(
StubModel(),
domain="cacu",
scenario="tamizaje",
cohort_builder=AlwaysRejectCohortBuilder(),
reject_inapplicable=True,
)
with pytest.raises(ApplicabilityRejected):
service.predict_and_record({"edad": 40}, pac_id_hospital="H-1")
+70
View File
@@ -0,0 +1,70 @@
import pytest
from core.governance.enums import ArtifactKind, Environment
from models.registry import PromotionBlocked, registry
def test_dev_version_cannot_be_promoted_and_says_why(governance_db, mlflow_tracking):
version = registry.register(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
assert registry.status("cacu", "tamizaje", version) == "desarrollo"
with pytest.raises(PromotionBlocked) as blocked:
registry.promote("cacu", "tamizaje", version)
failed = {check.code for check in blocked.value.checks if not check.passed}
assert failed == {"ML-02", "ML-03", "MLD-01", "MLD-01b", "MLD-03", "ML-01b"}
def test_promotion_retires_the_previous_version_of_the_scenario(production_ready):
domain, scenario, first = production_ready("v1")
_, _, second = production_ready("v2", metrics={"auc": 0.84})
assert registry.status(domain, scenario, first) == "candidata"
registry.promote(domain, scenario, first)
registry.promote(domain, scenario, second)
assert registry.status(domain, scenario, first) == "retirada"
assert registry.status(domain, scenario, second) == "produccion"
other_domain, other_scenario, other_version = production_ready("v1-dx", scenario="diagnostico")
registry.promote(other_domain, other_scenario, other_version)
assert registry.status(domain, scenario, second) == "produccion"
def test_reports_can_be_attached_after_training(production_ready):
domain, scenario, version = production_ready("v1")
registry.attach_reports(domain, scenario, version, clinical_validation_report_uri=None)
assert not next(c for c in registry.checks(domain, scenario, version) if c.code == "MLD-01b").passed
registry.attach_reports(domain, scenario, version, clinical_validation_report_uri="docs/clinica-v2.pdf")
assert all(c.passed for c in registry.checks(domain, scenario, version))
with pytest.raises(ValueError):
registry.attach_reports(domain, scenario, version, metrics="{}")
def test_artifacts_are_logged_to_the_run(production_ready):
domain, scenario, version = production_ready("v1")
lineage = registry.lineage(domain, scenario, version)
assert any(path.startswith(ArtifactKind.ONNX_CHECKPOINT.value) for path in lineage["artifacts"])
def test_retire_and_lineage_and_compare(production_ready):
domain, scenario, first = production_ready("v1", metrics={"auc": 0.8, "brier": 0.2})
_, _, second = production_ready("v2", metrics={"auc": 0.85})
registry.promote(domain, scenario, second)
lineage = registry.lineage(domain, scenario, second)
assert lineage["cohort_version"]["version_hash"] == "hash-v2"
assert lineage["model_version"]["status"] == "produccion"
diff = {row["metric"]: row for row in registry.compare(domain, scenario, first, second)["metrics"]}
assert diff["auc"]["delta"] == pytest.approx(0.05) and diff["brier"]["delta"] is None
registry.retire(domain, scenario, second)
assert registry.status(domain, scenario, second) == "retirada"
with pytest.raises(ValueError):
registry.retire(domain, scenario, second)
def test_invalid_onnx_checkpoint_is_rejected(production_ready):
from models.export import inspect_onnx_metadata
with pytest.raises(ValueError, match="ONNX"):
import tempfile
from pathlib import Path
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "x.onnx"
path.write_bytes(b"weights")
inspect_onnx_metadata(path)
+51
View File
@@ -0,0 +1,51 @@
import pytest
from core.governance.enums import ArtifactKind, Environment
from models.registry import registry
from models.training import ReadOnlyRepository, TrainingRun
def test_prod_run_requires_cohort_version_id():
with pytest.raises(ValueError, match="cohort_version_id"):
TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.PROD)
def test_dev_run_does_not_require_cohort_version_id(mlflow_tracking):
run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
assert run.cohort_version_id is None
def test_finish_registers_model_version_and_artifacts(mlflow_tracking, tmp_path):
checkpoint = tmp_path / "model.onnx"
checkpoint.write_bytes(b"fake-onnx-bytes")
run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
run.log_artifact(ArtifactKind.ONNX_CHECKPOINT, checkpoint, metadata={"opset": 17})
version = run.finish(metrics={"auc": 0.81})
mv = registry.get("cacu", "tamizaje", version)
assert mv.tags["environment"] == Environment.DEV.value
metrics = registry.client.get_run(mv.run_id).data.metrics
assert metrics["auc"] == 0.81
artifacts = [a.path for a in registry.client.list_artifacts(mv.run_id, path=ArtifactKind.ONNX_CHECKPOINT.value)]
assert any(path.endswith("model.onnx") for path in artifacts)
def test_read_only_repository_blocks_writes(cacu_db):
from persistance.cacu import paciente_repository
read_only = ReadOnlyRepository(paciente_repository)
assert read_only.list() == []
with pytest.raises(PermissionError, match="ML-04"):
read_only.create(object())
with pytest.raises(PermissionError, match="ML-04"):
read_only.open_session()
def test_training_run_repository_is_read_only(cacu_db, mlflow_tracking):
run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
repo = run.repository("paciente")
assert isinstance(repo, ReadOnlyRepository)
with pytest.raises(PermissionError):
repo.create(object())