add import audit trail, live indicator recompute, reportes endpoints; production hardening
This commit is contained in:
+1
-1
@@ -68,7 +68,7 @@ def create_app() -> Flask:
|
||||
@app.errorhandler(413)
|
||||
def too_large(_exc):
|
||||
limit_mb = app.config["MAX_CONTENT_LENGTH"] // (1024 * 1024)
|
||||
return jsonify({"error": f"request larger than {limit_mb} MB"}), 413
|
||||
return jsonify({"error": f"la solicitud excede {limit_mb} MB"}), 413
|
||||
|
||||
app.register_blueprint(cacu_bp, url_prefix="/cacu")
|
||||
app.register_blueprint(cama_bp, url_prefix="/cama")
|
||||
|
||||
@@ -1,41 +1,7 @@
|
||||
from flask import Blueprint, jsonify, request
|
||||
from flask import Blueprint
|
||||
|
||||
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):
|
||||
"""Read one CaCu patient by primary key."""
|
||||
paciente = paciente_repository.get(pac_id)
|
||||
if paciente is None:
|
||||
return jsonify({"error": "not found"}), 404
|
||||
return jsonify(paciente.model_dump())
|
||||
|
||||
|
||||
@cacu_bp.post("/predict")
|
||||
def predict():
|
||||
"""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:
|
||||
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,38 +1,7 @@
|
||||
from flask import Blueprint, jsonify, request
|
||||
from flask import Blueprint
|
||||
|
||||
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>")
|
||||
def get_paciente(pac_id: int):
|
||||
paciente = paciente_repository.get(pac_id)
|
||||
if paciente is None:
|
||||
return jsonify({"error": "not found"}), 404
|
||||
return jsonify(paciente.model_dump())
|
||||
|
||||
|
||||
@cama_bp.post("/predict")
|
||||
def predict():
|
||||
"""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:
|
||||
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())
|
||||
|
||||
@@ -13,12 +13,12 @@ _MAX_PAGE = 500
|
||||
def list_rows(target: str):
|
||||
spec = ENTITY_REGISTRY.get(target)
|
||||
if spec is None:
|
||||
return jsonify({"error": f"unknown target: {target!r}"}), 404
|
||||
return jsonify({"error": f"destino desconocido: {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
|
||||
return jsonify({"error": "limit y offset deben ser números enteros"}), 400
|
||||
rows = spec.repository.list(limit=limit, offset=offset)
|
||||
return jsonify(
|
||||
{
|
||||
|
||||
+27
-101
@@ -1,29 +1,19 @@
|
||||
"""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.
|
||||
their promotion, 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.
|
||||
Versions and artifacts live in MLflow (`models.registry`); training runs
|
||||
elsewhere and registers its result through `POST /model-versions`, naming
|
||||
the indicator kit cohort build it was trained on (`cohorte_armado_id`).
|
||||
"""
|
||||
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 flask import Blueprint, Response, jsonify, request
|
||||
from models.ocr import OCR_JOBS, OcrJob, 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.governance import extraction_run_repository
|
||||
from persistance.repository import Repository
|
||||
|
||||
governance_bp = Blueprint("governance", __name__)
|
||||
@@ -39,9 +29,11 @@ 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:
|
||||
def _ocr_job(domain: str | None, entity: str | None) -> OcrJob:
|
||||
job = OCR_JOBS.get((domain, entity))
|
||||
return (job.repository, job.columns) if job else None
|
||||
if job is None:
|
||||
raise LookupError(f"no hay un trabajo de OCR registrado para (domain={domain!r}, entity={entity!r})")
|
||||
return job
|
||||
|
||||
|
||||
def _pk_name(repository: Repository) -> str:
|
||||
@@ -61,7 +53,7 @@ def list_model_versions():
|
||||
@governance_bp.post("/model-versions")
|
||||
def register_model_version():
|
||||
"""Registers a trained version: `{domain, scenario,
|
||||
environment: DEV|PROD, cohort_version_id?, metrics?, hyperparameters?,
|
||||
environment: DEV|PROD, cohorte_armado_id?, metrics?, hyperparameters?,
|
||||
technical_validation_report_uri?, clinical_validation_report_uri?,
|
||||
interpretability_report_uri?}`."""
|
||||
body = request.get_json(silent=True) or {}
|
||||
@@ -72,7 +64,7 @@ def register_model_version():
|
||||
domain=body["domain"],
|
||||
scenario=body["scenario"],
|
||||
environment=body["environment"],
|
||||
cohort_version_id=body.get("cohort_version_id"),
|
||||
cohorte_armado_id=body.get("cohorte_armado_id"),
|
||||
metrics=body.get("metrics"),
|
||||
hyperparameters=body.get("hyperparameters"),
|
||||
**{k: body[k] for k in REPORT_TAGS if k in body},
|
||||
@@ -80,11 +72,6 @@ def register_model_version():
|
||||
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."""
|
||||
@@ -121,19 +108,9 @@ def retire_model_version(domain: str, scenario: str, version: str):
|
||||
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."""
|
||||
"""Multipart `file` and `kind` (ArtifactKind); logged to the version's MLflow run."""
|
||||
from core.governance.enums import ArtifactKind
|
||||
|
||||
upload = request.files.get("file")
|
||||
@@ -146,48 +123,7 @@ def upload_artifact(domain: str, scenario: str, version: str):
|
||||
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]})
|
||||
# -- OCR ---------------------------------------------------------------------------------
|
||||
|
||||
|
||||
@governance_bp.get("/ocr/jobs")
|
||||
@@ -209,13 +145,9 @@ def list_ocr_jobs():
|
||||
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
|
||||
Filtering happens in Python: `Repository.list` only supports equality."""
|
||||
job = _ocr_job(domain, entity)
|
||||
repository, spec = job.repository, job.columns
|
||||
|
||||
status = request.args.get("status", "review")
|
||||
limit = int(request.args.get("limit", 100))
|
||||
@@ -238,7 +170,7 @@ def list_ocr_rows(domain: str, entity: str):
|
||||
return estatus == OcrEstatus.REALIZADO.value
|
||||
return True
|
||||
|
||||
candidates = [row for row in repository.list(limit=2000) if matches(row)]
|
||||
candidates = [row for row in repository.iter_all() if matches(row)]
|
||||
page = candidates[offset : offset + limit]
|
||||
rows = [
|
||||
{
|
||||
@@ -259,13 +191,11 @@ def list_ocr_rows(domain: str, entity: str):
|
||||
@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
|
||||
job = _ocr_job(domain, entity)
|
||||
repository, spec = job.repository, job.columns
|
||||
row = repository.get(pk)
|
||||
if row is None:
|
||||
return jsonify({"error": "not found"}), 404
|
||||
return jsonify({"error": "no se encontró el registro"}), 404
|
||||
blob = getattr(row, spec.blob_field, None)
|
||||
if blob is None:
|
||||
return jsonify({"error": "esta fila no tiene un PDF almacenado"}), 404
|
||||
@@ -277,10 +207,8 @@ 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
|
||||
job = _ocr_job(domain, entity)
|
||||
repository, spec = job.repository, job.columns
|
||||
|
||||
body = request.get_json(silent=True) or {}
|
||||
values = body.get("values")
|
||||
@@ -294,7 +222,7 @@ def correct_ocr_row(domain: str, entity: str, pk: int):
|
||||
with repository.open_session() as session:
|
||||
tracked = session.get(repository.model, pk)
|
||||
if tracked is None:
|
||||
return jsonify({"error": "not found"}), 404
|
||||
return jsonify({"error": "no se encontró el registro"}), 404
|
||||
for column, value in values.items():
|
||||
setattr(tracked, column, value)
|
||||
setattr(tracked, spec.estatus_field, OcrEstatus.REALIZADO.value)
|
||||
@@ -313,7 +241,7 @@ def correct_ocr_row(domain: str, entity: str, pk: int):
|
||||
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.",
|
||||
transform_description="Corrección manual",
|
||||
estatus=EstatusExtraccion.COMPLETADA,
|
||||
)
|
||||
)
|
||||
@@ -327,9 +255,7 @@ def run_ocr():
|
||||
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
|
||||
job = _ocr_job(domain, entity)
|
||||
|
||||
try:
|
||||
summary = run_pending_extractions(
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""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
|
||||
import logging
|
||||
|
||||
from flask import Blueprint, Response, jsonify, request
|
||||
|
||||
@@ -14,6 +15,7 @@ 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 (
|
||||
DatabaseRefused,
|
||||
ImportRequestError,
|
||||
commit_sources,
|
||||
serialize_errors,
|
||||
@@ -28,6 +30,7 @@ from webapi.imports.services.introspection_service import (
|
||||
)
|
||||
|
||||
imports_bp = Blueprint("imports", __name__)
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class BadRequest(Exception):
|
||||
@@ -45,20 +48,20 @@ def _bad_request(exc: Exception):
|
||||
def _json_body() -> dict:
|
||||
body = request.get_json(silent=True)
|
||||
if not isinstance(body, dict):
|
||||
raise BadRequest("request body must be a JSON object")
|
||||
raise BadRequest("el cuerpo de la solicitud debe ser un objeto JSON")
|
||||
return body
|
||||
|
||||
|
||||
def _require(mapping: dict, key: str):
|
||||
value = mapping.get(key)
|
||||
if value in (None, ""):
|
||||
raise BadRequest(f"missing {key}")
|
||||
raise BadRequest(f"falta {key}")
|
||||
return value
|
||||
|
||||
|
||||
def _uploaded_file() -> tuple[str, bytes]:
|
||||
if "file" not in request.files:
|
||||
raise BadRequest("missing file")
|
||||
raise BadRequest("falta el archivo")
|
||||
upload = request.files["file"]
|
||||
return upload.filename or "", upload.read()
|
||||
|
||||
@@ -67,12 +70,12 @@ 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}")
|
||||
raise BadRequest(f"falta {key}")
|
||||
return default
|
||||
try:
|
||||
return int(raw)
|
||||
except ValueError as exc:
|
||||
raise BadRequest(f"{key} must be an integer") from exc
|
||||
raise BadRequest(f"{key} debe ser un número entero") from exc
|
||||
|
||||
|
||||
def _form_json(key: str, default=None):
|
||||
@@ -82,12 +85,12 @@ def _form_json(key: str, default=None):
|
||||
try:
|
||||
return json.loads(raw)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise BadRequest(f"{key} must be JSON: {exc}") from exc
|
||||
raise BadRequest(f"{key} debe ser JSON válido: {exc}") from exc
|
||||
|
||||
|
||||
def _outcome(exc: Exception) -> str:
|
||||
"""How an attempt that raised is logged."""
|
||||
if isinstance(exc, ImportRequestError) and str(exc).startswith("the database refused"):
|
||||
if isinstance(exc, DatabaseRefused):
|
||||
return "rechazada_por_la_base"
|
||||
if isinstance(exc, (BadRequest, ConnectorError, ExtractionError, ImportRequestError)):
|
||||
return "solicitud_invalida"
|
||||
@@ -148,7 +151,7 @@ def preview_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")
|
||||
raise BadRequest(f"{kind!r} no es una fuente de archivo")
|
||||
options = _form_json("options", {}) or {}
|
||||
if "file_name" in cls.option_names:
|
||||
options.setdefault("file_name", name)
|
||||
@@ -226,7 +229,7 @@ def pdf_table_preview():
|
||||
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")
|
||||
raise BadRequest("falta page_number o 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")))
|
||||
@@ -253,7 +256,7 @@ def document_extract():
|
||||
body = _json_body()
|
||||
_require(body, "target")
|
||||
if not body.get("files"):
|
||||
raise BadRequest("missing files")
|
||||
raise BadRequest("faltan los archivos")
|
||||
return jsonify(document_report(body))
|
||||
|
||||
|
||||
@@ -269,7 +272,7 @@ def document_page_image():
|
||||
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]")
|
||||
raise BadRequest("bbox debe ser [x0, y0, x1, y1]")
|
||||
return Response(reader.render_region(raw, page_number, BBox(*map(float, bbox)), dpi=dpi), mimetype="image/png")
|
||||
|
||||
|
||||
@@ -317,14 +320,19 @@ def commit():
|
||||
audit.succeed()
|
||||
finally:
|
||||
import_audit.record(audit)
|
||||
written = sum(r.created + r.updated for r in results)
|
||||
if written and audit.domain:
|
||||
ColaDeRecalculo().solicitar(audit.domain)
|
||||
recalculating = False
|
||||
if audit.domain and any(r.created or r.updated for r in results):
|
||||
try:
|
||||
ColaDeRecalculo().solicitar(audit.domain)
|
||||
recalculating = True
|
||||
except OSError:
|
||||
# The rows are already saved; failing here would invite a duplicate retry.
|
||||
log.exception("no se pudo solicitar el recálculo de %s", audit.domain)
|
||||
return jsonify(
|
||||
{
|
||||
"ok": all(r.rejected == 0 for r in results),
|
||||
"audit_id": audit.id,
|
||||
"indicadores_en_recalculo": bool(written and audit.domain),
|
||||
"indicadores_en_recalculo": recalculating,
|
||||
"results": [
|
||||
{
|
||||
"target": r.target,
|
||||
|
||||
@@ -1,40 +1,7 @@
|
||||
from flask import Blueprint, jsonify, request
|
||||
|
||||
from models.prediction import ApplicabilityRejected, PredictionService
|
||||
from models.tea import TeaModel
|
||||
from flask import Blueprint
|
||||
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/<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
|
||||
return jsonify(paciente.model_dump())
|
||||
|
||||
|
||||
@tea_bp.post("/predict")
|
||||
def predict():
|
||||
"""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:
|
||||
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())
|
||||
|
||||
+6
-15
@@ -8,8 +8,8 @@ A rejected catalog value is written verbatim only when at least
|
||||
`WEBAPI_REPORT_MIN_COUNT` rows share it, so a rare (identifying) value never
|
||||
appears.
|
||||
|
||||
`ImportAudit` collects the facts while the import runs; an `AuditSink`
|
||||
decides where the finished record goes.
|
||||
`ImportAudit` collects the facts while the import runs; `JsonlAuditSink`
|
||||
appends the finished record.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -19,7 +19,6 @@ import os
|
||||
import re
|
||||
import time
|
||||
import uuid
|
||||
from abc import ABC, abstractmethod
|
||||
from collections import Counter, defaultdict
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timezone
|
||||
@@ -246,15 +245,7 @@ class ImportAudit:
|
||||
return record
|
||||
|
||||
|
||||
class AuditSink(ABC):
|
||||
@abstractmethod
|
||||
def write(self, record: dict[str, Any]) -> None: ...
|
||||
|
||||
@abstractmethod
|
||||
def read(self) -> list[dict[str, Any]]: ...
|
||||
|
||||
|
||||
class JsonlAuditSink(AuditSink):
|
||||
class JsonlAuditSink:
|
||||
"""One JSON object per line; appends are locked so several gunicorn
|
||||
workers can share the file."""
|
||||
|
||||
@@ -287,14 +278,14 @@ class JsonlAuditSink(AuditSink):
|
||||
return records
|
||||
|
||||
|
||||
def default_sink() -> AuditSink:
|
||||
def default_sink() -> JsonlAuditSink:
|
||||
return JsonlAuditSink(report_dir() / "importaciones.jsonl")
|
||||
|
||||
|
||||
def record(audit: ImportAudit, sink: AuditSink | None = None) -> None:
|
||||
def record(audit: ImportAudit) -> None:
|
||||
"""Writes the record; a full disk must not turn a successful import into an error."""
|
||||
try:
|
||||
(sink or default_sink()).write(audit.as_dict())
|
||||
default_sink().write(audit.as_dict())
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
@@ -53,9 +53,6 @@ class Connector(ABC):
|
||||
"""Builds a ready-to-read connector from the JSON a client sends
|
||||
in an import request's `payload`."""
|
||||
|
||||
@abstractmethod
|
||||
def get_columns(self) -> list[SourceColumn]: ...
|
||||
|
||||
@abstractmethod
|
||||
def preview(self, *, limit: int = 20) -> PreviewResult: ...
|
||||
|
||||
@@ -88,6 +85,6 @@ def decode_file(payload: dict[str, Any], key: str = "file_base64") -> bytes:
|
||||
try:
|
||||
return base64.b64decode(payload[key], validate=True)
|
||||
except KeyError as exc:
|
||||
raise ConnectorError(f"missing {key}") from exc
|
||||
raise ConnectorError(f"falta {key}") from exc
|
||||
except (binascii.Error, ValueError, TypeError) as exc:
|
||||
raise ConnectorError(f"{key} is not valid base64: {exc}") from exc
|
||||
raise ConnectorError(f"{key} no es base64 válido: {exc}") from exc
|
||||
|
||||
@@ -30,7 +30,7 @@ class CsvConnector(FileConnector):
|
||||
def __init__(self, raw: bytes, *, delimiter: str | None = None, encoding: str | None = None):
|
||||
self._encoding, text = _decode(raw, encoding)
|
||||
if "\x00" in text:
|
||||
raise ConnectorError("file looks binary, not a delimited text file")
|
||||
raise ConnectorError("el archivo parece binario, no un texto delimitado")
|
||||
self._delimiter = delimiter or _sniff_delimiter(text)
|
||||
try:
|
||||
self._df = pd.read_csv(
|
||||
@@ -42,7 +42,7 @@ class CsvConnector(FileConnector):
|
||||
skipinitialspace=True,
|
||||
)
|
||||
except Exception as exc: # pandas raises a variety of error types
|
||||
raise ConnectorError(f"could not parse CSV: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudo leer el CSV: {exc}") from exc
|
||||
self._df.columns = [str(c).strip() for c in self._df.columns]
|
||||
|
||||
def _dataframe(self) -> pd.DataFrame:
|
||||
@@ -58,7 +58,7 @@ def _decode(raw: bytes, encoding: str | None) -> tuple[str, str]:
|
||||
return candidate, raw.decode(candidate)
|
||||
except (UnicodeDecodeError, LookupError):
|
||||
continue
|
||||
raise ConnectorError(f"could not decode CSV as {encoding or ' / '.join(_FALLBACK_ENCODINGS)}")
|
||||
raise ConnectorError(f"no se pudo decodificar el CSV como {encoding or ' / '.join(_FALLBACK_ENCODINGS)}")
|
||||
|
||||
|
||||
def _sniff_delimiter(text: str) -> str:
|
||||
|
||||
@@ -82,14 +82,14 @@ class DocumentConnector(DataFrameConnector):
|
||||
overrides: dict[str, dict[str, Any]] | None = None,
|
||||
):
|
||||
if not files:
|
||||
raise ConnectorError("no documents given")
|
||||
raise ConnectorError("no se recibieron documentos")
|
||||
entity = ENTITY_REGISTRY.get(target)
|
||||
if entity is None:
|
||||
raise ConnectorError(f"unknown target: {target!r}")
|
||||
raise ConnectorError(f"destino desconocido: {target!r}")
|
||||
if segmentation not in SEGMENTERS:
|
||||
raise ConnectorError(f"unknown segmentation {segmentation!r} (available: {', '.join(SEGMENTERS)})")
|
||||
raise ConnectorError(f"segmentación desconocida {segmentation!r} (disponibles: {', '.join(SEGMENTERS)})")
|
||||
if ocr_mode not in ("auto", "always", "never"):
|
||||
raise ConnectorError(f"unknown ocr_mode {ocr_mode!r}")
|
||||
raise ConnectorError(f"ocr_mode desconocido {ocr_mode!r}")
|
||||
self.files = files
|
||||
self.target = target
|
||||
self.specs = field_specs_for(entity, key_pattern=key_pattern)
|
||||
@@ -175,12 +175,9 @@ class DocumentConnector(DataFrameConnector):
|
||||
return combine_pages(parts) if parts else None
|
||||
|
||||
def _record_image(self, record: ExtractedRecord) -> bytes | None:
|
||||
"""A PNG of the clearest picture embedded on the record's pages (a
|
||||
mammogram, a lesion photo) — mappable onto a target's own image
|
||||
column (e.g. `mast_dicom_blob`), the same way `documento` maps onto
|
||||
a PDF column. A `scan` is the page itself, not a distinct picture,
|
||||
so a `figure` wins when both are present; with several figures, the
|
||||
first one found is used."""
|
||||
"""A PNG of the first picture embedded on the record's pages (a mammogram,
|
||||
a lesion photo), mappable onto an image column such as `mast_dicom_blob`.
|
||||
A `figure` wins over a `scan`, which is the whole page."""
|
||||
by_name = dict(self.files)
|
||||
candidates = [(document, image) for document, image in record.images if document in by_name]
|
||||
if not candidates:
|
||||
|
||||
@@ -29,19 +29,20 @@ class EdfConnector(FileConnector):
|
||||
extensions = ("edf",)
|
||||
option_names = ("file_name",)
|
||||
|
||||
def __init__(self, raw: bytes, *, file_name: str = "registro.edf"):
|
||||
self.files = [(file_name, raw)]
|
||||
def __init__(self, files: list[tuple[str, bytes]]):
|
||||
self.files = files
|
||||
self._df: pd.DataFrame | None = None
|
||||
|
||||
@classmethod
|
||||
def from_bytes(cls, raw: bytes, options: dict[str, Any] | None = None) -> "EdfConnector":
|
||||
return cls([((options or {}).get("file_name") or "registro.edf", raw)])
|
||||
|
||||
@classmethod
|
||||
def from_payload(cls, payload: dict[str, Any]) -> "EdfConnector":
|
||||
"""Accepts one file (`file_base64` + `options.file_name`) or several
|
||||
(`files: [{name, file_base64}]`)."""
|
||||
"""One file (`file_base64` + `options.file_name`) or several (`files: [{name, file_base64}]`)."""
|
||||
if not payload.get("files"):
|
||||
return super().from_payload(payload)
|
||||
connector = cls(b"", file_name="")
|
||||
connector.files = [(f.get("name") or f"registro_{i}.edf", decode_file(f)) for i, f in enumerate(payload["files"], 1)]
|
||||
return connector
|
||||
return cls([(f.get("name") or f"registro_{i}.edf", decode_file(f)) for i, f in enumerate(payload["files"], 1)])
|
||||
|
||||
def metadata(self) -> dict[str, Any]:
|
||||
return {"files": [name for name, _ in self.files]}
|
||||
|
||||
@@ -25,15 +25,15 @@ class ExcelConnector(FileConnector):
|
||||
try:
|
||||
self._workbook = pd.ExcelFile(io.BytesIO(raw), engine="openpyxl")
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not open Excel file: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudo abrir el archivo de Excel: {exc}") from exc
|
||||
|
||||
self._sheet = sheet_name if sheet_name not in (None, "") else self._workbook.sheet_names[0]
|
||||
if isinstance(self._sheet, str) and self._sheet not in self._workbook.sheet_names:
|
||||
raise ConnectorError(f"sheet {self._sheet!r} not found — available: {self._workbook.sheet_names}")
|
||||
raise ConnectorError(f"no existe la hoja {self._sheet!r} (disponibles: {self._workbook.sheet_names})")
|
||||
try:
|
||||
self._df = self._workbook.parse(self._sheet, dtype=object)
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not read sheet {self._sheet!r}: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudo leer la hoja {self._sheet!r}: {exc}") from exc
|
||||
self._df.columns = [str(c).strip() for c in self._df.columns]
|
||||
|
||||
def list_sheets(self) -> list[str]:
|
||||
|
||||
@@ -26,19 +26,19 @@ class JsonConnector(FileConnector):
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not parse JSON: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudo leer el JSON: {exc}") from exc
|
||||
|
||||
if record_path:
|
||||
try:
|
||||
for key in record_path.split("."):
|
||||
data = data[key]
|
||||
except (KeyError, TypeError, IndexError) as exc:
|
||||
raise ConnectorError(f"record_path {record_path!r} not found: {exc}") from exc
|
||||
raise ConnectorError(f"no se encontró record_path {record_path!r}: {exc}") from exc
|
||||
|
||||
if isinstance(data, dict):
|
||||
data = data.get("data", [data])
|
||||
if not isinstance(data, list) or not all(isinstance(record, dict) for record in data):
|
||||
raise ConnectorError("JSON source must resolve to a list of objects")
|
||||
raise ConnectorError("el JSON debe dar una lista de objetos")
|
||||
|
||||
self._record_path = record_path
|
||||
self._df = pd.DataFrame([_flatten(record) for record in data], dtype=object)
|
||||
|
||||
@@ -54,7 +54,7 @@ class RegionSpec:
|
||||
try:
|
||||
return cls(str(raw["target_field"]), [int(n) for n in raw["page_numbers"]], tuple(float(v) for v in raw["bbox"]))
|
||||
except (KeyError, TypeError, ValueError) as exc:
|
||||
raise ConnectorError(f"invalid region: {exc}") from exc
|
||||
raise ConnectorError(f"región inválida: {exc}") from exc
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -81,7 +81,7 @@ class PdfConnector(DataFrameConnector):
|
||||
elif mode == "regions":
|
||||
connector.extract_regions([RegionSpec.parse(r) for r in payload["regions"]], dpi=int(payload.get("dpi", _DEFAULT_DPI)))
|
||||
else:
|
||||
raise ConnectorError(f"unknown pdf mode: {mode!r}")
|
||||
raise ConnectorError(f"modo de PDF desconocido: {mode!r}")
|
||||
return connector
|
||||
|
||||
def __init__(self, file_bytes: bytes):
|
||||
@@ -89,7 +89,7 @@ class PdfConnector(DataFrameConnector):
|
||||
try:
|
||||
self._pdf = pdfplumber.open(io.BytesIO(file_bytes))
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not open PDF: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudo abrir el PDF: {exc}") from exc
|
||||
|
||||
self._table_grid: list[list[str | None]] | None = None
|
||||
self._region_rows: dict[str, list[str | None]] | None = None
|
||||
@@ -120,12 +120,12 @@ class PdfConnector(DataFrameConnector):
|
||||
try:
|
||||
tables = page.find_tables()
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not detect tables on page {page.page_number}: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudieron detectar tablas en la página {page.page_number}: {exc}") from exc
|
||||
for table in tables:
|
||||
try:
|
||||
grid = table.extract()
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not extract table on page {page.page_number}: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudo extraer la tabla de la página {page.page_number}: {exc}") from exc
|
||||
if len(grid) < 2:
|
||||
continue # header + >=1 data row required
|
||||
candidates.append(
|
||||
@@ -145,9 +145,9 @@ class PdfConnector(DataFrameConnector):
|
||||
cropped = page.within_bbox(bbox, strict=False)
|
||||
grid = cropped.extract_table()
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not extract table at {bbox} on page {page_number}: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudo extraer la tabla en {bbox} de la página {page_number}: {exc}") from exc
|
||||
if not grid or len(grid) < 2:
|
||||
raise ConnectorError(f"no usable table found at {bbox} on page {page_number}")
|
||||
raise ConnectorError(f"no se encontró una tabla utilizable en {bbox} de la página {page_number}")
|
||||
self._table_grid = grid
|
||||
self._region_rows = None
|
||||
|
||||
@@ -161,14 +161,14 @@ class PdfConnector(DataFrameConnector):
|
||||
try:
|
||||
image = page.to_image(resolution=dpi).original
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not render page {page_number}: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudo dibujar la página {page_number}: {exc}") from exc
|
||||
buffer = io.BytesIO()
|
||||
image.save(buffer, format="PNG")
|
||||
return buffer.getvalue()
|
||||
|
||||
def extract_regions(self, regions: list[RegionSpec], dpi: int = _DEFAULT_DPI) -> dict[str, list[str | None]]:
|
||||
if not regions:
|
||||
raise ConnectorError("no regions given")
|
||||
raise ConnectorError("no se indicaron regiones")
|
||||
_check_dpi(dpi)
|
||||
|
||||
by_page: dict[int, list[RegionSpec]] = {}
|
||||
@@ -183,8 +183,9 @@ class PdfConnector(DataFrameConnector):
|
||||
page = self._page(page_number)
|
||||
lines = self._lines_for_page(page, by_page[page_number], dpi)
|
||||
for row in self._cluster_rows(lines, page_number):
|
||||
for region in by_page[page_number]:
|
||||
result[region.target_field].append(row.get(region.target_field))
|
||||
# Every field gets a cell per row, even regions not drawn on this page.
|
||||
for field_name in result:
|
||||
result[field_name].append(row.get(field_name))
|
||||
|
||||
self._region_rows = result
|
||||
self._table_grid = None
|
||||
@@ -210,7 +211,7 @@ class PdfConnector(DataFrameConnector):
|
||||
try:
|
||||
region_lines = page.within_bbox(point_bbox, strict=False).extract_text_lines()
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not extract text for region {region.target_field!r}: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudo extraer el texto de la región {region.target_field!r}: {exc}") from exc
|
||||
for line in region_lines:
|
||||
text = (line.get("text") or "").strip()
|
||||
if not text:
|
||||
@@ -228,7 +229,7 @@ class PdfConnector(DataFrameConnector):
|
||||
try:
|
||||
rendered_image = page.to_image(resolution=dpi).original
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not render page {page.page_number}: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudo dibujar la página {page.page_number}: {exc}") from exc
|
||||
img_w, img_h = rendered_image.size
|
||||
crop_box = (
|
||||
max(0, round(x0n * img_w)),
|
||||
@@ -242,7 +243,7 @@ class PdfConnector(DataFrameConnector):
|
||||
try:
|
||||
data = pytesseract.image_to_data(cropped, output_type=Output.DICT, lang=DEFAULT_LANG, config=_OCR_CONFIG)
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"OCR failed for region {region.target_field!r}: {exc}") from exc
|
||||
raise ConnectorError(f"falló el OCR de la región {region.target_field!r}: {exc}") from exc
|
||||
for words in group_words(data):
|
||||
text = " ".join(w["text"] for w in words).strip()
|
||||
if not text:
|
||||
@@ -306,7 +307,7 @@ class PdfConnector(DataFrameConnector):
|
||||
self.warnings.append(
|
||||
ExtractionWarning(
|
||||
page_number=page_number,
|
||||
message=f"alignment conflict on field(s) {duplicated}: cluster split at largest internal gap",
|
||||
message=f"conflicto de alineación en {duplicated}: el grupo se dividió en el mayor espacio interno",
|
||||
)
|
||||
)
|
||||
return self._split_conflicts(left, page_number) + self._split_conflicts(right, page_number)
|
||||
@@ -322,13 +323,13 @@ class PdfConnector(DataFrameConnector):
|
||||
return pd.DataFrame(data_rows, columns=columns)
|
||||
if self._region_rows is not None:
|
||||
return pd.DataFrame(self._region_rows)
|
||||
raise ConnectorError("no table or region resolved — call select_table() or extract_regions() first")
|
||||
raise ConnectorError("no hay tabla ni regiones seleccionadas")
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _page(self, page_number: int):
|
||||
if not (1 <= page_number <= self.page_count):
|
||||
raise ConnectorError(f"page_number out of range: {page_number}")
|
||||
raise ConnectorError(f"page_number fuera de rango: {page_number}")
|
||||
return self._pdf.pages[page_number - 1]
|
||||
|
||||
@staticmethod
|
||||
@@ -340,7 +341,7 @@ class PdfConnector(DataFrameConnector):
|
||||
|
||||
def _check_dpi(dpi: int) -> None:
|
||||
if not (_MIN_DPI <= dpi <= _MAX_DPI):
|
||||
raise ConnectorError(f"dpi must be between {_MIN_DPI} and {_MAX_DPI}, got {dpi}")
|
||||
raise ConnectorError(f"dpi debe estar entre {_MIN_DPI} y {_MAX_DPI} (se recibió {dpi})")
|
||||
|
||||
|
||||
def _table_confidence(grid: list[list[str | None]]) -> float:
|
||||
|
||||
@@ -16,17 +16,17 @@ def register_connector(cls: type[Connector]) -> type[Connector]:
|
||||
def connector_class(kind: str | None) -> type[Connector]:
|
||||
cls = CONNECTORS.get(kind or "")
|
||||
if cls is None:
|
||||
raise ConnectorError(f"unknown source kind {kind!r} (available: {', '.join(sorted(CONNECTORS))})")
|
||||
raise ConnectorError(f"tipo de fuente desconocido {kind!r} (disponibles: {', '.join(sorted(CONNECTORS))})")
|
||||
return cls
|
||||
|
||||
|
||||
def build_connector(kind: str | None, payload: dict[str, Any]) -> Connector:
|
||||
if not isinstance(payload, dict):
|
||||
raise ConnectorError("payload must be an object")
|
||||
raise ConnectorError("payload debe ser un objeto")
|
||||
try:
|
||||
return connector_class(kind).from_payload(payload)
|
||||
except KeyError as exc:
|
||||
raise ConnectorError(f"missing field in payload: {exc}") from exc
|
||||
raise ConnectorError(f"falta un campo en payload: {exc}") from exc
|
||||
|
||||
|
||||
def kind_for_filename(filename: str) -> str | None:
|
||||
|
||||
@@ -91,21 +91,21 @@ class SqlConnector(Connector):
|
||||
return cls(cls.server_url(payload["server"]))
|
||||
if payload.get("connection_string"):
|
||||
return cls(payload["connection_string"])
|
||||
raise ConnectorError("missing server or connection_string")
|
||||
raise ConnectorError("falta server o connection_string")
|
||||
|
||||
@classmethod
|
||||
def server_url(cls, server: dict[str, Any]) -> sa.engine.URL:
|
||||
engine = cls.ENGINES.get(server.get("engine", ""))
|
||||
if engine is None:
|
||||
raise ConnectorError(f"unknown engine {server.get('engine')!r} (available: {', '.join(cls.ENGINES)})")
|
||||
raise ConnectorError(f"motor desconocido {server.get('engine')!r} (disponibles: {', '.join(cls.ENGINES)})")
|
||||
if not engine.available:
|
||||
raise ConnectorError(f"the {engine.label} driver ({engine.driver_module}) is not installed on the server")
|
||||
raise ConnectorError(f"el controlador de {engine.label} ({engine.driver_module}) no está instalado en el servidor")
|
||||
if not server.get("host") or not server.get("database"):
|
||||
raise ConnectorError("host and database are required")
|
||||
raise ConnectorError("se requieren el servidor (host) y la base de datos")
|
||||
try:
|
||||
port = int(server.get("port") or engine.default_port)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ConnectorError("port must be a number") from exc
|
||||
raise ConnectorError("el puerto debe ser un número") from exc
|
||||
return sa.engine.URL.create(
|
||||
engine.drivername,
|
||||
username=server.get("user") or None,
|
||||
@@ -121,7 +121,7 @@ class SqlConnector(Connector):
|
||||
try:
|
||||
self._engine = sa.create_engine(url, poolclass=NullPool)
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"invalid connection string: {exc}") from exc
|
||||
raise ConnectorError(f"cadena de conexión inválida: {exc}") from exc
|
||||
self._table: sa.Table | None = None
|
||||
self._query: str | None = None
|
||||
|
||||
@@ -134,7 +134,7 @@ class SqlConnector(Connector):
|
||||
except ConnectorError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not connect: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudo conectar: {exc}") from exc
|
||||
|
||||
def get_dialect(self) -> str:
|
||||
return self._engine.dialect.name
|
||||
@@ -143,27 +143,27 @@ class SqlConnector(Connector):
|
||||
try:
|
||||
return sa.inspect(self._engine).get_schema_names()
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not list schemas: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudieron listar los esquemas: {exc}") from exc
|
||||
|
||||
def list_tables(self, *, schema: str | None = None) -> list[str]:
|
||||
try:
|
||||
inspector = sa.inspect(self._engine)
|
||||
return inspector.get_table_names(schema=schema) + inspector.get_view_names(schema=schema)
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not list tables: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudieron listar las tablas: {exc}") from exc
|
||||
|
||||
def list_columns(self, table_name: str, *, schema: str | None = None) -> list[SourceColumn]:
|
||||
try:
|
||||
columns = sa.inspect(self._engine).get_columns(table_name, schema=schema)
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not list columns: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudieron listar las columnas: {exc}") from exc
|
||||
return [SourceColumn(name=c["name"], inferred_type=_sa_type_to_kind(c["type"])) for c in columns]
|
||||
|
||||
def select_table(self, table_name: str, *, schema: str | None = None) -> "SqlConnector":
|
||||
try:
|
||||
self._table = sa.Table(table_name, sa.MetaData(), schema=schema, autoload_with=self._engine)
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not open table {table_name!r}: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudo abrir la tabla {table_name!r}: {exc}") from exc
|
||||
self._query = None
|
||||
return self
|
||||
|
||||
@@ -173,9 +173,6 @@ class SqlConnector(Connector):
|
||||
|
||||
# -- Connector ----------------------------------------------------------
|
||||
|
||||
def get_columns(self) -> list[SourceColumn]:
|
||||
return self.preview(limit=200).columns
|
||||
|
||||
def preview(self, *, limit: int = 20) -> PreviewResult:
|
||||
statement = self._selectable()
|
||||
try:
|
||||
@@ -187,7 +184,7 @@ class SqlConnector(Connector):
|
||||
except ConnectorError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not read rows: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudieron leer las filas: {exc}") from exc
|
||||
return PreviewResult(columns=self._columns(names, rows), sample_rows=rows, total_rows=total)
|
||||
|
||||
def read_rows(self, column_mapping: dict[str, str]) -> Iterator[dict[str, Any]]:
|
||||
@@ -200,7 +197,7 @@ class SqlConnector(Connector):
|
||||
except ConnectorError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not read rows: {exc}") from exc
|
||||
raise ConnectorError(f"no se pudieron leer las filas: {exc}") from exc
|
||||
|
||||
# -- internals ----------------------------------------------------------
|
||||
|
||||
@@ -209,7 +206,7 @@ class SqlConnector(Connector):
|
||||
return sa.select(self._table).subquery("source")
|
||||
if self._query:
|
||||
return _text_subquery(self._query)
|
||||
raise ConnectorError("no table or query selected — call select_table()/select_query() first")
|
||||
raise ConnectorError("no hay tabla ni consulta seleccionada")
|
||||
|
||||
def _columns(self, names: list[str], rows: list[dict[str, Any]]) -> list[SourceColumn]:
|
||||
if self._table is not None:
|
||||
|
||||
@@ -18,7 +18,8 @@ from sqlalchemy.exc import ArgumentError
|
||||
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
|
||||
_DEFAULT_DIALECTS = "mysql,mariadb,postgresql,mssql,oracle"
|
||||
_DEFAULT_DIALECTS = "mysql,mariadb,postgresql,mssql"
|
||||
_DEFAULT_PORTS = {"mysql": 3306, "mariadb": 3306, "postgresql": 5432, "mssql": 1433}
|
||||
_LEADING_COMMENTS = re.compile(r"^\s*((--[^\n]*\n)|(/\*.*?\*/)|\s)*", re.S)
|
||||
|
||||
|
||||
@@ -40,27 +41,27 @@ class SqlSourcePolicy:
|
||||
try:
|
||||
url = connection if isinstance(connection, URL) else make_url(connection)
|
||||
except ArgumentError as exc:
|
||||
raise ConnectorError(f"invalid connection string: {exc}") from exc
|
||||
raise ConnectorError(f"cadena de conexión inválida: {exc}") from exc
|
||||
dialect = url.get_backend_name()
|
||||
if dialect not in self.allowed_dialects:
|
||||
raise ConnectorError(
|
||||
f"dialect {dialect!r} is not allowed for import sources (allowed: {', '.join(sorted(self.allowed_dialects))})"
|
||||
f"el motor {dialect!r} no está permitido como fuente (permitidos: {', '.join(sorted(self.allowed_dialects))})"
|
||||
)
|
||||
if self.allowed_hosts is not None and (url.host or "").lower() not in self.allowed_hosts:
|
||||
raise ConnectorError(f"host {url.host!r} is not in the allowed import-source hosts")
|
||||
raise ConnectorError(f"el servidor {url.host!r} no está entre los permitidos como fuente")
|
||||
if _same_database(url, _own_database_urls()):
|
||||
raise ConnectorError("this connection points at the application's own database — not a valid import source")
|
||||
raise ConnectorError("esta conexión apunta a una base de datos de la propia aplicación; no puede ser una fuente")
|
||||
return url
|
||||
|
||||
@staticmethod
|
||||
def check_query(query: str) -> str:
|
||||
statement = query.strip().rstrip(";").strip()
|
||||
if ";" in statement:
|
||||
raise ConnectorError("custom SQL must be a single statement")
|
||||
raise ConnectorError("la consulta debe ser una sola instrucción")
|
||||
body = _LEADING_COMMENTS.sub("", statement, count=1)
|
||||
first_word = body.split(None, 1)[0].upper() if body else ""
|
||||
if first_word not in ("SELECT", "WITH"):
|
||||
raise ConnectorError("custom SQL must be a SELECT (or WITH ... SELECT) query")
|
||||
raise ConnectorError("la consulta debe ser un SELECT (o WITH ... SELECT)")
|
||||
return statement
|
||||
|
||||
|
||||
@@ -85,6 +86,8 @@ def _same_database(candidate: URL, own: list[URL]) -> bool:
|
||||
def key(url: URL) -> tuple:
|
||||
if url.get_backend_name() == "sqlite":
|
||||
return ("sqlite", os.path.realpath(url.database or ""))
|
||||
return (url.get_backend_name(), (url.host or "localhost").lower(), url.port, (url.database or "").lower())
|
||||
backend = url.get_backend_name()
|
||||
port = url.port or _DEFAULT_PORTS.get(backend)
|
||||
return (backend, (url.host or "localhost").lower(), port, (url.database or "").lower())
|
||||
|
||||
return key(candidate) in {key(url) for url in own}
|
||||
|
||||
@@ -16,9 +16,6 @@ class DataFrameConnector(Connector):
|
||||
@abstractmethod
|
||||
def _dataframe(self) -> pd.DataFrame: ...
|
||||
|
||||
def get_columns(self) -> list[SourceColumn]:
|
||||
return columns_from_dataframe(self._dataframe())
|
||||
|
||||
def preview(self, *, limit: int = 20) -> PreviewResult:
|
||||
df = self._dataframe()
|
||||
return PreviewResult(
|
||||
|
||||
@@ -11,6 +11,8 @@ SYNONYMS: dict[str, set[str]] = {
|
||||
"pac_id_hospital": {
|
||||
"id_hospital", "hospital_id", "expediente", "num_expediente", "no_expediente", "numero_expediente",
|
||||
"exp", "nss", "id_paciente", "paciente_id", "folio_paciente", "clave_paciente",
|
||||
# A source may name the patient column after the entity.
|
||||
"paciente",
|
||||
},
|
||||
"pac_fecha_nacimiento": {"fecha_nacimiento", "dob", "birth_date", "fecha_nac", "fec_nac", "f_nac", "f_nacimiento", "nacimiento"},
|
||||
"pac_sexo": {"sexo", "genero", "gender", "sex"},
|
||||
@@ -31,15 +33,11 @@ SYNONYMS: dict[str, set[str]] = {
|
||||
"bx_cin_grado": {"grado_cin", "cin", "resultado_histopatologico", "diagnostico_histopatologico"},
|
||||
"bh_fecha": {"fecha", "tomada", "fecha_toma", "fecha_muestra"},
|
||||
}
|
||||
# A source may name the patient column after the entity ("Paciente" holding
|
||||
# the expediente).
|
||||
SYNONYMS["pac_id_hospital"] |= {"paciente", "clave_paciente"}
|
||||
|
||||
# Scores per match kind; the 1:1 assignment takes the best-scoring pairs first.
|
||||
_EXACT, _NORMALIZED, _SYNONYM, _UNPREFIXED = 1.0, 0.9, 0.8, 0.75
|
||||
_WORD_FLOOR, _FUZZY_CAP = 0.5, 0.7
|
||||
# Words that carry no meaning for matching ("Fecha *de* solicitud") and are
|
||||
# too short to be anything but units ("kg", "g/dl").
|
||||
# Words that carry no meaning for matching ("Fecha *de* solicitud").
|
||||
_STOPWORDS = {"de", "del", "la", "el", "los", "las", "en", "por", "para", "con"}
|
||||
_NEAR_WORD = 0.8
|
||||
|
||||
@@ -63,6 +61,7 @@ def _normalize(name: str) -> str:
|
||||
|
||||
|
||||
def _words(normalized: str) -> list[str]:
|
||||
"""Meaningful words; two letters or fewer are units ("kg") or noise."""
|
||||
return [w for w in re.split(r"[^a-z0-9]+", normalized) if len(w) > 2 and w not in _STOPWORDS]
|
||||
|
||||
|
||||
@@ -89,7 +88,7 @@ def _unprefixed(target: str) -> str:
|
||||
return rest if rest else head
|
||||
|
||||
|
||||
class ColumnMatcher:
|
||||
def suggest_mapping(source_columns: list[str], target_fields: list[str]) -> list[MatchSuggestion]:
|
||||
"""Exact name -> normalized (case/accents/separators) -> static synonym
|
||||
table -> name without the table prefix -> word-level similarity -> no
|
||||
match.
|
||||
@@ -97,68 +96,60 @@ class ColumnMatcher:
|
||||
The 1:1 assignment is global: all (source, target) pairs are scored and
|
||||
claimed best-first, so a weak fuzzy match early in the file cannot take
|
||||
a target from an exact match later in it."""
|
||||
candidates: list[tuple[float, int, str, str, str]] = []
|
||||
for position, source in enumerate(source_columns):
|
||||
for target in target_fields:
|
||||
scored = _score(source, target)
|
||||
if scored is not None:
|
||||
score, reason = scored
|
||||
# -position: on equal scores the earlier source column wins.
|
||||
candidates.append((score, -position, source, target, reason))
|
||||
|
||||
def suggest(self, source_columns: list[str], target_fields: list[str]) -> list[MatchSuggestion]:
|
||||
candidates: list[tuple[float, int, str, str, str]] = []
|
||||
for position, source in enumerate(source_columns):
|
||||
for target in target_fields:
|
||||
scored = self._score(source, target)
|
||||
if scored is not None:
|
||||
score, reason = scored
|
||||
# -position: on equal scores the earlier source column wins.
|
||||
candidates.append((score, -position, source, target, reason))
|
||||
claimed_sources: dict[str, MatchSuggestion] = {}
|
||||
claimed_targets: set[str] = set()
|
||||
for score, _, source, target, reason in sorted(candidates, reverse=True):
|
||||
if source in claimed_sources or target in claimed_targets:
|
||||
continue
|
||||
claimed_sources[source] = MatchSuggestion(source, target, round(score, 2), reason)
|
||||
claimed_targets.add(target)
|
||||
|
||||
claimed_sources: dict[str, MatchSuggestion] = {}
|
||||
claimed_targets: set[str] = set()
|
||||
for score, _, source, target, reason in sorted(candidates, reverse=True):
|
||||
if source in claimed_sources or target in claimed_targets:
|
||||
continue
|
||||
claimed_sources[source] = MatchSuggestion(source, target, round(score, 2), reason)
|
||||
claimed_targets.add(target)
|
||||
return [claimed_sources.get(source, MatchSuggestion(source, None, 0.0, "none")) for source in source_columns]
|
||||
|
||||
return [claimed_sources.get(source, MatchSuggestion(source, None, 0.0, "none")) for source in source_columns]
|
||||
|
||||
@classmethod
|
||||
def _score(cls, source: str, target: str) -> tuple[float, str] | None:
|
||||
if source == target:
|
||||
return _EXACT, "exact"
|
||||
# A dotted (flattened JSON) name also matches by its last segment:
|
||||
# "paciente.expediente" is an expediente.
|
||||
variants = [source] + ([source.rsplit(".", 1)[-1]] if "." in source else [])
|
||||
scored = [s for s in (cls._score_one(v, target) for v in variants) if s is not None]
|
||||
return max(scored, key=lambda s: s[0]) if scored else None
|
||||
def _score(source: str, target: str) -> tuple[float, str] | None:
|
||||
if source == target:
|
||||
return _EXACT, "exact"
|
||||
# A dotted (flattened JSON) name also matches by its last segment:
|
||||
# "paciente.expediente" is an expediente.
|
||||
variants = [source] + ([source.rsplit(".", 1)[-1]] if "." in source else [])
|
||||
scored = [s for s in (_score_one(v, target) for v in variants) if s is not None]
|
||||
return max(scored, key=lambda s: s[0]) if scored else None
|
||||
|
||||
@staticmethod
|
||||
def _score_one(source: str, target: str) -> tuple[float, str] | None:
|
||||
normalized_source, normalized_target = _normalize(source), _normalize(target)
|
||||
if normalized_source == normalized_target:
|
||||
return _NORMALIZED, "normalized"
|
||||
if normalized_source in SYNONYMS.get(target, set()):
|
||||
return _SYNONYM, "synonym"
|
||||
unprefixed_target = _unprefixed(normalized_target)
|
||||
if normalized_source == unprefixed_target:
|
||||
return _UNPREFIXED, "unprefixed"
|
||||
# Not every field has a table prefix (`hemoglobina_g_dl`), so words
|
||||
# are compared against both the full and the unprefixed name. When
|
||||
# the target *does* have real content beyond its prefix ("eeg" in
|
||||
# "eeg_estudio"), that prefix is dropped from the full-name words
|
||||
# first: every column in the table shares it, so a source word
|
||||
# matching only that (e.g. "eeg_id" ~ "eeg_estudio", both just
|
||||
# carrying "eeg") is not real evidence of a relationship. When the
|
||||
# target has no content beyond its prefix (it isn't really a
|
||||
# "prefix_field" name, e.g. "hemoglobina_g_dl"), nothing is dropped.
|
||||
unprefixed_target_words = _words(unprefixed_target)
|
||||
prefix_token = normalized_target.split("_", 1)[0]
|
||||
target_words_full = (
|
||||
[w for w in _words(normalized_target) if w != prefix_token]
|
||||
if unprefixed_target_words
|
||||
else _words(normalized_target)
|
||||
)
|
||||
source_words = _words(normalized_source)
|
||||
words = max(_word_score(source_words, target_words_full), _word_score(source_words, unprefixed_target_words))
|
||||
if words >= _WORD_FLOOR:
|
||||
# 0.5..0.7 by word overlap, plus a tiny whole-string tiebreak so
|
||||
# "fecha_reporte" prefers bx_fecha_reporte over another one-word overlap.
|
||||
ratio = difflib.SequenceMatcher(None, normalized_source, unprefixed_target).ratio()
|
||||
return min(0.5 + (words - _WORD_FLOOR) * 0.36 + ratio * 0.02, _FUZZY_CAP), "fuzzy"
|
||||
return None
|
||||
|
||||
def _score_one(source: str, target: str) -> tuple[float, str] | None:
|
||||
normalized_source, normalized_target = _normalize(source), _normalize(target)
|
||||
if normalized_source == normalized_target:
|
||||
return _NORMALIZED, "normalized"
|
||||
if normalized_source in SYNONYMS.get(target, set()):
|
||||
return _SYNONYM, "synonym"
|
||||
unprefixed_target = _unprefixed(normalized_target)
|
||||
if normalized_source == unprefixed_target:
|
||||
return _UNPREFIXED, "unprefixed"
|
||||
# Words are compared against the full and the unprefixed name, since not every
|
||||
# field has a table prefix (`hemoglobina_g_dl`). The prefix itself is shared by
|
||||
# every column of the table ("eeg_id" ~ "eeg_estudio"), so it is not evidence.
|
||||
unprefixed_target_words = _words(unprefixed_target)
|
||||
prefix_token = normalized_target.split("_", 1)[0]
|
||||
target_words_full = (
|
||||
[w for w in _words(normalized_target) if w != prefix_token]
|
||||
if unprefixed_target_words
|
||||
else _words(normalized_target)
|
||||
)
|
||||
source_words = _words(normalized_source)
|
||||
words = max(_word_score(source_words, target_words_full), _word_score(source_words, unprefixed_target_words))
|
||||
if words >= _WORD_FLOOR:
|
||||
# 0.5..0.7 by word overlap, plus a tiny whole-string tiebreak so
|
||||
# "fecha_reporte" prefers bx_fecha_reporte over another one-word overlap.
|
||||
ratio = difflib.SequenceMatcher(None, normalized_source, unprefixed_target).ratio()
|
||||
return min(0.5 + (words - _WORD_FLOOR) * 0.36 + ratio * 0.02, _FUZZY_CAP), "fuzzy"
|
||||
return None
|
||||
|
||||
@@ -1,18 +1,15 @@
|
||||
"""Import schema for `core.cacu.models.BiometriaHematica` (full blood count panel)."""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import HospitalId, coerce_date, required_str
|
||||
from webapi.imports.schemas.coercion import FlexDate, RequiredHospitalId
|
||||
|
||||
|
||||
class BiometriaHematicaImportSchema(ImportSchema):
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
pac_id_hospital: RequiredHospitalId
|
||||
ord_numero_hospital: Optional[int] = None
|
||||
bh_fecha: Optional[date] = None
|
||||
bh_fecha: FlexDate = None
|
||||
|
||||
eritrocitos_mill_ul: Optional[float] = None
|
||||
hemoglobina_g_dl: Optional[float] = None
|
||||
@@ -35,13 +32,3 @@ class BiometriaHematicaImportSchema(ImportSchema):
|
||||
|
||||
plaquetas_mil_ul: Optional[float] = None
|
||||
vpm_fl: Optional[float] = None
|
||||
|
||||
@field_validator("pac_id_hospital", mode="before")
|
||||
@classmethod
|
||||
def _required_pac_id_hospital(cls, v):
|
||||
return required_str(v, field_name="pac_id_hospital")
|
||||
|
||||
@field_validator("bh_fecha", mode="before")
|
||||
@classmethod
|
||||
def _coerce_fecha(cls, v):
|
||||
return coerce_date(v)
|
||||
|
||||
@@ -1,34 +1,21 @@
|
||||
"""Import schema for `core.cacu.models.BiopsiaCervical`."""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.cacu.enums import GRADO_CIN_ALIAS, GradoCIN
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, HospitalId, coerce_date, required_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, RequiredHospitalId
|
||||
|
||||
_GRADO_CIN_CATALOG = Catalog(GradoCIN, GRADO_CIN_ALIAS)
|
||||
|
||||
|
||||
class BiopsiaCervicalImportSchema(ImportSchema):
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
pac_id_hospital: RequiredHospitalId
|
||||
ord_numero_hospital: Optional[int] = None
|
||||
cit_id: Optional[int] = None
|
||||
bx_fecha_solicitud: Optional[date] = None
|
||||
bx_fecha_reporte: Optional[date] = None
|
||||
bx_fecha_solicitud: FlexDate = None
|
||||
bx_fecha_reporte: FlexDate = None
|
||||
bx_observaciones: Optional[str] = None
|
||||
bx_cin_grado: CatalogValue(_GRADO_CIN_CATALOG) = None
|
||||
bx_pdf_blob: Optional[bytes] = None
|
||||
bx_ocr_confianza: Optional[float] = None
|
||||
|
||||
@field_validator("pac_id_hospital", mode="before")
|
||||
@classmethod
|
||||
def _required_pac_id_hospital(cls, v):
|
||||
return required_str(v, field_name="pac_id_hospital")
|
||||
|
||||
@field_validator("bx_fecha_solicitud", "bx_fecha_reporte", mode="before")
|
||||
@classmethod
|
||||
def _coerce_dates(cls, v):
|
||||
return coerce_date(v)
|
||||
|
||||
@@ -3,14 +3,11 @@
|
||||
`cit_calidad_especimen` stays a plain string: Core's alias dict for it maps to
|
||||
`bool`, not to a canonical string, so it can't back a catalog.
|
||||
"""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.cacu.enums import CELULAS_ESCAMOSAS_ALIAS, CelulasEscamosas, ResultadoVPH
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, HospitalId, coerce_date, required_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, RequiredHospitalId
|
||||
|
||||
_CELULAS_ESCAMOSAS_CATALOG = Catalog(CelulasEscamosas, CELULAS_ESCAMOSAS_ALIAS)
|
||||
_RESULTADO_VPH_CATALOG = Catalog(ResultadoVPH)
|
||||
@@ -21,10 +18,10 @@ class CitologiaCervicalImportSchema(ImportSchema):
|
||||
# natural key) still point at this record.
|
||||
cit_id: Optional[int] = None
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
pac_id_hospital: RequiredHospitalId
|
||||
ord_numero_hospital: Optional[int] = None
|
||||
cit_fecha_toma: Optional[date] = None
|
||||
cit_fecha_reporte: Optional[date] = None
|
||||
cit_fecha_toma: FlexDate = None
|
||||
cit_fecha_reporte: FlexDate = None
|
||||
cit_calidad_especimen: Optional[str] = None
|
||||
cit_pdf_blob: Optional[bytes] = None
|
||||
cit_observaciones: Optional[str] = None
|
||||
@@ -39,13 +36,3 @@ class CitologiaCervicalImportSchema(ImportSchema):
|
||||
cit_vph_resultado: CatalogValue(_RESULTADO_VPH_CATALOG) = None
|
||||
cit_vph_genotipo_16: Optional[int] = None
|
||||
cit_vph_genotipo_18: Optional[int] = None
|
||||
|
||||
@field_validator("pac_id_hospital", mode="before")
|
||||
@classmethod
|
||||
def _required_pac_id_hospital(cls, v):
|
||||
return required_str(v, field_name="pac_id_hospital")
|
||||
|
||||
@field_validator("cit_fecha_toma", "cit_fecha_reporte", mode="before")
|
||||
@classmethod
|
||||
def _coerce_dates(cls, v):
|
||||
return coerce_date(v)
|
||||
|
||||
@@ -8,14 +8,11 @@ per the model's own docstring, linking an episode to the note/order it came
|
||||
from and to its predecessor is the job of the not-yet-built IND-02/IND-03
|
||||
episode-correlation logic, not a plain field-mapping import.
|
||||
"""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.cacu.enums import ESPECIALIDAD_ALIAS, Especialidad, TIPO_EPISODIO_ALIAS, TipoEpisodio
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, HospitalId, coerce_date, required_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, RequiredHospitalId
|
||||
|
||||
_TIPO_EPISODIO_CATALOG = Catalog(TipoEpisodio, TIPO_EPISODIO_ALIAS)
|
||||
_ESPECIALIDAD_CATALOG = Catalog(Especialidad, ESPECIALIDAD_ALIAS)
|
||||
@@ -23,20 +20,10 @@ _ESPECIALIDAD_CATALOG = Catalog(Especialidad, ESPECIALIDAD_ALIAS)
|
||||
|
||||
class EpisodioClinicoImportSchema(ImportSchema):
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
pac_id_hospital: RequiredHospitalId
|
||||
tipo_episodio: CatalogValue(_TIPO_EPISODIO_CATALOG) = None
|
||||
cie10_codigo: Optional[str] = None
|
||||
especialidad_medica: CatalogValue(_ESPECIALIDAD_CATALOG) = None
|
||||
evento_fecha: Optional[date] = None
|
||||
ventana_inicio: Optional[date] = None
|
||||
ventana_fin: Optional[date] = None
|
||||
|
||||
@field_validator("pac_id_hospital", mode="before")
|
||||
@classmethod
|
||||
def _required_pac_id_hospital(cls, v):
|
||||
return required_str(v, field_name="pac_id_hospital")
|
||||
|
||||
@field_validator("evento_fecha", "ventana_inicio", "ventana_fin", mode="before")
|
||||
@classmethod
|
||||
def _coerce_dates(cls, v):
|
||||
return coerce_date(v)
|
||||
evento_fecha: FlexDate = None
|
||||
ventana_inicio: FlexDate = None
|
||||
ventana_fin: FlexDate = None
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
"""Import schema for `core.cacu.models.NotaMedica`."""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.cacu.enums import ESPECIALIDAD_ALIAS, Especialidad, TIPO_NOTA_ALIAS, TipoNota
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, HospitalId, coerce_date, required_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, RequiredHospitalId, RequiredStr
|
||||
|
||||
_ESPECIALIDAD_CATALOG = Catalog(Especialidad, ESPECIALIDAD_ALIAS)
|
||||
_TIPO_NOTA_CATALOG = Catalog(TipoNota, TIPO_NOTA_ALIAS)
|
||||
@@ -14,12 +11,12 @@ _TIPO_NOTA_CATALOG = Catalog(TipoNota, TIPO_NOTA_ALIAS)
|
||||
|
||||
class NotaMedicaImportSchema(ImportSchema):
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
nm_id_hospital: str
|
||||
pac_id_hospital: RequiredHospitalId
|
||||
nm_id_hospital: RequiredStr
|
||||
nm_nota_previa_id: Optional[str] = None
|
||||
nm_tipo_nota: CatalogValue(_TIPO_NOTA_CATALOG) = None
|
||||
nm_especialidad: CatalogValue(_ESPECIALIDAD_CATALOG) = None
|
||||
nm_fecha: Optional[date] = None
|
||||
nm_fecha: FlexDate = None
|
||||
nm_medico_tratante: Optional[str] = None
|
||||
nm_motivo_consulta: Optional[str] = None
|
||||
nm_interrogatorio: Optional[str] = None
|
||||
@@ -39,18 +36,3 @@ class NotaMedicaImportSchema(ImportSchema):
|
||||
nm_presion_arterial_sistolica: Optional[int] = None
|
||||
nm_presion_arterial_diastolica: Optional[int] = None
|
||||
nm_temperatura: Optional[float] = None
|
||||
|
||||
@field_validator("pac_id_hospital", mode="before")
|
||||
@classmethod
|
||||
def _required_pac_id_hospital(cls, v):
|
||||
return required_str(v, field_name="pac_id_hospital")
|
||||
|
||||
@field_validator("nm_id_hospital", mode="before")
|
||||
@classmethod
|
||||
def _required_nm_id_hospital(cls, v):
|
||||
return required_str(v, field_name="nm_id_hospital")
|
||||
|
||||
@field_validator("nm_fecha", mode="before")
|
||||
@classmethod
|
||||
def _coerce_fecha(cls, v):
|
||||
return coerce_date(v)
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
"""Import schema for `core.cacu.models.OrdenesEstudio` (one order per row, one study type each)."""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.cacu.enums import TIPO_ESTUDIO_ALIAS, TipoEstudio
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, HospitalId, coerce_date, required_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, RequiredHospitalId
|
||||
|
||||
_TIPO_ESTUDIO_CATALOG = Catalog(TipoEstudio, TIPO_ESTUDIO_ALIAS)
|
||||
|
||||
@@ -16,24 +13,14 @@ class OrdenesEstudioImportSchema(ImportSchema):
|
||||
# natural key) still point at this record.
|
||||
ord_id: Optional[int] = None
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
pac_id_hospital: RequiredHospitalId
|
||||
ord_numero_hospital: int
|
||||
ord_tipo_estudio: CatalogValue(_TIPO_ESTUDIO_CATALOG) = None
|
||||
ord_fecha: Optional[date] = None
|
||||
ord_fecha_solicitud: Optional[date] = None
|
||||
ord_fecha_resultado: Optional[date] = None
|
||||
ord_fecha: FlexDate = None
|
||||
ord_fecha_solicitud: FlexDate = None
|
||||
ord_fecha_resultado: FlexDate = None
|
||||
ord_estatus: Optional[str] = None
|
||||
ord_diagnostico: Optional[str] = None
|
||||
ord_observaciones: Optional[str] = None
|
||||
ord_especialidad: Optional[str] = None
|
||||
ord_medico_solicitante: Optional[str] = None
|
||||
|
||||
@field_validator("pac_id_hospital", mode="before")
|
||||
@classmethod
|
||||
def _required_pac_id_hospital(cls, v):
|
||||
return required_str(v, field_name="pac_id_hospital")
|
||||
|
||||
@field_validator("ord_fecha", "ord_fecha_solicitud", "ord_fecha_resultado", mode="before")
|
||||
@classmethod
|
||||
def _coerce_dates(cls, v):
|
||||
return coerce_date(v)
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
"""Import schema for `core.cacu.models.Paciente`."""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.cacu.enums import DEPENDENCIA_ALIAS, Dependencia, PARENTESCO_ALIAS, Parentesco, SEXO_BIOLOGICO_ALIAS, SexoBiologico
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, CodigoPostal, HospitalId, coerce_postal_code, required_date, required_str
|
||||
from webapi.imports.schemas.coercion import (
|
||||
Catalog,
|
||||
CatalogValue,
|
||||
PostalCode,
|
||||
RequiredDate,
|
||||
RequiredHospitalId,
|
||||
)
|
||||
|
||||
# Dependencia/Parentesco: Core marks both catalogs as tentative.
|
||||
_DEPENDENCIA_CATALOG = Catalog(Dependencia, DEPENDENCIA_ALIAS, strict=False)
|
||||
@@ -18,25 +21,10 @@ class PacienteImportSchema(ImportSchema):
|
||||
# The source's own id, kept so rows that reference it by id (not by a
|
||||
# natural key) still point at this record.
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
pac_id_hospital: RequiredHospitalId
|
||||
pac_sexo: CatalogValue(_SEXO_BIOLOGICO_CATALOG) = None
|
||||
# IND-01: required, since age at each event of interest is derived from it.
|
||||
pac_fecha_nacimiento: date
|
||||
pac_codigo_postal: Optional[CodigoPostal] = None
|
||||
pac_fecha_nacimiento: RequiredDate
|
||||
pac_codigo_postal: PostalCode = None
|
||||
pac_dependencia: CatalogValue(_DEPENDENCIA_CATALOG) = None
|
||||
pac_parentesco: CatalogValue(_PARENTESCO_CATALOG) = None
|
||||
|
||||
@field_validator("pac_id_hospital", mode="before")
|
||||
@classmethod
|
||||
def _required_id_hospital(cls, v):
|
||||
return required_str(v, field_name="pac_id_hospital")
|
||||
|
||||
@field_validator("pac_fecha_nacimiento", mode="before")
|
||||
@classmethod
|
||||
def _coerce_fecha_nacimiento(cls, v):
|
||||
return required_date(v, field_name="pac_fecha_nacimiento")
|
||||
|
||||
@field_validator("pac_codigo_postal", mode="before")
|
||||
@classmethod
|
||||
def _coerce_codigo_postal(cls, v):
|
||||
return coerce_postal_code(v)
|
||||
|
||||
@@ -1,18 +1,15 @@
|
||||
"""Import schema for `core.cama.models.BiometriaHematica` (full blood count panel)."""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import HospitalId, coerce_date, required_str
|
||||
from webapi.imports.schemas.coercion import FlexDate, RequiredHospitalId
|
||||
|
||||
|
||||
class BiometriaHematicaImportSchema(ImportSchema):
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
pac_id_hospital: RequiredHospitalId
|
||||
ord_numero_hospital: Optional[int] = None
|
||||
bh_fecha: Optional[date] = None
|
||||
bh_fecha: FlexDate = None
|
||||
|
||||
eritrocitos_mill_ul: Optional[float] = None
|
||||
hemoglobina_g_dl: Optional[float] = None
|
||||
@@ -35,13 +32,3 @@ class BiometriaHematicaImportSchema(ImportSchema):
|
||||
|
||||
plaquetas_mil_ul: Optional[float] = None
|
||||
vpm_fl: Optional[float] = None
|
||||
|
||||
@field_validator("pac_id_hospital", mode="before")
|
||||
@classmethod
|
||||
def _required_pac_id_hospital(cls, v):
|
||||
return required_str(v, field_name="pac_id_hospital")
|
||||
|
||||
@field_validator("bh_fecha", mode="before")
|
||||
@classmethod
|
||||
def _coerce_fecha(cls, v):
|
||||
return coerce_date(v)
|
||||
|
||||
@@ -1,34 +1,21 @@
|
||||
"""Import schema for `core.cama.models.BiopsiaMama`."""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.cama.enums import GradoHistologicoMama
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, HospitalId, coerce_date, required_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, RequiredHospitalId
|
||||
|
||||
_GRADO_HISTOLOGICO_MAMA_CATALOG = Catalog(GradoHistologicoMama)
|
||||
|
||||
|
||||
class BiopsiaMamaImportSchema(ImportSchema):
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
pac_id_hospital: RequiredHospitalId
|
||||
ord_id: Optional[int] = None
|
||||
ord_numero_hospital: Optional[int] = None
|
||||
mast_id: Optional[int] = None
|
||||
bx_fecha_solicitud: Optional[date] = None
|
||||
bx_fecha_reporte: Optional[date] = None
|
||||
bx_fecha_solicitud: FlexDate = None
|
||||
bx_fecha_reporte: FlexDate = None
|
||||
bx_grado_histologico: CatalogValue(_GRADO_HISTOLOGICO_MAMA_CATALOG) = None
|
||||
bx_pdf_blob: Optional[bytes] = None
|
||||
bx_ocr_confianza: Optional[float] = None
|
||||
|
||||
@field_validator("pac_id_hospital", mode="before")
|
||||
@classmethod
|
||||
def _required_pac_id_hospital(cls, v):
|
||||
return required_str(v, field_name="pac_id_hospital")
|
||||
|
||||
@field_validator("bx_fecha_solicitud", "bx_fecha_reporte", mode="before")
|
||||
@classmethod
|
||||
def _coerce_dates(cls, v):
|
||||
return coerce_date(v)
|
||||
|
||||
@@ -2,14 +2,11 @@
|
||||
`webapi.imports.schemas.cacu.episodio_clinico.EpisodioClinicoImportSchema`
|
||||
(see its docstring for why `nm_id`/`episodio_anterior_id` are excluded).
|
||||
"""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.cama.enums import ESPECIALIDAD_ALIAS, Especialidad, TIPO_EPISODIO_ALIAS, TipoEpisodio
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, HospitalId, coerce_date, required_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, RequiredHospitalId
|
||||
|
||||
_TIPO_EPISODIO_CATALOG = Catalog(TipoEpisodio, TIPO_EPISODIO_ALIAS)
|
||||
_ESPECIALIDAD_CATALOG = Catalog(Especialidad, ESPECIALIDAD_ALIAS)
|
||||
@@ -17,20 +14,10 @@ _ESPECIALIDAD_CATALOG = Catalog(Especialidad, ESPECIALIDAD_ALIAS)
|
||||
|
||||
class EpisodioClinicoImportSchema(ImportSchema):
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
pac_id_hospital: RequiredHospitalId
|
||||
tipo_episodio: CatalogValue(_TIPO_EPISODIO_CATALOG) = None
|
||||
cie10_codigo: Optional[str] = None
|
||||
especialidad_medica: CatalogValue(_ESPECIALIDAD_CATALOG) = None
|
||||
evento_fecha: Optional[date] = None
|
||||
ventana_inicio: Optional[date] = None
|
||||
ventana_fin: Optional[date] = None
|
||||
|
||||
@field_validator("pac_id_hospital", mode="before")
|
||||
@classmethod
|
||||
def _required_pac_id_hospital(cls, v):
|
||||
return required_str(v, field_name="pac_id_hospital")
|
||||
|
||||
@field_validator("evento_fecha", "ventana_inicio", "ventana_fin", mode="before")
|
||||
@classmethod
|
||||
def _coerce_dates(cls, v):
|
||||
return coerce_date(v)
|
||||
evento_fecha: FlexDate = None
|
||||
ventana_inicio: FlexDate = None
|
||||
ventana_fin: FlexDate = None
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
"""Import schema for `core.cama.models.Mastografia`."""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.cama.enums import BIRADS, BIRADS_ALIAS
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, HospitalId, coerce_date, required_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, RequiredHospitalId
|
||||
|
||||
_BIRADS_CATALOG = Catalog(BIRADS, BIRADS_ALIAS)
|
||||
|
||||
@@ -16,22 +13,12 @@ class MastografiaImportSchema(ImportSchema):
|
||||
# natural key) still point at this record.
|
||||
mast_id: Optional[int] = None
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
pac_id_hospital: RequiredHospitalId
|
||||
ord_id: Optional[int] = None
|
||||
ord_numero_hospital: Optional[int] = None
|
||||
mast_fecha_toma: Optional[date] = None
|
||||
mast_fecha_reporte: Optional[date] = None
|
||||
mast_fecha_toma: FlexDate = None
|
||||
mast_fecha_reporte: FlexDate = None
|
||||
mast_calidad_imagen: Optional[str] = None
|
||||
mast_birads: CatalogValue(_BIRADS_CATALOG) = None
|
||||
mast_dicom_blob: Optional[bytes] = None
|
||||
mast_interpretacion: Optional[str] = None
|
||||
|
||||
@field_validator("pac_id_hospital", mode="before")
|
||||
@classmethod
|
||||
def _required_pac_id_hospital(cls, v):
|
||||
return required_str(v, field_name="pac_id_hospital")
|
||||
|
||||
@field_validator("mast_fecha_toma", "mast_fecha_reporte", mode="before")
|
||||
@classmethod
|
||||
def _coerce_dates(cls, v):
|
||||
return coerce_date(v)
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
"""Import schema for `core.cama.models.NotaMedica`."""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.cama.enums import ESPECIALIDAD_ALIAS, Especialidad, TIPO_NOTA_ALIAS, TipoNota
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, HospitalId, coerce_date, required_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, RequiredHospitalId, RequiredStr
|
||||
|
||||
_ESPECIALIDAD_CATALOG = Catalog(Especialidad, ESPECIALIDAD_ALIAS)
|
||||
_TIPO_NOTA_CATALOG = Catalog(TipoNota, TIPO_NOTA_ALIAS)
|
||||
@@ -14,12 +11,12 @@ _TIPO_NOTA_CATALOG = Catalog(TipoNota, TIPO_NOTA_ALIAS)
|
||||
|
||||
class NotaMedicaImportSchema(ImportSchema):
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
nm_id_hospital: str
|
||||
pac_id_hospital: RequiredHospitalId
|
||||
nm_id_hospital: RequiredStr
|
||||
nm_nota_previa_id: Optional[str] = None
|
||||
nm_tipo_nota: CatalogValue(_TIPO_NOTA_CATALOG) = None
|
||||
nm_especialidad: CatalogValue(_ESPECIALIDAD_CATALOG) = None
|
||||
nm_fecha: Optional[date] = None
|
||||
nm_fecha: FlexDate = None
|
||||
nm_medico_tratante: Optional[str] = None
|
||||
nm_motivo_consulta: Optional[str] = None
|
||||
nm_interrogatorio: Optional[str] = None
|
||||
@@ -39,18 +36,3 @@ class NotaMedicaImportSchema(ImportSchema):
|
||||
nm_presion_arterial_sistolica: Optional[int] = None
|
||||
nm_presion_arterial_diastolica: Optional[int] = None
|
||||
nm_temperatura: Optional[float] = None
|
||||
|
||||
@field_validator("pac_id_hospital", mode="before")
|
||||
@classmethod
|
||||
def _required_pac_id_hospital(cls, v):
|
||||
return required_str(v, field_name="pac_id_hospital")
|
||||
|
||||
@field_validator("nm_id_hospital", mode="before")
|
||||
@classmethod
|
||||
def _required_nm_id_hospital(cls, v):
|
||||
return required_str(v, field_name="nm_id_hospital")
|
||||
|
||||
@field_validator("nm_fecha", mode="before")
|
||||
@classmethod
|
||||
def _coerce_fecha(cls, v):
|
||||
return coerce_date(v)
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
"""Import schema for `core.cama.models.OrdenesEstudio` (one order per row, one study type each)."""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.cama.enums import TIPO_ESTUDIO_ALIAS, TipoEstudio
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, HospitalId, coerce_date, required_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, RequiredHospitalId
|
||||
|
||||
_TIPO_ESTUDIO_CATALOG = Catalog(TipoEstudio, TIPO_ESTUDIO_ALIAS)
|
||||
|
||||
@@ -16,24 +13,14 @@ class OrdenesEstudioImportSchema(ImportSchema):
|
||||
# natural key) still point at this record.
|
||||
ord_id: Optional[int] = None
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
pac_id_hospital: RequiredHospitalId
|
||||
ord_numero_hospital: int
|
||||
ord_tipo_estudio: CatalogValue(_TIPO_ESTUDIO_CATALOG) = None
|
||||
ord_fecha: Optional[date] = None
|
||||
ord_fecha_solicitud: Optional[date] = None
|
||||
ord_fecha_resultado: Optional[date] = None
|
||||
ord_fecha: FlexDate = None
|
||||
ord_fecha_solicitud: FlexDate = None
|
||||
ord_fecha_resultado: FlexDate = None
|
||||
ord_estatus: Optional[str] = None
|
||||
ord_diagnostico: Optional[str] = None
|
||||
ord_observaciones: Optional[str] = None
|
||||
ord_especialidad: Optional[str] = None
|
||||
ord_medico_solicitante: Optional[str] = None
|
||||
|
||||
@field_validator("pac_id_hospital", mode="before")
|
||||
@classmethod
|
||||
def _required_pac_id_hospital(cls, v):
|
||||
return required_str(v, field_name="pac_id_hospital")
|
||||
|
||||
@field_validator("ord_fecha", "ord_fecha_solicitud", "ord_fecha_resultado", mode="before")
|
||||
@classmethod
|
||||
def _coerce_dates(cls, v):
|
||||
return coerce_date(v)
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
"""Import schema for `core.cama.models.Paciente`."""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.cama.enums import DEPENDENCIA_ALIAS, Dependencia, PARENTESCO_ALIAS, Parentesco, SEXO_BIOLOGICO_ALIAS, SexoBiologico
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, CodigoPostal, HospitalId, coerce_postal_code, required_date, required_str
|
||||
from webapi.imports.schemas.coercion import (
|
||||
Catalog,
|
||||
CatalogValue,
|
||||
PostalCode,
|
||||
RequiredDate,
|
||||
RequiredHospitalId,
|
||||
)
|
||||
|
||||
# Dependencia/Parentesco: Core marks both catalogs as tentative.
|
||||
_DEPENDENCIA_CATALOG = Catalog(Dependencia, DEPENDENCIA_ALIAS, strict=False)
|
||||
@@ -18,25 +21,10 @@ class PacienteImportSchema(ImportSchema):
|
||||
# The source's own id, kept so rows that reference it by id (not by a
|
||||
# natural key) still point at this record.
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
pac_id_hospital: RequiredHospitalId
|
||||
pac_sexo: CatalogValue(_SEXO_BIOLOGICO_CATALOG) = None
|
||||
# IND-01: required, since age at each event of interest is derived from it.
|
||||
pac_fecha_nacimiento: date
|
||||
pac_codigo_postal: Optional[CodigoPostal] = None
|
||||
pac_fecha_nacimiento: RequiredDate
|
||||
pac_codigo_postal: PostalCode = None
|
||||
pac_dependencia: CatalogValue(_DEPENDENCIA_CATALOG) = None
|
||||
pac_parentesco: CatalogValue(_PARENTESCO_CATALOG) = None
|
||||
|
||||
@field_validator("pac_id_hospital", mode="before")
|
||||
@classmethod
|
||||
def _required_id_hospital(cls, v):
|
||||
return required_str(v, field_name="pac_id_hospital")
|
||||
|
||||
@field_validator("pac_codigo_postal", mode="before")
|
||||
@classmethod
|
||||
def _coerce_codigo_postal(cls, v):
|
||||
return coerce_postal_code(v)
|
||||
|
||||
@field_validator("pac_fecha_nacimiento", mode="before")
|
||||
@classmethod
|
||||
def _coerce_fecha_nacimiento(cls, v):
|
||||
return required_date(v, field_name="pac_fecha_nacimiento")
|
||||
|
||||
@@ -7,7 +7,7 @@ from datetime import date, datetime
|
||||
from enum import Enum
|
||||
from typing import Annotated, Any, Optional, Type
|
||||
|
||||
from pydantic import BeforeValidator, StringConstraints
|
||||
from pydantic import BeforeValidator, StringConstraints, ValidationInfo
|
||||
|
||||
from core.columns import HOSPITAL_ID_LENGTH
|
||||
from extraction import ExtractionError
|
||||
@@ -18,9 +18,9 @@ from extraction.signals import EegRecording
|
||||
HospitalId = Annotated[str, StringConstraints(max_length=HOSPITAL_ID_LENGTH)]
|
||||
|
||||
|
||||
def required_str(v: Any, *, field_name: str) -> str:
|
||||
def required_str(v: Any, info: ValidationInfo) -> str:
|
||||
if v is None or str(v).strip() == "":
|
||||
raise ValueError(f"{field_name} es requerido")
|
||||
raise ValueError(f"{info.field_name} es requerido")
|
||||
return str(v).strip()
|
||||
|
||||
|
||||
@@ -34,10 +34,10 @@ def optional_str(v: Any) -> Any:
|
||||
_DAY_FIRST_FORMATS = ("%d/%m/%Y", "%d-%m-%Y", "%d.%m.%Y", "%Y/%m/%d")
|
||||
|
||||
|
||||
def required_date(v: Any, *, field_name: str) -> Any:
|
||||
def required_date(v: Any, info: ValidationInfo) -> Any:
|
||||
coerced = coerce_date(v)
|
||||
if coerced is None:
|
||||
raise ValueError(f"{field_name} es requerido")
|
||||
raise ValueError(f"{info.field_name} es requerido")
|
||||
return coerced
|
||||
|
||||
|
||||
@@ -67,16 +67,6 @@ def coerce_date(v: Any) -> Any:
|
||||
return v
|
||||
|
||||
|
||||
def coerce_datetime(v: Any) -> Any:
|
||||
if v is None or (isinstance(v, str) and not v.strip()):
|
||||
return None
|
||||
if isinstance(v, datetime):
|
||||
return v
|
||||
if isinstance(v, str):
|
||||
return datetime.fromisoformat(v.strip())
|
||||
return v
|
||||
|
||||
|
||||
class Catalog:
|
||||
"""A closed set of valid values for one field: an `Enum`'s values plus any
|
||||
aliases for them, matched case-insensitively. Built from the Enum because
|
||||
@@ -132,10 +122,6 @@ def CatalogValue(catalog: Catalog): # noqa: N802 (used in annotations, like a t
|
||||
return Annotated[Optional[str], BeforeValidator(catalog.coerce), catalog]
|
||||
|
||||
|
||||
def coerce_alias(v: Any, catalog: Catalog) -> Any:
|
||||
return catalog.coerce(v)
|
||||
|
||||
|
||||
def coerce_postal_code(v: Any) -> Any:
|
||||
"""Mexican postal codes are 5 digits. A numeric source (Excel cell, SQL
|
||||
INT column) has already dropped the leading zero, so restore it."""
|
||||
@@ -170,3 +156,15 @@ def edf_file(v: Any) -> Any:
|
||||
except ExtractionError as exc:
|
||||
raise ValueError(f"no es un archivo EDF válido: {exc}") from exc
|
||||
return bytes(v)
|
||||
|
||||
|
||||
# Field types. Blank cells become None; required ones say which field is missing.
|
||||
OptionalStr = Annotated[Optional[str], BeforeValidator(optional_str)]
|
||||
# A TEA record's own id as the source sends it (its primary key is String(36)).
|
||||
SourceId = Annotated[Optional[Annotated[str, StringConstraints(max_length=36)]], BeforeValidator(optional_str)]
|
||||
RequiredStr = Annotated[str, BeforeValidator(required_str)]
|
||||
RequiredHospitalId = Annotated[HospitalId, BeforeValidator(required_str)]
|
||||
FlexDate = Annotated[Optional[date], BeforeValidator(coerce_date)]
|
||||
RequiredDate = Annotated[date, BeforeValidator(required_date)]
|
||||
PostalCode = Annotated[Optional[CodigoPostal], BeforeValidator(coerce_postal_code)]
|
||||
EdfFile = Annotated[Optional[bytes], BeforeValidator(edf_file)]
|
||||
|
||||
@@ -6,34 +6,8 @@ Keys are `"<domain>.<ModelName>"`, since some names (`NotaMedica`) repeat
|
||||
across domains.
|
||||
"""
|
||||
from dataclasses import dataclass
|
||||
from typing import Sequence, Type
|
||||
from typing import Sequence
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from core.cacu.models import BiometriaHematica as CacuBiometriaHematica
|
||||
from core.cacu.models import BiopsiaCervical as CacuBiopsiaCervical
|
||||
from core.cacu.models import CitologiaCervical as CacuCitologiaCervical
|
||||
from core.cacu.models import EpisodioClinico as CacuEpisodioClinico
|
||||
from core.cacu.models import NotaMedica as CacuNotaMedica
|
||||
from core.cacu.models import OrdenesEstudio as CacuOrdenesEstudio
|
||||
from core.cacu.models import Paciente as CacuPaciente
|
||||
from core.cama.models import BiometriaHematica as CamaBiometriaHematica
|
||||
from core.cama.models import BiopsiaMama as CamaBiopsiaMama
|
||||
from core.cama.models import EpisodioClinico as CamaEpisodioClinico
|
||||
from core.cama.models import Mastografia as CamaMastografia
|
||||
from core.cama.models import NotaMedica as CamaNotaMedica
|
||||
from core.cama.models import OrdenesEstudio as CamaOrdenesEstudio
|
||||
from core.cama.models import Paciente as CamaPaciente
|
||||
from core.tea.models import AntecedentesMaternosGestacion as TeaAntecedentesMaternosGestacion
|
||||
from core.tea.models import EegEstudio as TeaEegEstudio
|
||||
from core.tea.models import EegSegmento as TeaEegSegmento
|
||||
from core.tea.models import EvaluacionPsicologica as TeaEvaluacionPsicologica
|
||||
from core.tea.models import InstrumentoAplicado as TeaInstrumentoAplicado
|
||||
from core.tea.models import NotaMedica as TeaNotaMedica
|
||||
from core.tea.models import OrdenesEstudio as TeaOrdenesEstudio
|
||||
from core.tea.models import Pacientes as TeaPacientes
|
||||
from core.tea.models import PartoNeonatal as TeaPartoNeonatal
|
||||
from core.tea.models import PotencialesEvocadosAuditivos as TeaPotencialesEvocadosAuditivos
|
||||
from persistance.cacu import biometria_hematica_repository as cacu_biometria_hematica_repository
|
||||
from persistance.cacu import biopsia_cervical_repository as cacu_biopsia_cervical_repository
|
||||
from persistance.cacu import citologia_cervical_repository as cacu_citologia_cervical_repository
|
||||
@@ -49,6 +23,7 @@ from persistance.cama import nota_medica_repository as cama_nota_medica_reposito
|
||||
from persistance.cama import ordenes_estudio_repository as cama_ordenes_estudio_repository
|
||||
from persistance.cama import paciente_repository as cama_paciente_repository
|
||||
from persistance.repository import Repository
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from persistance.tea import antecedentes_maternos_gestacion_repository as tea_antecedentes_maternos_gestacion_repository
|
||||
from persistance.tea import eeg_estudio_repository as tea_eeg_estudio_repository
|
||||
from persistance.tea import eeg_segmento_repository as tea_eeg_segmento_repository
|
||||
@@ -107,59 +82,54 @@ from webapi.imports.schemas.tea.potenciales_evocados_auditivos import (
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class EntitySpec:
|
||||
schema: Type[BaseModel]
|
||||
model: type
|
||||
schema: type[ImportSchema]
|
||||
repository: Repository
|
||||
conflict_fields: Sequence[str] | None
|
||||
|
||||
@property
|
||||
def model(self) -> type:
|
||||
return self.repository.model
|
||||
|
||||
|
||||
ENTITY_REGISTRY: dict[str, EntitySpec] = {
|
||||
"cacu.Paciente": EntitySpec(
|
||||
schema=CacuPacienteImportSchema,
|
||||
model=CacuPaciente,
|
||||
repository=cacu_paciente_repository,
|
||||
conflict_fields=("pac_id_hospital",),
|
||||
),
|
||||
"tea.Pacientes": EntitySpec(
|
||||
schema=PacientesImportSchema,
|
||||
model=TeaPacientes,
|
||||
repository=tea_pacientes_repository,
|
||||
# The source's own id; TEA's child tables reference it directly.
|
||||
conflict_fields=("pac_id",),
|
||||
),
|
||||
"cacu.OrdenesEstudio": EntitySpec(
|
||||
schema=CacuOrdenesEstudioImportSchema,
|
||||
model=CacuOrdenesEstudio,
|
||||
repository=cacu_ordenes_estudio_repository,
|
||||
conflict_fields=("ord_numero_hospital",),
|
||||
),
|
||||
"cacu.CitologiaCervical": EntitySpec(
|
||||
schema=CitologiaCervicalImportSchema,
|
||||
model=CacuCitologiaCervical,
|
||||
repository=cacu_citologia_cervical_repository,
|
||||
conflict_fields=("pac_id_hospital", "ord_numero_hospital"),
|
||||
),
|
||||
"cacu.BiopsiaCervical": EntitySpec(
|
||||
schema=BiopsiaCervicalImportSchema,
|
||||
model=CacuBiopsiaCervical,
|
||||
repository=cacu_biopsia_cervical_repository,
|
||||
conflict_fields=("pac_id_hospital", "ord_numero_hospital"),
|
||||
),
|
||||
"cacu.NotaMedica": EntitySpec(
|
||||
schema=CacuNotaMedicaImportSchema,
|
||||
model=CacuNotaMedica,
|
||||
repository=cacu_nota_medica_repository,
|
||||
conflict_fields=("pac_id_hospital", "nm_id_hospital"),
|
||||
),
|
||||
"cacu.BiometriaHematica": EntitySpec(
|
||||
schema=CacuBiometriaHematicaImportSchema,
|
||||
model=CacuBiometriaHematica,
|
||||
repository=cacu_biometria_hematica_repository,
|
||||
conflict_fields=None,
|
||||
),
|
||||
"cacu.EpisodioClinico": EntitySpec(
|
||||
schema=CacuEpisodioClinicoImportSchema,
|
||||
model=CacuEpisodioClinico,
|
||||
repository=cacu_episodio_clinico_repository,
|
||||
# No hospital-visible identifier of its own, like EvaluacionPsicologica
|
||||
# or PartoNeonatal; a patient can have several episodes.
|
||||
@@ -167,73 +137,61 @@ ENTITY_REGISTRY: dict[str, EntitySpec] = {
|
||||
),
|
||||
"cama.Paciente": EntitySpec(
|
||||
schema=CamaPacienteImportSchema,
|
||||
model=CamaPaciente,
|
||||
repository=cama_paciente_repository,
|
||||
conflict_fields=("pac_id_hospital",),
|
||||
),
|
||||
"cama.OrdenesEstudio": EntitySpec(
|
||||
schema=CamaOrdenesEstudioImportSchema,
|
||||
model=CamaOrdenesEstudio,
|
||||
repository=cama_ordenes_estudio_repository,
|
||||
conflict_fields=("ord_numero_hospital",),
|
||||
),
|
||||
"cama.Mastografia": EntitySpec(
|
||||
schema=MastografiaImportSchema,
|
||||
model=CamaMastografia,
|
||||
repository=cama_mastografia_repository,
|
||||
conflict_fields=("pac_id_hospital", "ord_numero_hospital"),
|
||||
),
|
||||
"cama.BiopsiaMama": EntitySpec(
|
||||
schema=BiopsiaMamaImportSchema,
|
||||
model=CamaBiopsiaMama,
|
||||
repository=cama_biopsia_mama_repository,
|
||||
conflict_fields=("pac_id_hospital", "ord_numero_hospital"),
|
||||
),
|
||||
"cama.NotaMedica": EntitySpec(
|
||||
schema=CamaNotaMedicaImportSchema,
|
||||
model=CamaNotaMedica,
|
||||
repository=cama_nota_medica_repository,
|
||||
conflict_fields=("pac_id_hospital", "nm_id_hospital"),
|
||||
),
|
||||
"cama.BiometriaHematica": EntitySpec(
|
||||
schema=CamaBiometriaHematicaImportSchema,
|
||||
model=CamaBiometriaHematica,
|
||||
repository=cama_biometria_hematica_repository,
|
||||
conflict_fields=None,
|
||||
),
|
||||
"cama.EpisodioClinico": EntitySpec(
|
||||
schema=CamaEpisodioClinicoImportSchema,
|
||||
model=CamaEpisodioClinico,
|
||||
repository=cama_episodio_clinico_repository,
|
||||
conflict_fields=None,
|
||||
),
|
||||
"tea.OrdenesEstudio": EntitySpec(
|
||||
schema=TeaOrdenesEstudioImportSchema,
|
||||
model=TeaOrdenesEstudio,
|
||||
repository=tea_ordenes_estudio_repository,
|
||||
conflict_fields=("ord_id_hospital",),
|
||||
),
|
||||
"tea.NotaMedica": EntitySpec(
|
||||
schema=TeaNotaMedicaImportSchema,
|
||||
model=TeaNotaMedica,
|
||||
repository=tea_nota_medica_repository,
|
||||
conflict_fields=("nm_id_hospital",),
|
||||
),
|
||||
"tea.EvaluacionPsicologica": EntitySpec(
|
||||
schema=EvaluacionPsicologicaImportSchema,
|
||||
model=TeaEvaluacionPsicologica,
|
||||
repository=tea_evaluacion_psicologica_repository,
|
||||
conflict_fields=None,
|
||||
),
|
||||
"tea.PotencialesEvocadosAuditivos": EntitySpec(
|
||||
schema=PotencialesEvocadosAuditivosImportSchema,
|
||||
model=TeaPotencialesEvocadosAuditivos,
|
||||
repository=tea_potenciales_evocados_auditivos_repository,
|
||||
conflict_fields=None,
|
||||
),
|
||||
"tea.EegEstudio": EntitySpec(
|
||||
schema=EegEstudioImportSchema,
|
||||
model=TeaEegEstudio,
|
||||
repository=tea_eeg_estudio_repository,
|
||||
# The EDF file and its scanned report describe the same study; both
|
||||
# the `edf` connector (from the file's own admin code) and a
|
||||
@@ -243,25 +201,21 @@ ENTITY_REGISTRY: dict[str, EntitySpec] = {
|
||||
),
|
||||
"tea.EegSegmento": EntitySpec(
|
||||
schema=EegSegmentoImportSchema,
|
||||
model=TeaEegSegmento,
|
||||
repository=tea_eeg_segmento_repository,
|
||||
conflict_fields=None,
|
||||
),
|
||||
"tea.InstrumentoAplicado": EntitySpec(
|
||||
schema=InstrumentoAplicadoImportSchema,
|
||||
model=TeaInstrumentoAplicado,
|
||||
repository=tea_instrumento_aplicado_repository,
|
||||
conflict_fields=None,
|
||||
),
|
||||
"tea.AntecedentesMaternosGestacion": EntitySpec(
|
||||
schema=AntecedentesMaternosGestacionImportSchema,
|
||||
model=TeaAntecedentesMaternosGestacion,
|
||||
repository=tea_antecedentes_maternos_gestacion_repository,
|
||||
conflict_fields=None,
|
||||
),
|
||||
"tea.PartoNeonatal": EntitySpec(
|
||||
schema=PartoNeonatalImportSchema,
|
||||
model=TeaPartoNeonatal,
|
||||
repository=tea_parto_neonatal_repository,
|
||||
conflict_fields=None,
|
||||
),
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
optional, like TEA's Core; system-managed `amg_created_at`/`amg_updated_at`/`amg_fuente_sistema` are excluded."""
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.tea.enums import (
|
||||
CategoriaPesoMaterno,
|
||||
FuenteAntecedenteMaterno,
|
||||
@@ -12,7 +10,7 @@ from core.tea.enums import (
|
||||
VolumenLiquidoAmniotico,
|
||||
)
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, optional_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, OptionalStr
|
||||
|
||||
_FUENTE_ANTECEDENTE_MATERNO_CATALOG = Catalog(FuenteAntecedenteMaterno)
|
||||
_CATEGORIA_PESO_MATERNO_CATALOG = Catalog(CategoriaPesoMaterno)
|
||||
@@ -23,7 +21,7 @@ _VOLUMEN_LIQUIDO_AMNIOTICO_CATALOG = Catalog(VolumenLiquidoAmniotico)
|
||||
|
||||
class AntecedentesMaternosGestacionImportSchema(ImportSchema):
|
||||
amg_pac_id: Optional[int] = None
|
||||
amg_id_madre_seudonimo: Optional[str] = None
|
||||
amg_id_madre_seudonimo: OptionalStr = None
|
||||
amg_fuente_antecedente: CatalogValue(_FUENTE_ANTECEDENTE_MATERNO_CATALOG) = None
|
||||
amg_flag_vinculo_verificado: Optional[int] = None
|
||||
amg_imc_pregestacional: Optional[float] = None
|
||||
@@ -34,7 +32,7 @@ class AntecedentesMaternosGestacionImportSchema(ImportSchema):
|
||||
amg_antecedente_aborto: Optional[int] = None
|
||||
amg_embarazo_multiple: CatalogValue(_TIPO_EMBARAZO_CATALOG) = None
|
||||
amg_infeccion_gestacion: Optional[int] = None
|
||||
amg_infeccion_tipo: Optional[str] = None
|
||||
amg_infeccion_tipo: OptionalStr = None
|
||||
amg_infeccion_hospitalizacion: Optional[int] = None
|
||||
amg_diabetes_gestacional: Optional[int] = None
|
||||
amg_hipertension_preeclampsia: CatalogValue(_TRASTORNO_HIPERTENSIVO_GESTACION_CATALOG) = None
|
||||
@@ -50,17 +48,8 @@ class AntecedentesMaternosGestacionImportSchema(ImportSchema):
|
||||
amg_estres_agudo: Optional[int] = None
|
||||
amg_trastorno_neurologico: Optional[int] = None
|
||||
amg_liquido_amniotico: CatalogValue(_VOLUMEN_LIQUIDO_AMNIOTICO_CATALOG) = None
|
||||
amg_medicamentos_gestacion: Optional[str] = None
|
||||
amg_medicamentos_gestacion: OptionalStr = None
|
||||
amg_farmaco_riesgo_neurodesarrollo: Optional[int] = None
|
||||
amg_observaciones: Optional[str] = None
|
||||
amg_observaciones: OptionalStr = None
|
||||
amg_ocr_confianza: Optional[float] = None
|
||||
amg_nlp_version: Optional[str] = None
|
||||
|
||||
@field_validator(
|
||||
"amg_id_madre_seudonimo", "amg_infeccion_tipo",
|
||||
"amg_medicamentos_gestacion", "amg_observaciones", "amg_nlp_version",
|
||||
mode="before",
|
||||
)
|
||||
@classmethod
|
||||
def _optional_str_fields(cls, v):
|
||||
return optional_str(v)
|
||||
amg_nlp_version: OptionalStr = None
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
"""Import schema for `core.tea.models.EegEstudio`. All fields optional, like TEA's
|
||||
Core; system-managed `eeg_created_at`/`eeg_updated_at` are excluded."""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.tea.enums import (
|
||||
CalidadTecnicaEeg,
|
||||
ConclusionEeg,
|
||||
@@ -17,7 +14,7 @@ from core.tea.enums import (
|
||||
TipoGrafoelemento,
|
||||
)
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import edf_file, Catalog, CatalogValue, coerce_date, optional_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, EdfFile, FlexDate, OptionalStr, SourceId
|
||||
|
||||
_FUENTE_INTERPRETACION_EEG_CATALOG = Catalog(FuenteInterpretacionEeg)
|
||||
_ESTADO_REGISTRO_EEG_CATALOG = Catalog(EstadoRegistroEeg)
|
||||
@@ -31,23 +28,25 @@ _CONCLUSION_EEG_CATALOG = Catalog(ConclusionEeg)
|
||||
|
||||
|
||||
class EegEstudioImportSchema(ImportSchema):
|
||||
eeg_ord_id: Optional[str] = None
|
||||
# The source's own id, kept so rows that reference it by id still point at this record.
|
||||
eeg_id: SourceId = None
|
||||
eeg_ord_id: OptionalStr = None
|
||||
eeg_pac_id: Optional[int] = None
|
||||
eeg_reporte_disponible: Optional[int] = None
|
||||
eeg_fuente_interpretacion: CatalogValue(_FUENTE_INTERPRETACION_EEG_CATALOG) = None
|
||||
eeg_fecha_nacimiento_archivo: Optional[date] = None
|
||||
eeg_fecha_nacimiento_archivo: FlexDate = None
|
||||
eeg_edad_meses: Optional[float] = None
|
||||
eeg_fecha_estudio: Optional[date] = None
|
||||
eeg_fecha_reporte: Optional[date] = None
|
||||
eeg_fecha_estudio: FlexDate = None
|
||||
eeg_fecha_reporte: FlexDate = None
|
||||
eeg_dias_respuesta: Optional[int] = None
|
||||
eeg_medico_interpreta: Optional[str] = None
|
||||
eeg_medico_interpreta: OptionalStr = None
|
||||
eeg_estado_registro: CatalogValue(_ESTADO_REGISTRO_EEG_CATALOG) = None
|
||||
eeg_privacion_sueno: Optional[int] = None
|
||||
eeg_sedacion: Optional[int] = None
|
||||
eeg_sedacion_farmaco: Optional[str] = None
|
||||
eeg_sedacion_farmaco: OptionalStr = None
|
||||
eeg_duracion_min: Optional[float] = None
|
||||
eeg_calidad_tecnica: CatalogValue(_CALIDAD_TECNICA_EEG_CATALOG) = None
|
||||
eeg_descripcion_senal: Optional[str] = None
|
||||
eeg_descripcion_senal: OptionalStr = None
|
||||
eeg_ritmo_base_frecuencia: Optional[float] = None
|
||||
eeg_ritmo_base_amplitud: Optional[int] = None
|
||||
eeg_simetria: CatalogValue(_SIMETRIA_CATALOG) = None
|
||||
@@ -55,36 +54,16 @@ class EegEstudioImportSchema(ImportSchema):
|
||||
eeg_actividad_epileptiforme: Optional[int] = None
|
||||
eeg_tipo_grafoelemento: CatalogValue(_TIPO_GRAFOELEMENTO_CATALOG) = None
|
||||
eeg_distribucion_anormalidad: CatalogValue(_DISTRIBUCION_ANORMALIDAD_CATALOG) = None
|
||||
eeg_localizacion: Optional[str] = None
|
||||
eeg_localizacion: OptionalStr = None
|
||||
eeg_activacion_sueno: Optional[int] = None
|
||||
eeg_lentificacion: CatalogValue(_LENTIFICACION_CATALOG) = None
|
||||
eeg_crisis_registradas: Optional[int] = None
|
||||
eeg_respuesta_fotoestimulacion: CatalogValue(_RESPUESTA_FOTOESTIMULACION_CATALOG) = None
|
||||
eeg_conclusion_texto: Optional[str] = None
|
||||
eeg_conclusion_texto: OptionalStr = None
|
||||
eeg_conclusion_categoria: CatalogValue(_CONCLUSION_EEG_CATALOG) = None
|
||||
eeg_id_registro_laboratorio: Optional[str] = None
|
||||
eeg_pdf_ruta: Optional[str] = None
|
||||
eeg_id_registro_laboratorio: OptionalStr = None
|
||||
eeg_pdf_ruta: OptionalStr = None
|
||||
eeg_ocr_confianza: Optional[float] = None
|
||||
eeg_nlp_version: Optional[str] = None
|
||||
eeg_nlp_version: OptionalStr = None
|
||||
eeg_utilizable: Optional[int] = None
|
||||
eeg_estudio: Optional[bytes] = None
|
||||
|
||||
@field_validator(
|
||||
"eeg_ord_id", "eeg_medico_interpreta", "eeg_sedacion_farmaco",
|
||||
"eeg_descripcion_senal", "eeg_localizacion", "eeg_conclusion_texto",
|
||||
"eeg_id_registro_laboratorio", "eeg_pdf_ruta", "eeg_nlp_version",
|
||||
mode="before",
|
||||
)
|
||||
@classmethod
|
||||
def _optional_str_fields(cls, v):
|
||||
return optional_str(v)
|
||||
|
||||
@field_validator("eeg_fecha_nacimiento_archivo", "eeg_fecha_estudio", "eeg_fecha_reporte", mode="before")
|
||||
@classmethod
|
||||
def _coerce_dates(cls, v):
|
||||
return coerce_date(v)
|
||||
|
||||
@field_validator("eeg_estudio", mode="before")
|
||||
@classmethod
|
||||
def _valid_edf(cls, v):
|
||||
return edf_file(v)
|
||||
eeg_estudio: EdfFile = None
|
||||
|
||||
@@ -2,27 +2,20 @@
|
||||
TEA's Core."""
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import optional_str
|
||||
from webapi.imports.schemas.coercion import OptionalStr
|
||||
|
||||
|
||||
class EegSegmentoImportSchema(ImportSchema):
|
||||
seg_eeg_id: Optional[str] = None
|
||||
seg_estado: Optional[str] = None
|
||||
seg_eeg_id: OptionalStr = None
|
||||
seg_estado: OptionalStr = None
|
||||
seg_inicio_s: Optional[float] = None
|
||||
seg_fin_s: Optional[float] = None
|
||||
seg_duracion_s: Optional[float] = None
|
||||
seg_fuente: Optional[str] = None
|
||||
seg_fuente: OptionalStr = None
|
||||
seg_frecuencia_flash_hz: Optional[float] = None
|
||||
seg_n_destellos: Optional[int] = None
|
||||
seg_cobertura: Optional[float] = None
|
||||
seg_rms_uv: Optional[float] = None
|
||||
seg_emg: Optional[float] = None
|
||||
seg_p2p_max_uv: Optional[float] = None
|
||||
|
||||
@field_validator("seg_eeg_id", "seg_estado", "seg_fuente", mode="before")
|
||||
@classmethod
|
||||
def _optional_str_fields(cls, v):
|
||||
return optional_str(v)
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
"""Import schema for `core.tea.models.EvaluacionPsicologica`, including the 28
|
||||
ADOS-2 item columns. All fields optional, like TEA's Core; system-managed `psi_created_at`/`psi_updated_at` are excluded."""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.tea.enums import (
|
||||
ClasificacionAdos2,
|
||||
InstrumentoTamizaje,
|
||||
@@ -13,7 +10,7 @@ from core.tea.enums import (
|
||||
VentanaMadurativa,
|
||||
)
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, coerce_date, optional_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, OptionalStr, SourceId
|
||||
|
||||
_VENTANA_MADURATIVA_CATALOG = Catalog(VentanaMadurativa)
|
||||
_INSTRUMENTO_TAMIZAJE_CATALOG = Catalog(InstrumentoTamizaje)
|
||||
@@ -23,12 +20,14 @@ _CLASIFICACION_ADOS2_CATALOG = Catalog(ClasificacionAdos2)
|
||||
|
||||
|
||||
class EvaluacionPsicologicaImportSchema(ImportSchema):
|
||||
psi_ord_id: Optional[str] = None
|
||||
# The source's own id, kept so rows that reference it by id still point at this record.
|
||||
psi_id: SourceId = None
|
||||
psi_ord_id: OptionalStr = None
|
||||
psi_pac_id: Optional[int] = None
|
||||
psi_fecha_entrevista_inicial: Optional[date] = None
|
||||
psi_fecha_ados2: Optional[date] = None
|
||||
psi_fecha_evaluacion: Optional[date] = None
|
||||
psi_psicologo: Optional[str] = None
|
||||
psi_fecha_entrevista_inicial: FlexDate = None
|
||||
psi_fecha_ados2: FlexDate = None
|
||||
psi_fecha_evaluacion: FlexDate = None
|
||||
psi_psicologo: OptionalStr = None
|
||||
psi_edad_meses: Optional[float] = None
|
||||
psi_ventana_madurativa: CatalogValue(_VENTANA_MADURATIVA_CATALOG) = None
|
||||
psi_instrumento_tamizaje: CatalogValue(_INSTRUMENTO_TAMIZAJE_CATALOG) = None
|
||||
@@ -80,22 +79,8 @@ class EvaluacionPsicologicaImportSchema(ImportSchema):
|
||||
psi_css_umbral_aplicado: Optional[int] = None
|
||||
psi_caso_confirmado: Optional[int] = None
|
||||
psi_cars_total: Optional[float] = None
|
||||
psi_otros_instrumentos: Optional[str] = None
|
||||
psi_otros_instrumentos: OptionalStr = None
|
||||
psi_regresion_desarrollo: Optional[int] = None
|
||||
psi_diagnostico_texto: Optional[str] = None
|
||||
psi_diagnostico_texto: OptionalStr = None
|
||||
psi_ocr_confianza: Optional[float] = None
|
||||
psi_nlp_version: Optional[str] = None
|
||||
|
||||
@field_validator(
|
||||
"psi_ord_id", "psi_psicologo", "psi_otros_instrumentos",
|
||||
"psi_diagnostico_texto", "psi_nlp_version",
|
||||
mode="before",
|
||||
)
|
||||
@classmethod
|
||||
def _optional_str_fields(cls, v):
|
||||
return optional_str(v)
|
||||
|
||||
@field_validator("psi_fecha_entrevista_inicial", "psi_fecha_ados2", "psi_fecha_evaluacion", mode="before")
|
||||
@classmethod
|
||||
def _coerce_fecha(cls, v):
|
||||
return coerce_date(v)
|
||||
psi_nlp_version: OptionalStr = None
|
||||
|
||||
@@ -1,24 +1,13 @@
|
||||
"""Import schema for `core.tea.models.InstrumentoAplicado`. All fields
|
||||
optional, like TEA's Core."""
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import optional_str
|
||||
from webapi.imports.schemas.coercion import OptionalStr
|
||||
|
||||
|
||||
class InstrumentoAplicadoImportSchema(ImportSchema):
|
||||
ins_psi_id: Optional[str] = None
|
||||
ins_instrumento: Optional[str] = None
|
||||
ins_informante: Optional[str] = None
|
||||
ins_area: Optional[str] = None
|
||||
ins_interpretacion: Optional[str] = None
|
||||
|
||||
@field_validator(
|
||||
"ins_psi_id", "ins_instrumento", "ins_informante", "ins_area", "ins_interpretacion",
|
||||
mode="before",
|
||||
)
|
||||
@classmethod
|
||||
def _optional_str_fields(cls, v):
|
||||
return optional_str(v)
|
||||
ins_psi_id: OptionalStr = None
|
||||
ins_instrumento: OptionalStr = None
|
||||
ins_informante: OptionalStr = None
|
||||
ins_area: OptionalStr = None
|
||||
ins_interpretacion: OptionalStr = None
|
||||
|
||||
@@ -1,13 +1,10 @@
|
||||
"""Import schema for `core.tea.models.NotaMedica`. All fields optional, like TEA's
|
||||
Core; system-managed `nm_created_at`/`nm_updated_at`/`nm_fuente_sistema` are excluded."""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.tea.enums import Especialidad, Pronostico, TipoNota, VentanaMadurativa
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, coerce_date, optional_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, OptionalStr
|
||||
|
||||
_TIPO_NOTA_CATALOG = Catalog(TipoNota)
|
||||
_ESPECIALIDAD_CATALOG = Catalog(Especialidad)
|
||||
@@ -17,27 +14,27 @@ _PRONOSTICO_CATALOG = Catalog(Pronostico)
|
||||
|
||||
class NotaMedicaImportSchema(ImportSchema):
|
||||
nm_pac_id: Optional[int] = None
|
||||
nm_id_hospital: Optional[str] = None
|
||||
nm_nota_previa_id: Optional[str] = None
|
||||
nm_id_hospital: OptionalStr = None
|
||||
nm_nota_previa_id: OptionalStr = None
|
||||
nm_tipo_nota: CatalogValue(_TIPO_NOTA_CATALOG) = None
|
||||
nm_especialidad: CatalogValue(_ESPECIALIDAD_CATALOG) = None
|
||||
nm_fecha: Optional[date] = None
|
||||
nm_fecha: FlexDate = None
|
||||
nm_edad_meses: Optional[float] = None
|
||||
nm_ventana_madurativa: CatalogValue(_VENTANA_MADURATIVA_CATALOG) = None
|
||||
nm_medico_tratante: Optional[str] = None
|
||||
nm_motivo_consulta: Optional[str] = None
|
||||
nm_interrogatorio: Optional[str] = None
|
||||
nm_medico_tratante: OptionalStr = None
|
||||
nm_motivo_consulta: OptionalStr = None
|
||||
nm_interrogatorio: OptionalStr = None
|
||||
nm_regresion_referida: Optional[int] = None
|
||||
nm_antecedente_familiar_tea: Optional[int] = None
|
||||
nm_perimetro_cefalico: Optional[float] = None
|
||||
nm_diagnostico_texto: Optional[str] = None
|
||||
nm_cie_codigo: Optional[str] = None
|
||||
nm_cie_descripcion: Optional[str] = None
|
||||
nm_tratamiento_texto: Optional[str] = None
|
||||
nm_receta: Optional[str] = None
|
||||
nm_plan_estudios: Optional[str] = None
|
||||
nm_diagnostico_texto: OptionalStr = None
|
||||
nm_cie_codigo: OptionalStr = None
|
||||
nm_cie_descripcion: OptionalStr = None
|
||||
nm_tratamiento_texto: OptionalStr = None
|
||||
nm_receta: OptionalStr = None
|
||||
nm_plan_estudios: OptionalStr = None
|
||||
nm_pronostico: CatalogValue(_PRONOSTICO_CATALOG) = None
|
||||
nm_observaciones: Optional[str] = None
|
||||
nm_observaciones: OptionalStr = None
|
||||
nm_masa_corporal: Optional[float] = None
|
||||
nm_talla: Optional[float] = None
|
||||
nm_imc_visita: Optional[float] = None
|
||||
@@ -46,20 +43,4 @@ class NotaMedicaImportSchema(ImportSchema):
|
||||
nm_presion_arterial_sistolica: Optional[int] = None
|
||||
nm_presion_arterial_diastolica: Optional[int] = None
|
||||
nm_temperatura: Optional[float] = None
|
||||
nm_pdf_ruta: Optional[str] = None
|
||||
|
||||
@field_validator(
|
||||
"nm_id_hospital", "nm_nota_previa_id", "nm_medico_tratante",
|
||||
"nm_motivo_consulta", "nm_interrogatorio", "nm_diagnostico_texto", "nm_cie_codigo",
|
||||
"nm_cie_descripcion", "nm_tratamiento_texto", "nm_receta", "nm_plan_estudios",
|
||||
"nm_observaciones", "nm_pdf_ruta",
|
||||
mode="before",
|
||||
)
|
||||
@classmethod
|
||||
def _optional_str_fields(cls, v):
|
||||
return optional_str(v)
|
||||
|
||||
@field_validator("nm_fecha", mode="before")
|
||||
@classmethod
|
||||
def _coerce_fecha(cls, v):
|
||||
return coerce_date(v)
|
||||
nm_pdf_ruta: OptionalStr = None
|
||||
|
||||
@@ -1,13 +1,10 @@
|
||||
"""Import schema for `core.tea.models.OrdenesEstudio`. All fields optional, like
|
||||
TEA's Core; system-managed `ord_*_created_at`/`ord_updated_at`/`ord_fuente_sistema` are excluded."""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.tea.enums import TIPO_ESTUDIO_ALIAS, Especialidad, EstatusEstudio, TipoEstudio, VentanaMadurativa
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, coerce_date, optional_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, OptionalStr, SourceId
|
||||
|
||||
_ESPECIALIDAD_CATALOG = Catalog(Especialidad)
|
||||
_TIPO_ESTUDIO_CATALOG = Catalog(TipoEstudio, TIPO_ESTUDIO_ALIAS)
|
||||
@@ -16,38 +13,25 @@ _VENTANA_MADURATIVA_CATALOG = Catalog(VentanaMadurativa)
|
||||
|
||||
|
||||
class OrdenesEstudioImportSchema(ImportSchema):
|
||||
# The source's own id, kept so rows that reference it by id still point at this record.
|
||||
ord_id: SourceId = None
|
||||
ord_pac_id: Optional[int] = None
|
||||
ord_nota_medica_id: Optional[str] = None
|
||||
ord_id_hospital: Optional[str] = None
|
||||
ord_fecha: Optional[date] = None
|
||||
ord_medico_solicitante: Optional[str] = None
|
||||
ord_nota_medica_id: OptionalStr = None
|
||||
ord_id_hospital: OptionalStr = None
|
||||
ord_fecha: FlexDate = None
|
||||
ord_medico_solicitante: OptionalStr = None
|
||||
ord_especialidad: CatalogValue(_ESPECIALIDAD_CATALOG) = None
|
||||
ord_diagnostico_asignado: Optional[str] = None
|
||||
ord_cie_asignado: Optional[str] = None
|
||||
ord_diagnostico_asignado: OptionalStr = None
|
||||
ord_cie_asignado: OptionalStr = None
|
||||
ord_dias_vigencia: Optional[int] = None
|
||||
ord_fecha_vencimiento: Optional[date] = None
|
||||
ord_fecha_vencimiento: FlexDate = None
|
||||
ord_tipo_estudio: CatalogValue(_TIPO_ESTUDIO_CATALOG) = None
|
||||
ord_estatus: CatalogValue(_ESTATUS_ESTUDIO_CATALOG) = None
|
||||
ord_fecha_realizacion: Optional[date] = None
|
||||
ord_fecha_resultado: Optional[date] = None
|
||||
ord_fecha_realizacion: FlexDate = None
|
||||
ord_fecha_resultado: FlexDate = None
|
||||
ord_dias_espera: Optional[int] = None
|
||||
ord_proveedor: Optional[str] = None
|
||||
ord_proveedor: OptionalStr = None
|
||||
ord_edad_meses: Optional[float] = None
|
||||
ord_ventana_madurativa: CatalogValue(_VENTANA_MADURATIVA_CATALOG) = None
|
||||
ord_pdf_ruta: Optional[str] = None
|
||||
ord_observaciones: Optional[str] = None
|
||||
|
||||
@field_validator(
|
||||
"ord_nota_medica_id", "ord_id_hospital", "ord_medico_solicitante",
|
||||
"ord_diagnostico_asignado", "ord_cie_asignado", "ord_proveedor", "ord_pdf_ruta",
|
||||
"ord_observaciones",
|
||||
mode="before",
|
||||
)
|
||||
@classmethod
|
||||
def _optional_str_fields(cls, v):
|
||||
return optional_str(v)
|
||||
|
||||
@field_validator("ord_fecha", "ord_fecha_vencimiento", "ord_fecha_realizacion", "ord_fecha_resultado", mode="before")
|
||||
@classmethod
|
||||
def _coerce_dates(cls, v):
|
||||
return coerce_date(v)
|
||||
ord_pdf_ruta: OptionalStr = None
|
||||
ord_observaciones: OptionalStr = None
|
||||
|
||||
@@ -3,14 +3,11 @@ Core; system-managed `pac_created_at`/`pac_updated_at`/`pac_fuente_sistema` are
|
||||
|
||||
`pac_id` is importable: every other TEA table references the patient by the
|
||||
source system's integer id, so it has to be kept, not renumbered."""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.tea.enums import Parentesco, SexoBiologico
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, coerce_date, optional_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, OptionalStr
|
||||
|
||||
_SEXO_CATALOG = Catalog(SexoBiologico)
|
||||
_PARENTESCO_CATALOG = Catalog(Parentesco)
|
||||
@@ -18,20 +15,10 @@ _PARENTESCO_CATALOG = Catalog(Parentesco)
|
||||
|
||||
class PacientesImportSchema(ImportSchema):
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: Optional[str] = None
|
||||
pac_id_titular: Optional[str] = None
|
||||
pac_id_hospital: OptionalStr = None
|
||||
pac_id_titular: OptionalStr = None
|
||||
pac_parentesco: CatalogValue(_PARENTESCO_CATALOG) = None
|
||||
pac_fecha_nacimiento: Optional[date] = None
|
||||
pac_fecha_nacimiento: FlexDate = None
|
||||
pac_sexo: CatalogValue(_SEXO_CATALOG) = None
|
||||
pac_codigo_postal_vigente: Optional[str] = None
|
||||
pac_dependencia: Optional[str] = None
|
||||
|
||||
@field_validator("pac_id_hospital", "pac_id_titular", "pac_codigo_postal_vigente", "pac_dependencia", mode="before")
|
||||
@classmethod
|
||||
def _optional_str_fields(cls, v):
|
||||
return optional_str(v)
|
||||
|
||||
@field_validator("pac_fecha_nacimiento", mode="before")
|
||||
@classmethod
|
||||
def _coerce_fecha_nacimiento(cls, v):
|
||||
return coerce_date(v)
|
||||
pac_codigo_postal_vigente: OptionalStr = None
|
||||
pac_dependencia: OptionalStr = None
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
TEA's Core; system-managed `pnn_created_at`/`pnn_updated_at`/`pnn_fuente_sistema` are excluded."""
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.tea.enums import (
|
||||
ClasificacionEdadGestacional,
|
||||
ComplicacionIntraparto,
|
||||
@@ -12,7 +10,7 @@ from core.tea.enums import (
|
||||
TipoParto,
|
||||
)
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, optional_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, OptionalStr
|
||||
|
||||
_FUENTE_ANTECEDENTE_NEONATAL_CATALOG = Catalog(FuenteAntecedenteNeonatal)
|
||||
_TIPO_PARTO_CATALOG = Catalog(TipoParto)
|
||||
@@ -45,16 +43,8 @@ class PartoNeonatalImportSchema(ImportSchema):
|
||||
pnn_hipoglucemia_neonatal: Optional[int] = None
|
||||
pnn_anoxia: Optional[int] = None
|
||||
pnn_sindrome_congenito: Optional[int] = None
|
||||
pnn_sindrome_congenito_desc: Optional[str] = None
|
||||
pnn_sindrome_congenito_desc: OptionalStr = None
|
||||
pnn_flag_riesgo_neonatal: Optional[int] = None
|
||||
pnn_observaciones: Optional[str] = None
|
||||
pnn_observaciones: OptionalStr = None
|
||||
pnn_ocr_confianza: Optional[float] = None
|
||||
pnn_nlp_version: Optional[str] = None
|
||||
|
||||
@field_validator(
|
||||
"pnn_sindrome_congenito_desc", "pnn_observaciones", "pnn_nlp_version",
|
||||
mode="before",
|
||||
)
|
||||
@classmethod
|
||||
def _optional_str_fields(cls, v):
|
||||
return optional_str(v)
|
||||
pnn_nlp_version: OptionalStr = None
|
||||
|
||||
@@ -1,22 +1,19 @@
|
||||
"""Import schema for `core.tea.models.PotencialesEvocadosAuditivos`. All fields
|
||||
optional, like TEA's Core; system-managed `pea_created_at`/`pea_updated_at` are excluded."""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.tea.enums import GradoHipoacusia
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, coerce_date, optional_str
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, FlexDate, OptionalStr
|
||||
|
||||
_GRADO_HIPOACUSIA_CATALOG = Catalog(GradoHipoacusia)
|
||||
|
||||
|
||||
class PotencialesEvocadosAuditivosImportSchema(ImportSchema):
|
||||
pea_ord_id: Optional[str] = None
|
||||
pea_ord_id: OptionalStr = None
|
||||
pea_pac_id: Optional[int] = None
|
||||
pea_fecha_estudio: Optional[date] = None
|
||||
pea_medico_interpreta: Optional[str] = None
|
||||
pea_fecha_estudio: FlexDate = None
|
||||
pea_medico_interpreta: OptionalStr = None
|
||||
pea_umbral_od: Optional[int] = None
|
||||
pea_umbral_oi: Optional[int] = None
|
||||
pea_latencia_v_od: Optional[float] = None
|
||||
@@ -24,19 +21,6 @@ class PotencialesEvocadosAuditivosImportSchema(ImportSchema):
|
||||
pea_interpico_i_v_od: Optional[float] = None
|
||||
pea_interpico_i_v_oi: Optional[float] = None
|
||||
pea_grado_hipoacusia: CatalogValue(_GRADO_HIPOACUSIA_CATALOG) = None
|
||||
pea_conclusion_texto: Optional[str] = None
|
||||
pea_conclusion_texto: OptionalStr = None
|
||||
pea_flag_diferencial_auditivo: Optional[int] = None
|
||||
pea_ocr_confianza: Optional[float] = None
|
||||
|
||||
@field_validator(
|
||||
"pea_ord_id", "pea_medico_interpreta", "pea_conclusion_texto",
|
||||
mode="before",
|
||||
)
|
||||
@classmethod
|
||||
def _optional_str_fields(cls, v):
|
||||
return optional_str(v)
|
||||
|
||||
@field_validator("pea_fecha_estudio", mode="before")
|
||||
@classmethod
|
||||
def _coerce_fecha(cls, v):
|
||||
return coerce_date(v)
|
||||
|
||||
@@ -25,6 +25,10 @@ class ImportRequestError(Exception):
|
||||
bad connection string or an invalid on_conflict. Mapped to HTTP 400."""
|
||||
|
||||
|
||||
class DatabaseRefused(ImportRequestError):
|
||||
"""The database rejected the batch at write time; nothing was written."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ImportSource:
|
||||
"""One parsed and structurally validated entry of a request's `sources`."""
|
||||
@@ -40,32 +44,32 @@ class ImportSource:
|
||||
@classmethod
|
||||
def parse(cls, raw: Any) -> "ImportSource":
|
||||
if not isinstance(raw, dict):
|
||||
raise ImportRequestError("each source must be an object")
|
||||
raise ImportRequestError("cada fuente debe ser un objeto")
|
||||
target = raw.get("target")
|
||||
if not target:
|
||||
raise ImportRequestError("source is missing 'target'")
|
||||
raise ImportRequestError("a la fuente le falta 'target'")
|
||||
spec = ENTITY_REGISTRY.get(target)
|
||||
if spec is None:
|
||||
raise ImportRequestError(f"unknown target: {target!r}")
|
||||
raise ImportRequestError(f"destino desconocido: {target!r}")
|
||||
|
||||
fields = set(spec.schema.model_fields)
|
||||
mapping = raw.get("column_mapping") or {}
|
||||
defaults = raw.get("defaults") or {}
|
||||
if not isinstance(mapping, dict) or not isinstance(defaults, dict):
|
||||
raise ImportRequestError("'column_mapping' and 'defaults' must be objects")
|
||||
raise ImportRequestError("'column_mapping' y 'defaults' deben ser objetos")
|
||||
unknown = sorted((set(mapping.values()) | set(defaults)) - fields)
|
||||
if unknown:
|
||||
raise ImportRequestError(f"{target} has no field(s) {unknown}")
|
||||
raise ImportRequestError(f"{target} no tiene los campos {unknown}")
|
||||
targets = list(mapping.values())
|
||||
duplicated = sorted({t for t in targets if targets.count(t) > 1})
|
||||
if duplicated:
|
||||
raise ImportRequestError(f"more than one source column mapped to {duplicated}")
|
||||
raise ImportRequestError(f"más de una columna de origen asignada a {duplicated}")
|
||||
if not mapping and not defaults:
|
||||
raise ImportRequestError(f"source for {target} maps no columns")
|
||||
raise ImportRequestError(f"la fuente de {target} no asigna ninguna columna")
|
||||
|
||||
payload = raw.get("payload")
|
||||
if not isinstance(payload, dict):
|
||||
raise ImportRequestError("source is missing 'payload'")
|
||||
raise ImportRequestError("a la fuente le falta 'payload'")
|
||||
return cls(
|
||||
source_type=raw.get("source_type", ""),
|
||||
target=target,
|
||||
@@ -159,12 +163,12 @@ class SourceCommitResult:
|
||||
|
||||
def _parse_batch(raw_sources: Any) -> list[ImportSource]:
|
||||
if not isinstance(raw_sources, list) or not raw_sources:
|
||||
raise ImportRequestError("'sources' must be a non-empty list")
|
||||
raise ImportRequestError("'sources' debe ser una lista no vacía")
|
||||
sources = [ImportSource.parse(raw) for raw in raw_sources]
|
||||
domains = sorted({source.domain for source in sources})
|
||||
if len(domains) > 1:
|
||||
raise ImportRequestError(
|
||||
f"a batch cannot mix domains — got {domains}, every source must target the same one"
|
||||
f"un lote no puede mezclar dominios ({', '.join(domains)}): todas las fuentes deben ir al mismo"
|
||||
)
|
||||
return sources
|
||||
|
||||
@@ -214,11 +218,8 @@ def merge_duplicates(sources: list[ImportSource], rows: list[list[dict[str, Any]
|
||||
|
||||
|
||||
def _key_part(value: Any) -> Any:
|
||||
"""Normalized for comparison across sources: a CSV's natural key is
|
||||
always a string ("5001"), while a typed source (the document extractor,
|
||||
a SQL column) can hand back an int or a date for the very same value.
|
||||
Stringifying both sides is what lets rows that describe the same record
|
||||
actually match, instead of silently landing as two separate ones."""
|
||||
"""Normalized for comparison across sources: a CSV key is the string "5001"
|
||||
where a typed source gives the int 5001."""
|
||||
if _is_blank(value):
|
||||
return None
|
||||
return str(value).strip().upper()
|
||||
@@ -232,14 +233,14 @@ def commit_sources(
|
||||
try:
|
||||
policy = ConflictPolicy(on_conflict)
|
||||
except ValueError as exc:
|
||||
raise ImportRequestError(f"invalid on_conflict: {on_conflict!r}") from exc
|
||||
raise ImportRequestError(f"on_conflict inválido: {on_conflict!r}") from exc
|
||||
|
||||
sources = _parse_batch(raw_sources)
|
||||
tracked = [audit.source(source) for source in sources] if audit else []
|
||||
if policy is ConflictPolicy.UPSERT:
|
||||
keyless = sorted({s.target for s in sources if not s.spec.conflict_fields})
|
||||
if keyless:
|
||||
raise ImportRequestError(f"{', '.join(keyless)} has no natural key — on_conflict=upsert is not valid for it")
|
||||
raise ImportRequestError(f"{', '.join(keyless)} no tiene llave natural: on_conflict=upsert no aplica")
|
||||
|
||||
# Read + validate everything before opening the write transaction, so a
|
||||
# slow source (OCR, a remote SQL table) never holds database locks.
|
||||
@@ -274,7 +275,7 @@ def commit_sources(
|
||||
"row_index": validation.accepted_rows[outcome.index].row_index,
|
||||
"field": ",".join(source.spec.conflict_fields or ()),
|
||||
"category": "conflict",
|
||||
"message": outcome.error or "conflict",
|
||||
"message": outcome.error or "conflicto",
|
||||
"raw_value": _jsonable(
|
||||
validation.accepted_rows[outcome.index].data.get((source.spec.conflict_fields or ("",))[0])
|
||||
),
|
||||
@@ -303,7 +304,10 @@ def commit_sources(
|
||||
session.commit()
|
||||
except SQLAlchemyError as exc:
|
||||
session.rollback()
|
||||
raise ImportRequestError(f"the database refused the batch, nothing was written: {exc.__class__.__name__}: {exc.orig if hasattr(exc, 'orig') else exc}") from exc
|
||||
detail = exc.orig if hasattr(exc, "orig") else exc
|
||||
raise DatabaseRefused(
|
||||
f"la base de datos rechazó el lote y no se escribió nada: {exc.__class__.__name__}: {detail}"
|
||||
) from exc
|
||||
finally:
|
||||
session.close()
|
||||
return [results[i] for i in range(len(validated))]
|
||||
|
||||
@@ -9,7 +9,7 @@ from webapi.imports.connectors import Connector, ConnectorError
|
||||
from webapi.imports.connectors.document import DocumentConnector
|
||||
from webapi.imports.connectors.pdf import PdfConnector, RegionSpec
|
||||
from webapi.imports.connectors.tabular import columns_from_dataframe, rows_from_dataframe
|
||||
from webapi.imports.mapping.column_matcher import ColumnMatcher
|
||||
from webapi.imports.mapping import column_matcher
|
||||
from webapi.imports.schemas.registry import ENTITY_REGISTRY
|
||||
|
||||
|
||||
@@ -18,8 +18,8 @@ def suggest_mapping(source_columns: list[str], target_key: str | None) -> list[d
|
||||
return []
|
||||
spec = ENTITY_REGISTRY.get(target_key)
|
||||
if spec is None:
|
||||
raise ConnectorError(f"unknown target: {target_key!r}")
|
||||
matches = ColumnMatcher().suggest(source_columns, list(spec.schema.model_fields.keys()))
|
||||
raise ConnectorError(f"destino desconocido: {target_key!r}")
|
||||
matches = column_matcher.suggest_mapping(source_columns, list(spec.schema.model_fields.keys()))
|
||||
return [
|
||||
{"source_column": m.source_column, "target_field": m.target_field, "confidence": m.confidence, "reason": m.reason}
|
||||
for m in matches
|
||||
|
||||
@@ -5,8 +5,8 @@ same batch.
|
||||
|
||||
Links are derived from Core's columns: an entity with both `pac_id` and
|
||||
`pac_id_hospital` links to its domain's `Paciente`, and one with both
|
||||
`ord_id` and `ord_numero_hospital` links to its `OrdenesEstudio`. TEA uses
|
||||
UUID keys without such pairs, so it gets no links.
|
||||
`ord_id` and `ord_numero_hospital` links to its `OrdenesEstudio`. TEA's child
|
||||
tables carry the source's patient id itself (`*_pac_id`), so it needs none.
|
||||
"""
|
||||
from dataclasses import dataclass
|
||||
from functools import cache
|
||||
|
||||
+12
-22
@@ -3,8 +3,8 @@
|
||||
A successful import asks for a recomputation (`ColaDeRecalculo.solicitar`),
|
||||
which only drops a marker file. A separate process (`python -m
|
||||
webapi.indicadores_vivos`, the `indicadores` compose service) picks the
|
||||
markers up and runs that domain's pipeline with Hamilton (`webapi.pipeline`):
|
||||
catalogs -> staging to facts -> views -> registry -> definitions -> reports.
|
||||
markers up and runs that domain's cycle (`orquestacion.correr`): catalogs ->
|
||||
staging to facts -> views -> registry -> definitions -> reports.
|
||||
Requests that arrive while a domain is running are folded into one more run.
|
||||
|
||||
State lives in files under `INDICADORES_DIR`: `pendiente/<dominio>` markers
|
||||
@@ -18,6 +18,7 @@ import json
|
||||
import logging
|
||||
import os
|
||||
import signal
|
||||
import threading
|
||||
import time
|
||||
from datetime import date, datetime, timezone
|
||||
from pathlib import Path
|
||||
@@ -97,10 +98,7 @@ class ColaDeRecalculo:
|
||||
|
||||
def correr(self, dominio: str, *, desde: int | None = None, hasta: int | None = None) -> dict[str, Any]:
|
||||
"""Runs the domain's graph (without `migrar`: the API migrates on startup)."""
|
||||
from orquestacion import Contexto
|
||||
from orquestacion.aristas import aristas_de
|
||||
|
||||
from webapi.pipeline import correr
|
||||
from orquestacion import Contexto, correr, pasos_de
|
||||
|
||||
desde = desde or int(os.environ.get("INDICADORES_DESDE", date.today().year - 5))
|
||||
hasta = hasta or int(os.environ.get("INDICADORES_HASTA", date.today().year))
|
||||
@@ -110,11 +108,10 @@ class ColaDeRecalculo:
|
||||
entrada: dict[str, Any] = {"inicio": inicio, "anios": [desde, hasta]}
|
||||
try:
|
||||
ctx = Contexto(dominio, desde, hasta, permitir_sin_definir=True)
|
||||
nombres = [a.nombre for a in aristas_de(dominio) if a.nombre != "migrar"]
|
||||
pasos = correr(ctx, solo=nombres)
|
||||
pasos = correr(ctx, solo=[p for p in pasos_de(dominio) if p != "migrar"])
|
||||
entrada.update(
|
||||
estado="ok",
|
||||
pasos=[{"arista": p.arista, "segundos": round(p.segundos, 2), "resumen": _short(p.resumen)} for p in pasos],
|
||||
pasos=[{"paso": p.nombre, "segundos": round(p.segundos, 2), "resumen": _short(p.resumen)} for p in pasos],
|
||||
)
|
||||
except Exception as exc: # the worker must survive a failing domain
|
||||
log.exception("recálculo de %s falló", dominio)
|
||||
@@ -144,22 +141,15 @@ def main() -> None:
|
||||
if os.environ.get("INDICADORES_AL_INICIAR", "1") == "1":
|
||||
for dominio in DOMINIOS:
|
||||
cola.solicitar(dominio)
|
||||
stopping = False
|
||||
|
||||
def _stop(*_):
|
||||
nonlocal stopping
|
||||
stopping = True
|
||||
|
||||
signal.signal(signal.SIGTERM, _stop)
|
||||
signal.signal(signal.SIGINT, _stop)
|
||||
stop = threading.Event()
|
||||
signal.signal(signal.SIGTERM, lambda *_: stop.set())
|
||||
signal.signal(signal.SIGINT, lambda *_: stop.set())
|
||||
log.info("indicadores en vivo: revisando cada %.0f s en %s", interval, cola.base)
|
||||
while not stopping:
|
||||
while True:
|
||||
for dominio in cola.atender():
|
||||
log.info("%s: %s", dominio, cola.estado()[dominio].get("estado"))
|
||||
for _ in range(int(interval * 10)):
|
||||
if stopping:
|
||||
break
|
||||
time.sleep(0.1)
|
||||
if stop.wait(interval):
|
||||
break
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -1,89 +0,0 @@
|
||||
"""Runs a domain's indicator pipeline with Hamilton.
|
||||
|
||||
The steps are the kit's own transformations as Orquestacion declares them
|
||||
(`orquestacion.aristas.aristas_de`): each one names the table groups it reads
|
||||
and writes, and moves data only through the database. Here every step becomes
|
||||
a Hamilton node whose inputs are the steps that write what it reads, so
|
||||
Hamilton orders and runs the graph; nothing of Orquestacion's own executor is
|
||||
used. Steps left out of `solo` are given as overrides and don't run.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import inspect
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from types import ModuleType
|
||||
from typing import Any, Callable, Sequence
|
||||
|
||||
from hamilton import ad_hoc_utils, driver
|
||||
from orquestacion.arista import Arista, Contexto
|
||||
from orquestacion.aristas import aristas_de
|
||||
from orquestacion.repositorios import repositorios_de
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Paso:
|
||||
"""What a step left: its short summary and how long it took. `None` summary: not run."""
|
||||
|
||||
arista: str
|
||||
resumen: Any
|
||||
segundos: float
|
||||
|
||||
|
||||
def _node(arista: Arista, ctx: Contexto, inputs: Sequence[str]) -> Callable[..., Paso]:
|
||||
def run(**_upstream: Paso) -> Paso:
|
||||
started = time.monotonic()
|
||||
return Paso(arista.nombre, arista.correr(ctx), time.monotonic() - started)
|
||||
|
||||
run.__name__ = arista.nombre
|
||||
run.__doc__ = arista.descripcion
|
||||
run.__annotations__ = {name: Paso for name in inputs} | {"return": Paso}
|
||||
run.__signature__ = inspect.Signature(
|
||||
[inspect.Parameter(name, inspect.Parameter.KEYWORD_ONLY, annotation=Paso) for name in inputs],
|
||||
return_annotation=Paso,
|
||||
)
|
||||
return run
|
||||
|
||||
|
||||
def modulo(ctx: Contexto, aristas: Sequence[Arista]) -> ModuleType:
|
||||
"""The Hamilton module of a domain: one function per step."""
|
||||
writer = {vertex: arista.nombre for arista in aristas for vertex in arista.escribe}
|
||||
nodes = []
|
||||
for arista in aristas:
|
||||
inputs = sorted({writer[v] for v in arista.lee if v in writer and writer[v] != arista.nombre})
|
||||
nodes.append(_node(arista, ctx, inputs))
|
||||
return ad_hoc_utils.create_temporary_module(*nodes)
|
||||
|
||||
|
||||
def correr(ctx: Contexto, *, solo: Sequence[str] | None = None) -> list[Paso]:
|
||||
"""Runs the domain's steps (all, or only `solo`) in dependency order."""
|
||||
if ctx.repos is None:
|
||||
ctx = Contexto(ctx.proyecto, ctx.anio_inicio, ctx.anio_fin, ctx.corte, ctx.permitir_sin_definir,
|
||||
ctx.parametros, repos=repositorios_de(ctx.proyecto))
|
||||
aristas = aristas_de(ctx.proyecto)
|
||||
nombres = [a.nombre for a in aristas]
|
||||
wanted = [n for n in nombres if solo is None or n in solo]
|
||||
skipped = {n: Paso(n, None, 0.0) for n in nombres if n not in wanted}
|
||||
dr = driver.Builder().with_modules(modulo(ctx, aristas)).build()
|
||||
results = dr.execute(wanted, overrides=skipped)
|
||||
return [results[n] for n in _order(dr, wanted)]
|
||||
|
||||
|
||||
def _order(dr: driver.Driver, wanted: Sequence[str]) -> list[str]:
|
||||
"""Topological order of the requested steps, for reporting."""
|
||||
graph = dr.graph
|
||||
order: list[str] = []
|
||||
seen: set[str] = set()
|
||||
|
||||
def visit(name: str) -> None:
|
||||
if name in seen:
|
||||
return
|
||||
seen.add(name)
|
||||
for dependency in graph.nodes[name].dependencies:
|
||||
visit(dependency.name)
|
||||
if name in wanted:
|
||||
order.append(name)
|
||||
|
||||
for name in wanted:
|
||||
visit(name)
|
||||
return order
|
||||
Reference in New Issue
Block a user