integration layer; merge work on indicators from forks with existing ingestion pipeline
This commit is contained in:
@@ -1,14 +1,18 @@
|
||||
from flask import Blueprint, jsonify
|
||||
from flask import Blueprint, jsonify, request
|
||||
|
||||
from models.cacu import CaCuModel
|
||||
from models.prediction import ApplicabilityRejected, PredictionService
|
||||
from persistance.cacu import paciente_repository
|
||||
from persistance.db import get_cacu_session
|
||||
from webapi.indicadores import registrar_indicadores
|
||||
|
||||
cacu_bp = Blueprint("cacu", __name__)
|
||||
registrar_indicadores(cacu_bp, "cacu", get_cacu_session)
|
||||
|
||||
|
||||
@cacu_bp.get("/pacientes/<int:pac_id>")
|
||||
def get_paciente(pac_id: int):
|
||||
"""Example read route — proves WebApi resolves Persistance's repository API."""
|
||||
"""Read one CaCu patient by primary key."""
|
||||
paciente = paciente_repository.get(pac_id)
|
||||
if paciente is None:
|
||||
return jsonify({"error": "not found"}), 404
|
||||
@@ -17,9 +21,21 @@ def get_paciente(pac_id: int):
|
||||
|
||||
@cacu_bp.post("/predict")
|
||||
def predict():
|
||||
"""Example predict route — proves WebApi resolves the models package."""
|
||||
model = CaCuModel()
|
||||
"""Predict and record the result against the active `ModelVersion` (MLD-4/MLD-5).
|
||||
|
||||
Returns 501 while `CaCuModel.predict` is not implemented."""
|
||||
body = request.get_json(silent=True) or {}
|
||||
service = PredictionService(CaCuModel(), domain="cacu", scenario=body.get("scenario", "tamizaje"))
|
||||
try:
|
||||
return jsonify({"prediction": model.predict(data=None)})
|
||||
prediction = service.predict_and_record(
|
||||
body.get("data"),
|
||||
pac_id_hospital=body.get("pac_id_hospital", ""),
|
||||
episodio_id=body.get("episodio_id"),
|
||||
)
|
||||
except NotImplementedError as exc:
|
||||
return jsonify({"error": str(exc)}), 501
|
||||
except ApplicabilityRejected as exc:
|
||||
return jsonify({"error": str(exc)}), 422
|
||||
except RuntimeError as exc:
|
||||
return jsonify({"error": str(exc)}), 503
|
||||
return jsonify(prediction.model_dump())
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
from flask import Blueprint, jsonify
|
||||
from flask import Blueprint, jsonify, request
|
||||
|
||||
from models.cama import CaMaModel
|
||||
from models.prediction import ApplicabilityRejected, PredictionService
|
||||
from persistance.cama import paciente_repository
|
||||
from persistance.db import get_cama_session
|
||||
from webapi.indicadores import registrar_indicadores
|
||||
|
||||
cama_bp = Blueprint("cama", __name__)
|
||||
registrar_indicadores(cama_bp, "cama", get_cama_session)
|
||||
|
||||
|
||||
@cama_bp.get("/pacientes/<int:pac_id>")
|
||||
@@ -16,8 +20,19 @@ def get_paciente(pac_id: int):
|
||||
|
||||
@cama_bp.post("/predict")
|
||||
def predict():
|
||||
model = CaMaModel()
|
||||
"""Predict and record the result against the active `ModelVersion` (MLD-4/MLD-5)."""
|
||||
body = request.get_json(silent=True) or {}
|
||||
service = PredictionService(CaMaModel(), domain="cama", scenario=body.get("scenario", "tamizaje"))
|
||||
try:
|
||||
return jsonify({"prediction": model.predict(data=None)})
|
||||
prediction = service.predict_and_record(
|
||||
body.get("data"),
|
||||
pac_id_hospital=body.get("pac_id_hospital", ""),
|
||||
episodio_id=body.get("episodio_id"),
|
||||
)
|
||||
except NotImplementedError as exc:
|
||||
return jsonify({"error": str(exc)}), 501
|
||||
except ApplicabilityRejected as exc:
|
||||
return jsonify({"error": str(exc)}), 422
|
||||
except RuntimeError as exc:
|
||||
return jsonify({"error": str(exc)}), 503
|
||||
return jsonify(prediction.model_dump())
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
"""Generic paginated read access to every importable table through its
|
||||
`Repository`, so clients can inspect what an import wrote."""
|
||||
from flask import Blueprint, jsonify, request
|
||||
|
||||
from webapi.imports.schemas.registry import ENTITY_REGISTRY
|
||||
|
||||
data_bp = Blueprint("data", __name__)
|
||||
|
||||
_MAX_PAGE = 500
|
||||
|
||||
|
||||
@data_bp.get("/<target>")
|
||||
def list_rows(target: str):
|
||||
spec = ENTITY_REGISTRY.get(target)
|
||||
if spec is None:
|
||||
return jsonify({"error": f"unknown target: {target!r}"}), 404
|
||||
try:
|
||||
limit = min(max(int(request.args.get("limit", 50)), 1), _MAX_PAGE)
|
||||
offset = max(int(request.args.get("offset", 0)), 0)
|
||||
except ValueError:
|
||||
return jsonify({"error": "limit/offset must be integers"}), 400
|
||||
rows = spec.repository.list(limit=limit, offset=offset)
|
||||
return jsonify(
|
||||
{
|
||||
"target": target,
|
||||
"total": spec.repository.count(),
|
||||
"limit": limit,
|
||||
"offset": offset,
|
||||
# Table order (JSON objects get their keys sorted on the way out).
|
||||
"columns": [column.name for column in spec.model.__table__.columns],
|
||||
"rows": [row.model_dump() for row in rows],
|
||||
}
|
||||
)
|
||||
@@ -0,0 +1,355 @@
|
||||
"""Model governance (ML, MLD, EL and VAR requirements): model versions and
|
||||
their promotion, cohorts, predictions, and the OCR extraction jobs with
|
||||
their manual review queue.
|
||||
|
||||
Training, versioning and artifact storage live in MLflow (`models.registry`
|
||||
is a thin layer over it); training runs anywhere, registering the result
|
||||
through `POST /model-versions`. Browsing/downloading a logged artifact goes
|
||||
straight to the MLflow tracking server's own UI/API, not through here.
|
||||
"""
|
||||
from dataclasses import asdict
|
||||
|
||||
from flask import Blueprint, Response, jsonify, request
|
||||
|
||||
from core.governance.enums import EstatusExtraccion
|
||||
from core.governance.models import ExtractionRun
|
||||
from core.ocr import OcrEstatus
|
||||
from models.cohort import COHORT_BUILDERS, describe_builder
|
||||
from models.ocr import OCR_JOBS, OcrColumnSpec, run_pending_extractions
|
||||
from models.registry import REPORT_TAGS, PromotionBlocked, registry
|
||||
from persistance.governance import (
|
||||
cohort_exclusion_count_repository,
|
||||
cohort_exclusion_repository,
|
||||
cohort_version_repository,
|
||||
extraction_run_repository,
|
||||
model_prediction_repository,
|
||||
)
|
||||
from persistance.repository import Repository
|
||||
|
||||
governance_bp = Blueprint("governance", __name__)
|
||||
|
||||
|
||||
@governance_bp.errorhandler(LookupError)
|
||||
def _not_found(exc: LookupError):
|
||||
return jsonify({"error": str(exc)}), 404
|
||||
|
||||
|
||||
@governance_bp.errorhandler(ValueError)
|
||||
def _bad_request(exc: ValueError):
|
||||
return jsonify({"error": str(exc)}), 400
|
||||
|
||||
|
||||
def _ocr_job_or_404(domain: str | None, entity: str | None) -> tuple[Repository, OcrColumnSpec] | None:
|
||||
job = OCR_JOBS.get((domain, entity))
|
||||
return (job.repository, job.columns) if job else None
|
||||
|
||||
|
||||
def _pk_name(repository: Repository) -> str:
|
||||
return next(iter(repository.model.__table__.primary_key.columns)).name
|
||||
|
||||
|
||||
# -- model versions ----------------------------------------------------------------
|
||||
|
||||
|
||||
@governance_bp.get("/model-versions")
|
||||
def list_model_versions():
|
||||
"""`?domain=` alone matches every scenario of that domain; `?domain=&scenario=`
|
||||
matches one; neither matches everything."""
|
||||
return jsonify({"model_versions": registry.versions(request.args.get("domain"), request.args.get("scenario"))})
|
||||
|
||||
|
||||
@governance_bp.post("/model-versions")
|
||||
def register_model_version():
|
||||
"""Registers a trained version: `{domain, scenario,
|
||||
environment: DEV|PROD, cohort_version_id?, metrics?, hyperparameters?,
|
||||
technical_validation_report_uri?, clinical_validation_report_uri?,
|
||||
interpretability_report_uri?}`."""
|
||||
body = request.get_json(silent=True) or {}
|
||||
missing = [k for k in ("domain", "scenario", "environment") if not body.get(k)]
|
||||
if missing:
|
||||
return jsonify({"error": f"faltan campos: {missing}"}), 400
|
||||
version = registry.register(
|
||||
domain=body["domain"],
|
||||
scenario=body["scenario"],
|
||||
environment=body["environment"],
|
||||
cohort_version_id=body.get("cohort_version_id"),
|
||||
metrics=body.get("metrics"),
|
||||
hyperparameters=body.get("hyperparameters"),
|
||||
**{k: body[k] for k in REPORT_TAGS if k in body},
|
||||
)
|
||||
return jsonify(registry.describe(body["domain"], body["scenario"], version)), 201
|
||||
|
||||
|
||||
@governance_bp.get("/model-versions/<domain>/<scenario>/<version>")
|
||||
def get_model_version(domain: str, scenario: str, version: str):
|
||||
return jsonify(registry.describe(domain, scenario, version))
|
||||
|
||||
|
||||
@governance_bp.patch("/model-versions/<domain>/<scenario>/<version>/reports")
|
||||
def attach_reports(domain: str, scenario: str, version: str):
|
||||
"""MLD-01/01b/03 documents, usually written after training."""
|
||||
body = request.get_json(silent=True) or {}
|
||||
registry.attach_reports(domain, scenario, version, **body)
|
||||
return jsonify(registry.describe(domain, scenario, version))
|
||||
|
||||
|
||||
@governance_bp.get("/model-versions/<domain>/<scenario>/<version>/lineage")
|
||||
def model_version_lineage(domain: str, scenario: str, version: str):
|
||||
return jsonify(registry.lineage(domain, scenario, version))
|
||||
|
||||
|
||||
@governance_bp.get("/model-versions/<domain>/<scenario>/<version>/checks")
|
||||
def model_version_checks(domain: str, scenario: str, version: str):
|
||||
checks = registry.checks(domain, scenario, version)
|
||||
return jsonify({"ready": all(c.passed for c in checks), "checks": [asdict(c) for c in checks]})
|
||||
|
||||
|
||||
@governance_bp.post("/model-versions/<domain>/<scenario>/<version>/promote")
|
||||
def promote_model_version(domain: str, scenario: str, version: str):
|
||||
"""Puts the version in production, tagging the previous one of its
|
||||
scenario `retirada_en`. 409 with the failing checks when it isn't ready."""
|
||||
try:
|
||||
registry.promote(domain, scenario, version)
|
||||
except PromotionBlocked as blocked:
|
||||
return jsonify({"error": str(blocked), "checks": [asdict(c) for c in blocked.checks]}), 409
|
||||
return jsonify(registry.describe(domain, scenario, version))
|
||||
|
||||
|
||||
@governance_bp.post("/model-versions/<domain>/<scenario>/<version>/retire")
|
||||
def retire_model_version(domain: str, scenario: str, version: str):
|
||||
registry.retire(domain, scenario, version)
|
||||
return jsonify(registry.describe(domain, scenario, version))
|
||||
|
||||
|
||||
@governance_bp.get("/model-versions/<domain>/<scenario>/compare")
|
||||
def compare_model_versions(domain: str, scenario: str):
|
||||
a, b = request.args.get("a"), request.args.get("b")
|
||||
if not a or not b:
|
||||
return jsonify({"error": "a y b deben ser versiones de MLflow"}), 400
|
||||
return jsonify(registry.compare(domain, scenario, a, b))
|
||||
|
||||
|
||||
@governance_bp.post("/model-versions/<domain>/<scenario>/<version>/artifacts")
|
||||
def upload_artifact(domain: str, scenario: str, version: str):
|
||||
"""Multipart: `file`, `kind` (ArtifactKind) — logs it to the version's
|
||||
MLflow run. Browse/download logged artifacts via the MLflow tracking
|
||||
server directly, not through here."""
|
||||
from core.governance.enums import ArtifactKind
|
||||
|
||||
upload = request.files.get("file")
|
||||
if upload is None:
|
||||
return jsonify({"error": "falta file"}), 400
|
||||
kinds = [k.value for k in ArtifactKind]
|
||||
if request.form.get("kind") not in kinds:
|
||||
return jsonify({"error": f"kind debe ser uno de {kinds}"}), 400
|
||||
registry.add_artifact(domain, scenario, version, kind=ArtifactKind(request.form["kind"]), filename=upload.filename or "artefacto", data=upload.read())
|
||||
return jsonify(registry.describe(domain, scenario, version)), 201
|
||||
|
||||
|
||||
# -- cohorts ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@governance_bp.get("/cohort-scenarios")
|
||||
def list_cohort_scenarios():
|
||||
"""Scenarios with a registered `CohortBuilder` (see models.cohort.register_cohort_builder)."""
|
||||
return jsonify({"scenarios": [describe_builder(cls) for cls in COHORT_BUILDERS.values()]})
|
||||
|
||||
|
||||
@governance_bp.post("/cohort-versions")
|
||||
def build_cohort_version():
|
||||
"""Builds and freezes a new cohort version: `{domain, scenario, description?}`."""
|
||||
body = request.get_json(silent=True) or {}
|
||||
builder = COHORT_BUILDERS.get((body.get("domain"), body.get("scenario")))
|
||||
if builder is None:
|
||||
return jsonify({"error": f"no hay un CohortBuilder registrado para ({body.get('domain')!r}, {body.get('scenario')!r})"}), 404
|
||||
return jsonify(builder().build(description=body.get("description")).model_dump()), 201
|
||||
|
||||
|
||||
@governance_bp.get("/cohort-versions")
|
||||
def list_cohort_versions():
|
||||
filters = {k: v for k, v in request.args.items() if k in {"domain", "scenario"}}
|
||||
versions = cohort_version_repository.list(limit=200, **filters)
|
||||
return jsonify({"cohort_versions": [v.model_dump() for v in versions]})
|
||||
|
||||
|
||||
@governance_bp.get("/cohort-versions/<int:cohort_version_id>/exclusions")
|
||||
def get_cohort_exclusions(cohort_version_id: int):
|
||||
"""EL-05/EL-07: per-criterion counts and the per-episode log behind them."""
|
||||
counts = cohort_exclusion_count_repository.list(limit=1000, cohort_version_id=cohort_version_id)
|
||||
detail = cohort_exclusion_repository.list(limit=1000, cohort_version_id=cohort_version_id)
|
||||
return jsonify({"counts": [c.model_dump() for c in counts], "detail": [d.model_dump() for d in detail]})
|
||||
|
||||
|
||||
# -- predictions and OCR -------------------------------------------------------------------
|
||||
|
||||
|
||||
@governance_bp.get("/predictions")
|
||||
def list_predictions():
|
||||
filters = {k: v for k, v in request.args.items() if k in {"domain", "pac_id_hospital", "mlflow_run_id", "modelo_nombre", "modelo_version"}}
|
||||
predictions = model_prediction_repository.list(limit=200, **filters)
|
||||
return jsonify({"predictions": [p.model_dump() for p in predictions]})
|
||||
|
||||
|
||||
@governance_bp.get("/ocr/jobs")
|
||||
def list_ocr_jobs():
|
||||
"""The configured OCR jobs, with the result columns each one fills."""
|
||||
jobs = [
|
||||
{
|
||||
"domain": job.domain,
|
||||
"entity": job.entity,
|
||||
"label": job.label,
|
||||
"result_fields": list(job.columns.result_field_map.values()),
|
||||
}
|
||||
for job in OCR_JOBS.values()
|
||||
]
|
||||
return jsonify({"jobs": jobs})
|
||||
|
||||
|
||||
@governance_bp.get("/ocr/<domain>/<entity>/rows")
|
||||
def list_ocr_rows(domain: str, entity: str):
|
||||
"""Rows of an OCR job filtered by `status`: `review` (the default, rows
|
||||
flagged `requiere_revision`), `pending`, `failed`, `done` or `all`.
|
||||
|
||||
Filtering happens in Python because `Repository.list` only supports
|
||||
equality filters; a review queue is small."""
|
||||
job = _ocr_job_or_404(domain, entity)
|
||||
if job is None:
|
||||
return jsonify({"error": f"no hay job de OCR registrado para (domain={domain!r}, entity={entity!r})"}), 404
|
||||
repository, spec = job
|
||||
|
||||
status = request.args.get("status", "review")
|
||||
limit = int(request.args.get("limit", 100))
|
||||
offset = int(request.args.get("offset", 0))
|
||||
pk_name = _pk_name(repository)
|
||||
|
||||
def matches(row) -> bool:
|
||||
if getattr(row, spec.blob_field, None) is None:
|
||||
return False
|
||||
estatus = getattr(row, spec.estatus_field, None)
|
||||
if status == "all":
|
||||
return True
|
||||
if status == "review":
|
||||
return bool(getattr(row, spec.requiere_revision_field, None))
|
||||
if status == "pending":
|
||||
return estatus in (None, OcrEstatus.PENDIENTE.value)
|
||||
if status == "failed":
|
||||
return estatus == OcrEstatus.FALLIDO.value
|
||||
if status == "done":
|
||||
return estatus == OcrEstatus.REALIZADO.value
|
||||
return True
|
||||
|
||||
candidates = [row for row in repository.list(limit=2000) if matches(row)]
|
||||
page = candidates[offset : offset + limit]
|
||||
rows = [
|
||||
{
|
||||
"id": getattr(row, pk_name),
|
||||
"pac_id_hospital": getattr(row, "pac_id_hospital", None),
|
||||
"values": {column: getattr(row, column, None) for column in spec.result_field_map.values()},
|
||||
"confianza": getattr(row, spec.confianza_field, None),
|
||||
"estatus": getattr(row, spec.estatus_field, None),
|
||||
"requiere_revision": getattr(row, spec.requiere_revision_field, None),
|
||||
"metodo_principal": getattr(row, spec.metodo_principal_field, None),
|
||||
"metodo_alternativo": getattr(row, spec.metodo_alternativo_field, None),
|
||||
}
|
||||
for row in page
|
||||
]
|
||||
return jsonify({"rows": rows, "total": len(candidates)})
|
||||
|
||||
|
||||
@governance_bp.get("/ocr/<domain>/<entity>/<int:pk>/blob")
|
||||
def get_ocr_blob(domain: str, entity: str, pk: int):
|
||||
"""Raw bytes of the row's stored PDF, for the review UI's page viewer."""
|
||||
job = _ocr_job_or_404(domain, entity)
|
||||
if job is None:
|
||||
return jsonify({"error": f"no hay job de OCR registrado para (domain={domain!r}, entity={entity!r})"}), 404
|
||||
repository, spec = job
|
||||
row = repository.get(pk)
|
||||
if row is None:
|
||||
return jsonify({"error": "not found"}), 404
|
||||
blob = getattr(row, spec.blob_field, None)
|
||||
if blob is None:
|
||||
return jsonify({"error": "esta fila no tiene un PDF almacenado"}), 404
|
||||
return Response(blob, mimetype="application/pdf")
|
||||
|
||||
|
||||
@governance_bp.post("/ocr/<domain>/<entity>/<int:pk>/correct")
|
||||
def correct_ocr_row(domain: str, entity: str, pk: int):
|
||||
"""Stores values entered by a reviewer for an OCR row. Marks the row
|
||||
done with method "manual" (VAR-03), clears `requiere_revision`, and logs
|
||||
an `ExtractionRun` like an automated run (VAR-07/08)."""
|
||||
job = _ocr_job_or_404(domain, entity)
|
||||
if job is None:
|
||||
return jsonify({"error": f"no hay job de OCR registrado para (domain={domain!r}, entity={entity!r})"}), 404
|
||||
repository, spec = job
|
||||
|
||||
body = request.get_json(silent=True) or {}
|
||||
values = body.get("values")
|
||||
if not isinstance(values, dict) or not values:
|
||||
return jsonify({"error": "'values' es requerido y debe tener al menos un campo"}), 400
|
||||
allowed = set(spec.result_field_map.values())
|
||||
unknown = set(values) - allowed
|
||||
if unknown:
|
||||
return jsonify({"error": f"columnas no permitidas para esta entidad: {sorted(unknown)}"}), 400
|
||||
|
||||
with repository.open_session() as session:
|
||||
tracked = session.get(repository.model, pk)
|
||||
if tracked is None:
|
||||
return jsonify({"error": "not found"}), 404
|
||||
for column, value in values.items():
|
||||
setattr(tracked, column, value)
|
||||
setattr(tracked, spec.estatus_field, OcrEstatus.REALIZADO.value)
|
||||
setattr(tracked, spec.requiere_revision_field, False)
|
||||
setattr(tracked, spec.metodo_principal_field, "manual")
|
||||
setattr(tracked, spec.metodo_alternativo_field, None)
|
||||
setattr(tracked, spec.confianza_field, float(body["confianza"]) if "confianza" in body else 1.0)
|
||||
session.add(tracked)
|
||||
session.commit()
|
||||
session.refresh(tracked)
|
||||
updated = tracked.model_dump()
|
||||
|
||||
extraction_run_repository.create(
|
||||
ExtractionRun(
|
||||
domain=domain,
|
||||
entity=entity,
|
||||
entity_pk=str(pk),
|
||||
column_extracted=",".join(sorted(values)),
|
||||
transform_description="Corrección manual vía UI de gobernanza — usuario revisó el PDF y escribió el valor directamente.",
|
||||
estatus=EstatusExtraccion.COMPLETADA,
|
||||
)
|
||||
)
|
||||
return jsonify(updated)
|
||||
|
||||
|
||||
@governance_bp.post("/ocr/run")
|
||||
def run_ocr():
|
||||
"""Runs an OCR job over pending rows. Rows already `REALIZADO` are
|
||||
skipped, so repeated calls are safe (VAR-09)."""
|
||||
body = request.get_json(silent=True) or {}
|
||||
domain = body.get("domain")
|
||||
entity = body.get("entity")
|
||||
job = OCR_JOBS.get((domain, entity))
|
||||
if job is None:
|
||||
return jsonify({"error": f"no hay job de OCR registrado para (domain={domain!r}, entity={entity!r})"}), 400
|
||||
|
||||
try:
|
||||
summary = run_pending_extractions(
|
||||
job.repository,
|
||||
job.columns,
|
||||
job.extractor(),
|
||||
domain=domain,
|
||||
entity=entity,
|
||||
governance_repository=extraction_run_repository,
|
||||
source_description=body.get("source_description"),
|
||||
limit=int(body.get("limit", 500)),
|
||||
)
|
||||
except NotImplementedError as exc:
|
||||
return jsonify({"error": str(exc)}), 501
|
||||
|
||||
return jsonify(
|
||||
{
|
||||
"processed": summary.processed,
|
||||
"skipped_already_done": summary.skipped_already_done,
|
||||
"failed": summary.failed,
|
||||
"needs_review": summary.needs_review,
|
||||
}
|
||||
)
|
||||
@@ -0,0 +1,311 @@
|
||||
"""Import routes. They only parse the request and shape the response; the
|
||||
work happens in `webapi.imports`. Errors map to HTTP 400 in one place."""
|
||||
import json
|
||||
|
||||
from flask import Blueprint, Response, jsonify, request
|
||||
|
||||
from extraction import BBox, ExtractionError
|
||||
from extraction.readers import reader_for
|
||||
from webapi.imports.connectors import ConnectorError, build_connector, catalog, connector_class, kind_for_filename
|
||||
from webapi.imports.connectors.base import decode_file
|
||||
from webapi.imports.connectors.pdf import PdfConnector
|
||||
from webapi.imports.connectors.sql import SqlConnector
|
||||
from webapi.imports.connectors.tabular import FileConnector
|
||||
from webapi.imports.schemas.registry import ENTITY_REGISTRY
|
||||
from webapi.imports.services.import_service import (
|
||||
ImportRequestError,
|
||||
commit_sources,
|
||||
serialize_errors,
|
||||
validate_source,
|
||||
)
|
||||
from webapi.imports.services.introspection_service import (
|
||||
detect_pdf,
|
||||
document_report,
|
||||
extract_pdf_regions,
|
||||
preview_with_suggestions,
|
||||
)
|
||||
|
||||
imports_bp = Blueprint("imports", __name__)
|
||||
|
||||
|
||||
class BadRequest(Exception):
|
||||
"""Missing or malformed request parameter."""
|
||||
|
||||
|
||||
@imports_bp.errorhandler(BadRequest)
|
||||
@imports_bp.errorhandler(ConnectorError)
|
||||
@imports_bp.errorhandler(ExtractionError)
|
||||
@imports_bp.errorhandler(ImportRequestError)
|
||||
def _bad_request(exc: Exception):
|
||||
return jsonify({"error": str(exc)}), 400
|
||||
|
||||
|
||||
def _json_body() -> dict:
|
||||
body = request.get_json(silent=True)
|
||||
if not isinstance(body, dict):
|
||||
raise BadRequest("request body must be a JSON object")
|
||||
return body
|
||||
|
||||
|
||||
def _require(mapping: dict, key: str):
|
||||
value = mapping.get(key)
|
||||
if value in (None, ""):
|
||||
raise BadRequest(f"missing {key}")
|
||||
return value
|
||||
|
||||
|
||||
def _uploaded_file() -> tuple[str, bytes]:
|
||||
if "file" not in request.files:
|
||||
raise BadRequest("missing file")
|
||||
upload = request.files["file"]
|
||||
return upload.filename or "", upload.read()
|
||||
|
||||
|
||||
def _form_int(key: str, default: int | None = None) -> int:
|
||||
raw = request.form.get(key)
|
||||
if raw is None:
|
||||
if default is None:
|
||||
raise BadRequest(f"missing {key}")
|
||||
return default
|
||||
try:
|
||||
return int(raw)
|
||||
except ValueError as exc:
|
||||
raise BadRequest(f"{key} must be an integer") from exc
|
||||
|
||||
|
||||
def _form_json(key: str, default=None):
|
||||
raw = request.form.get(key)
|
||||
if raw in (None, ""):
|
||||
return default
|
||||
try:
|
||||
return json.loads(raw)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise BadRequest(f"{key} must be JSON: {exc}") from exc
|
||||
|
||||
|
||||
# -- catalog -------------------------------------------------------------------
|
||||
|
||||
|
||||
@imports_bp.get("/connectors")
|
||||
def get_connectors():
|
||||
"""Every source kind the server can read, with what the client needs to
|
||||
offer it (accepted extensions, SQL engines and whether their driver is
|
||||
installed, document segmentation strategies)."""
|
||||
return jsonify({"connectors": catalog()})
|
||||
|
||||
|
||||
@imports_bp.get("/targets")
|
||||
def get_targets():
|
||||
targets = []
|
||||
for key, spec in ENTITY_REGISTRY.items():
|
||||
schema_json = spec.schema.model_json_schema()
|
||||
required = set(schema_json.get("required", []))
|
||||
fields = [
|
||||
{"name": name, "required": name in required, "type": _json_schema_type(prop)}
|
||||
for name, prop in schema_json.get("properties", {}).items()
|
||||
]
|
||||
domain, _, table = key.partition(".")
|
||||
targets.append(
|
||||
{
|
||||
"key": key,
|
||||
"domain": domain,
|
||||
"table": table,
|
||||
"conflict_fields": list(spec.conflict_fields) if spec.conflict_fields else None,
|
||||
"fields": fields,
|
||||
}
|
||||
)
|
||||
return jsonify({"targets": targets})
|
||||
|
||||
|
||||
def _json_schema_type(prop: dict) -> str:
|
||||
"""`Optional[X]` renders as `anyOf: [X, null]`: report X and its format."""
|
||||
candidates = prop.get("anyOf") or [prop]
|
||||
for candidate in candidates:
|
||||
if candidate.get("type") and candidate["type"] != "null":
|
||||
return candidate.get("format") or candidate["type"]
|
||||
return "string"
|
||||
|
||||
|
||||
# -- generic preview --------------------------------------------------------------
|
||||
|
||||
|
||||
@imports_bp.post("/sources/file/preview")
|
||||
def preview_file():
|
||||
"""Multipart upload of any file connector (`source_kind` may be omitted
|
||||
and is then inferred from the file name)."""
|
||||
name, raw = _uploaded_file()
|
||||
kind = request.form.get("source_kind") or kind_for_filename(name)
|
||||
cls = connector_class(kind)
|
||||
if not issubclass(cls, FileConnector):
|
||||
raise BadRequest(f"{kind!r} is not a file source")
|
||||
options = _form_json("options", {}) or {}
|
||||
if "file_name" in cls.option_names:
|
||||
options.setdefault("file_name", name)
|
||||
connector = cls.from_bytes(raw, options)
|
||||
return jsonify(preview_with_suggestions(connector, request.form.get("target")))
|
||||
|
||||
|
||||
@imports_bp.post("/sources/<kind>/preview")
|
||||
def preview_source(kind: str):
|
||||
"""JSON preview for any connector: `{"payload": {...}, "target": "cacu.Paciente"}`,
|
||||
the same payload an import source carries."""
|
||||
body = _json_body()
|
||||
payload = _require(body, "payload")
|
||||
if kind == "document":
|
||||
payload = {**payload, "target": payload.get("target") or body.get("target")}
|
||||
return jsonify(preview_with_suggestions(build_connector(kind, payload), body.get("target")))
|
||||
|
||||
|
||||
# -- SQL browsing -------------------------------------------------------------------
|
||||
|
||||
|
||||
@imports_bp.post("/sources/sql/test-connection")
|
||||
def sql_test_connection():
|
||||
connector = SqlConnector.connect(_json_body())
|
||||
connector.test_connection()
|
||||
return jsonify({"ok": True, "dialect": connector.get_dialect()})
|
||||
|
||||
|
||||
@imports_bp.post("/sources/sql/schemas")
|
||||
def sql_schemas():
|
||||
return jsonify({"schemas": SqlConnector.connect(_json_body()).list_schemas()})
|
||||
|
||||
|
||||
@imports_bp.post("/sources/sql/tables")
|
||||
def sql_tables():
|
||||
body = _json_body()
|
||||
return jsonify({"tables": SqlConnector.connect(body).list_tables(schema=body.get("schema"))})
|
||||
|
||||
|
||||
@imports_bp.post("/sources/sql/columns")
|
||||
def sql_columns():
|
||||
body = _json_body()
|
||||
columns = SqlConnector.connect(body).list_columns(_require(body, "table"), schema=body.get("schema"))
|
||||
return jsonify({"columns": [{"name": c.name, "inferred_type": c.inferred_type} for c in columns]})
|
||||
|
||||
|
||||
@imports_bp.post("/sources/sql/preview")
|
||||
def sql_preview():
|
||||
body = _json_body()
|
||||
connector = SqlConnector.connect(body)
|
||||
if body.get("query"):
|
||||
connector.select_query(body["query"])
|
||||
else:
|
||||
connector.select_table(_require(body, "table"), schema=body.get("schema"))
|
||||
return jsonify(preview_with_suggestions(connector, body.get("target")))
|
||||
|
||||
|
||||
# -- PDF tables -------------------------------------------------------------------------
|
||||
|
||||
|
||||
@imports_bp.post("/sources/pdf/detect")
|
||||
def pdf_detect():
|
||||
return jsonify(detect_pdf(_uploaded_file()[1]))
|
||||
|
||||
|
||||
@imports_bp.post("/sources/pdf/page-image")
|
||||
def pdf_page_image():
|
||||
png = PdfConnector(_uploaded_file()[1]).render_page_image(_form_int("page_number"), dpi=_form_int("dpi", 150))
|
||||
return Response(png, mimetype="image/png")
|
||||
|
||||
|
||||
@imports_bp.post("/sources/pdf/table/preview")
|
||||
def pdf_table_preview():
|
||||
raw = _uploaded_file()[1]
|
||||
page_number = _form_int("page_number")
|
||||
bbox = _form_json("bbox")
|
||||
if not isinstance(bbox, list) or len(bbox) != 4:
|
||||
raise BadRequest("missing page_number or bbox")
|
||||
connector = PdfConnector(raw)
|
||||
connector.select_table(page_number, tuple(float(v) for v in bbox))
|
||||
return jsonify(preview_with_suggestions(connector, request.form.get("target")))
|
||||
|
||||
|
||||
@imports_bp.post("/sources/pdf/regions/extract")
|
||||
def pdf_regions_extract():
|
||||
body = _json_body()
|
||||
raw = decode_file(body)
|
||||
regions = _require(body, "regions")
|
||||
return jsonify(extract_pdf_regions(raw, regions, dpi=int(body.get("dpi", 150)), target_key=body.get("target")))
|
||||
|
||||
|
||||
# -- documents ------------------------------------------------------------------------------
|
||||
|
||||
|
||||
@imports_bp.post("/sources/document/extract")
|
||||
def document_extract():
|
||||
"""Reads the documents, splits them into patient records and extracts
|
||||
the target's fields: `{files: [{name, file_base64}], target,
|
||||
segmentation?, pages_per_record?, ocr_mode?, key_pattern?, overrides?}`.
|
||||
Each record comes back with per-field confidence and evidence, conflicts
|
||||
between sources, and the images found on its pages."""
|
||||
body = _json_body()
|
||||
_require(body, "target")
|
||||
if not body.get("files"):
|
||||
raise BadRequest("missing files")
|
||||
return jsonify(document_report(body))
|
||||
|
||||
|
||||
@imports_bp.post("/sources/document/page-image")
|
||||
def document_page_image():
|
||||
"""PNG of one page of any supported document; with `bbox` (normalized,
|
||||
JSON list) only that region, e.g. an embedded image."""
|
||||
name, raw = _uploaded_file()
|
||||
reader = reader_for(name, raw)
|
||||
page_number = _form_int("page_number")
|
||||
dpi = min(max(_form_int("dpi", 150), 50), 300)
|
||||
bbox = _form_json("bbox")
|
||||
if bbox is None:
|
||||
return Response(reader.render_page(raw, page_number, dpi=dpi), mimetype="image/png")
|
||||
if not isinstance(bbox, list) or len(bbox) != 4:
|
||||
raise BadRequest("bbox must be [x0, y0, x1, y1]")
|
||||
return Response(reader.render_region(raw, page_number, BBox(*map(float, bbox)), dpi=dpi), mimetype="image/png")
|
||||
|
||||
|
||||
# -- validate and load -------------------------------------------------------------------------
|
||||
|
||||
|
||||
@imports_bp.post("/validate")
|
||||
def validate():
|
||||
result = validate_source(_require(_json_body(), "source"))
|
||||
return jsonify(
|
||||
{
|
||||
"total_rows": result.total_rows,
|
||||
"valid_count": result.valid_count,
|
||||
"error_count": result.error_count,
|
||||
"errors": serialize_errors(result),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@imports_bp.post("/commit")
|
||||
def commit():
|
||||
"""`{sources: [...], on_conflict: "reject"|"upsert", merge_duplicates: bool}`.
|
||||
With `merge_duplicates`, rows of different sources sharing a natural key
|
||||
are combined into one record before writing."""
|
||||
body = _json_body()
|
||||
results = commit_sources(
|
||||
_require(body, "sources"),
|
||||
on_conflict=body.get("on_conflict", "reject"),
|
||||
merge=bool(body.get("merge_duplicates", False)),
|
||||
)
|
||||
return jsonify(
|
||||
{
|
||||
"ok": all(r.rejected == 0 for r in results),
|
||||
"results": [
|
||||
{
|
||||
"target": r.target,
|
||||
"label": r.label,
|
||||
"total": r.total,
|
||||
"created": r.created,
|
||||
"updated": r.updated,
|
||||
"rejected": r.rejected,
|
||||
"merged": r.merged,
|
||||
"errors": r.errors,
|
||||
"warnings": r.warnings,
|
||||
"linked": r.linked,
|
||||
}
|
||||
for r in results
|
||||
],
|
||||
}
|
||||
)
|
||||
@@ -1,13 +1,17 @@
|
||||
from flask import Blueprint, jsonify
|
||||
from flask import Blueprint, jsonify, request
|
||||
|
||||
from models.prediction import ApplicabilityRejected, PredictionService
|
||||
from models.tea import TeaModel
|
||||
from persistance.db import get_tea_session
|
||||
from persistance.tea import pacientes_repository
|
||||
from webapi.indicadores import registrar_indicadores
|
||||
|
||||
tea_bp = Blueprint("tea", __name__)
|
||||
registrar_indicadores(tea_bp, "tea", get_tea_session)
|
||||
|
||||
|
||||
@tea_bp.get("/pacientes/<string:pac_id>")
|
||||
def get_paciente(pac_id: str):
|
||||
@tea_bp.get("/pacientes/<int:pac_id>")
|
||||
def get_paciente(pac_id: int):
|
||||
paciente = pacientes_repository.get(pac_id)
|
||||
if paciente is None:
|
||||
return jsonify({"error": "not found"}), 404
|
||||
@@ -16,8 +20,21 @@ def get_paciente(pac_id: str):
|
||||
|
||||
@tea_bp.post("/predict")
|
||||
def predict():
|
||||
model = TeaModel()
|
||||
"""Predict and record the result against the active `ModelVersion` (MLD-4/MLD-5).
|
||||
|
||||
Returns 501 while `TeaModel.predict` is not implemented."""
|
||||
body = request.get_json(silent=True) or {}
|
||||
service = PredictionService(TeaModel(), domain="tea", scenario=body.get("scenario", "tamizaje"))
|
||||
try:
|
||||
return jsonify({"prediction": model.predict(data=None)})
|
||||
prediction = service.predict_and_record(
|
||||
body.get("data"),
|
||||
pac_id_hospital=body.get("pac_id_hospital", ""),
|
||||
episodio_id=body.get("episodio_id"),
|
||||
)
|
||||
except NotImplementedError as exc:
|
||||
return jsonify({"error": str(exc)}), 501
|
||||
except ApplicabilityRejected as exc:
|
||||
return jsonify({"error": str(exc)}), 422
|
||||
except RuntimeError as exc:
|
||||
return jsonify({"error": str(exc)}), 503
|
||||
return jsonify(prediction.model_dump())
|
||||
|
||||
Reference in New Issue
Block a user