Compare commits
79 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c326f4901d | |||
| 37c456c5ef | |||
| edd3093d5d | |||
| 323240dd30 | |||
| 326502f90c | |||
| 2c5568f5d1 | |||
| 87a0893ee4 | |||
| 82f7a18a9f | |||
| b4db5f9b2c | |||
| 06f1cadc4b | |||
| b61a4863d1 | |||
| 6c1d098619 | |||
| 4063a9824b | |||
| f26d32a010 | |||
| b61843b639 | |||
| 80049112aa | |||
| ec5d945f71 | |||
| 54b1995681 | |||
| 52bcf34720 | |||
| d92d1697b8 | |||
| 983680ead3 | |||
| 3300ec3048 | |||
| 8a2ce3bbb4 | |||
| eda8dde354 | |||
| 08f240cde9 | |||
| 80b3d23b75 | |||
| b401f98f19 | |||
| 9e5aa20092 | |||
| 88b22b9491 | |||
| d7624c7e0f | |||
| c9b60b190b | |||
| 4ef38c18e2 | |||
| f830003abd | |||
| 3a18af9516 | |||
| 29186909cc | |||
| c7caf56f83 | |||
| 0a4deea370 | |||
| 25955b80e8 | |||
| 8b0b121aaa | |||
| 11c648ac36 | |||
| ae4638e4dd | |||
| 51bcdbdfe3 | |||
| 4212c4d0b5 | |||
| d59c20432e | |||
| d8d834f308 | |||
| f6e8b09dd0 | |||
| 2131ff60a5 | |||
| a4c3d6c1b0 | |||
| e3e774fca4 | |||
| 09691afc76 | |||
| 70c9506b97 | |||
| 7222cbdb49 | |||
| 7e25dde319 | |||
| 052fb23fab | |||
| b515746406 | |||
| 3438a3135b | |||
| 88bbc6155f | |||
| e434e085fe | |||
| e4967347f5 | |||
| 4793cf01f0 | |||
| 8fa2be8aab | |||
| de4485094f | |||
| 074fdb5305 | |||
| 135f23e898 | |||
| d3f7aeb537 | |||
| 1e878b8942 | |||
| dffd33a7bc | |||
| 9c89c9e10d | |||
| 7dbb4b75fc | |||
| 05980899a2 | |||
| cb9115c435 | |||
| 26cf994d1a | |||
| 806302ee5d | |||
| 0dd5c035bc | |||
| e2ed1e9dfb | |||
| 1c53276b55 | |||
| 326250ffb3 | |||
| cddf91185b | |||
| df921f13cd |
@@ -1,9 +1,2 @@
|
||||
__pycache__/
|
||||
*.pyc
|
||||
.venv/
|
||||
.pytest_cache/
|
||||
.coverage
|
||||
*.egg-info/
|
||||
.env
|
||||
uv.lock
|
||||
*.db
|
||||
|
||||
-39
@@ -1,39 +0,0 @@
|
||||
# Build context is the repo root (see docker-compose.yml) so the sibling
|
||||
# packages Core/, Persistance/, Extraction/, models/, indicadores_kit/ and
|
||||
# Orquestacion/ can be copied.
|
||||
FROM python:3.12-slim
|
||||
|
||||
# Tesseract (with Spanish data) for scanned documents; pytesseract only wraps the binary.
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
tesseract-ocr tesseract-ocr-spa \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
RUN pip install --no-cache-dir uv
|
||||
|
||||
WORKDIR /app
|
||||
COPY Core/ Core/
|
||||
COPY Persistance/ Persistance/
|
||||
COPY Extraction/ Extraction/
|
||||
COPY models/ models/
|
||||
COPY indicadores_kit/ indicadores_kit/
|
||||
COPY Orquestacion/ Orquestacion/
|
||||
COPY WebApi/ WebApi/
|
||||
|
||||
# Migrations need the MySQL/PostgreSQL drivers when *_DATABASE_URL points there.
|
||||
RUN cd Persistance && uv sync --no-dev --extra drivers
|
||||
# Drivers for the SQL import sources (MySQL/MariaDB, PostgreSQL, SQL Server).
|
||||
RUN cd WebApi && uv sync --no-dev --extra sql-drivers
|
||||
# The indicator pipeline (staging -> facts -> reports), run with
|
||||
# `python -m orquestacion ciclo <proyecto> ...` after an import.
|
||||
RUN cd Orquestacion && uv sync --no-dev --extra drivers
|
||||
|
||||
ENV CACU_DATABASE_URL=sqlite:////data/cacu.db
|
||||
ENV CAMA_DATABASE_URL=sqlite:////data/cama.db
|
||||
ENV TEA_DATABASE_URL=sqlite:////data/tea.db
|
||||
ENV GOVERNANCE_DATABASE_URL=sqlite:////data/governance.db
|
||||
ENV MODELS_ARTIFACT_ROOT=/data/artifacts
|
||||
|
||||
RUN chmod +x /app/WebApi/docker-entrypoint.sh
|
||||
|
||||
EXPOSE 5000
|
||||
ENTRYPOINT ["/app/WebApi/docker-entrypoint.sh"]
|
||||
@@ -1,32 +0,0 @@
|
||||
#!/bin/sh
|
||||
set -e
|
||||
|
||||
mkdir -p /data
|
||||
|
||||
# SQLite won't create a missing parent directory for its database file.
|
||||
for url in "$CACU_DATABASE_URL" "$CAMA_DATABASE_URL" "$TEA_DATABASE_URL" "$GOVERNANCE_DATABASE_URL"; do
|
||||
case "$url" in
|
||||
sqlite:///*) mkdir -p "$(dirname "${url#sqlite:///}")" ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# --no-sync: the image's environments were synced at build time; syncing at
|
||||
# startup would try to reach the package index (and pull dev deps).
|
||||
cd /app/Persistance
|
||||
uv run --no-sync alembic -c persistance/cacu/alembic.ini upgrade head
|
||||
uv run --no-sync alembic -c persistance/cama/alembic.ini upgrade head
|
||||
uv run --no-sync alembic -c persistance/tea/alembic.ini upgrade head
|
||||
uv run --no-sync alembic -c persistance/governance/alembic.ini upgrade head
|
||||
|
||||
cd /app/WebApi
|
||||
# Container's own network namespace — no AirPlay conflict here, keep it on
|
||||
# the port the Dockerfile EXPOSEs and docker-compose.yml maps from.
|
||||
PORT="${PORT:-5000}"
|
||||
# gunicorn, not Flask's development server. Long timeout: OCR over a
|
||||
# multi-page scanned PDF runs inside a single request.
|
||||
exec uv run --no-sync gunicorn \
|
||||
--bind "0.0.0.0:${PORT}" \
|
||||
--workers "${WEBAPI_WORKERS:-2}" \
|
||||
--timeout "${WEBAPI_TIMEOUT:-600}" \
|
||||
--access-logfile - \
|
||||
"webapi:create_app()"
|
||||
@@ -1,14 +0,0 @@
|
||||
import os
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Default avoids port 5000 — on macOS that's squatted by the AirPlay
|
||||
# Receiver service (ControlCenter), which answers with a bare 403 and
|
||||
# makes this look like a broken server rather than "port taken."
|
||||
# Docker's entrypoint overrides this back to 5000 for the container's
|
||||
# own internal port (see docker-entrypoint.sh), which is fine since
|
||||
# that's an isolated network namespace, not the host.
|
||||
app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 5050)))
|
||||
+18
-38
@@ -1,47 +1,27 @@
|
||||
[project]
|
||||
name = "webapi"
|
||||
version = "0.1.0"
|
||||
description = "Flask REST API fronting Persistance (reads) and models (train/predict) for CaCu, CaMa and TEA."
|
||||
version = "0.0.0"
|
||||
description = "FastAPI: FHIR routes, control routes, the auth dependency."
|
||||
requires-python = ">=3.12"
|
||||
dependencies = [
|
||||
"flask>=3.0",
|
||||
"core",
|
||||
"persistance",
|
||||
"models[export]",
|
||||
"extraction",
|
||||
"indicadores-kit",
|
||||
"pandas>=2.0",
|
||||
"openpyxl>=3.1",
|
||||
"sqlalchemy>=2.0",
|
||||
"pydantic>=2.0",
|
||||
"pdfplumber>=0.11",
|
||||
"pytesseract>=0.3.10",
|
||||
"Pillow>=10.0",
|
||||
"flask-cors>=4.0",
|
||||
"gunicorn>=23.0",
|
||||
"fastapi[standard]",
|
||||
"dagster-graphql",
|
||||
"authlib>=1.6",
|
||||
"fastapi-users[sqlalchemy]>=15",
|
||||
"aiosqlite>=0.20",
|
||||
"asyncpg>=0.30",
|
||||
"requests",
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
sql-drivers = [
|
||||
"psycopg2-binary>=2.9",
|
||||
"pymysql>=1.1",
|
||||
"pymssql>=2.3",
|
||||
]
|
||||
|
||||
[tool.uv.sources]
|
||||
persistance = { path = "../Persistance", editable = true }
|
||||
models = { path = "../models", editable = true }
|
||||
extraction = { path = "../Extraction", editable = true }
|
||||
indicadores-kit = { path = "../indicadores_kit", editable = true }
|
||||
|
||||
[build-system]
|
||||
requires = ["hatchling"]
|
||||
build-backend = "hatchling.build"
|
||||
requires = ["uv_build>=0.12,<0.13"]
|
||||
build-backend = "uv_build"
|
||||
|
||||
[tool.hatch.build.targets.wheel]
|
||||
packages = ["webapi"]
|
||||
|
||||
[dependency-groups]
|
||||
dev = [
|
||||
"pytest>=8.0.0",
|
||||
"reportlab>=4.0",
|
||||
]
|
||||
[tool.uv.build-backend]
|
||||
module-name = "webapi"
|
||||
module-root = ""
|
||||
[tool.uv.sources]
|
||||
core = { workspace = true }
|
||||
persistance = { workspace = true }
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
"""Shared test wiring.
|
||||
|
||||
`persistance.settings.settings` is a module-level singleton and the
|
||||
`persistance.db.get_<domain>_engine` functions are `@lru_cache`d, so changing
|
||||
`<DOMAIN>_DATABASE_URL` alone has no effect once an engine exists.
|
||||
`wire_domain` resets all three (env var, singleton, cache).
|
||||
"""
|
||||
import os
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
# Tests use throwaway SQLite files as "arbitrary SQL sources"; production
|
||||
# excludes sqlite by default (see webapi.imports.connectors.sql_policy).
|
||||
os.environ.setdefault("WEBAPI_SQL_ALLOWED_DIALECTS", "sqlite,mysql,mariadb,postgresql,mssql,oracle")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def wire_domain():
|
||||
"""Factory fixture: `wire_domain("cacu")` points the domain at a fresh temp
|
||||
SQLite file for this module and returns its path. Temp files are removed
|
||||
when the module finishes."""
|
||||
created_paths: list[str] = []
|
||||
|
||||
def _wire(domain: str) -> str:
|
||||
db_path = tempfile.NamedTemporaryFile(suffix=".db", delete=False).name
|
||||
url = f"sqlite:///{db_path}"
|
||||
os.environ[f"{domain.upper()}_DATABASE_URL"] = url
|
||||
|
||||
from persistance import db as persistance_db
|
||||
from persistance import settings as persistance_settings
|
||||
|
||||
setattr(persistance_settings.settings, f"{domain}_database_url", url)
|
||||
getattr(persistance_db, f"get_{domain}_engine").cache_clear()
|
||||
created_paths.append(db_path)
|
||||
_migrate(domain)
|
||||
return db_path
|
||||
|
||||
yield _wire
|
||||
|
||||
for path in created_paths:
|
||||
os.unlink(path)
|
||||
|
||||
|
||||
def _migrate(domain: str) -> None:
|
||||
"""Builds the schema with the Alembic migrations rather than
|
||||
`metadata.create_all`, so tests run against the deployed schema and a
|
||||
broken migration fails the suite."""
|
||||
from alembic import command
|
||||
from alembic.config import Config
|
||||
|
||||
import persistance
|
||||
|
||||
ini = Path(persistance.__file__).parent / domain / "alembic.ini"
|
||||
command.upgrade(Config(str(ini)), "head")
|
||||
@@ -1,56 +0,0 @@
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(wire_domain):
|
||||
wire_domain("cacu")
|
||||
|
||||
from datetime import date
|
||||
|
||||
from core.cacu.models import Paciente
|
||||
from persistance import db as persistance_db
|
||||
|
||||
engine = persistance_db.get_cacu_engine()
|
||||
|
||||
from sqlmodel import Session
|
||||
|
||||
with Session(engine) as session:
|
||||
session.add(Paciente(pac_id_hospital="H-1", pac_sexo="Femenino", pac_fecha_nacimiento=date(1990, 1, 1)))
|
||||
session.commit()
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as client:
|
||||
yield client
|
||||
|
||||
|
||||
def test_health(client):
|
||||
response = client.get("/health")
|
||||
assert response.status_code == 200
|
||||
assert response.get_json() == {"status": "ok"}
|
||||
|
||||
|
||||
def test_get_paciente(client):
|
||||
response = client.get("/cacu/pacientes/1")
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["pac_id_hospital"] == "H-1"
|
||||
|
||||
|
||||
def test_get_paciente_not_found(client):
|
||||
response = client.get("/cacu/pacientes/999")
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
def test_predict_not_implemented(client):
|
||||
response = client.post("/cacu/predict")
|
||||
assert response.status_code == 501
|
||||
|
||||
|
||||
def test_api_index_lists_routes_with_summaries():
|
||||
from webapi import create_app
|
||||
|
||||
routes = {r["path"]: r for r in create_app().test_client().get("/api").get_json()["routes"]}
|
||||
assert routes["/imports/connectors"]["methods"] == ["GET"]
|
||||
assert routes["/governance/model-versions/<domain>/<scenario>/<version>/promote"]["summary"].startswith("Puts the version in production")
|
||||
@@ -0,0 +1,37 @@
|
||||
import hashlib
|
||||
from io import BytesIO
|
||||
from zipfile import ZipFile
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException, UploadFile
|
||||
|
||||
from core.domains import Domain
|
||||
from persistance import config
|
||||
from webapi.models import import_models
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("kind", "status", "detail"),
|
||||
[
|
||||
("wrong_sha", 422, "not the one given"),
|
||||
("non_zip", 422, "not a bundle"),
|
||||
("untrusted", 403, "not trusted on this server"),
|
||||
],
|
||||
)
|
||||
def test_import_rejects_invalid_uploads(tmp_path, monkeypatch, kind, status, detail):
|
||||
monkeypatch.setattr(config, "DATA_DIR", tmp_path)
|
||||
if kind == "non_zip":
|
||||
data = b"hello"
|
||||
else:
|
||||
buffer = BytesIO()
|
||||
with ZipFile(buffer, "w") as archive:
|
||||
archive.writestr("manifest.json", "{}")
|
||||
data = buffer.getvalue()
|
||||
digest = hashlib.sha256(data).hexdigest()
|
||||
sent = "0" * 64 if kind == "wrong_sha" else digest
|
||||
|
||||
with pytest.raises(HTTPException) as rejected:
|
||||
import_models(Domain.TEA, sent, UploadFile(BytesIO(data), filename="bundle.zip"))
|
||||
assert rejected.value.status_code == status
|
||||
assert detail in rejected.value.detail
|
||||
assert not (tmp_path / "bundles" / f"{digest}.zip").exists()
|
||||
@@ -1,127 +0,0 @@
|
||||
import io
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import create_engine, text
|
||||
|
||||
from webapi.imports.connectors.csv_ import CsvConnector
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
from webapi.imports.connectors.excel import ExcelConnector
|
||||
from webapi.imports.connectors.json_ import JsonConnector
|
||||
from webapi.imports.connectors.sql import SqlConnector
|
||||
|
||||
|
||||
def test_csv_connector_reads_columns_and_rows():
|
||||
raw = b"nombre,edad\nAna,30\nLuis,40\n"
|
||||
connector = CsvConnector(raw)
|
||||
columns = {c.name: c.inferred_type for c in connector.get_columns()}
|
||||
assert columns == {"nombre": "string", "edad": "integer"}
|
||||
preview = connector.preview(limit=1)
|
||||
assert preview.total_rows == 2
|
||||
assert len(preview.sample_rows) == 1
|
||||
# Cells stay text; typing is the import schema's job (see CsvConnector).
|
||||
rows = list(connector.read_rows({"nombre": "pac_nombre", "edad": "pac_edad"}))
|
||||
assert rows == [{"pac_nombre": "Ana", "pac_edad": "30"}, {"pac_nombre": "Luis", "pac_edad": "40"}]
|
||||
|
||||
|
||||
def test_csv_connector_keeps_leading_zeros_and_blank_cells():
|
||||
raw = b"cp,exp\n01000,007\n,H-2\n"
|
||||
connector = CsvConnector(raw)
|
||||
assert {c.name: c.inferred_type for c in connector.get_columns()} == {"cp": "string", "exp": "string"}
|
||||
rows = list(connector.read_rows({"cp": "pac_codigo_postal", "exp": "pac_id_hospital"}))
|
||||
assert rows == [
|
||||
{"pac_codigo_postal": "01000", "pac_id_hospital": "007"},
|
||||
{"pac_codigo_postal": None, "pac_id_hospital": "H-2"},
|
||||
]
|
||||
|
||||
|
||||
def test_csv_connector_single_column_file():
|
||||
connector = CsvConnector(b"id\nH3\nH4\n")
|
||||
assert [c.name for c in connector.get_columns()] == ["id"]
|
||||
assert connector.metadata()["delimiter"] == ","
|
||||
|
||||
|
||||
def test_csv_connector_sniffs_semicolons_and_strips_excel_bom():
|
||||
raw = "\ufeffExpediente;Sexo\nH-1;F\n".encode("utf-8")
|
||||
connector = CsvConnector(raw)
|
||||
assert [c.name for c in connector.get_columns()] == ["Expediente", "Sexo"]
|
||||
assert connector.metadata() == {"delimiter": ";", "encoding": "utf-8-sig"}
|
||||
|
||||
|
||||
def test_csv_connector_falls_back_to_cp1252():
|
||||
raw = "nombre\nPeña\n".encode("cp1252")
|
||||
connector = CsvConnector(raw)
|
||||
assert list(connector.read_rows({"nombre": "n"})) == [{"n": "Peña"}]
|
||||
|
||||
|
||||
def test_csv_connector_bad_bytes_raise_connector_error():
|
||||
with pytest.raises(ConnectorError):
|
||||
CsvConnector(b"\xff\xfe\x00\x01not valid utf-8 csv bytes")
|
||||
|
||||
|
||||
def test_json_connector_reads_list_of_records():
|
||||
raw = b'[{"nombre": "Ana", "edad": 30}, {"nombre": "Luis", "edad": 40}]'
|
||||
connector = JsonConnector(raw)
|
||||
assert {c.name for c in connector.get_columns()} == {"nombre", "edad"}
|
||||
rows = list(connector.read_rows({"nombre": "pac_nombre"}))
|
||||
assert rows == [{"pac_nombre": "Ana"}, {"pac_nombre": "Luis"}]
|
||||
|
||||
|
||||
def test_json_connector_reads_wrapped_data_key():
|
||||
raw = b'{"data": [{"nombre": "Ana"}]}'
|
||||
connector = JsonConnector(raw)
|
||||
assert {c.name for c in connector.get_columns()} == {"nombre"}
|
||||
|
||||
|
||||
def test_json_connector_bad_json_raises_connector_error():
|
||||
with pytest.raises(ConnectorError):
|
||||
JsonConnector(b"{not valid json")
|
||||
|
||||
|
||||
def test_excel_connector_reads_columns_and_rows():
|
||||
pd = pytest.importorskip("pandas")
|
||||
buffer = io.BytesIO()
|
||||
pd.DataFrame({"nombre": ["Ana", "Luis"], "edad": [30, 40]}).to_excel(buffer, index=False, engine="openpyxl")
|
||||
connector = ExcelConnector(buffer.getvalue())
|
||||
assert connector.list_sheets() == ["Sheet1"]
|
||||
assert {c.name for c in connector.get_columns()} == {"nombre", "edad"}
|
||||
rows = list(connector.read_rows({"nombre": "pac_nombre"}))
|
||||
assert rows == [{"pac_nombre": "Ana"}, {"pac_nombre": "Luis"}]
|
||||
|
||||
|
||||
def test_excel_connector_bad_bytes_raise_connector_error():
|
||||
with pytest.raises(ConnectorError):
|
||||
ExcelConnector(b"not an excel file")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sqlite_source_url(tmp_path):
|
||||
db_path = tmp_path / "source.db"
|
||||
url = f"sqlite:///{db_path}"
|
||||
engine = create_engine(url)
|
||||
with engine.begin() as conn:
|
||||
conn.execute(text("CREATE TABLE patients (nombre TEXT, edad INTEGER)"))
|
||||
conn.execute(text("INSERT INTO patients (nombre, edad) VALUES ('Ana', 30), ('Luis', 40)"))
|
||||
return url
|
||||
|
||||
|
||||
def test_sql_connector_introspection_and_rows(sqlite_source_url):
|
||||
connector = SqlConnector(sqlite_source_url)
|
||||
connector.test_connection()
|
||||
assert connector.get_dialect() == "sqlite"
|
||||
assert "patients" in connector.list_tables()
|
||||
columns = {c.name for c in connector.list_columns("patients")}
|
||||
assert columns == {"nombre", "edad"}
|
||||
|
||||
connector.select_table("patients")
|
||||
preview = connector.preview()
|
||||
assert preview.total_rows == 2
|
||||
rows = list(connector.read_rows({"nombre": "pac_nombre", "edad": "pac_edad"}))
|
||||
assert rows == [{"pac_nombre": "Ana", "pac_edad": 30}, {"pac_nombre": "Luis", "pac_edad": 40}]
|
||||
|
||||
|
||||
def test_sql_connector_bad_connection_string_raises_connector_error():
|
||||
# may fail either at construction (unknown dialect) or at connect time;
|
||||
# both must surface as ConnectorError rather than a raw sqlalchemy error
|
||||
with pytest.raises(ConnectorError):
|
||||
connector = SqlConnector("not-a-real://connection-string")
|
||||
connector.test_connection()
|
||||
@@ -1,91 +0,0 @@
|
||||
"""Exercises `SqlConnector` against a real MySQL server, covering
|
||||
MySQL-specific reflection (native `ENUM` columns, `pymysql` quirks, DATE
|
||||
types) that the SQLite-based tests don't reach. Skipped unless
|
||||
`MYSQL_TEST_URL` is set.
|
||||
|
||||
To stand one up locally:
|
||||
docker run -d --name isssteleon-mysql-test \
|
||||
-e MYSQL_ROOT_PASSWORD=<root_pw> -e MYSQL_DATABASE=hospital_legacy \
|
||||
-e MYSQL_USER=<user> -e MYSQL_PASSWORD=<pw> -p 3307:3306 mysql:8.0
|
||||
export MYSQL_TEST_URL="mysql+pymysql://<user>:<pw>@127.0.0.1:3307/hospital_legacy"
|
||||
"""
|
||||
import os
|
||||
|
||||
import pytest
|
||||
import sqlalchemy as sa
|
||||
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
from webapi.imports.connectors.sql import SqlConnector
|
||||
|
||||
MYSQL_TEST_URL = os.environ.get("MYSQL_TEST_URL")
|
||||
|
||||
pytestmark = pytest.mark.skipif(not MYSQL_TEST_URL, reason="MYSQL_TEST_URL not set — no real MySQL server to test against")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def legacy_table():
|
||||
"""A legacy table whose columns are unrelated to Core's naming, as in a
|
||||
third-party database we don't control."""
|
||||
engine = sa.create_engine(MYSQL_TEST_URL)
|
||||
table_name = "test_connectors_mysql_fixture"
|
||||
with engine.begin() as conn:
|
||||
conn.execute(sa.text(f"DROP TABLE IF EXISTS {table_name}"))
|
||||
conn.execute(
|
||||
sa.text(
|
||||
f"CREATE TABLE {table_name} ("
|
||||
" legacy_id VARCHAR(40) NOT NULL PRIMARY KEY,"
|
||||
" legacy_sexo ENUM('F','M'),"
|
||||
" legacy_nacimiento DATE"
|
||||
") ENGINE=InnoDB"
|
||||
)
|
||||
)
|
||||
conn.execute(
|
||||
sa.text(
|
||||
f"INSERT INTO {table_name} (legacy_id, legacy_sexo, legacy_nacimiento) VALUES "
|
||||
"('MYFIX-1', 'F', '1990-01-15'), ('MYFIX-2', 'M', '1985-06-20')"
|
||||
)
|
||||
)
|
||||
yield table_name
|
||||
with engine.begin() as conn:
|
||||
conn.execute(sa.text(f"DROP TABLE IF EXISTS {table_name}"))
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_connects_and_reports_mysql_dialect():
|
||||
connector = SqlConnector(MYSQL_TEST_URL)
|
||||
connector.test_connection()
|
||||
assert connector.get_dialect() == "mysql"
|
||||
|
||||
|
||||
def test_introspects_real_mysql_schema(legacy_table):
|
||||
connector = SqlConnector(MYSQL_TEST_URL)
|
||||
assert legacy_table in connector.list_tables()
|
||||
columns = {c.name: c.inferred_type for c in connector.list_columns(legacy_table)}
|
||||
assert columns["legacy_id"] == "string"
|
||||
assert columns["legacy_nacimiento"] == "date"
|
||||
# A native MySQL ENUM column is reflected as a string-like type.
|
||||
assert columns["legacy_sexo"] == "string"
|
||||
|
||||
|
||||
def test_reads_rows_with_column_mapping_against_real_mysql(legacy_table):
|
||||
connector = SqlConnector(MYSQL_TEST_URL)
|
||||
connector.select_table(legacy_table)
|
||||
preview = connector.preview()
|
||||
assert preview.total_rows == 2
|
||||
|
||||
rows = list(
|
||||
connector.read_rows({"legacy_id": "pac_id_hospital", "legacy_sexo": "pac_sexo", "legacy_nacimiento": "pac_fecha_nacimiento"})
|
||||
)
|
||||
by_id = {r["pac_id_hospital"]: r for r in rows}
|
||||
assert by_id["MYFIX-1"]["pac_sexo"] == "F"
|
||||
# Rows come straight from the driver, so a MySQL DATE is a `date`.
|
||||
import datetime as _dt
|
||||
|
||||
assert by_id["MYFIX-1"]["pac_fecha_nacimiento"] == _dt.date(1990, 1, 15)
|
||||
|
||||
|
||||
def test_bad_mysql_credentials_raise_connector_error():
|
||||
bad_url = MYSQL_TEST_URL.rsplit("@", 1)[-1]
|
||||
connector = SqlConnector(f"mysql+pymysql://nobody:wrongpassword@{bad_url}")
|
||||
with pytest.raises(ConnectorError):
|
||||
connector.test_connection()
|
||||
@@ -1,314 +0,0 @@
|
||||
"""Tests for `PdfConnector`. PDF fixtures are generated at test time with
|
||||
reportlab.
|
||||
|
||||
- `build_table_pdf()`: a ruled table with selectable text, for the table
|
||||
detection path.
|
||||
- `build_scanned_like_pdf()` / `build_three_column_pdf()`: text rendered into
|
||||
an image that fills the page, so there is no text layer and only the
|
||||
OCR/region path applies. The three-column variant uses known values per
|
||||
row so alignment can be checked.
|
||||
"""
|
||||
|
||||
import difflib
|
||||
import io
|
||||
|
||||
import pytest
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
from reportlab.lib import colors
|
||||
from reportlab.lib.pagesizes import letter
|
||||
from reportlab.lib.utils import ImageReader
|
||||
from reportlab.pdfgen import canvas
|
||||
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle
|
||||
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
from webapi.imports.connectors.pdf import PdfConnector, RegionSpec
|
||||
|
||||
# The synthetic "scanned" pages are drawn onto an image this size, then
|
||||
# stretched to fill the whole (letter-size) PDF page, so a normalized
|
||||
# 0..1 bbox computed from these pixel coordinates lines up with the region
|
||||
# regardless of the DPI used to re-render the page for OCR.
|
||||
IMG_W, IMG_H = 900, 1200
|
||||
COL_X = {"name": 40, "age": 340, "city": 620}
|
||||
COL_WIDTH = 260
|
||||
ROW_YS = [120, 320, 520]
|
||||
ROW_HEIGHT = 100
|
||||
|
||||
|
||||
def _font(size: int = 34) -> ImageFont.ImageFont:
|
||||
for path in (
|
||||
"/System/Library/Fonts/Helvetica.ttc",
|
||||
"/System/Library/Fonts/Supplemental/Arial.ttf",
|
||||
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
|
||||
):
|
||||
try:
|
||||
return ImageFont.truetype(path, size)
|
||||
except Exception:
|
||||
continue
|
||||
return ImageFont.load_default()
|
||||
|
||||
|
||||
def build_table_pdf(rows: list[tuple[str, str]]) -> bytes:
|
||||
buffer = io.BytesIO()
|
||||
doc = SimpleDocTemplate(buffer, pagesize=letter)
|
||||
data = [["pac_id_hospital", "pac_sexo"], *[[a, b] for a, b in rows]]
|
||||
table = Table(data)
|
||||
table.setStyle(
|
||||
TableStyle(
|
||||
[
|
||||
("GRID", (0, 0), (-1, -1), 1, colors.black),
|
||||
("FONTSIZE", (0, 0), (-1, -1), 12),
|
||||
("BOTTOMPADDING", (0, 0), (-1, -1), 8),
|
||||
("TOPPADDING", (0, 0), (-1, -1), 8),
|
||||
]
|
||||
)
|
||||
)
|
||||
doc.build([table])
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def _page_image(lines: list[str]) -> Image.Image:
|
||||
img = Image.new("RGB", (IMG_W, IMG_H), "white")
|
||||
draw = ImageDraw.Draw(img)
|
||||
font = _font()
|
||||
y = 40
|
||||
for line in lines:
|
||||
draw.text((40, y), line, fill="black", font=font)
|
||||
y += 60
|
||||
return img
|
||||
|
||||
|
||||
def build_scanned_like_pdf(pages_lines: list[list[str]]) -> bytes:
|
||||
buffer = io.BytesIO()
|
||||
c = canvas.Canvas(buffer, pagesize=letter)
|
||||
page_w, page_h = letter
|
||||
for lines in pages_lines:
|
||||
img = _page_image(lines)
|
||||
reader_buf = io.BytesIO()
|
||||
img.save(reader_buf, format="PNG")
|
||||
reader_buf.seek(0)
|
||||
c.drawImage(ImageReader(reader_buf), 0, 0, width=page_w, height=page_h)
|
||||
c.showPage()
|
||||
c.save()
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def _three_column_page_image(rows: list[tuple[str, str, str]]) -> Image.Image:
|
||||
img = Image.new("RGB", (IMG_W, IMG_H), "white")
|
||||
draw = ImageDraw.Draw(img)
|
||||
font = _font()
|
||||
for y, (name, age, city) in zip(ROW_YS, rows):
|
||||
draw.text((COL_X["name"], y), name, fill="black", font=font)
|
||||
draw.text((COL_X["age"], y), age, fill="black", font=font)
|
||||
draw.text((COL_X["city"], y), city, fill="black", font=font)
|
||||
return img
|
||||
|
||||
|
||||
def build_three_column_pdf(pages_rows: list[list[tuple[str, str, str]]]) -> bytes:
|
||||
buffer = io.BytesIO()
|
||||
c = canvas.Canvas(buffer, pagesize=letter)
|
||||
page_w, page_h = letter
|
||||
for rows in pages_rows:
|
||||
img = _three_column_page_image(rows)
|
||||
reader_buf = io.BytesIO()
|
||||
img.save(reader_buf, format="PNG")
|
||||
reader_buf.seek(0)
|
||||
c.drawImage(ImageReader(reader_buf), 0, 0, width=page_w, height=page_h)
|
||||
c.showPage()
|
||||
c.save()
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def _norm_bbox(field: str) -> tuple[float, float, float, float]:
|
||||
x0 = COL_X[field]
|
||||
x1 = x0 + COL_WIDTH
|
||||
y0 = ROW_YS[0] - 60
|
||||
y1 = ROW_YS[-1] + ROW_HEIGHT
|
||||
return (x0 / IMG_W, y0 / IMG_H, x1 / IMG_W, y1 / IMG_H)
|
||||
|
||||
|
||||
def _similar(a: str, b: str, threshold: float = 0.7) -> bool:
|
||||
return difflib.SequenceMatcher(None, a.strip().lower(), b.strip().lower()).ratio() >= threshold
|
||||
|
||||
|
||||
ROWS = [("Ana Garcia", "30", "Monterrey"), ("Luis Perez", "40", "Saltillo"), ("Marta Ruiz", "50", "Torreon")]
|
||||
ROWS_PAGE_2 = [("Elena Diaz", "60", "Chihuahua"), ("Jorge Nava", "22", "Durango"), ("Sofia Reyes", "35", "Culiacan")]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# Classification
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_has_text_layer_true_for_table_pdf():
|
||||
connector = PdfConnector(build_table_pdf([("H-TAB-1", "F"), ("H-TAB-2", "M")]))
|
||||
assert connector.has_text_layer() is True
|
||||
|
||||
|
||||
def test_has_text_layer_false_for_scanned_pdf():
|
||||
connector = PdfConnector(build_scanned_like_pdf([["Ana Garcia", "Luis Perez"]]))
|
||||
assert connector.has_text_layer() is False
|
||||
|
||||
|
||||
def test_malformed_pdf_bytes_raise_connector_error():
|
||||
with pytest.raises(ConnectorError):
|
||||
PdfConnector(b"not a pdf at all")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# Ruled table detection
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_detect_tables_finds_candidate_with_right_shape_on_table_pdf():
|
||||
connector = PdfConnector(build_table_pdf([("H-TAB-1", "F"), ("H-TAB-2", "M"), ("H-TAB-3", "F")]))
|
||||
candidates = connector.detect_tables()
|
||||
assert len(candidates) == 1
|
||||
candidate = candidates[0]
|
||||
assert candidate.page_number == 1
|
||||
assert len(candidate.grid) == 4 # header + 3 data rows
|
||||
assert len(candidate.grid[0]) == 2
|
||||
assert candidate.grid[0] == ["pac_id_hospital", "pac_sexo"]
|
||||
assert candidate.grid[1][0] == "H-TAB-1"
|
||||
|
||||
|
||||
def test_detect_tables_empty_on_scanned_pdf():
|
||||
connector = PdfConnector(build_scanned_like_pdf([["Ana Garcia", "Luis Perez"]]))
|
||||
assert connector.detect_tables() == []
|
||||
|
||||
|
||||
def test_select_table_then_connector_abc_roundtrip():
|
||||
connector = PdfConnector(build_table_pdf([("H-TAB-1", "F"), ("H-TAB-2", "M")]))
|
||||
candidate = connector.detect_tables()[0]
|
||||
connector.select_table(candidate.page_number, candidate.bbox)
|
||||
|
||||
columns = {c.name for c in connector.get_columns()}
|
||||
assert columns == {"pac_id_hospital", "pac_sexo"}
|
||||
|
||||
preview = connector.preview(limit=1)
|
||||
assert preview.total_rows == 2
|
||||
assert len(preview.sample_rows) == 1
|
||||
|
||||
rows = list(connector.read_rows({"pac_id_hospital": "pac_id_hospital", "pac_sexo": "pac_sexo"}))
|
||||
assert rows == [
|
||||
{"pac_id_hospital": "H-TAB-1", "pac_sexo": "F"},
|
||||
{"pac_id_hospital": "H-TAB-2", "pac_sexo": "M"},
|
||||
]
|
||||
|
||||
|
||||
def test_select_table_out_of_range_page_raises_connector_error():
|
||||
connector = PdfConnector(build_table_pdf([("H-TAB-1", "F")]))
|
||||
with pytest.raises(ConnectorError):
|
||||
connector.select_table(99, (0, 0, 100, 100))
|
||||
|
||||
|
||||
def test_read_rows_before_resolution_raises_connector_error():
|
||||
connector = PdfConnector(build_table_pdf([("H-TAB-1", "F")]))
|
||||
with pytest.raises(ConnectorError):
|
||||
connector.get_columns()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# Rendering
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_render_page_image_returns_valid_png_with_expected_aspect_ratio():
|
||||
connector = PdfConnector(build_scanned_like_pdf([["hello"]]))
|
||||
png_bytes = connector.render_page_image(1, dpi=150)
|
||||
image = Image.open(io.BytesIO(png_bytes))
|
||||
assert image.format == "PNG"
|
||||
page_w, page_h = letter
|
||||
expected_ratio = page_w / page_h
|
||||
actual_ratio = image.width / image.height
|
||||
assert abs(actual_ratio - expected_ratio) < 0.01
|
||||
|
||||
|
||||
def test_render_page_image_out_of_range_raises_connector_error():
|
||||
connector = PdfConnector(build_scanned_like_pdf([["hello"]]))
|
||||
with pytest.raises(ConnectorError):
|
||||
connector.render_page_image(7)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# OCR / region path
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_single_region_ocr_matches_known_column():
|
||||
connector = PdfConnector(build_three_column_pdf([ROWS]))
|
||||
region = RegionSpec(target_field="name", page_numbers=[1], bbox=_norm_bbox("name"))
|
||||
result = connector.extract_regions([region])
|
||||
assert len(result["name"]) == 3
|
||||
for actual, (expected, _, _) in zip(result["name"], ROWS):
|
||||
assert _similar(actual, expected), f"{actual!r} not close enough to {expected!r}"
|
||||
|
||||
|
||||
def test_multi_region_row_alignment_matches_ground_truth():
|
||||
"""Three columns OCR'd independently must recombine into the rows they
|
||||
came from."""
|
||||
connector = PdfConnector(build_three_column_pdf([ROWS]))
|
||||
regions = [
|
||||
RegionSpec(target_field="name", page_numbers=[1], bbox=_norm_bbox("name")),
|
||||
RegionSpec(target_field="age", page_numbers=[1], bbox=_norm_bbox("age")),
|
||||
RegionSpec(target_field="city", page_numbers=[1], bbox=_norm_bbox("city")),
|
||||
]
|
||||
result = connector.extract_regions(regions)
|
||||
|
||||
assert len(result["name"]) == len(result["age"]) == len(result["city"]) == 3
|
||||
for i, (expected_name, expected_age, expected_city) in enumerate(ROWS):
|
||||
assert _similar(result["name"][i], expected_name), f"row {i} name mismatch: {result['name'][i]!r}"
|
||||
assert _similar(result["age"][i], expected_age), f"row {i} age mismatch: {result['age'][i]!r}"
|
||||
assert _similar(result["city"][i], expected_city), f"row {i} city mismatch: {result['city'][i]!r}"
|
||||
|
||||
rows = list(
|
||||
connector.read_rows({"name": "name", "age": "age", "city": "city"})
|
||||
)
|
||||
assert len(rows) == 3
|
||||
assert _similar(rows[0]["name"], ROWS[0][0])
|
||||
|
||||
|
||||
def test_two_page_apply_to_every_page_regions():
|
||||
connector = PdfConnector(build_three_column_pdf([ROWS, ROWS_PAGE_2]))
|
||||
regions = [
|
||||
RegionSpec(target_field="name", page_numbers=[1, 2], bbox=_norm_bbox("name")),
|
||||
RegionSpec(target_field="age", page_numbers=[1, 2], bbox=_norm_bbox("age")),
|
||||
RegionSpec(target_field="city", page_numbers=[1, 2], bbox=_norm_bbox("city")),
|
||||
]
|
||||
result = connector.extract_regions(regions)
|
||||
|
||||
all_rows = ROWS + ROWS_PAGE_2
|
||||
assert len(result["name"]) == 6
|
||||
for i, (expected_name, expected_age, expected_city) in enumerate(all_rows):
|
||||
assert _similar(result["name"][i], expected_name), f"row {i}: {result['name']}"
|
||||
assert _similar(result["age"][i], expected_age)
|
||||
assert _similar(result["city"][i], expected_city)
|
||||
|
||||
# page 1's rows precede page 2's, not just correct as a set
|
||||
assert _similar(result["name"][0], ROWS[0][0])
|
||||
assert _similar(result["name"][3], ROWS_PAGE_2[0][0])
|
||||
|
||||
|
||||
def test_extract_regions_before_resolution_then_read_rows_uses_region_mode():
|
||||
connector = PdfConnector(build_three_column_pdf([ROWS]))
|
||||
regions = [
|
||||
RegionSpec(target_field="name", page_numbers=[1], bbox=_norm_bbox("name")),
|
||||
RegionSpec(target_field="age", page_numbers=[1], bbox=_norm_bbox("age")),
|
||||
]
|
||||
connector.extract_regions(regions)
|
||||
columns = {c.name for c in connector.get_columns()}
|
||||
assert columns == {"name", "age"}
|
||||
|
||||
|
||||
def test_split_conflict_records_warning_without_dropping_data():
|
||||
connector = PdfConnector(build_three_column_pdf([ROWS]))
|
||||
connector.warnings = []
|
||||
lines = [
|
||||
{"target_field": "a", "y": 100, "height": 20, "text": "A1"},
|
||||
{"target_field": "b", "y": 108, "height": 20, "text": "B1"},
|
||||
{"target_field": "a", "y": 116, "height": 20, "text": "A2"},
|
||||
]
|
||||
rows = connector._cluster_rows(lines, page_number=1)
|
||||
total_values = sum(len(row) for row in rows)
|
||||
assert total_values == 3 # nothing silently dropped
|
||||
assert len(connector.warnings) == 1
|
||||
assert connector.warnings[0].page_number == 1
|
||||
@@ -1,309 +0,0 @@
|
||||
"""Endpoint tests for `/governance/*` and the `/cacu/predict`,`/cama/predict`
|
||||
MLD-4/MLD-5 wiring through `models.prediction.PredictionService`."""
|
||||
import os
|
||||
import tempfile
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(wire_domain):
|
||||
wire_domain("cacu")
|
||||
wire_domain("governance")
|
||||
|
||||
# A local, SQLite-backed MLflow tracking store for this module — no
|
||||
# server, no network. `chdir` into the same temp dir: an experiment with
|
||||
# no explicit artifact_location falls back to `./mlruns` relative to the
|
||||
# CWD (production never sets one either; the real MLflow server picks it).
|
||||
import mlflow
|
||||
|
||||
tmp_dir = tempfile.mkdtemp()
|
||||
uri = f"sqlite:///{os.path.join(tmp_dir, 'mlflow.db')}"
|
||||
os.environ["MLFLOW_TRACKING_URI"] = uri
|
||||
mlflow.set_tracking_uri(uri)
|
||||
previous_cwd = os.getcwd()
|
||||
os.chdir(tmp_dir)
|
||||
|
||||
from core.cacu.models import Paciente
|
||||
from persistance import db as persistance_db
|
||||
|
||||
with __import__("sqlmodel").Session(persistance_db.get_cacu_engine()) as session:
|
||||
session.add(Paciente(pac_id_hospital="H-1", pac_sexo="Femenino", pac_fecha_nacimiento=date(1990, 1, 1)))
|
||||
session.commit()
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as test_client:
|
||||
yield test_client
|
||||
|
||||
os.chdir(previous_cwd)
|
||||
del os.environ["MLFLOW_TRACKING_URI"]
|
||||
|
||||
|
||||
def test_predict_without_model_version_is_501(client):
|
||||
"""CaCuModel.predict is not implemented yet; no seeded MLflow version is
|
||||
needed to reach that state."""
|
||||
response = client.post("/cacu/predict", json={"pac_id_hospital": "H-1", "data": {"edad": 40}})
|
||||
assert response.status_code == 501
|
||||
|
||||
|
||||
def test_list_model_versions_empty(client):
|
||||
response = client.get("/governance/model-versions", query_string={"domain": "cacu", "scenario": "tamizaje-vacio"})
|
||||
assert response.status_code == 200
|
||||
assert response.get_json() == {"model_versions": []}
|
||||
|
||||
|
||||
def _cohort(tag: str) -> int:
|
||||
from core.governance.models import CohortVersion
|
||||
from persistance.governance import cohort_version_repository
|
||||
|
||||
cohort = CohortVersion(
|
||||
domain="cacu", scenario="tamizaje", criteria_version="v1", version_hash=f"hash-{tag}",
|
||||
source_table="cacu.episodioclinico", n_source=5, n_included=5,
|
||||
)
|
||||
return cohort_version_repository.create(cohort).cohort_version_id
|
||||
|
||||
|
||||
def _register(client, tag: str, *, scenario: str = "tamizaje", **extra) -> dict:
|
||||
body = {
|
||||
"domain": "cacu", "scenario": scenario, "environment": "PROD",
|
||||
"cohort_version_id": _cohort(tag), "metrics": {"auc": 0.8},
|
||||
"technical_validation_report_uri": "docs/tecnica.pdf",
|
||||
"clinical_validation_report_uri": "docs/clinica.pdf",
|
||||
"interpretability_report_uri": "docs/interpretabilidad.html",
|
||||
**extra,
|
||||
}
|
||||
response = client.post("/governance/model-versions", json=body)
|
||||
assert response.status_code == 201, response.get_json()
|
||||
return response.get_json()
|
||||
|
||||
|
||||
def _upload(client, domain: str, scenario: str, version: str, kind: str = "BALANCE_CLASES", name: str = "smote.json", data: bytes = b"{}"):
|
||||
files = {"file": (__import__("io").BytesIO(data), name), "kind": kind}
|
||||
return client.post(f"/governance/model-versions/{domain}/{scenario}/{version}/artifacts", data=files, content_type="multipart/form-data")
|
||||
|
||||
|
||||
def test_model_version_lifecycle_over_http(client):
|
||||
first = _register(client, "v1", scenario="lifecycle")
|
||||
assert first["status"] == "candidata"
|
||||
|
||||
checks = client.get(f"/governance/model-versions/cacu/lifecycle/{first['version']}/checks").get_json()
|
||||
assert checks["ready"] is False
|
||||
assert [c["code"] for c in checks["checks"] if not c["passed"]] == ["ML-01b"]
|
||||
blocked = client.post(f"/governance/model-versions/cacu/lifecycle/{first['version']}/promote")
|
||||
assert blocked.status_code == 409 and any(not c["passed"] for c in blocked.get_json()["checks"])
|
||||
|
||||
uploaded = _upload(client, "cacu", "lifecycle", first["version"])
|
||||
assert uploaded.status_code == 201
|
||||
assert client.post(f"/governance/model-versions/cacu/lifecycle/{first['version']}/promote").get_json()["status"] == "produccion"
|
||||
|
||||
second = _register(client, "v2", scenario="lifecycle", metrics={"auc": 0.86})
|
||||
_upload(client, "cacu", "lifecycle", second["version"])
|
||||
client.post(f"/governance/model-versions/cacu/lifecycle/{second['version']}/promote")
|
||||
listed = client.get("/governance/model-versions", query_string={"domain": "cacu", "scenario": "lifecycle"}).get_json()
|
||||
statuses = {v["version"]: v["status"] for v in listed["model_versions"]}
|
||||
assert statuses[first["version"]] == "retirada" and statuses[second["version"]] == "produccion"
|
||||
|
||||
lineage = client.get(f"/governance/model-versions/cacu/lifecycle/{second['version']}/lineage").get_json()
|
||||
assert lineage["cohort_version"]["version_hash"] == "hash-v2"
|
||||
assert lineage["artifacts"]
|
||||
|
||||
diff = client.get("/governance/model-versions/cacu/lifecycle/compare", query_string={"a": first["version"], "b": second["version"]}).get_json()
|
||||
assert diff["metrics"][0]["delta"] == pytest.approx(0.06)
|
||||
|
||||
retired = client.post(f"/governance/model-versions/cacu/lifecycle/{second['version']}/retire").get_json()
|
||||
assert retired["status"] == "retirada"
|
||||
|
||||
|
||||
def test_reports_can_be_attached_later(client):
|
||||
version = _register(client, "v3", scenario="reportes", clinical_validation_report_uri=None)
|
||||
response = client.patch(
|
||||
f"/governance/model-versions/cacu/reportes/{version['version']}/reports",
|
||||
json={"clinical_validation_report_uri": "docs/clinica-v3.pdf"},
|
||||
)
|
||||
assert response.get_json()["tags"]["clinical_validation_report_uri"] == "docs/clinica-v3.pdf"
|
||||
assert client.patch(f"/governance/model-versions/cacu/reportes/{version['version']}/reports", json={"metrics": "{}"}).status_code == 400
|
||||
|
||||
|
||||
def test_bad_registrations_and_uploads_are_rejected(client):
|
||||
assert client.post("/governance/model-versions", json={"domain": "cacu"}).status_code == 400
|
||||
dev = client.post("/governance/model-versions", json={"domain": "cacu", "scenario": "malas-subidas", "environment": "DEV"}).get_json()
|
||||
assert _upload(client, "cacu", "malas-subidas", dev["version"], kind="NOPE").status_code == 400
|
||||
assert _upload(client, "cacu", "malas-subidas", dev["version"], kind="ONNX_CHECKPOINT", name="m.onnx", data=b"junk").status_code == 400
|
||||
|
||||
|
||||
def test_model_version_not_found(client):
|
||||
assert client.get("/governance/model-versions/cacu/no-existe/999").status_code == 404
|
||||
|
||||
|
||||
def test_cohort_scenarios_and_build(client, monkeypatch):
|
||||
from models import cohort
|
||||
|
||||
class Demo(cohort.CohortBuilder):
|
||||
domain, scenario, criteria_version = "cacu", "demo", "v1"
|
||||
criteria = [cohort.ExclusionCriterion("SIN_CIE", "sin_codigo", lambda e: not e.get("cie10_codigo"), applicable_in_production=True)]
|
||||
|
||||
def fetch_episodes(self):
|
||||
return [{"episodio_id": 1, "pac_id_hospital": "H-1", "cie10_codigo": "C53"}, {"episodio_id": 2, "pac_id_hospital": "H-2"}]
|
||||
|
||||
monkeypatch.setitem(cohort.COHORT_BUILDERS, ("cacu", "demo"), Demo)
|
||||
[scenario] = [s for s in client.get("/governance/cohort-scenarios").get_json()["scenarios"] if s["scenario"] == "demo"]
|
||||
assert scenario["criteria"][0]["code"] == "SIN_CIE"
|
||||
built = client.post("/governance/cohort-versions", json={"domain": "cacu", "scenario": "demo"})
|
||||
assert built.status_code == 201 and built.get_json()["n_included"] == 1
|
||||
assert client.post("/governance/cohort-versions", json={"domain": "cacu", "scenario": "nope"}).status_code == 404
|
||||
|
||||
|
||||
def test_promote_unknown_model_version_is_404(client):
|
||||
assert client.post("/governance/model-versions/cacu/no-existe/999/promote").status_code == 404
|
||||
|
||||
|
||||
def test_cohort_version_exclusions_endpoint(client):
|
||||
from core.governance.models import CohortExclusion, CohortExclusionCount, CohortVersion
|
||||
from persistance.governance import (
|
||||
cohort_exclusion_count_repository,
|
||||
cohort_exclusion_repository,
|
||||
cohort_version_repository,
|
||||
)
|
||||
|
||||
cohort = cohort_version_repository.create(
|
||||
CohortVersion(
|
||||
domain="cacu",
|
||||
scenario="tamizaje",
|
||||
criteria_version="v1",
|
||||
version_hash="hash123",
|
||||
source_table="cacu.episodioclinico",
|
||||
n_source=10,
|
||||
n_included=8,
|
||||
)
|
||||
)
|
||||
cohort_exclusion_repository.create(
|
||||
CohortExclusion(
|
||||
cohort_version_id=cohort.cohort_version_id,
|
||||
pac_id_hospital="H-9",
|
||||
criterion_code="EDAD_FUERA_DE_RANGO",
|
||||
reason_code="EDAD<25",
|
||||
)
|
||||
)
|
||||
cohort_exclusion_count_repository.create(
|
||||
CohortExclusionCount(
|
||||
cohort_version_id=cohort.cohort_version_id,
|
||||
criterion_code="EDAD_FUERA_DE_RANGO",
|
||||
reason_code="EDAD<25",
|
||||
count=2,
|
||||
)
|
||||
)
|
||||
|
||||
response = client.get(f"/governance/cohort-versions/{cohort.cohort_version_id}/exclusions")
|
||||
assert response.status_code == 200
|
||||
body = response.get_json()
|
||||
assert body["counts"][0]["count"] == 2
|
||||
assert body["detail"][0]["pac_id_hospital"] == "H-9"
|
||||
|
||||
|
||||
def test_ocr_run_unknown_job_is_400(client):
|
||||
response = client.post("/governance/ocr/run", json={"domain": "cacu", "entity": "no_such_entity"})
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
def test_ocr_run_extracts_results_and_flags_unreadable_reports(client):
|
||||
from core.cacu.models import CitologiaCervical
|
||||
from extraction.testing import text_pdf
|
||||
from persistance.cacu import citologia_cervical_repository
|
||||
from persistance.governance import extraction_run_repository
|
||||
|
||||
report = text_pdf([["LABORATORIO DE BIOLOGIA MOLECULAR", "Expediente: H-OCR-1", "VPH alto riesgo: POSITIVO", "Genotipo 16: NO DETECTADO", "Genotipo 18: DETECTADO"]])
|
||||
good = citologia_cervical_repository.create(CitologiaCervical(pac_id_hospital="H-OCR-1", cit_vph_pdf_blob=report))
|
||||
bad = citologia_cervical_repository.create(CitologiaCervical(pac_id_hospital="H-OCR-2", cit_vph_pdf_blob=b"%PDF-fake"))
|
||||
|
||||
body = client.post("/governance/ocr/run", json={"domain": "cacu", "entity": "citologia_cervical"}).get_json()
|
||||
assert body["processed"] >= 1 and body["failed"] >= 1
|
||||
|
||||
good = citologia_cervical_repository.get(good.cit_id)
|
||||
assert (good.cit_vph_resultado, good.cit_vph_genotipo_16, good.cit_vph_genotipo_18) == ("POSITIVO", 0, 1)
|
||||
assert good.cit_vph_ocr_estatus == "REALIZADO" and good.cit_vph_ocr_requiere_revision is False
|
||||
assert good.cit_vph_ocr_metodo_principal == "pdf-texto" and good.cit_vph_ocr_confianza >= 0.8
|
||||
bad = citologia_cervical_repository.get(bad.cit_id)
|
||||
assert bad.cit_vph_ocr_estatus == "FALLIDO" and bad.cit_vph_ocr_requiere_revision is True
|
||||
assert extraction_run_repository.count(entity_pk=str(good.cit_id)) == 1
|
||||
|
||||
again = client.post("/governance/ocr/run", json={"domain": "cacu", "entity": "citologia_cervical"}).get_json()
|
||||
assert again["skipped_already_done"] >= 1
|
||||
|
||||
|
||||
def test_list_ocr_jobs(client):
|
||||
body = client.get("/governance/ocr/jobs").get_json()
|
||||
keys = {(j["domain"], j["entity"]) for j in body["jobs"]}
|
||||
assert ("cacu", "citologia_cervical") in keys
|
||||
assert ("cacu", "biopsia_cervical") in keys
|
||||
assert ("cama", "biopsia_mama") in keys
|
||||
cacu_vph = next(j for j in body["jobs"] if (j["domain"], j["entity"]) == ("cacu", "citologia_cervical"))
|
||||
assert set(cacu_vph["result_fields"]) == {"cit_vph_resultado", "cit_vph_genotipo_16", "cit_vph_genotipo_18"}
|
||||
|
||||
|
||||
def test_ocr_rows_unknown_job_is_404(client):
|
||||
assert client.get("/governance/ocr/cacu/no_such_entity/rows").status_code == 404
|
||||
|
||||
|
||||
def test_ocr_review_queue_blob_and_manual_correction(client):
|
||||
from core.cacu.models import CitologiaCervical
|
||||
from persistance.cacu import citologia_cervical_repository
|
||||
|
||||
row = citologia_cervical_repository.create(
|
||||
CitologiaCervical(
|
||||
pac_id_hospital="H-1",
|
||||
cit_vph_pdf_blob=b"%PDF-review-me",
|
||||
cit_vph_ocr_estatus="FALLIDO",
|
||||
cit_vph_ocr_requiere_revision=True,
|
||||
)
|
||||
)
|
||||
|
||||
review = client.get("/governance/ocr/cacu/citologia_cervical/rows", query_string={"status": "review"})
|
||||
assert review.status_code == 200
|
||||
review_body = review.get_json()
|
||||
assert row.cit_id in {r["id"] for r in review_body["rows"]}
|
||||
|
||||
blob_response = client.get(f"/governance/ocr/cacu/citologia_cervical/{row.cit_id}/blob")
|
||||
assert blob_response.status_code == 200
|
||||
assert blob_response.data == b"%PDF-review-me"
|
||||
assert blob_response.content_type == "application/pdf"
|
||||
|
||||
correction = client.post(
|
||||
f"/governance/ocr/cacu/citologia_cervical/{row.cit_id}/correct",
|
||||
json={"values": {"cit_vph_resultado": "POSITIVO"}, "confianza": 1.0},
|
||||
)
|
||||
assert correction.status_code == 200
|
||||
corrected = correction.get_json()
|
||||
assert corrected["cit_vph_resultado"] == "POSITIVO"
|
||||
assert corrected["cit_vph_ocr_estatus"] == "REALIZADO"
|
||||
assert corrected["cit_vph_ocr_requiere_revision"] is False
|
||||
assert corrected["cit_vph_ocr_metodo_principal"] == "manual"
|
||||
|
||||
done = client.get("/governance/ocr/cacu/citologia_cervical/rows", query_string={"status": "review"})
|
||||
assert row.cit_id not in {r["id"] for r in done.get_json()["rows"]}
|
||||
|
||||
from persistance.governance import extraction_run_repository
|
||||
|
||||
runs = extraction_run_repository.list(entity="citologia_cervical")
|
||||
assert any("manual" in (r.transform_description or "").lower() for r in runs)
|
||||
|
||||
|
||||
def test_ocr_correct_rejects_unknown_column(client):
|
||||
from core.cacu.models import CitologiaCervical
|
||||
from persistance.cacu import citologia_cervical_repository
|
||||
|
||||
row = citologia_cervical_repository.create(
|
||||
CitologiaCervical(pac_id_hospital="H-2", cit_vph_pdf_blob=b"%PDF-2")
|
||||
)
|
||||
response = client.post(
|
||||
f"/governance/ocr/cacu/citologia_cervical/{row.cit_id}/correct",
|
||||
json={"values": {"pac_id_hospital": "HACKED"}},
|
||||
)
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
def test_ocr_blob_not_found_for_unknown_row(client):
|
||||
assert client.get("/governance/ocr/cacu/citologia_cervical/999999/blob").status_code == 404
|
||||
@@ -1,265 +0,0 @@
|
||||
"""End-to-end tests (Flask test client, SQLite) of how a batch fills the
|
||||
database from several sources: strict catalogs, upserts that keep unmapped
|
||||
columns, defaults, atomic batches, itemized conflicts, and 400s for malformed
|
||||
requests."""
|
||||
import base64
|
||||
import io
|
||||
import json
|
||||
|
||||
import openpyxl
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(wire_domain):
|
||||
wire_domain("cacu")
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
def _b64(raw: bytes) -> str:
|
||||
return base64.b64encode(raw).decode()
|
||||
|
||||
|
||||
def _csv(text: str, mapping: dict, *, target="cacu.Paciente", **extra) -> dict:
|
||||
return {"source_type": "csv", "target": target, "column_mapping": mapping, "payload": {"file_base64": _b64(text.encode())}, **extra}
|
||||
|
||||
|
||||
def _rows(client, target):
|
||||
return {r["pac_id_hospital"]: r for r in client.get(f"/data/{target}?limit=500").get_json()["rows"]}
|
||||
|
||||
|
||||
def test_catalog_values_are_enforced_and_aliases_resolved(client):
|
||||
source = _csv(
|
||||
"exp,sexo,dep,nac\nCAT-1,f,calles y caminos,1990-01-01\nCAT-2,GARBAGE,,1990-01-01\nCAT-3,Masculino,SECRETARIA DE SALUD,1990-01-01\n",
|
||||
{"exp": "pac_id_hospital", "sexo": "pac_sexo", "dep": "pac_dependencia", "nac": "pac_fecha_nacimiento"},
|
||||
)
|
||||
body = client.post("/imports/validate", json={"source": source}).get_json()
|
||||
assert body["valid_count"] == 2
|
||||
assert [(e["row_index"], e["field"], e["category"], e["raw_value"]) for e in body["errors"]] == [
|
||||
(1, "pac_sexo", "out_of_catalog", "GARBAGE")
|
||||
]
|
||||
|
||||
client.post("/imports/commit", json={"sources": [source]})
|
||||
rows = _rows(client, "cacu.Paciente")
|
||||
assert rows["CAT-1"]["pac_sexo"] == "Femenino"
|
||||
assert rows["CAT-1"]["pac_dependencia"] == "CALLES Y CAMINOS" # alias normalized
|
||||
# Dependencia is a tentative catalog in Core, so unknown values are kept.
|
||||
assert rows["CAT-3"]["pac_dependencia"] == "SECRETARIA DE SALUD"
|
||||
|
||||
|
||||
def test_postal_codes_keep_leading_zeros_and_are_validated(client):
|
||||
source = _csv(
|
||||
"exp,cp,nac\nCP-1,01000,1990-01-01\nCP-2,6400,1990-01-01\nCP-3,64000a,1990-01-01\n",
|
||||
{"exp": "pac_id_hospital", "cp": "pac_codigo_postal", "nac": "pac_fecha_nacimiento"},
|
||||
)
|
||||
body = client.post("/imports/commit", json={"sources": [source]}).get_json()
|
||||
assert body["results"][0]["created"] == 1
|
||||
rows = _rows(client, "cacu.Paciente")
|
||||
assert rows["CP-1"]["pac_codigo_postal"] == "01000"
|
||||
assert "CP-2" not in rows and "CP-3" not in rows # 4 digits / non-digit
|
||||
|
||||
|
||||
def test_upsert_only_touches_mapped_columns(client):
|
||||
client.post(
|
||||
"/imports/commit",
|
||||
json={"sources": [_csv("exp,sexo,nac\nUP-1,F,15/01/1990\n", {"exp": "pac_id_hospital", "sexo": "pac_sexo", "nac": "pac_fecha_nacimiento"})]},
|
||||
)
|
||||
# pac_fecha_nacimiento is required (IND-01), so every row, insert or
|
||||
# upsert, must carry it. pac_sexo is the field that must stay untouched
|
||||
# when a later source doesn't map it.
|
||||
body = client.post(
|
||||
"/imports/commit",
|
||||
json={
|
||||
"sources": [
|
||||
_csv(
|
||||
"exp,cp,nac\nUP-1,64000,15/01/1990\n",
|
||||
{"exp": "pac_id_hospital", "cp": "pac_codigo_postal", "nac": "pac_fecha_nacimiento"},
|
||||
)
|
||||
],
|
||||
"on_conflict": "upsert",
|
||||
},
|
||||
).get_json()
|
||||
assert body["results"][0]["updated"] == 1
|
||||
row = _rows(client, "cacu.Paciente")["UP-1"]
|
||||
assert (row["pac_sexo"], row["pac_fecha_nacimiento"], row["pac_codigo_postal"]) == ("Femenino", "1990-01-15", "64000")
|
||||
|
||||
|
||||
def test_defaults_fill_unmapped_fields_and_blank_cells(client):
|
||||
source = _csv(
|
||||
"exp,dep,nac\nDEF-1,,1990-01-01\nDEF-2,GOBIERNO,1990-01-01\n",
|
||||
{"exp": "pac_id_hospital", "dep": "pac_dependencia", "nac": "pac_fecha_nacimiento"},
|
||||
defaults={"pac_dependencia": "CALLES Y CAMINOS", "pac_parentesco": "afiliado"},
|
||||
)
|
||||
assert client.post("/imports/commit", json={"sources": [source]}).get_json()["results"][0]["created"] == 2
|
||||
rows = _rows(client, "cacu.Paciente")
|
||||
assert rows["DEF-1"]["pac_dependencia"] == "CALLES Y CAMINOS"
|
||||
assert rows["DEF-2"]["pac_dependencia"] == "GOBIERNO"
|
||||
# Defaults go through the same validation/normalization as mapped cells.
|
||||
assert rows["DEF-1"]["pac_parentesco"] == rows["DEF-2"]["pac_parentesco"] == "Afiliado"
|
||||
|
||||
|
||||
def test_several_sources_compose_several_tables_in_one_batch(client):
|
||||
"""One Excel workbook feeds two tables (a source per sheet), a CSV adds
|
||||
more patients, and a JSON source feeds a third table, all in one batch
|
||||
and one transaction."""
|
||||
workbook = openpyxl.Workbook()
|
||||
pacientes = workbook.active
|
||||
pacientes.title = "Pacientes"
|
||||
pacientes.append(["Expediente", "Sexo", "Nacimiento"])
|
||||
pacientes.append(["MIX-1", "F", "1990-01-01"])
|
||||
ordenes = workbook.create_sheet("Ordenes")
|
||||
ordenes.append(["Folio", "Expediente", "Tipo"])
|
||||
ordenes.append([9001, "MIX-1", "Solicitud de Papanicolao en Base Liquida"])
|
||||
buffer = io.BytesIO()
|
||||
workbook.save(buffer)
|
||||
xlsx = _b64(buffer.getvalue())
|
||||
|
||||
preview = client.post(
|
||||
"/imports/sources/file/preview",
|
||||
data={"file": (io.BytesIO(buffer.getvalue()), "libro.xlsx"), "source_kind": "excel", "target": "cacu.OrdenesEstudio", "options": json.dumps({"sheet_name": "Ordenes"})},
|
||||
content_type="multipart/form-data",
|
||||
).get_json()
|
||||
assert preview["source_metadata"] == {"sheets": ["Pacientes", "Ordenes"], "sheet_name": "Ordenes"}
|
||||
assert [c["name"] for c in preview["columns"]] == ["Folio", "Expediente", "Tipo"]
|
||||
|
||||
batch = [
|
||||
{"source_type": "excel", "label": "libro.xlsx › Pacientes", "target": "cacu.Paciente", "column_mapping": {"Expediente": "pac_id_hospital", "Sexo": "pac_sexo", "Nacimiento": "pac_fecha_nacimiento"}, "payload": {"file_base64": xlsx, "options": {"sheet_name": "Pacientes"}}},
|
||||
_csv("id,genero,nac\nMIX-2,M,1990-01-01\n", {"id": "pac_id_hospital", "genero": "pac_sexo", "nac": "pac_fecha_nacimiento"}, label="extra.csv"),
|
||||
{"source_type": "excel", "target": "cacu.OrdenesEstudio", "column_mapping": {"Folio": "ord_numero_hospital", "Expediente": "pac_id_hospital", "Tipo": "ord_tipo_estudio"}, "payload": {"file_base64": xlsx, "options": {"sheet_name": "Ordenes"}}},
|
||||
{"source_type": "json", "target": "cacu.BiometriaHematica", "column_mapping": {"paciente.exp": "pac_id_hospital", "hb": "hemoglobina_g_dl"}, "payload": {"file_base64": _b64(json.dumps([{"paciente": {"exp": "MIX-1"}, "hb": 13.5}]).encode())}},
|
||||
]
|
||||
body = client.post("/imports/commit", json={"sources": batch}).get_json()
|
||||
assert body["ok"] is True
|
||||
assert [(r["label"], r["target"], r["created"]) for r in body["results"]] == [
|
||||
("libro.xlsx › Pacientes", "cacu.Paciente", 1),
|
||||
("extra.csv", "cacu.Paciente", 1),
|
||||
(None, "cacu.OrdenesEstudio", 1),
|
||||
(None, "cacu.BiometriaHematica", 1),
|
||||
]
|
||||
assert {"MIX-1", "MIX-2"} <= set(_rows(client, "cacu.Paciente"))
|
||||
orden = client.get("/data/cacu.OrdenesEstudio").get_json()["rows"][0]
|
||||
assert orden["ord_numero_hospital"] == 9001
|
||||
|
||||
|
||||
def test_conflicts_are_itemized_with_their_row(client):
|
||||
body = client.post(
|
||||
"/imports/commit",
|
||||
json={
|
||||
"sources": [
|
||||
_csv(
|
||||
"exp,nac\nDUP-1,1990-01-01\nDUP-1,1990-01-01\n",
|
||||
{"exp": "pac_id_hospital", "nac": "pac_fecha_nacimiento"},
|
||||
)
|
||||
]
|
||||
},
|
||||
).get_json()
|
||||
result = body["results"][0]
|
||||
assert (result["created"], result["rejected"]) == (1, 1)
|
||||
assert result["errors"] == [
|
||||
{"row_index": 1, "field": "pac_id_hospital", "category": "conflict", "message": "conflict on ('pac_id_hospital',)", "raw_value": "DUP-1"}
|
||||
]
|
||||
|
||||
|
||||
def test_a_failing_source_rolls_back_the_whole_batch(client, monkeypatch):
|
||||
from sqlalchemy.exc import OperationalError
|
||||
|
||||
from persistance.repository import Repository
|
||||
|
||||
original = Repository.bulk_upsert
|
||||
calls = {"n": 0}
|
||||
|
||||
def flaky(self, objs, **kwargs):
|
||||
calls["n"] += 1
|
||||
if calls["n"] == 2:
|
||||
raise OperationalError("INSERT ...", {}, Exception("disk full"))
|
||||
return original(self, objs, **kwargs)
|
||||
|
||||
monkeypatch.setattr(Repository, "bulk_upsert", flaky)
|
||||
response = client.post(
|
||||
"/imports/commit",
|
||||
json={
|
||||
"sources": [
|
||||
_csv("exp,nac\nATOM-1,1990-01-01\n", {"exp": "pac_id_hospital", "nac": "pac_fecha_nacimiento"}),
|
||||
_csv("exp,nac\nATOM-2,1990-01-01\n", {"exp": "pac_id_hospital", "nac": "pac_fecha_nacimiento"}),
|
||||
]
|
||||
},
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert "nothing was written" in response.get_json()["error"]
|
||||
assert not {"ATOM-1", "ATOM-2"} & set(_rows(client, "cacu.Paciente"))
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"payload",
|
||||
[
|
||||
{"sources": [{"source_type": "csv", "column_mapping": {"a": "pac_id_hospital"}, "payload": {"file_base64": "YQ=="}}]},
|
||||
{"sources": [{"source_type": "csv", "target": "cacu.Paciente", "payload": {"file_base64": "YQ=="}}]},
|
||||
{"sources": [{"source_type": "csv", "target": "cacu.Paciente", "column_mapping": {"a": "pac_id_hospital"}, "payload": {"file_base64": "%%%not-base64"}}]},
|
||||
{"sources": [{"source_type": "csv", "target": "cacu.Paciente", "column_mapping": {"a": "no_such_field"}, "payload": {"file_base64": "YQ=="}}]},
|
||||
{"sources": [{"source_type": "csv", "target": "cacu.Paciente", "column_mapping": {"a": "pac_sexo", "b": "pac_sexo"}, "payload": {"file_base64": "YQ=="}}]},
|
||||
{"sources": "nope"},
|
||||
{"sources": [{"source_type": "pdf", "target": "cacu.Paciente", "column_mapping": {"a": "pac_id_hospital"}, "payload": {"file_base64": "YQ==", "mode": "regions", "regions": [], "dpi": 5000}}]},
|
||||
],
|
||||
)
|
||||
def test_malformed_commits_are_400_not_500(client, payload):
|
||||
response = client.post("/imports/commit", json=payload)
|
||||
assert response.status_code == 400, response.get_json()
|
||||
assert response.get_json()["error"]
|
||||
|
||||
|
||||
def test_page_image_rejects_absurd_dpi(client):
|
||||
from reportlab.pdfgen import canvas
|
||||
|
||||
buffer = io.BytesIO()
|
||||
pdf = canvas.Canvas(buffer)
|
||||
pdf.drawString(72, 720, "hola")
|
||||
pdf.save()
|
||||
response = client.post(
|
||||
"/imports/sources/pdf/page-image",
|
||||
data={"file": (io.BytesIO(buffer.getvalue()), "a.pdf"), "page_number": "1", "dpi": "5000"},
|
||||
content_type="multipart/form-data",
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert "dpi" in response.get_json()["error"]
|
||||
|
||||
|
||||
def test_data_endpoint_pages_through_the_repository(client):
|
||||
body = client.get("/data/cacu.Paciente?limit=2").get_json()
|
||||
assert body["limit"] == 2 and len(body["rows"]) == 2 and body["total"] >= 2
|
||||
assert client.get("/data/cacu.Nope").status_code == 404
|
||||
|
||||
|
||||
def test_children_are_linked_to_parents_loaded_in_the_same_batch_whatever_the_order(client):
|
||||
"""Biopsies listed before their patients still get `pac_id` filled, since
|
||||
parents are written first within the batch's transaction. A child whose
|
||||
patient doesn't exist keeps a null FK."""
|
||||
from webapi.imports.services.link_resolver import dependency_rank, links_for
|
||||
|
||||
assert [link.fk_field for link in links_for("cacu.BiopsiaCervical")] == ["pac_id"]
|
||||
assert links_for("cacu.Paciente") == ()
|
||||
assert [link.fk_field for link in links_for("cama.Mastografia")] == ["pac_id", "ord_id"]
|
||||
assert dependency_rank("cama.Paciente") < dependency_rank("cama.OrdenesEstudio") < dependency_rank("cama.Mastografia")
|
||||
|
||||
batch = [
|
||||
_csv("exp,grado\nLINK-1,NORMAL\nNO-SUCH-PATIENT,NORMAL\n", {"exp": "pac_id_hospital", "grado": "bx_cin_grado"}, target="cacu.BiopsiaCervical"),
|
||||
_csv("exp,nac\nLINK-1,1990-01-01\n", {"exp": "pac_id_hospital", "nac": "pac_fecha_nacimiento"}),
|
||||
]
|
||||
body = client.post("/imports/commit", json={"sources": batch}).get_json()
|
||||
assert [r["target"] for r in body["results"]] == ["cacu.BiopsiaCervical", "cacu.Paciente"]
|
||||
assert body["results"][0]["linked"] == {"pac_id": 1}
|
||||
|
||||
patient = _rows(client, "cacu.Paciente")["LINK-1"]
|
||||
biopsies = {r["pac_id_hospital"]: r for r in client.get("/data/cacu.BiopsiaCervical?limit=500").get_json()["rows"]}
|
||||
assert biopsies["LINK-1"]["pac_id"] == patient["pac_id"]
|
||||
assert biopsies["NO-SUCH-PATIENT"]["pac_id"] is None
|
||||
|
||||
|
||||
def test_data_endpoint_reports_columns_in_table_order(client):
|
||||
body = client.get("/data/cacu.Paciente?limit=1").get_json()
|
||||
assert body["columns"][:2] == ["pac_id", "pac_id_hospital"]
|
||||
@@ -1,228 +0,0 @@
|
||||
import base64
|
||||
import io
|
||||
import json
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import create_engine, text
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(wire_domain):
|
||||
wire_domain("cacu")
|
||||
wire_domain("tea")
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
_PACIENTE_MAPPING = {
|
||||
"pac_id_hospital": "pac_id_hospital",
|
||||
"pac_sexo": "pac_sexo",
|
||||
"pac_fecha_nacimiento": "pac_fecha_nacimiento",
|
||||
}
|
||||
|
||||
|
||||
def _csv_source(csv_bytes: bytes, *, target: str, column_mapping: dict | None = None) -> dict:
|
||||
return {
|
||||
"source_type": "csv",
|
||||
"target": target,
|
||||
"column_mapping": column_mapping or _PACIENTE_MAPPING,
|
||||
"payload": {"file_base64": base64.b64encode(csv_bytes).decode()},
|
||||
}
|
||||
|
||||
|
||||
def _json_source(records: list[dict], *, target: str, column_mapping: dict | None = None) -> dict:
|
||||
raw = json.dumps(records).encode()
|
||||
return {
|
||||
"source_type": "json",
|
||||
"target": target,
|
||||
"column_mapping": column_mapping or _PACIENTE_MAPPING,
|
||||
"payload": {"file_base64": base64.b64encode(raw).decode()},
|
||||
}
|
||||
|
||||
|
||||
def test_get_targets_lists_registered_entities(client):
|
||||
response = client.get("/imports/targets")
|
||||
assert response.status_code == 200
|
||||
keys = {t["key"] for t in response.get_json()["targets"]}
|
||||
assert {"cacu.Paciente", "tea.Pacientes"} <= keys
|
||||
cacu_target = next(t for t in response.get_json()["targets"] if t["key"] == "cacu.Paciente")
|
||||
assert cacu_target["conflict_fields"] == ["pac_id_hospital"]
|
||||
assert any(f["name"] == "pac_id_hospital" and f["required"] for f in cacu_target["fields"])
|
||||
|
||||
|
||||
def test_file_preview_returns_columns_sample_rows_and_suggested_mapping(client):
|
||||
csv_bytes = b"pac_id_hospital,Sexo\nH-PREVIEW-1,F\n"
|
||||
data = {
|
||||
"file": (io.BytesIO(csv_bytes), "pacientes.csv"),
|
||||
"source_kind": "csv",
|
||||
"target": "cacu.Paciente",
|
||||
}
|
||||
response = client.post("/imports/sources/file/preview", data=data, content_type="multipart/form-data")
|
||||
assert response.status_code == 200
|
||||
body = response.get_json()
|
||||
assert {c["name"] for c in body["columns"]} == {"pac_id_hospital", "Sexo"}
|
||||
assert body["total_rows"] == 1
|
||||
suggested = {m["source_column"]: m["target_field"] for m in body["suggested_mapping"]}
|
||||
assert suggested["pac_id_hospital"] == "pac_id_hospital"
|
||||
assert suggested["Sexo"] == "pac_sexo"
|
||||
|
||||
|
||||
def test_validate_reports_row_errors_without_writing(client):
|
||||
csv_bytes = b"pac_id_hospital,pac_sexo,pac_fecha_nacimiento\nH-VALIDATE-1,F,1990-01-01\n,M,1990-01-01\n"
|
||||
response = client.post("/imports/validate", json={"source": _csv_source(csv_bytes, target="cacu.Paciente")})
|
||||
assert response.status_code == 200
|
||||
body = response.get_json()
|
||||
assert body["total_rows"] == 2
|
||||
assert body["valid_count"] == 1
|
||||
assert body["error_count"] == 1
|
||||
assert body["errors"][0]["field"] == "pac_id_hospital"
|
||||
# not written
|
||||
assert client.get("/cacu/pacientes/999").status_code == 404
|
||||
|
||||
|
||||
def test_commit_multi_source_batch_mixes_file_and_sql_within_one_domain(client, tmp_path):
|
||||
# A batch can mix file and SQL sources targeting the same domain: here a
|
||||
# CSV and a live SQL connection both land in cacu.Paciente in one commit.
|
||||
# Uses its own SQL fixture (distinct hospital id) because the row in
|
||||
# `sql_source_db` is also used by another test against this cacu.db.
|
||||
source_db_path = tmp_path / "batch_source.db"
|
||||
source_engine = create_engine(f"sqlite:///{source_db_path}")
|
||||
with source_engine.begin() as conn:
|
||||
conn.execute(text("CREATE TABLE hospital_patients (id_hospital TEXT, sexo TEXT, nacimiento TEXT)"))
|
||||
conn.execute(
|
||||
text(
|
||||
"INSERT INTO hospital_patients (id_hospital, sexo, nacimiento) VALUES ('H-SQL-BATCH-1', 'M', '1990-01-01')"
|
||||
)
|
||||
)
|
||||
|
||||
cacu_csv = b"pac_id_hospital,pac_sexo,pac_fecha_nacimiento\nH-BATCH-1,F,1990-01-01\n"
|
||||
csv_source = _csv_source(cacu_csv, target="cacu.Paciente")
|
||||
sql_source = {
|
||||
"source_type": "sql",
|
||||
"target": "cacu.Paciente",
|
||||
"column_mapping": {"id_hospital": "pac_id_hospital", "sexo": "pac_sexo", "nacimiento": "pac_fecha_nacimiento"},
|
||||
"payload": {"connection_string": f"sqlite:///{source_db_path}", "table": "hospital_patients"},
|
||||
}
|
||||
|
||||
response = client.post("/imports/commit", json={"sources": [csv_source, sql_source], "on_conflict": "reject"})
|
||||
assert response.status_code == 200
|
||||
body = response.get_json()
|
||||
assert body["ok"] is True
|
||||
assert [r["target"] for r in body["results"]] == ["cacu.Paciente", "cacu.Paciente"]
|
||||
assert sum(r["created"] for r in body["results"]) == 2
|
||||
|
||||
# First test in this file to write into cacu.Paciente, so autoincrement
|
||||
# ids 1/2 are deterministic (pytest runs this module's tests in
|
||||
# definition order).
|
||||
created_hospital_ids = {client.get(f"/cacu/pacientes/{i}").get_json()["pac_id_hospital"] for i in (1, 2)}
|
||||
assert created_hospital_ids == {"H-BATCH-1", "H-SQL-BATCH-1"}
|
||||
|
||||
|
||||
def test_commit_rejects_a_batch_mixing_domains(client):
|
||||
cacu_source = _csv_source(b"pac_id_hospital,pac_sexo\nH-MIX-1,F\n", target="cacu.Paciente")
|
||||
tea_source = _json_source([{"pac_id_hospital": "T-MIX-1", "pac_sexo": "F"}], target="tea.Pacientes")
|
||||
|
||||
response = client.post("/imports/commit", json={"sources": [cacu_source, tea_source], "on_conflict": "reject"})
|
||||
assert response.status_code == 400
|
||||
assert "domain" in response.get_json()["error"].lower()
|
||||
|
||||
|
||||
def test_commit_on_conflict_reject_then_upsert(client):
|
||||
first_csv = b"pac_id_hospital,pac_sexo,pac_fecha_nacimiento\nH-CONFLICT-1,F,1990-01-01\n"
|
||||
first = client.post(
|
||||
"/imports/commit",
|
||||
json={"sources": [_csv_source(first_csv, target="cacu.Paciente")], "on_conflict": "reject"},
|
||||
)
|
||||
assert first.get_json()["results"][0]["created"] == 1
|
||||
|
||||
reject_again = client.post(
|
||||
"/imports/commit",
|
||||
json={"sources": [_csv_source(first_csv, target="cacu.Paciente")], "on_conflict": "reject"},
|
||||
)
|
||||
reject_body = reject_again.get_json()["results"][0]
|
||||
assert reject_body["created"] == 0
|
||||
assert reject_body["rejected"] == 1
|
||||
|
||||
upsert_csv = b"pac_id_hospital,pac_sexo,pac_fecha_nacimiento\nH-CONFLICT-1,M,1990-01-01\n"
|
||||
upsert = client.post(
|
||||
"/imports/commit",
|
||||
json={"sources": [_csv_source(upsert_csv, target="cacu.Paciente")], "on_conflict": "upsert"},
|
||||
)
|
||||
upsert_body = upsert.get_json()["results"][0]
|
||||
assert upsert_body["created"] == 0
|
||||
assert upsert_body["updated"] == 1
|
||||
|
||||
|
||||
def test_commit_upsert_rejected_for_target_without_natural_key(client):
|
||||
source = _json_source(
|
||||
[{"psi_pac_id": 1}], target="tea.EvaluacionPsicologica", column_mapping={"psi_pac_id": "psi_pac_id"}
|
||||
)
|
||||
response = client.post("/imports/commit", json={"sources": [source], "on_conflict": "upsert"})
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
def test_tea_patient_keeps_the_source_id_and_reimport_updates_it(client):
|
||||
mapping = {"pac_id": "pac_id", "pac_id_hospital": "pac_id_hospital", "pac_sexo": "pac_sexo"}
|
||||
first = _json_source([{"pac_id": 9001, "pac_id_hospital": "T-SRC-1", "pac_sexo": "F"}],
|
||||
target="tea.Pacientes", column_mapping=mapping)
|
||||
body = client.post("/imports/commit", json={"sources": [first], "on_conflict": "upsert"}).get_json()
|
||||
assert body["results"][0]["created"] == 1
|
||||
|
||||
again = _json_source([{"pac_id": 9001, "pac_id_hospital": "T-SRC-1", "pac_sexo": "M"}],
|
||||
target="tea.Pacientes", column_mapping=mapping)
|
||||
body = client.post("/imports/commit", json={"sources": [again], "on_conflict": "upsert"}).get_json()
|
||||
assert body["results"][0]["created"] == 0
|
||||
assert body["results"][0]["updated"] == 1
|
||||
|
||||
paciente = client.get("/tea/pacientes/9001").get_json()
|
||||
assert paciente["pac_id_hospital"] == "T-SRC-1"
|
||||
assert paciente["pac_sexo"] == "M"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sql_source_db(tmp_path):
|
||||
db_path = tmp_path / "external_source.db"
|
||||
url = f"sqlite:///{db_path}"
|
||||
engine = create_engine(url)
|
||||
with engine.begin() as conn:
|
||||
conn.execute(text("CREATE TABLE hospital_patients (id_hospital TEXT, sexo TEXT, nacimiento TEXT)"))
|
||||
conn.execute(
|
||||
text("INSERT INTO hospital_patients (id_hospital, sexo, nacimiento) VALUES ('H-SQL-1', 'F', '1990-01-01')")
|
||||
)
|
||||
return url
|
||||
|
||||
|
||||
def test_sql_source_introspection_preview_and_commit(client, sql_source_db):
|
||||
test_conn = client.post("/imports/sources/sql/test-connection", json={"connection_string": sql_source_db})
|
||||
assert test_conn.status_code == 200
|
||||
assert test_conn.get_json()["dialect"] == "sqlite"
|
||||
|
||||
tables = client.post("/imports/sources/sql/tables", json={"connection_string": sql_source_db})
|
||||
assert "hospital_patients" in tables.get_json()["tables"]
|
||||
|
||||
columns = client.post(
|
||||
"/imports/sources/sql/columns", json={"connection_string": sql_source_db, "table": "hospital_patients"}
|
||||
)
|
||||
assert {c["name"] for c in columns.get_json()["columns"]} == {"id_hospital", "sexo", "nacimiento"}
|
||||
|
||||
preview = client.post(
|
||||
"/imports/sources/sql/preview",
|
||||
json={"connection_string": sql_source_db, "table": "hospital_patients", "target": "cacu.Paciente"},
|
||||
)
|
||||
assert preview.status_code == 200
|
||||
assert preview.get_json()["total_rows"] == 1
|
||||
|
||||
sql_import_source = {
|
||||
"source_type": "sql",
|
||||
"target": "cacu.Paciente",
|
||||
"column_mapping": {"id_hospital": "pac_id_hospital", "sexo": "pac_sexo", "nacimiento": "pac_fecha_nacimiento"},
|
||||
"payload": {"connection_string": sql_source_db, "table": "hospital_patients"},
|
||||
}
|
||||
commit_response = client.post("/imports/commit", json={"sources": [sql_import_source], "on_conflict": "reject"})
|
||||
assert commit_response.status_code == 200
|
||||
assert commit_response.get_json()["results"][0]["created"] == 1
|
||||
@@ -1,164 +0,0 @@
|
||||
"""Fills `cacu.Paciente` from a MySQL legacy table, a CSV and a JSON file in
|
||||
one batch, through the HTTP endpoints with the `pymysql` driver.
|
||||
|
||||
Skipped unless `MYSQL_TEST_URL` is set; see `tests/test_connectors_mysql.py`
|
||||
for a local setup.
|
||||
"""
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
|
||||
import pytest
|
||||
import sqlalchemy as sa
|
||||
|
||||
MYSQL_TEST_URL = os.environ.get("MYSQL_TEST_URL")
|
||||
|
||||
pytestmark = pytest.mark.skipif(not MYSQL_TEST_URL, reason="MYSQL_TEST_URL not set — no real MySQL server to test against")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(wire_domain):
|
||||
wire_domain("cacu")
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def mysql_legacy_source():
|
||||
"""A legacy MySQL table whose column names and types are unrelated to
|
||||
`Core`'s `Paciente`."""
|
||||
engine = sa.create_engine(MYSQL_TEST_URL)
|
||||
table_name = "test_multisource_legacy_patients"
|
||||
with engine.begin() as conn:
|
||||
conn.execute(sa.text(f"DROP TABLE IF EXISTS {table_name}"))
|
||||
conn.execute(
|
||||
sa.text(
|
||||
f"CREATE TABLE {table_name} ("
|
||||
" expediente VARCHAR(40) NOT NULL PRIMARY KEY,"
|
||||
" sexo_paciente ENUM('F','M')"
|
||||
") ENGINE=InnoDB"
|
||||
)
|
||||
)
|
||||
conn.execute(
|
||||
sa.text(
|
||||
f"INSERT INTO {table_name} (expediente, sexo_paciente) VALUES "
|
||||
"('MYSQL-MULTI-1', 'F'), ('MYSQL-MULTI-2', 'M')"
|
||||
)
|
||||
)
|
||||
yield table_name
|
||||
with engine.begin() as conn:
|
||||
conn.execute(sa.text(f"DROP TABLE IF EXISTS {table_name}"))
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_sql_source_http_endpoints_browse_real_mysql_schema(client, mysql_legacy_source):
|
||||
"""The schema-browsing flow the WebApp SQL wizard drives (test-connection
|
||||
-> schemas -> tables -> columns -> preview) against MySQL."""
|
||||
test_conn = client.post("/imports/sources/sql/test-connection", json={"connection_string": MYSQL_TEST_URL})
|
||||
assert test_conn.status_code == 200
|
||||
assert test_conn.get_json()["dialect"] == "mysql"
|
||||
|
||||
schemas = client.post("/imports/sources/sql/schemas", json={"connection_string": MYSQL_TEST_URL})
|
||||
assert "hospital_legacy" in schemas.get_json()["schemas"]
|
||||
|
||||
tables = client.post(
|
||||
"/imports/sources/sql/tables", json={"connection_string": MYSQL_TEST_URL, "schema": "hospital_legacy"}
|
||||
)
|
||||
assert mysql_legacy_source in tables.get_json()["tables"]
|
||||
|
||||
columns = client.post(
|
||||
"/imports/sources/sql/columns",
|
||||
json={"connection_string": MYSQL_TEST_URL, "table": mysql_legacy_source, "schema": "hospital_legacy"},
|
||||
)
|
||||
assert {c["name"] for c in columns.get_json()["columns"]} == {"expediente", "sexo_paciente"}
|
||||
|
||||
preview = client.post(
|
||||
"/imports/sources/sql/preview",
|
||||
json={
|
||||
"connection_string": MYSQL_TEST_URL,
|
||||
"table": mysql_legacy_source,
|
||||
"schema": "hospital_legacy",
|
||||
"target": "cacu.Paciente",
|
||||
},
|
||||
)
|
||||
assert preview.status_code == 200
|
||||
body = preview.get_json()
|
||||
assert body["total_rows"] == 2
|
||||
suggested = {m["source_column"]: m["target_field"] for m in body["suggested_mapping"]}
|
||||
# "expediente" is a column_matcher synonym for pac_id_hospital.
|
||||
assert suggested.get("expediente") == "pac_id_hospital"
|
||||
|
||||
|
||||
def test_commit_batch_mixes_mysql_json_and_csv_into_one_domain(client, mysql_legacy_source):
|
||||
csv_bytes = b"pac_id_hospital,pac_sexo\nCSV-MULTI-1,F\n"
|
||||
csv_source = {
|
||||
"source_type": "csv",
|
||||
"target": "cacu.Paciente",
|
||||
"column_mapping": {"pac_id_hospital": "pac_id_hospital", "pac_sexo": "pac_sexo"},
|
||||
"payload": {"file_base64": base64.b64encode(csv_bytes).decode()},
|
||||
}
|
||||
|
||||
json_records = [{"id_hospital": "JSON-MULTI-1", "sexo": "M"}]
|
||||
json_source = {
|
||||
"source_type": "json",
|
||||
"target": "cacu.Paciente",
|
||||
"column_mapping": {"id_hospital": "pac_id_hospital", "sexo": "pac_sexo"},
|
||||
"payload": {"file_base64": base64.b64encode(json.dumps(json_records).encode()).decode()},
|
||||
}
|
||||
|
||||
sql_source = {
|
||||
"source_type": "sql",
|
||||
"target": "cacu.Paciente",
|
||||
"column_mapping": {"expediente": "pac_id_hospital", "sexo_paciente": "pac_sexo"},
|
||||
"payload": {"connection_string": MYSQL_TEST_URL, "table": mysql_legacy_source},
|
||||
}
|
||||
|
||||
response = client.post(
|
||||
"/imports/commit",
|
||||
json={"sources": [csv_source, json_source, sql_source], "on_conflict": "reject"},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
body = response.get_json()
|
||||
assert body["ok"] is True
|
||||
assert [r["target"] for r in body["results"]] == ["cacu.Paciente"] * 3
|
||||
# csv: 1 row, json: 1 row, mysql: 2 rows
|
||||
assert [r["created"] for r in body["results"]] == [1, 1, 2]
|
||||
|
||||
all_ids = {client.get(f"/cacu/pacientes/{i}").get_json()["pac_id_hospital"] for i in range(1, 5)}
|
||||
assert all_ids == {"CSV-MULTI-1", "JSON-MULTI-1", "MYSQL-MULTI-1", "MYSQL-MULTI-2"}
|
||||
|
||||
|
||||
def test_commit_upsert_against_mysql_source_updates_existing_row(client, mysql_legacy_source):
|
||||
# MYSQL-MULTI-1 already exists (created above with sexo 'F'). Mutate the
|
||||
# source row and re-import with on_conflict=upsert.
|
||||
engine = sa.create_engine(MYSQL_TEST_URL)
|
||||
with engine.begin() as conn:
|
||||
conn.execute(
|
||||
sa.text(f"UPDATE {mysql_legacy_source} SET sexo_paciente = 'M' WHERE expediente = 'MYSQL-MULTI-1'")
|
||||
)
|
||||
engine.dispose()
|
||||
|
||||
sql_source = {
|
||||
"source_type": "sql",
|
||||
"target": "cacu.Paciente",
|
||||
"column_mapping": {"expediente": "pac_id_hospital", "sexo_paciente": "pac_sexo"},
|
||||
"payload": {"connection_string": MYSQL_TEST_URL, "table": mysql_legacy_source},
|
||||
}
|
||||
response = client.post("/imports/commit", json={"sources": [sql_source], "on_conflict": "upsert"})
|
||||
assert response.status_code == 200
|
||||
result = response.get_json()["results"][0]
|
||||
# Both rows already exist from the previous test. Upsert reports
|
||||
# "updated" for every conflicting row whether or not its values changed,
|
||||
# per Repository.bulk_upsert's contract.
|
||||
assert result["updated"] == 2
|
||||
assert result["created"] == 0
|
||||
|
||||
updated = client.get("/cacu/pacientes/3").get_json()
|
||||
assert updated["pac_id_hospital"] == "MYSQL-MULTI-1"
|
||||
# 'M' is coerced through SEXO_BIOLOGICO_ALIAS into the canonical value.
|
||||
assert updated["pac_sexo"] == "Masculino"
|
||||
@@ -1,273 +0,0 @@
|
||||
"""Endpoint tests for the PDF routes. One round trip per resolution path:
|
||||
- detect -> table/preview -> validate -> commit, for the ruled-table
|
||||
path, writing into `cacu.Paciente`.
|
||||
- detect -> page-image -> regions/extract -> validate -> commit, for the
|
||||
OCR/region path, writing into `tea.Pacientes`.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import io
|
||||
import json
|
||||
|
||||
import pytest
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
from reportlab.lib import colors
|
||||
from reportlab.lib.pagesizes import letter
|
||||
from reportlab.lib.utils import ImageReader
|
||||
from reportlab.pdfgen import canvas
|
||||
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(wire_domain):
|
||||
wire_domain("cacu")
|
||||
wire_domain("tea")
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# Fixture PDFs
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def _build_table_pdf(rows: list[tuple[str, str, str]]) -> bytes:
|
||||
buffer = io.BytesIO()
|
||||
doc = SimpleDocTemplate(buffer, pagesize=letter)
|
||||
data = [["pac_id_hospital", "pac_sexo", "pac_fecha_nacimiento"], *[list(row) for row in rows]]
|
||||
table = Table(data)
|
||||
table.setStyle(
|
||||
TableStyle(
|
||||
[
|
||||
("GRID", (0, 0), (-1, -1), 1, colors.black),
|
||||
("FONTSIZE", (0, 0), (-1, -1), 12),
|
||||
("BOTTOMPADDING", (0, 0), (-1, -1), 8),
|
||||
("TOPPADDING", (0, 0), (-1, -1), 8),
|
||||
]
|
||||
)
|
||||
)
|
||||
doc.build([table])
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
_IMG_W, _IMG_H = 900, 1200
|
||||
|
||||
|
||||
def _font(size: int = 34):
|
||||
for path in (
|
||||
"/System/Library/Fonts/Helvetica.ttc",
|
||||
"/System/Library/Fonts/Supplemental/Arial.ttf",
|
||||
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
|
||||
):
|
||||
try:
|
||||
return ImageFont.truetype(path, size)
|
||||
except Exception:
|
||||
continue
|
||||
return ImageFont.load_default()
|
||||
|
||||
|
||||
def _build_scanned_form_pdf(id_hospital: str, sexo: str) -> bytes:
|
||||
"""A scanned-like page with two text blocks at known pixel positions and
|
||||
no text layer, so only the OCR/region path applies."""
|
||||
img = Image.new("RGB", (_IMG_W, _IMG_H), "white")
|
||||
draw = ImageDraw.Draw(img)
|
||||
font = _font()
|
||||
draw.text((40, 100), id_hospital, fill="black", font=font)
|
||||
draw.text((400, 100), sexo, fill="black", font=font)
|
||||
|
||||
buffer = io.BytesIO()
|
||||
c = canvas.Canvas(buffer, pagesize=letter)
|
||||
page_w, page_h = letter
|
||||
reader_buf = io.BytesIO()
|
||||
img.save(reader_buf, format="PNG")
|
||||
reader_buf.seek(0)
|
||||
c.drawImage(ImageReader(reader_buf), 0, 0, width=page_w, height=page_h)
|
||||
c.showPage()
|
||||
c.save()
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
_ID_HOSPITAL_BBOX = (20 / _IMG_W, 60 / _IMG_H, 350 / _IMG_W, 180 / _IMG_H)
|
||||
_SEXO_BBOX = (380 / _IMG_W, 60 / _IMG_H, 500 / _IMG_W, 180 / _IMG_H)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# Table path: detect -> table/preview -> validate -> commit (cacu.Paciente)
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_pdf_table_round_trip_detect_preview_validate_commit(client):
|
||||
pdf_bytes = _build_table_pdf([("H-PDF-TAB-1", "F", "1990-01-01"), ("H-PDF-TAB-2", "M", "1985-06-15")])
|
||||
|
||||
detect_response = client.post(
|
||||
"/imports/sources/pdf/detect",
|
||||
data={"file": (io.BytesIO(pdf_bytes), "table.pdf")},
|
||||
content_type="multipart/form-data",
|
||||
)
|
||||
assert detect_response.status_code == 200
|
||||
detect_body = detect_response.get_json()
|
||||
assert detect_body["page_count"] == 1
|
||||
assert detect_body["has_text_layer"] is True
|
||||
assert len(detect_body["table_candidates"]) == 1
|
||||
candidate = detect_body["table_candidates"][0]
|
||||
assert candidate["row_count"] == 2
|
||||
assert candidate["column_count"] == 3
|
||||
|
||||
preview_response = client.post(
|
||||
"/imports/sources/pdf/table/preview",
|
||||
data={
|
||||
"file": (io.BytesIO(pdf_bytes), "table.pdf"),
|
||||
"page_number": str(candidate["page_number"]),
|
||||
"bbox": json.dumps(candidate["bbox"]),
|
||||
"target": "cacu.Paciente",
|
||||
},
|
||||
content_type="multipart/form-data",
|
||||
)
|
||||
assert preview_response.status_code == 200
|
||||
preview_body = preview_response.get_json()
|
||||
assert {c["name"] for c in preview_body["columns"]} == {"pac_id_hospital", "pac_sexo", "pac_fecha_nacimiento"}
|
||||
assert preview_body["total_rows"] == 2
|
||||
suggested = {m["source_column"]: m["target_field"] for m in preview_body["suggested_mapping"]}
|
||||
assert suggested["pac_id_hospital"] == "pac_id_hospital"
|
||||
|
||||
source = {
|
||||
"source_type": "pdf",
|
||||
"target": "cacu.Paciente",
|
||||
"column_mapping": {
|
||||
"pac_id_hospital": "pac_id_hospital",
|
||||
"pac_sexo": "pac_sexo",
|
||||
"pac_fecha_nacimiento": "pac_fecha_nacimiento",
|
||||
},
|
||||
"payload": {
|
||||
"file_base64": base64.b64encode(pdf_bytes).decode(),
|
||||
"mode": "table",
|
||||
"page_number": candidate["page_number"],
|
||||
"bbox": candidate["bbox"],
|
||||
},
|
||||
}
|
||||
|
||||
validate_response = client.post("/imports/validate", json={"source": source})
|
||||
assert validate_response.status_code == 200
|
||||
validate_body = validate_response.get_json()
|
||||
assert validate_body["total_rows"] == 2
|
||||
assert validate_body["valid_count"] == 2
|
||||
assert validate_body["error_count"] == 0
|
||||
|
||||
commit_response = client.post("/imports/commit", json={"sources": [source], "on_conflict": "reject"})
|
||||
assert commit_response.status_code == 200
|
||||
commit_body = commit_response.get_json()
|
||||
assert commit_body["ok"] is True
|
||||
result = commit_body["results"][0]
|
||||
assert result["target"] == "cacu.Paciente"
|
||||
assert result["created"] == 2
|
||||
|
||||
# this is the first write into cacu.Paciente in this module's temp DB
|
||||
created = client.get("/cacu/pacientes/1")
|
||||
assert created.status_code == 200
|
||||
assert created.get_json()["pac_id_hospital"] == "H-PDF-TAB-1"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# page-image endpoint
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_pdf_page_image_returns_png(client):
|
||||
pdf_bytes = _build_scanned_form_pdf("H-IMG-1", "F")
|
||||
response = client.post(
|
||||
"/imports/sources/pdf/page-image",
|
||||
data={"file": (io.BytesIO(pdf_bytes), "form.pdf"), "page_number": "1"},
|
||||
content_type="multipart/form-data",
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert response.content_type == "image/png"
|
||||
image = Image.open(io.BytesIO(response.data))
|
||||
assert image.format == "PNG"
|
||||
|
||||
|
||||
def test_pdf_page_image_missing_file_returns_400(client):
|
||||
response = client.post(
|
||||
"/imports/sources/pdf/page-image", data={"page_number": "1"}, content_type="multipart/form-data"
|
||||
)
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# OCR/region path: detect -> page-image -> regions/extract -> validate ->
|
||||
# commit (tea.Pacientes)
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_pdf_region_round_trip_detect_image_extract_validate_commit(client):
|
||||
pdf_bytes = _build_scanned_form_pdf("H-PDF-OCR-1", "F")
|
||||
|
||||
detect_response = client.post(
|
||||
"/imports/sources/pdf/detect",
|
||||
data={"file": (io.BytesIO(pdf_bytes), "form.pdf")},
|
||||
content_type="multipart/form-data",
|
||||
)
|
||||
assert detect_response.status_code == 200
|
||||
detect_body = detect_response.get_json()
|
||||
assert detect_body["has_text_layer"] is False
|
||||
assert detect_body["table_candidates"] == []
|
||||
|
||||
image_response = client.post(
|
||||
"/imports/sources/pdf/page-image",
|
||||
data={"file": (io.BytesIO(pdf_bytes), "form.pdf"), "page_number": "1"},
|
||||
content_type="multipart/form-data",
|
||||
)
|
||||
assert image_response.status_code == 200
|
||||
assert Image.open(io.BytesIO(image_response.data)).format == "PNG"
|
||||
|
||||
regions = [
|
||||
{"target_field": "pac_id_hospital", "page_numbers": [1], "bbox": list(_ID_HOSPITAL_BBOX)},
|
||||
{"target_field": "pac_sexo", "page_numbers": [1], "bbox": list(_SEXO_BBOX)},
|
||||
]
|
||||
extract_response = client.post(
|
||||
"/imports/sources/pdf/regions/extract",
|
||||
json={"file_base64": base64.b64encode(pdf_bytes).decode(), "regions": regions},
|
||||
)
|
||||
assert extract_response.status_code == 200
|
||||
extract_body = extract_response.get_json()
|
||||
assert extract_body["rows"] == [{"pac_id_hospital": "H-PDF-OCR-1", "pac_sexo": "F"}]
|
||||
assert extract_body["warnings"] == []
|
||||
|
||||
source = {
|
||||
"source_type": "pdf",
|
||||
"target": "tea.Pacientes",
|
||||
"column_mapping": {"pac_id_hospital": "pac_id_hospital", "pac_sexo": "pac_sexo"},
|
||||
"payload": {
|
||||
"file_base64": base64.b64encode(pdf_bytes).decode(),
|
||||
"mode": "regions",
|
||||
"regions": regions,
|
||||
},
|
||||
}
|
||||
|
||||
validate_response = client.post("/imports/validate", json={"source": source})
|
||||
assert validate_response.status_code == 200
|
||||
validate_body = validate_response.get_json()
|
||||
assert validate_body["total_rows"] == 1
|
||||
assert validate_body["valid_count"] == 1
|
||||
|
||||
commit_response = client.post("/imports/commit", json={"sources": [source], "on_conflict": "reject"})
|
||||
assert commit_response.status_code == 200
|
||||
commit_body = commit_response.get_json()
|
||||
assert commit_body["ok"] is True
|
||||
result = commit_body["results"][0]
|
||||
assert result["target"] == "tea.Pacientes"
|
||||
assert result["created"] == 1
|
||||
|
||||
|
||||
def test_pdf_detect_missing_file_returns_400(client):
|
||||
response = client.post("/imports/sources/pdf/detect", data={}, content_type="multipart/form-data")
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
def test_pdf_regions_extract_missing_field_returns_400(client):
|
||||
response = client.post("/imports/sources/pdf/regions/extract", json={"regions": []})
|
||||
assert response.status_code == 400
|
||||
@@ -1,183 +0,0 @@
|
||||
"""Endpoint tests for `/tea/indicadores`, `/cacu/indicadores` and
|
||||
`/cama/indicadores`: the read side of the bronze/silver/gold pipeline
|
||||
(Persistance/persistance/aristas, indicadores_kit). Seeds one patient,
|
||||
runs the real `cargar`/`registro`/`definiciones`/`calcular` steps, then
|
||||
hits the HTTP layer."""
|
||||
from datetime import date
|
||||
from functools import partial
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(wire_domain):
|
||||
wire_domain("tea")
|
||||
|
||||
from core.tea.models import Pacientes
|
||||
from persistance import db as persistance_db
|
||||
from persistance.tea import (
|
||||
staging_repository, carga_repository, def_parametro_repository,
|
||||
dim_periodo_repository, indicador_definicion_repository, calculo_repository,
|
||||
)
|
||||
from indicadores_kit.tea import etl
|
||||
from indicadores_kit.registry.parametros import leer_parametros, RUTA_PARAMETROS
|
||||
from indicadores_kit.registry.periodos import periodos_de_tipos
|
||||
from indicadores_kit.registry.measures import measures_de, rutas_de_measures
|
||||
from indicadores_kit.serving.definiciones import leer_definiciones
|
||||
from indicadores_kit.mart.calculo import medir_con_unidades
|
||||
from indicadores_kit.tablas import tablas_de
|
||||
|
||||
with __import__("sqlmodel").Session(persistance_db.get_tea_engine()) as session:
|
||||
session.add(Pacientes(pac_id_hospital="H-1", pac_fecha_nacimiento=date(2020, 1, 1), pac_sexo="F"))
|
||||
session.commit()
|
||||
|
||||
staging = staging_repository.leer(etl.STAGING)
|
||||
lote = etl.lote_de_estudios(**staging)
|
||||
carga_repository.guardar_lote(**lote.para_guardar())
|
||||
|
||||
tablas = tablas_de("tea")
|
||||
measures = measures_de("tea")
|
||||
tipos = sorted({t for m in measures.values() for t in m.extension.publicacion.tipos_periodo})
|
||||
def_parametro_repository.reemplazar(leer_parametros(RUTA_PARAMETROS, tablas=tablas))
|
||||
dim_periodo_repository.agregar_faltantes(periodos_de_tipos(tipos, 2024, 2024, tablas=tablas))
|
||||
indicador_definicion_repository.reemplazar(leer_definiciones(rutas_de_measures("tea"), tablas=tablas))
|
||||
nombre, medida = next(iter(measures.items()))
|
||||
for tipo in medida.extension.publicacion.tipos_periodo:
|
||||
for periodo_id in calculo_repository.periodos(tipo, date(2024, 1, 1), date(2025, 1, 1)):
|
||||
medir = partial(medir_con_unidades, measure=medida, periodo_id=periodo_id, tablas=tablas,
|
||||
corte=None, permitir_sin_definir=True)
|
||||
calculo_repository.calcular(medir)
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
def test_list_indicadores(client):
|
||||
"""Only the 5 TEA measures not marked `oculto` in their own TOML publish
|
||||
to the catalog (the K01-K08/M02-M19 family is draft/internal); a hidden
|
||||
id still answers `/datos` directly, see `test_indicador_datos_...`."""
|
||||
response = client.get("/tea/indicadores")
|
||||
assert response.status_code == 200
|
||||
indicadores = response.get_json()
|
||||
assert isinstance(indicadores, list)
|
||||
assert len(indicadores) == 5
|
||||
assert {"id", "titulo", "contrato", "unidad", "sentido", "tipos_periodo", "estratos", "figuras"} <= indicadores[0].keys()
|
||||
|
||||
|
||||
def test_indicador_datos_returns_valid_json_no_bare_nan(client):
|
||||
response = client.get("/tea/indicadores/K01_evaluacion_3_meses/datos?periodos=2024-S1,2024-S2")
|
||||
assert response.status_code == 200
|
||||
# Pandas renders missing scores as NaN; the response must not leak the
|
||||
# bare (invalid-JSON) token -- it has to come through as `null`.
|
||||
assert "NaN" not in response.get_data(as_text=True)
|
||||
body = response.get_json()
|
||||
assert body["id"] == "K01_evaluacion_3_meses"
|
||||
assert set(body["periodos"]) == {"2024-S1", "2024-S2"}
|
||||
assert {row["periodo"] for row in body["filas"]} == {"2024-S1", "2024-S2"}
|
||||
|
||||
|
||||
def test_indicador_datos_without_periodos_defaults_to_available_ones(client):
|
||||
"""Unlike the old endpoint, omitting `periodos` is not an error: it
|
||||
reports whatever periods already have a computed report."""
|
||||
response = client.get("/tea/indicadores/K01_evaluacion_3_meses/datos")
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["periodos"]
|
||||
|
||||
|
||||
def test_indicador_datos_unknown_indicador_is_404(client):
|
||||
response = client.get("/tea/indicadores/NOPE/datos?periodos=2024-S1")
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
def test_indicador_datos_malformed_periodo_is_400(client):
|
||||
response = client.get("/tea/indicadores/K01_evaluacion_3_meses/datos?periodos=no-es-un-periodo")
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
def test_indicador_periodos_endpoint(client):
|
||||
response = client.get("/tea/indicadores/K01_evaluacion_3_meses/periodos")
|
||||
assert response.status_code == 200
|
||||
body = response.get_json()
|
||||
assert body["id"] == "K01_evaluacion_3_meses"
|
||||
assert isinstance(body["periodos"], list)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def cacu_client(wire_domain):
|
||||
"""CaCu reproduces a real id mismatch TEA's fixture doesn't: some of its
|
||||
TOML files are named in lowercase (`cacu_biopsias.toml`, the
|
||||
`measures_de` dict key) while their `measure.url` ends in uppercase
|
||||
(`cacu/CACU_BIOPSIAS`, the id `indicador_definicion.indicador` and the
|
||||
catalog publish) -- caught live by driving the WebApp dashboard against
|
||||
a real CaCu indicator, not by the TEA-only fixture above."""
|
||||
wire_domain("cacu")
|
||||
|
||||
from sqlmodel import Session
|
||||
from persistance import db as persistance_db
|
||||
from persistance.cacu import (
|
||||
staging_repository, carga_repository, def_parametro_repository as cacu_def_parametro_repository,
|
||||
dim_periodo_repository, indicador_definicion_repository, calculo_repository, vistas_repository,
|
||||
)
|
||||
from indicadores_kit.cacu import etl, fixtures
|
||||
from indicadores_kit.cdm.etl import lote_de_resultados
|
||||
from indicadores_kit.esquema import ddl_de_vistas
|
||||
from indicadores_kit.registry.parametros import leer_parametros, RUTA_PARAMETROS
|
||||
from indicadores_kit.registry.periodos import periodos_de_tipos
|
||||
from indicadores_kit.registry.measures import measures_de, rutas_de_measures
|
||||
from indicadores_kit.serving.definiciones import leer_definiciones
|
||||
from indicadores_kit.mart.calculo import medir_con_unidades
|
||||
from indicadores_kit.tablas import tablas_de
|
||||
|
||||
with Session(persistance_db.get_cacu_engine()) as session:
|
||||
fixtures.insertar(session)
|
||||
session.commit()
|
||||
|
||||
tablas = tablas_de("cacu")
|
||||
staging = staging_repository.leer(etl.STAGING)
|
||||
lote = etl.lote_de_estudios(**staging)
|
||||
carga_repository.guardar_lote(**lote.para_guardar())
|
||||
pacientes = staging_repository.leer({"pacientes": etl.STAGING["pacientes"]})["pacientes"]
|
||||
lote_resultados = lote_de_resultados(
|
||||
pacientes, staging_repository.leer(etl.STAGING_DE_RESULTADOS), etl.FUENTES_DE_RESULTADOS, tablas=tablas,
|
||||
)
|
||||
carga_repository.guardar_lote(**lote_resultados.para_guardar())
|
||||
vistas_repository.construir(ddl_de_vistas("cacu"))
|
||||
|
||||
measures = measures_de("cacu")
|
||||
tipos = sorted({t for m in measures.values() for t in m.extension.publicacion.tipos_periodo})
|
||||
cacu_def_parametro_repository.reemplazar(leer_parametros(RUTA_PARAMETROS, tablas=tablas))
|
||||
dim_periodo_repository.agregar_faltantes(periodos_de_tipos(tipos, 2025, 2025, tablas=tablas))
|
||||
indicador_definicion_repository.reemplazar(leer_definiciones(rutas_de_measures("cacu"), tablas=tablas))
|
||||
for medida in measures.values():
|
||||
for tipo in medida.extension.publicacion.tipos_periodo:
|
||||
for periodo_id in calculo_repository.periodos(tipo, date(2025, 1, 1), date(2026, 1, 1)):
|
||||
medir = partial(medir_con_unidades, measure=medida, periodo_id=periodo_id, tablas=tablas,
|
||||
corte=None, permitir_sin_definir=True)
|
||||
calculo_repository.calcular(medir)
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
def test_indicador_datos_uses_the_toml_key_not_measure_url(cacu_client):
|
||||
"""`cacu_biopsias`'s own `measure.url` ends in `CACU_BIOPSIAS` (uppercase),
|
||||
but `registrar_indicadores` publishes and looks measures up by
|
||||
`measures_de()`'s dict key (the lowercase TOML file stem) throughout, so
|
||||
the mismatch never reaches a client -- unlike the old, since-replaced
|
||||
`webapi.indicadores`, which published the uppercase `measure.url` id and
|
||||
needed its own `_measure_por_indicador` lookup to reconcile the two."""
|
||||
catalogo = cacu_client.get("/cacu/indicadores").get_json()
|
||||
assert any(i["id"] == "cacu_biopsias" for i in catalogo)
|
||||
assert not any(i["id"] == "CACU_BIOPSIAS" for i in catalogo)
|
||||
|
||||
response = cacu_client.get("/cacu/indicadores/cacu_biopsias/datos?periodos=2025-S1,2025-S2")
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["filas"]
|
||||
@@ -1,48 +0,0 @@
|
||||
"""WebApi and `models` talk to each other through the database, both ways,
|
||||
over the same Repository objects: rows imported over HTTP are what a
|
||||
model trains on, and rows a model writes are what the API serves."""
|
||||
import base64
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(wire_domain):
|
||||
wire_domain("cama")
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
def test_imported_rows_are_what_models_reads_and_model_writes_are_what_the_api_serves(client):
|
||||
from core.cama.models import Mastografia
|
||||
from models.cama import CaMaModel
|
||||
|
||||
csv = b"Expediente,BIRADS\nRT-1,BI-RADS 4\nRT-2,2\n"
|
||||
response = client.post(
|
||||
"/imports/commit",
|
||||
json={
|
||||
"sources": [
|
||||
{
|
||||
"source_type": "csv",
|
||||
"target": "cama.Mastografia",
|
||||
"column_mapping": {"Expediente": "pac_id_hospital", "BIRADS": "mast_birads"},
|
||||
"payload": {"file_base64": base64.b64encode(csv).decode()},
|
||||
}
|
||||
]
|
||||
},
|
||||
)
|
||||
assert response.get_json()["results"][0]["created"] == 2
|
||||
|
||||
model = CaMaModel()
|
||||
seen = {row["pac_id_hospital"]: row["mast_birads"] for row in model.dataset("mastografia")}
|
||||
assert seen == {"RT-1": "B4", "RT-2": "B2"}
|
||||
|
||||
model.repository("mastografia").create(Mastografia(pac_id_hospital="RT-FROM-MODEL", mast_birads="B1"))
|
||||
served = client.get("/data/cama.Mastografia").get_json()
|
||||
assert served["total"] == 3
|
||||
assert "RT-FROM-MODEL" in {row["pac_id_hospital"] for row in served["rows"]}
|
||||
@@ -1,372 +0,0 @@
|
||||
"""Connector catalog, SQL Server, EEG files and clinical documents, end to end."""
|
||||
import base64
|
||||
import io
|
||||
from datetime import date
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.dialects import mssql
|
||||
|
||||
from extraction.testing import edf_file, scanned_pdf, text_pdf
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(wire_domain):
|
||||
wire_domain("cacu")
|
||||
wire_domain("cama")
|
||||
wire_domain("tea")
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
def b64(raw: bytes) -> str:
|
||||
return base64.b64encode(raw).decode()
|
||||
|
||||
|
||||
def eeg(seconds: int = 8, rate: int = 128, **kwargs) -> bytes:
|
||||
t = np.arange(rate * seconds) / rate
|
||||
alpha = 40 * np.sin(2 * np.pi * 10 * t)
|
||||
return edf_file(signals={"EEG O1-REF": alpha, "EEG O2-REF": alpha, "EEG Fp1-REF": 20 * np.sin(2 * np.pi * 20 * t)}, sample_rate=rate, **kwargs)
|
||||
|
||||
|
||||
# -- catalog ------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_catalog_lists_every_connector(client):
|
||||
connectors = {c["kind"]: c for c in client.get("/imports/connectors").get_json()["connectors"]}
|
||||
assert {"csv", "excel", "json", "pdf", "document", "edf", "sql"} <= set(connectors)
|
||||
assert connectors["edf"]["extensions"] == ["edf"]
|
||||
assert "pdf" in connectors["document"]["extensions"] and "tif" in connectors["document"]["extensions"]
|
||||
assert {s["id"] for s in connectors["document"]["segmentations"]} == {"auto", "document", "pages", "key"}
|
||||
engines = {e["id"]: e for e in connectors["sql"]["engines"]}
|
||||
assert engines["mssql"]["label"] == "SQL Server" and engines["mssql"]["default_port"] == 1433
|
||||
assert engines["mssql"]["available"] is True
|
||||
|
||||
|
||||
# -- SQL Server ----------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_sql_server_url_is_built_from_form_fields():
|
||||
from webapi.imports.connectors.sql import SqlConnector
|
||||
|
||||
url = SqlConnector.server_url({"engine": "mssql", "host": "his.local", "database": "HIS", "user": "lector", "password": "p@ss:/w"})
|
||||
assert url.drivername == "mssql+pymssql"
|
||||
assert url.port == 1433
|
||||
assert url.password == "p@ss:/w"
|
||||
|
||||
|
||||
def test_sql_server_preview_compiles_to_top(monkeypatch):
|
||||
from webapi.imports.connectors.sql import _text_subquery
|
||||
|
||||
statement = sa.select(_text_subquery("SELECT * FROM pacientes")).limit(5)
|
||||
compiled = str(statement.compile(dialect=mssql.dialect(), compile_kwargs={"literal_binds": True}))
|
||||
assert "TOP 5" in compiled and "LIMIT" not in compiled
|
||||
|
||||
|
||||
def test_unknown_engine_and_missing_host_are_rejected(client):
|
||||
assert client.post("/imports/sources/sql/test-connection", json={"server": {"engine": "db2", "host": "x", "database": "y"}}).status_code == 400
|
||||
response = client.post("/imports/sources/sql/test-connection", json={"server": {"engine": "mssql", "database": "y"}})
|
||||
assert response.status_code == 400 and "host" in response.get_json()["error"]
|
||||
|
||||
|
||||
# -- EEG -----------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_edf_preview_maps_onto_eeg_estudio(client):
|
||||
data = {"file": (io.BytesIO(eeg()), "estudio_007.edf"), "target": "tea.EegEstudio"}
|
||||
body = client.post("/imports/sources/file/preview", data=data, content_type="multipart/form-data").get_json()
|
||||
[row] = body["sample_rows"]
|
||||
assert row["id_registro_laboratorio"] == "LAB-778"
|
||||
assert row["paciente"] == "EXP-0042"
|
||||
assert row["fecha_estudio"] == "2024-01-15"
|
||||
assert row["edad_meses"] == 56.0
|
||||
assert row["ritmo_base_frecuencia"] == pytest.approx(10, abs=0.3)
|
||||
assert "3 canales a 128 Hz" in row["descripcion_senal"]
|
||||
suggested = {m["source_column"]: m["target_field"] for m in body["suggested_mapping"]}
|
||||
assert suggested["estudio"] == "eeg_estudio"
|
||||
assert suggested["fecha_estudio"] == "eeg_fecha_estudio"
|
||||
assert suggested["ritmo_base_frecuencia"] == "eeg_ritmo_base_frecuencia"
|
||||
|
||||
|
||||
def test_several_edf_files_load_into_eeg_estudio_with_the_file(client):
|
||||
source = {
|
||||
"source_type": "edf",
|
||||
"target": "tea.EegEstudio",
|
||||
"column_mapping": {
|
||||
"id_registro_laboratorio": "eeg_id_registro_laboratorio",
|
||||
"paciente": "eeg_pac_id",
|
||||
"fecha_estudio": "eeg_fecha_estudio",
|
||||
"duracion_min": "eeg_duracion_min",
|
||||
"ritmo_base_frecuencia": "eeg_ritmo_base_frecuencia",
|
||||
"estudio": "eeg_estudio",
|
||||
},
|
||||
"payload": {"files": [{"name": "a.edf", "file_base64": b64(eeg())}, {"name": "b.edf", "file_base64": b64(eeg(recording="sin datos"))}]},
|
||||
}
|
||||
result = client.post("/imports/commit", json={"sources": [source]}).get_json()["results"][0]
|
||||
assert result["created"] == 2, result
|
||||
|
||||
from persistance.tea import eeg_estudio_repository
|
||||
|
||||
stored = {row.eeg_id_registro_laboratorio: row for row in eeg_estudio_repository.list()}
|
||||
assert set(stored) == {"LAB-778", "b"}
|
||||
assert stored["LAB-778"].eeg_estudio[:8].strip() == b"0"
|
||||
assert stored["LAB-778"].eeg_fecha_estudio == date(2024, 1, 15)
|
||||
|
||||
|
||||
def test_eeg_estudio_rejects_a_file_mne_cannot_read():
|
||||
from webapi.imports.schemas.service import validate_rows
|
||||
from webapi.imports.schemas.tea.eeg_estudio import EegEstudioImportSchema
|
||||
|
||||
result = validate_rows(EegEstudioImportSchema, [{"eeg_estudio": b"definitely not an EDF file" * 20}])
|
||||
[row] = result.rejected
|
||||
assert row.errors[0].field == "eeg_estudio"
|
||||
|
||||
|
||||
# -- clinical documents -----------------------------------------------------------------
|
||||
|
||||
|
||||
def _document_source(files: list[tuple[str, bytes]], target: str, mapping: dict, **options) -> dict:
|
||||
return {
|
||||
"source_type": "document",
|
||||
"target": target,
|
||||
"column_mapping": mapping,
|
||||
"payload": {"files": [{"name": n, "file_base64": b64(r)} for n, r in files], **options},
|
||||
"label": "documentos",
|
||||
}
|
||||
|
||||
|
||||
REPORTS = text_pdf(
|
||||
[
|
||||
["HOSPITAL REGIONAL - LABORATORIO DE PATOLOGIA", "Expediente: DOC-0001 Sexo: Femenino", "Fecha de nacimiento: 12/03/1981",
|
||||
"VPH alto riesgo: POSITIVO", "Genotipo 16: NO DETECTADO", "Genotipo 18: DETECTADO"],
|
||||
["Observaciones: muestra adecuada,", "con escaso moco cervical."],
|
||||
["Expediente: DOC-0002 Sexo: F", "Fecha de nacimiento: 1 de mayo de 1975",
|
||||
"Se identifica ADN de virus del papiloma humano de alto riesgo: NEGATIVO"],
|
||||
],
|
||||
image_on_page=2,
|
||||
)
|
||||
|
||||
|
||||
def test_document_extract_reports_records_evidence_and_images(client):
|
||||
body = client.post(
|
||||
"/imports/sources/document/extract",
|
||||
json={"files": [{"name": "lote.pdf", "file_base64": b64(REPORTS)}], "target": "cacu.CitologiaCervical"},
|
||||
).get_json()
|
||||
assert body["key_field"] == "pac_id_hospital"
|
||||
first, second = body["records"]
|
||||
assert first["key"] == "DOC-0001" and first["sources"] == [{"document": "lote.pdf", "page_numbers": [1, 2]}]
|
||||
assert first["fields"]["cit_vph_resultado"]["value"] == "POSITIVO"
|
||||
assert first["fields"]["cit_vph_genotipo_16"]["value"] == 0
|
||||
assert first["fields"]["cit_vph_genotipo_18"]["value"] == 1
|
||||
assert first["fields"]["cit_observaciones"]["value"] == "muestra adecuada, con escaso moco cervical."
|
||||
assert first["fields"]["cit_vph_resultado"]["page_number"] == 1
|
||||
assert [image["page_number"] for image in first["images"]] == [2]
|
||||
assert second["fields"]["cit_vph_resultado"]["value"] == "NEGATIVO"
|
||||
assert second["fields"]["cit_vph_resultado"]["method"] == "texto_libre"
|
||||
|
||||
|
||||
def test_document_page_and_image_render(client):
|
||||
data = {"file": (io.BytesIO(REPORTS), "lote.pdf"), "page_number": "2", "bbox": "[0.4, 0.4, 0.8, 0.7]"}
|
||||
response = client.post("/imports/sources/document/page-image", data=data, content_type="multipart/form-data")
|
||||
assert response.status_code == 200 and response.mimetype == "image/png"
|
||||
|
||||
|
||||
def test_documents_commit_with_overrides_and_the_record_pdf(client):
|
||||
mapping = {
|
||||
"pac_id_hospital": "pac_id_hospital",
|
||||
"cit_vph_resultado": "cit_vph_resultado",
|
||||
"cit_vph_genotipo_18": "cit_vph_genotipo_18",
|
||||
"documento": "cit_vph_pdf_blob",
|
||||
}
|
||||
source = _document_source([("lote.pdf", REPORTS)], "cacu.CitologiaCervical", mapping, overrides={"1": {"cit_vph_resultado": "INDETERMINADO"}})
|
||||
result = client.post("/imports/commit", json={"sources": [source]}).get_json()["results"][0]
|
||||
assert result["created"] == 2, result
|
||||
|
||||
from persistance.cacu import citologia_cervical_repository
|
||||
|
||||
rows = {r.pac_id_hospital: r for r in citologia_cervical_repository.list(limit=100) if r.pac_id_hospital.startswith("DOC-")}
|
||||
assert rows["DOC-0001"].cit_vph_resultado == "POSITIVO"
|
||||
assert rows["DOC-0002"].cit_vph_resultado == "INDETERMINADO"
|
||||
assert rows["DOC-0001"].cit_vph_pdf_blob.startswith(b"%PDF")
|
||||
|
||||
|
||||
def test_patient_scattered_across_csv_and_scanned_forms_is_merged(client):
|
||||
csv = b"expediente,sexo,codigo_postal\nMIX-0001,F,64000\nMIX-0002,M,01000\n"
|
||||
scan = scanned_pdf([["FICHA DE IDENTIFICACION", "Expediente: MIX-0001", "Fecha de nacimiento: 15/08/1979", "Sexo: Masculino"]])
|
||||
sources = [
|
||||
{
|
||||
"source_type": "csv",
|
||||
"target": "cacu.Paciente",
|
||||
"label": "padron.csv",
|
||||
"column_mapping": {"expediente": "pac_id_hospital", "sexo": "pac_sexo", "codigo_postal": "pac_codigo_postal"},
|
||||
"payload": {"file_base64": b64(csv)},
|
||||
},
|
||||
_document_source(
|
||||
[("ficha.pdf", scan)],
|
||||
"cacu.Paciente",
|
||||
{"pac_id_hospital": "pac_id_hospital", "pac_fecha_nacimiento": "pac_fecha_nacimiento", "pac_sexo": "pac_sexo"},
|
||||
),
|
||||
]
|
||||
# On its own the CSV lacks the required birth date.
|
||||
assert client.post("/imports/validate", json={"source": sources[0]}).get_json()["error_count"] == 2
|
||||
|
||||
padron, ficha = client.post("/imports/commit", json={"sources": sources, "merge_duplicates": True}).get_json()["results"]
|
||||
assert (padron["created"], padron["rejected"]) == (1, 1) # MIX-0002 has no birth date anywhere
|
||||
assert (ficha["merged"], ficha["created"]) == (1, 0)
|
||||
assert [(w["field"], w["raw_value"]) for w in ficha["warnings"]] == [("pac_sexo", "Masculino")]
|
||||
|
||||
from persistance.cacu import paciente_repository
|
||||
|
||||
[patient] = paciente_repository.list(pac_id_hospital="MIX-0001")
|
||||
assert patient.pac_fecha_nacimiento == date(1979, 8, 15)
|
||||
assert patient.pac_codigo_postal == "64000"
|
||||
|
||||
|
||||
EEG_REPORT = text_pdf(
|
||||
[
|
||||
["LABORATORIO DE NEUROFISIOLOGIA", "No. de estudio: LAB-778", "Fecha de estudio: 15/01/2024",
|
||||
"Simetría: SIMETRICO", "Médico interpreta: Dra. Ruiz"],
|
||||
["Conclusión: trazado con actividad de base simétrica,", "sin eventos epileptiformes durante el registro."],
|
||||
],
|
||||
image_on_page=2,
|
||||
)
|
||||
|
||||
# A second study id, distinct from LAB-778 (already used by an earlier test
|
||||
# against this module-scoped client/database), for the merge test below.
|
||||
EEG_REPORT_2 = text_pdf(
|
||||
[
|
||||
["LABORATORIO DE NEUROFISIOLOGIA", "No. de estudio: LAB-900", "Fecha de estudio: 20/02/2024",
|
||||
"Simetría: SIMETRICO", "Médico interpreta: Dra. Ruiz"],
|
||||
["Conclusión: trazado con actividad de base simétrica,", "sin eventos epileptiformes durante el registro."],
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def test_eeg_report_scattered_across_pages_merges_into_one_record(client):
|
||||
"""The report's demographics are on page 1, its conclusion on page 2 —
|
||||
non-contiguous fields the same way a multi-file upload would be, just
|
||||
without the file boundary. Proves the extractor merges by the lab's own
|
||||
study id, not by page adjacency."""
|
||||
body = client.post(
|
||||
"/imports/sources/document/extract",
|
||||
json={"files": [{"name": "reporte.pdf", "file_base64": b64(EEG_REPORT)}], "target": "tea.EegEstudio"},
|
||||
).get_json()
|
||||
assert body["key_field"] == "eeg_id_registro_laboratorio"
|
||||
[record] = body["records"]
|
||||
assert record["key"] == "LAB-778"
|
||||
assert record["sources"] == [{"document": "reporte.pdf", "page_numbers": [1, 2]}]
|
||||
assert record["fields"]["eeg_simetria"]["value"] == "SIMETRICO"
|
||||
assert record["fields"]["eeg_fecha_estudio"]["value"] == "2024-01-15"
|
||||
assert "sin eventos epileptiformes" in record["fields"]["eeg_conclusion_texto"]["value"]
|
||||
assert [image["page_number"] for image in record["images"]] == [2]
|
||||
|
||||
|
||||
def test_eeg_file_and_its_scanned_report_merge_into_one_eeg_estudio_row(client):
|
||||
"""The EDF connector computes signal fields from the file itself; the
|
||||
report PDF (read with NLP, across two pages) carries the clinician's
|
||||
interpretation. Different sources, same study — `eeg_id_registro_
|
||||
laboratorio` (the lab's own code, read from the EDF header by one side
|
||||
and from the report text by the other) is what lets them land on one
|
||||
`eeg_estudio` row instead of two half-populated ones."""
|
||||
edf_source = {
|
||||
"source_type": "edf",
|
||||
"target": "tea.EegEstudio",
|
||||
"label": "estudio.edf",
|
||||
"column_mapping": {
|
||||
"id_registro_laboratorio": "eeg_id_registro_laboratorio",
|
||||
"fecha_estudio": "eeg_fecha_estudio",
|
||||
"duracion_min": "eeg_duracion_min",
|
||||
"ritmo_base_frecuencia": "eeg_ritmo_base_frecuencia",
|
||||
"estudio": "eeg_estudio",
|
||||
},
|
||||
"payload": {"files": [{"name": "estudio.edf", "file_base64": b64(eeg(recording="Startdate 20-FEB-2024 LAB-900 Tec_Ruiz Nihon_Kohden"))}]},
|
||||
}
|
||||
document_source = _document_source(
|
||||
[("reporte.pdf", EEG_REPORT_2)],
|
||||
"tea.EegEstudio",
|
||||
{
|
||||
"eeg_id_registro_laboratorio": "eeg_id_registro_laboratorio",
|
||||
"eeg_simetria": "eeg_simetria",
|
||||
"eeg_conclusion_texto": "eeg_conclusion_texto",
|
||||
"eeg_medico_interpreta": "eeg_medico_interpreta",
|
||||
},
|
||||
)
|
||||
body = client.post(
|
||||
"/imports/commit", json={"sources": [edf_source, document_source], "merge_duplicates": True}
|
||||
).get_json()
|
||||
edf_result, doc_result = body["results"]
|
||||
assert edf_result["created"] == 1, body
|
||||
assert doc_result["merged"] == 1, body # absorbed into the EDF source's row, not inserted again
|
||||
|
||||
from persistance.tea import eeg_estudio_repository
|
||||
|
||||
[row] = eeg_estudio_repository.list(eeg_id_registro_laboratorio="LAB-900")
|
||||
# From the EDF file itself:
|
||||
assert row.eeg_duracion_min is not None
|
||||
assert row.eeg_estudio[:8].strip() == b"0"
|
||||
# From the scanned report, on the very same row:
|
||||
assert row.eeg_simetria == "SIMETRICO"
|
||||
assert "sin eventos epileptiformes" in row.eeg_conclusion_texto
|
||||
assert row.eeg_medico_interpreta == "Dra. Ruiz"
|
||||
|
||||
|
||||
def test_citologia_table_and_scanned_report_merge_on_the_order_number(client):
|
||||
"""The order/date come from a structured table (a CSV export of the lab's
|
||||
own HIS); the VPH result comes from NLP over the scanned report PDF.
|
||||
`(pac_id_hospital, ord_numero_hospital)` is what lets them land on one
|
||||
`citologiacervical` row instead of two half-populated ones."""
|
||||
csv = b"expediente,orden,fecha_toma\nMRG-0001,5001,2024-03-01\n"
|
||||
report = text_pdf([["LABORATORIO DE CITOLOGIA", "Expediente: MRG-0001", "No. de orden: 5001", "VPH alto riesgo: POSITIVO"]])
|
||||
sources = [
|
||||
{
|
||||
"source_type": "csv",
|
||||
"target": "cacu.CitologiaCervical",
|
||||
"label": "padron.csv",
|
||||
"column_mapping": {"expediente": "pac_id_hospital", "orden": "ord_numero_hospital", "fecha_toma": "cit_fecha_toma"},
|
||||
"payload": {"file_base64": b64(csv)},
|
||||
},
|
||||
_document_source(
|
||||
[("reporte.pdf", report)],
|
||||
"cacu.CitologiaCervical",
|
||||
{"pac_id_hospital": "pac_id_hospital", "ord_numero_hospital": "ord_numero_hospital", "cit_vph_resultado": "cit_vph_resultado"},
|
||||
),
|
||||
]
|
||||
tabla, documento = client.post("/imports/commit", json={"sources": sources, "merge_duplicates": True}).get_json()["results"]
|
||||
assert tabla["created"] == 1, tabla
|
||||
assert documento["merged"] == 1, documento # absorbed into the table row, not inserted again
|
||||
|
||||
from persistance.cacu import citologia_cervical_repository
|
||||
|
||||
[row] = citologia_cervical_repository.list(pac_id_hospital="MRG-0001")
|
||||
# From the structured table:
|
||||
assert row.ord_numero_hospital == 5001
|
||||
assert row.cit_fecha_toma == date(2024, 3, 1)
|
||||
# From the scanned report, on the very same row:
|
||||
assert row.cit_vph_resultado == "POSITIVO"
|
||||
|
||||
|
||||
def test_embedded_image_in_the_report_maps_onto_the_target_dicom_column(client):
|
||||
"""The report has a picture of the mammogram alongside its narrative
|
||||
text; `imagen` (like `documento`, the combined PDF) is mappable onto any
|
||||
target column, so it lands in `mast_dicom_blob` next to the fields read
|
||||
from the surrounding text."""
|
||||
report = text_pdf(
|
||||
[["LABORATORIO DE IMAGENOLOGIA", "Expediente: IMG-0001", "Interpretación: nódulo circunscrito en cuadrante superior externo."]],
|
||||
image_on_page=1,
|
||||
)
|
||||
mapping = {"pac_id_hospital": "pac_id_hospital", "mast_interpretacion": "mast_interpretacion", "imagen": "mast_dicom_blob"}
|
||||
source = _document_source([("reporte.pdf", report)], "cama.Mastografia", mapping)
|
||||
result = client.post("/imports/commit", json={"sources": [source]}).get_json()["results"][0]
|
||||
assert result["created"] == 1, result
|
||||
|
||||
from persistance.cama import mastografia_repository
|
||||
|
||||
[row] = mastografia_repository.list(pac_id_hospital="IMG-0001")
|
||||
assert "nódulo circunscrito" in row.mast_interpretacion
|
||||
assert row.mast_dicom_blob.startswith(b"\x89PNG")
|
||||
@@ -0,0 +1,161 @@
|
||||
import pytest
|
||||
from dagster import DagsterRunStatus
|
||||
from fastapi import HTTPException
|
||||
|
||||
from persistance.cluster import Progress
|
||||
from webapi.runs import _locked, cancel_run, shape
|
||||
|
||||
PAYLOAD = {
|
||||
"runId": "run",
|
||||
"jobName": "analyze",
|
||||
"status": "SUCCESS",
|
||||
"startTime": 1.0,
|
||||
"endTime": 4.0,
|
||||
"tags": [{"key": "domain", "value": "cacu"}],
|
||||
}
|
||||
|
||||
|
||||
def test_shape_splits_info_and_warnings():
|
||||
def event(level, message, step_key=None, kind="LogMessageEvent"):
|
||||
return {"__typename": kind, "level": level, "message": message, "stepKey": step_key}
|
||||
|
||||
run = shape(
|
||||
PAYLOAD,
|
||||
[
|
||||
event("INFO", "starting"),
|
||||
event("WARNING", "skipped", "analyze_studies"),
|
||||
event("DEBUG", "debug"),
|
||||
event("INFO", "engine", kind="EngineEvent"),
|
||||
event("INFO", "finished", "analyze_studies"),
|
||||
],
|
||||
)
|
||||
assert run.info == ["starting", "analyze_studies: finished"]
|
||||
assert run.warnings == ["analyze_studies: skipped"]
|
||||
assert run.error is None
|
||||
|
||||
warning_only = shape(PAYLOAD, [event("WARNING", "skipped")])
|
||||
assert warning_only.state == "succeeded"
|
||||
assert warning_only.error is None
|
||||
|
||||
steps = [
|
||||
{"stepKey": "waiting", "status": "SKIPPED", "startTime": None, "endTime": None},
|
||||
{"stepKey": "second", "status": "SUCCESS", "startTime": 2, "endTime": 4},
|
||||
{"stepKey": "first", "status": "SUCCESS", "startTime": 0, "endTime": 1},
|
||||
]
|
||||
assert [step.key for step in shape(PAYLOAD | {"stepStats": steps}, []).steps] == [
|
||||
"first", "second", "waiting",
|
||||
] # fmt: skip
|
||||
|
||||
capped = shape(
|
||||
PAYLOAD, [event(level, str(i)) for i in range(201) for level in ("INFO", "WARNING")]
|
||||
)
|
||||
assert capped.info == [str(i) for i in range(1, 201)]
|
||||
assert capped.warnings == [str(i) for i in range(200)]
|
||||
|
||||
|
||||
def test_shape_failure_message_is_the_ops_own_exception():
|
||||
failed = PAYLOAD | {"status": "FAILURE"}
|
||||
step_failure = {
|
||||
"__typename": "ExecutionStepFailureEvent",
|
||||
"error": {
|
||||
"message": "DagsterExecutionStepExecutionError: invocation failed",
|
||||
"causes": [
|
||||
{"message": "intermediate cause"},
|
||||
{"message": " LookupError: no EEG x|2026-01-01\nmore details "},
|
||||
],
|
||||
},
|
||||
}
|
||||
assert shape(failed, [step_failure]).error == "LookupError: no EEG x|2026-01-01"
|
||||
run_failure = {"__typename": "RunFailureEvent", "error": {"message": "x" * 501}}
|
||||
assert shape(failed, [step_failure, run_failure]).error == "x" * 500
|
||||
assert shape(failed, []).error == "the run failed"
|
||||
|
||||
|
||||
def test_shape_progress_tag():
|
||||
progress = Progress(
|
||||
phase="analyzing", done=3, total=6, elapsed_s=4, eta_s=4, mode="sync",
|
||||
scheduler=None, updated_at="2026-01-01T00:00:00Z",
|
||||
) # fmt: skip
|
||||
|
||||
def with_tag(value):
|
||||
return PAYLOAD | {"tags": [{"key": "isssteleon/progress", "value": value}]}
|
||||
|
||||
run = shape(with_tag(progress.model_dump_json()), [])
|
||||
assert run.progress is not None
|
||||
assert run.progress.done == 3
|
||||
assert run.progress.phase == "analyzing"
|
||||
assert shape(with_tag("{bad json"), []).progress is None
|
||||
for status, state in (
|
||||
("QUEUED", "queued"),
|
||||
("STARTING", "running"),
|
||||
("CANCELING", "cancelling"),
|
||||
("CANCELED", "cancelled"),
|
||||
):
|
||||
run = shape(PAYLOAD | {"status": status}, [])
|
||||
assert (run.status, run.state) == (status, state)
|
||||
assert shape(PAYLOAD | {"status": "UNKNOWN"}, []).state == "running"
|
||||
|
||||
|
||||
def test_shape_outputs():
|
||||
events = [
|
||||
{
|
||||
"__typename": "ExecutionStepOutputEvent",
|
||||
"stepKey": "preview_study",
|
||||
"outputName": "result",
|
||||
"metadataEntries": [
|
||||
{"label": "result", "jsonString": '{"eeg": {"valid": false}}'},
|
||||
{"label": "text"},
|
||||
],
|
||||
},
|
||||
]
|
||||
assert shape(PAYLOAD, events, outputs=True).outputs == {
|
||||
"preview_study.result": {"eeg": {"valid": False}}
|
||||
}
|
||||
assert shape(PAYLOAD, events, outputs=False).outputs is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("initial", [DagsterRunStatus.QUEUED, DagsterRunStatus.STARTED])
|
||||
def test_cancel_returns_the_terminal_or_cancelling_state(initial):
|
||||
class Client:
|
||||
status = initial
|
||||
|
||||
def get_run_status(self, run_id):
|
||||
return self.status
|
||||
|
||||
def terminate_run(self, run_id):
|
||||
self.status = {
|
||||
DagsterRunStatus.QUEUED: DagsterRunStatus.CANCELED,
|
||||
DagsterRunStatus.STARTED: DagsterRunStatus.CANCELING,
|
||||
}[self.status]
|
||||
|
||||
result = cancel_run("r1", client=Client())
|
||||
expected = (
|
||||
("CANCELED", "cancelled")
|
||||
if initial == DagsterRunStatus.QUEUED
|
||||
else ("CANCELING", "cancelling")
|
||||
)
|
||||
assert (result.id, result.status, result.state) == ("r1", *expected)
|
||||
|
||||
|
||||
def test_cancel_a_finished_run_is_409():
|
||||
class Client:
|
||||
def get_run_status(self, run_id):
|
||||
return DagsterRunStatus.SUCCESS
|
||||
|
||||
with pytest.raises(HTTPException) as error:
|
||||
cancel_run("r1", client=Client())
|
||||
assert error.value.status_code == 409
|
||||
assert error.value.detail == "the run already ended: succeeded"
|
||||
|
||||
|
||||
def test_a_storage_lock_is_distinguished_from_a_run_failure():
|
||||
assert _locked({"errors": [{"message": "OperationalError: database is locked"}]})
|
||||
assert _locked(
|
||||
{"data": {"logsForRun": {"__typename": "PythonError", "message": "database is locked"}}}
|
||||
)
|
||||
assert not _locked(
|
||||
{"data": {"logsForRun": {"__typename": "EventConnection", "message": "database is locked"}}}
|
||||
)
|
||||
assert not _locked(
|
||||
{"data": {"logsForRun": {"__typename": "PythonError", "message": "unknown error"}}}
|
||||
)
|
||||
@@ -1,233 +0,0 @@
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from webapi.imports.mapping.column_matcher import ColumnMatcher
|
||||
from webapi.imports.schemas.cacu.paciente import PacienteImportSchema
|
||||
from webapi.imports.schemas.classify import ErrorCategory, classify_error
|
||||
from webapi.imports.schemas.service import validate_rows
|
||||
from webapi.imports.schemas.tea.pacientes import PacientesImportSchema
|
||||
|
||||
|
||||
def test_paciente_schema_required_field_missing():
|
||||
with pytest.raises(ValidationError) as excinfo:
|
||||
PacienteImportSchema(pac_sexo="F")
|
||||
errors = excinfo.value.errors()
|
||||
assert any(e["loc"] == ("pac_id_hospital",) for e in errors)
|
||||
|
||||
|
||||
def test_paciente_schema_coerces_sexo_alias():
|
||||
schema = PacienteImportSchema(pac_id_hospital="H-1", pac_sexo="f", pac_fecha_nacimiento="1990-01-15")
|
||||
assert schema.pac_sexo == "Femenino"
|
||||
|
||||
schema2 = PacienteImportSchema(pac_id_hospital="H-2", pac_sexo="MASCULINO", pac_fecha_nacimiento="1990-01-15")
|
||||
assert schema2.pac_sexo == "Masculino"
|
||||
|
||||
|
||||
def test_paciente_schema_rejects_unknown_sexo():
|
||||
with pytest.raises(ValidationError):
|
||||
# pac_sexo has no enum constraint on the storage model, but this is
|
||||
# still a plain string field; feed something structurally invalid
|
||||
# (a date field) to prove type validation happens
|
||||
PacienteImportSchema(pac_id_hospital="H-1", pac_fecha_nacimiento="not-a-date")
|
||||
|
||||
|
||||
def test_paciente_schema_coerces_date_from_iso_string():
|
||||
schema = PacienteImportSchema(pac_id_hospital="H-1", pac_fecha_nacimiento="2020-01-15")
|
||||
assert schema.pac_fecha_nacimiento.isoformat() == "2020-01-15"
|
||||
|
||||
|
||||
def test_paciente_schema_coerces_date_from_datetime_object():
|
||||
from datetime import datetime
|
||||
|
||||
schema = PacienteImportSchema(pac_id_hospital="H-1", pac_fecha_nacimiento=datetime(2020, 1, 15, 10, 30))
|
||||
assert schema.pac_fecha_nacimiento.isoformat() == "2020-01-15"
|
||||
|
||||
|
||||
def test_tea_pacientes_schema_is_fully_optional():
|
||||
schema = PacientesImportSchema()
|
||||
assert schema.pac_id_hospital is None
|
||||
|
||||
|
||||
def test_tea_pacientes_schema_coerces_sexo_from_bare_enum_no_alias_dict():
|
||||
schema = PacientesImportSchema(pac_sexo="f")
|
||||
assert schema.pac_sexo == "F"
|
||||
|
||||
|
||||
def test_tea_pacientes_schema_coerces_parentesco():
|
||||
schema = PacientesImportSchema(pac_parentesco="hijo")
|
||||
assert schema.pac_parentesco == "HIJO"
|
||||
|
||||
|
||||
def test_classify_error_missing():
|
||||
try:
|
||||
PacienteImportSchema(pac_sexo="F")
|
||||
except ValidationError as exc:
|
||||
classified = [classify_error(e) for e in exc.errors()]
|
||||
assert any(c.category == ErrorCategory.MISSING and c.field == "pac_id_hospital" for c in classified)
|
||||
|
||||
|
||||
def test_classify_error_type_invalid():
|
||||
try:
|
||||
PacienteImportSchema(pac_id_hospital="H-1", pac_fecha_nacimiento="not-a-date")
|
||||
except ValidationError as exc:
|
||||
classified = [classify_error(e) for e in exc.errors()]
|
||||
assert any(c.category == ErrorCategory.TYPE_INVALID for c in classified)
|
||||
|
||||
|
||||
def test_validate_rows_never_aborts_on_a_bad_row():
|
||||
rows = [
|
||||
{"pac_id_hospital": "H-1", "pac_sexo": "F", "pac_fecha_nacimiento": "1990-01-15"},
|
||||
{"pac_sexo": "M"}, # missing required fields
|
||||
{"pac_id_hospital": "H-3", "pac_fecha_nacimiento": "1990-01-15"},
|
||||
]
|
||||
result = validate_rows(PacienteImportSchema, rows)
|
||||
assert result.total_rows == 3
|
||||
assert result.valid_count == 2
|
||||
assert result.error_count == 1
|
||||
assert result.rejected[0].row_index == 1
|
||||
|
||||
|
||||
def test_column_matcher_exact_normalized_synonym_fuzzy_none():
|
||||
matcher = ColumnMatcher()
|
||||
targets = ["pac_id_hospital", "pac_sexo", "pac_fecha_nacimiento"]
|
||||
|
||||
suggestions = matcher.suggest(
|
||||
["pac_id_hospital", "Sexo", "fecha_nacimiento", "columna_sin_relacion_xyz"], targets
|
||||
)
|
||||
by_source = {s.source_column: s for s in suggestions}
|
||||
|
||||
assert by_source["pac_id_hospital"].reason == "exact"
|
||||
assert by_source["pac_id_hospital"].target_field == "pac_id_hospital"
|
||||
|
||||
assert by_source["Sexo"].reason == "synonym"
|
||||
assert by_source["Sexo"].target_field == "pac_sexo"
|
||||
|
||||
assert by_source["fecha_nacimiento"].reason in ("synonym", "fuzzy")
|
||||
assert by_source["fecha_nacimiento"].target_field == "pac_fecha_nacimiento"
|
||||
|
||||
assert by_source["columna_sin_relacion_xyz"].target_field is None
|
||||
assert by_source["columna_sin_relacion_xyz"].reason == "none"
|
||||
|
||||
|
||||
def test_column_matcher_enforces_one_to_one():
|
||||
matcher = ColumnMatcher()
|
||||
# two source columns that would both match "pac_sexo" exactly-ish
|
||||
suggestions = matcher.suggest(["pac_sexo", "sexo"], ["pac_sexo"])
|
||||
matched_targets = [s.target_field for s in suggestions if s.target_field]
|
||||
assert matched_targets == ["pac_sexo"] # only the first claims it
|
||||
|
||||
|
||||
def test_coerce_date_accepts_iso_day_first_and_timestamps_but_not_impossible_dates():
|
||||
from datetime import date, datetime
|
||||
|
||||
from webapi.imports.schemas.coercion import coerce_date
|
||||
|
||||
assert coerce_date("1990-01-15") == date(1990, 1, 15)
|
||||
assert coerce_date("15/01/1990") == date(1990, 1, 15)
|
||||
assert coerce_date("15-01-1990") == date(1990, 1, 15)
|
||||
assert coerce_date("1990-01-15 00:00:00") == date(1990, 1, 15)
|
||||
assert coerce_date(datetime(1990, 1, 15, 8, 30)) == date(1990, 1, 15)
|
||||
assert coerce_date(" ") is None
|
||||
with pytest.raises(ValueError, match="no es una fecha válida"):
|
||||
coerce_date("31/02/1990")
|
||||
|
||||
|
||||
def test_catalog_is_case_insensitive_accepts_member_names_and_rejects_unknowns():
|
||||
from core.cacu.enums import SEXO_BIOLOGICO_ALIAS, SexoBiologico
|
||||
from webapi.imports.schemas.coercion import Catalog, coerce_alias
|
||||
|
||||
catalog = Catalog(SexoBiologico, SEXO_BIOLOGICO_ALIAS)
|
||||
assert coerce_alias(" femenino ", catalog) == "Femenino"
|
||||
assert coerce_alias("m", catalog) == "Masculino"
|
||||
assert coerce_alias("", catalog) is None
|
||||
with pytest.raises(ValueError, match="no está en el catálogo"):
|
||||
coerce_alias("X", catalog)
|
||||
|
||||
|
||||
def test_birads_subcategories_from_reports_are_not_rejected_as_out_of_catalog():
|
||||
"""`extraction.nlp.vocabulary.CLINICAL_TERMS` extracts BI-RADS 4A/4B/4C
|
||||
from narrative text (a standard ACR BI-RADS subcategory), but the schema
|
||||
only models the base B0-B6 categories; without an alias for them, every
|
||||
such report was silently unimportable."""
|
||||
from core.cama.mastografia.enums import BIRADS, BIRADS_ALIAS
|
||||
from webapi.imports.schemas.coercion import Catalog, coerce_alias
|
||||
|
||||
catalog = Catalog(BIRADS, BIRADS_ALIAS)
|
||||
for value in ("4A", "BI-RADS 4B", "bi-rads 4c"):
|
||||
assert coerce_alias(value, catalog) == "B4"
|
||||
|
||||
|
||||
def test_postal_code_restores_leading_zero_from_numeric_sources():
|
||||
from webapi.imports.schemas.coercion import coerce_postal_code
|
||||
|
||||
assert coerce_postal_code(1000) == "01000"
|
||||
assert coerce_postal_code(64000.0) == "64000"
|
||||
assert coerce_postal_code(" 01000 ") == "01000"
|
||||
assert coerce_postal_code("") is None
|
||||
|
||||
|
||||
def test_column_matcher_handles_accents_prefixes_and_global_one_to_one():
|
||||
matcher = ColumnMatcher()
|
||||
targets = ["pac_id_hospital", "pac_sexo", "pac_codigo_postal", "pac_fecha_nacimiento"]
|
||||
by_source = {
|
||||
s.source_column: s
|
||||
for s in matcher.suggest(["Fech nacim", "Género", "C.P.", "Expediente", "fecha_nacimiento"], targets)
|
||||
}
|
||||
assert by_source["Género"].target_field == "pac_sexo"
|
||||
assert by_source["C.P."].target_field == "pac_codigo_postal"
|
||||
assert by_source["Expediente"].target_field == "pac_id_hospital"
|
||||
# The synonym "fecha_nacimiento" wins pac_fecha_nacimiento even
|
||||
# though the weaker fuzzy "Fech nacim" comes first in the file.
|
||||
assert by_source["fecha_nacimiento"].target_field == "pac_fecha_nacimiento"
|
||||
assert by_source["Fech nacim"].target_field is None
|
||||
|
||||
|
||||
def test_column_matcher_matches_names_without_the_table_prefix():
|
||||
suggestion = ColumnMatcher().suggest(["hemoglobina_g_dl", "birads"], ["hemoglobina_g_dl", "mast_birads"])
|
||||
assert [(s.target_field, s.reason) for s in suggestion] == [("hemoglobina_g_dl", "exact"), ("mast_birads", "unprefixed")]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"target, source, expected",
|
||||
[
|
||||
# Match on shared meaning, not shared suffixes ("solicitaDO" vs "solicitaNTE").
|
||||
("cacu.OrdenesEstudio", "Estudio solicitado", "ord_tipo_estudio"),
|
||||
("cacu.OrdenesEstudio", "Paciente", "pac_id_hospital"),
|
||||
("cacu.NotaMedica", "Servicio", "nm_especialidad"),
|
||||
("cacu.NotaMedica", "Fecha consulta", "nm_fecha"),
|
||||
("cacu.NotaMedica", "Peso (kg)", "nm_masa_corporal"),
|
||||
# Flattened JSON paths match by their last segment; unprefixed fields by their words.
|
||||
("cacu.BiometriaHematica", "paciente.expediente", "pac_id_hospital"),
|
||||
("cacu.BiometriaHematica", "resultados.hemoglobina", "hemoglobina_g_dl"),
|
||||
("cacu.BiopsiaCervical", "Fecha de reporte", "bx_fecha_reporte"),
|
||||
],
|
||||
)
|
||||
def test_column_matcher_real_world_headers(target, source, expected):
|
||||
from webapi.imports.schemas.registry import ENTITY_REGISTRY
|
||||
|
||||
fields = list(ENTITY_REGISTRY[target].schema.model_fields)
|
||||
assert ColumnMatcher().suggest([source], fields)[0].target_field == expected
|
||||
|
||||
|
||||
def test_column_matcher_does_not_guess_from_shared_letters_alone():
|
||||
from webapi.imports.schemas.registry import ENTITY_REGISTRY
|
||||
|
||||
fields = list(ENTITY_REGISTRY["cacu.NotaMedica"].schema.model_fields)
|
||||
assert ColumnMatcher().suggest(["Observaciones del servicio xyz", "Clave única"], fields)[1].target_field is None
|
||||
|
||||
|
||||
def test_catalog_for_exposes_field_catalog_and_errors_stay_on_field():
|
||||
from webapi.imports.schemas.coercion import Catalog
|
||||
|
||||
catalog = PacienteImportSchema.catalog_for("pac_sexo")
|
||||
assert isinstance(catalog, Catalog)
|
||||
assert catalog.choices["F"] == "Femenino"
|
||||
assert PacienteImportSchema.catalog_for("pac_codigo_postal") is None
|
||||
|
||||
with pytest.raises(ValidationError) as excinfo:
|
||||
PacienteImportSchema(pac_id_hospital="H-1", pac_sexo="X", pac_fecha_nacimiento="1990-01-15")
|
||||
(error,) = excinfo.value.errors()
|
||||
classified = classify_error(error)
|
||||
assert classified.field == "pac_sexo"
|
||||
assert classified.category == ErrorCategory.OUT_OF_CATALOG
|
||||
assert "no está en el catálogo" in classified.message
|
||||
@@ -1,92 +0,0 @@
|
||||
"""Smoke-tests that every `ENTITY_REGISTRY` import schema is importable and
|
||||
constructible, plus spot checks of enum-alias coercion."""
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from webapi.imports.schemas.registry import ENTITY_REGISTRY
|
||||
from webapi.imports.schemas.cama.ordenes_estudio import OrdenesEstudioImportSchema as CamaOrdenesEstudioImportSchema
|
||||
from webapi.imports.schemas.tea.eeg_estudio import EegEstudioImportSchema
|
||||
from webapi.imports.schemas.cacu.biopsia_cervical import BiopsiaCervicalImportSchema
|
||||
|
||||
|
||||
# Domains whose Core layer is fully permissive (every field Optional);
|
||||
# see `tea/pacientes.py`'s docstring. CaCu/CaMa entities all carry at least
|
||||
# one business-required field (`pac_id_hospital` and friends).
|
||||
_FULLY_OPTIONAL_PREFIXES = ("tea.",)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("entity_key", list(ENTITY_REGISTRY.keys()))
|
||||
def test_every_registered_schema_is_constructible(entity_key):
|
||||
spec = ENTITY_REGISTRY[entity_key]
|
||||
schema_cls = spec.schema
|
||||
|
||||
if entity_key.startswith(_FULLY_OPTIONAL_PREFIXES):
|
||||
# Fully permissive: an empty row must construct cleanly.
|
||||
instance = schema_cls()
|
||||
assert instance is not None
|
||||
else:
|
||||
# Has at least one required field: an empty row must be rejected.
|
||||
with pytest.raises(ValidationError):
|
||||
schema_cls()
|
||||
|
||||
|
||||
def test_entity_registry_has_twenty_two_entries():
|
||||
assert len(ENTITY_REGISTRY) == 22
|
||||
|
||||
|
||||
def test_entity_registry_keys_cover_all_three_domains():
|
||||
keys = set(ENTITY_REGISTRY.keys())
|
||||
assert "cacu.Paciente" in keys
|
||||
assert "cacu.OrdenesEstudio" in keys
|
||||
assert "cacu.CitologiaCervical" in keys
|
||||
assert "cacu.BiopsiaCervical" in keys
|
||||
assert "cacu.NotaMedica" in keys
|
||||
assert "cacu.BiometriaHematica" in keys
|
||||
assert "cama.Paciente" in keys
|
||||
assert "cama.OrdenesEstudio" in keys
|
||||
assert "cama.Mastografia" in keys
|
||||
assert "cama.BiopsiaMama" in keys
|
||||
assert "cama.NotaMedica" in keys
|
||||
assert "cama.BiometriaHematica" in keys
|
||||
assert "tea.Pacientes" in keys
|
||||
assert "tea.OrdenesEstudio" in keys
|
||||
assert "tea.NotaMedica" in keys
|
||||
assert "tea.EvaluacionPsicologica" in keys
|
||||
assert "tea.PotencialesEvocadosAuditivos" in keys
|
||||
assert "tea.EegEstudio" in keys
|
||||
assert "tea.AntecedentesMaternosGestacion" in keys
|
||||
assert "tea.PartoNeonatal" in keys
|
||||
|
||||
|
||||
# --- Spot checks -----------------------------------------------------------
|
||||
# CaMa entity with a required, unique integer ord_numero_hospital and an
|
||||
# *_ALIAS-backed enum field.
|
||||
def test_cama_ordenes_estudio_requires_numero_hospital_and_coerces_tipo_estudio():
|
||||
with pytest.raises(ValidationError) as excinfo:
|
||||
CamaOrdenesEstudioImportSchema(pac_id_hospital="H-1")
|
||||
errors = excinfo.value.errors()
|
||||
assert any(e["loc"] == ("ord_numero_hospital",) for e in errors)
|
||||
|
||||
schema = CamaOrdenesEstudioImportSchema(
|
||||
pac_id_hospital="H-1", ord_numero_hospital=12345, ord_tipo_estudio="biopsia chica"
|
||||
)
|
||||
assert schema.ord_tipo_estudio == "BIOPSIA_CHICA"
|
||||
|
||||
|
||||
# TEA entity with a bare Enum field (no *_ALIAS dict), so the schema builds
|
||||
# a Catalog from the Enum alone, as in tea/pacientes.py.
|
||||
def test_tea_eeg_estudio_coerces_simetria_from_bare_enum_no_alias_dict():
|
||||
schema = EegEstudioImportSchema(eeg_simetria="simetrico")
|
||||
assert schema.eeg_simetria == "SIMETRICO"
|
||||
|
||||
|
||||
# CaCu entity with a real *_ALIAS-backed field (GRADO_CIN_ALIAS).
|
||||
def test_cacu_biopsia_cervical_coerces_cin_grado_alias():
|
||||
schema = BiopsiaCervicalImportSchema(
|
||||
pac_id_hospital="H-1",
|
||||
bx_cin_grado="LESION INTRAEPITELIAL ESCAMOSA DE BAJO GRADO",
|
||||
)
|
||||
assert schema.bx_cin_grado == "LIEBG"
|
||||
|
||||
with pytest.raises(ValidationError):
|
||||
BiopsiaCervicalImportSchema(bx_cin_grado="LIEBG") # pac_id_hospital missing
|
||||
@@ -0,0 +1,140 @@
|
||||
import sqlite3
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from webapi import sources
|
||||
from webapi.main import app
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(own_platform, monkeypatch):
|
||||
monkeypatch.setenv("SOURCE_ROOTS", str(own_platform / "shared"))
|
||||
(own_platform / "shared" / "reportes" / "2026").mkdir(parents=True)
|
||||
with TestClient(app) as c:
|
||||
yield c
|
||||
|
||||
|
||||
def probe(client, kind, **answers):
|
||||
response = client.post("/ingest/sources/test", json={"type": kind, "answers": answers})
|
||||
assert response.status_code == 200, response.text
|
||||
return response.json()
|
||||
|
||||
|
||||
def test_the_dialog_lists_every_kind_with_its_questions(client):
|
||||
found = client.get("/ingest/sources/types").json()
|
||||
assert {"database", "files", "cloud", "web"} <= set(found["groups"])
|
||||
assert found["types"]["sqlserver"]["fields"]["password"]["type"] == "password"
|
||||
|
||||
|
||||
def test_an_unknown_server_and_a_missing_answer_say_so_plainly(client):
|
||||
gone = probe(client, "sqlserver", host="nowhere.invalid", database="P", user="u",
|
||||
password="p") # fmt: skip
|
||||
assert not gone["ok"] and gone["message"].startswith(("No se encontró", "El servidor no"))
|
||||
assert probe(client, "postgresql", host="h")["message"].startswith("falta «Base de datos»")
|
||||
|
||||
|
||||
def test_a_sqlite_file_lists_its_tables_then_shows_rows(client, own_platform):
|
||||
path = own_platform / "shared" / "hospital.db"
|
||||
with sqlite3.connect(path) as con:
|
||||
con.execute("create table pacientes (id int, nombre text)")
|
||||
con.execute("insert into pacientes values (1, 'Ana')")
|
||||
assert probe(client, "sqlite", path=str(path))["tables"] == ["pacientes"]
|
||||
rows = probe(client, "sqlite", path=str(path), table="pacientes")["rows"]
|
||||
assert rows == [{"id": 1, "nombre": "Ana"}]
|
||||
|
||||
|
||||
def test_server_folders_are_browsed_only_under_the_mounted_roots(client, own_platform):
|
||||
roots = client.get("/ingest/sources/browse").json()["entries"]
|
||||
assert [e["name"] for e in roots] == ["shared"]
|
||||
inside = client.get("/ingest/sources/browse", params={"path": roots[0]["path"]}).json()
|
||||
assert [e["name"] for e in inside["entries"]] == ["reportes"]
|
||||
assert client.get("/ingest/sources/browse", params={"path": "/etc"}).status_code == 404
|
||||
escape = str(own_platform / "shared" / ".." / "data")
|
||||
assert client.get("/ingest/sources/browse", params={"path": escape}).status_code == 404
|
||||
|
||||
|
||||
def test_a_folder_uploaded_from_a_computer_is_read_as_spreadsheets_or_documents(client):
|
||||
sent = [("files", ("informes/enero/a.csv", b"folio,resultado\n1,NEGATIVO\n")),
|
||||
("files", ("informes/b.pdf", b"%PDF-1.4 ..."))] # fmt: skip
|
||||
uploaded = client.post("/ingest/uploads", files=sent).json()
|
||||
assert sorted(uploaded["files"]) == ["informes/b.pdf", "informes/enero/a.csv"]
|
||||
more = client.post("/ingest/uploads", files=[("files", ("../../fuera.csv", b"x\n"))],
|
||||
data={"folder": uploaded["bucket_url"]}).json() # fmt: skip
|
||||
assert more["files"] == ["fuera.csv"] and more["bucket_url"] == uploaded["bucket_url"]
|
||||
other = client.post("/ingest/uploads", files=[("files", ("x", b"x"))], data={"folder": "/"})
|
||||
assert other.status_code == 422
|
||||
rows = probe(client, "upload", folder=uploaded["bucket_url"], pattern="**/*.csv",
|
||||
read_as="dlt.sources.filesystem:read_csv")["rows"] # fmt: skip
|
||||
assert rows == [{"folio": 1, "resultado": "NEGATIVO"}]
|
||||
files = probe(client, "upload", folder=uploaded["bucket_url"], pattern="**/*.pdf")["rows"]
|
||||
assert [f["file_name"] for f in files] == ["b.pdf"]
|
||||
|
||||
|
||||
def test_an_empty_folder_says_what_to_check(client, own_platform):
|
||||
found = probe(client, "server_folder", folder=str(own_platform / "shared" / "reportes"))
|
||||
assert found["ok"] and "Revise la ruta" in found["message"]
|
||||
|
||||
|
||||
def test_a_sign_in_button_without_an_app_registration_says_who_must_register_one(client):
|
||||
found = client.get("/ingest/sources/oauth/google/start", params={"origin": "http://x"})
|
||||
assert found.status_code == 503 and "GOOGLE_CLIENT_ID" in found.json()["detail"]
|
||||
|
||||
|
||||
def test_signing_in_hands_the_account_to_the_dialog(client, monkeypatch, tmp_path):
|
||||
from authlib.integrations.httpx_client import OAuth2Client, oauth2_client
|
||||
|
||||
httpx = oauth2_client.httpx2
|
||||
|
||||
monkeypatch.setenv("MICROSOFT_CLIENT_ID", "app")
|
||||
monkeypatch.setenv("MICROSOFT_CLIENT_SECRET", "app-secret")
|
||||
exchanged = {}
|
||||
|
||||
def provider(request: httpx.Request) -> httpx.Response:
|
||||
exchanged["body"] = request.content.decode()
|
||||
return httpx.Response(200, json={"access_token": "at", "refresh_token": "rt",
|
||||
"token_type": "Bearer", "expires_in": 3600}) # fmt: skip
|
||||
|
||||
def client_for(found, env, redirect_uri):
|
||||
return OAuth2Client(env["client_id"], env["client_secret"], scope=found.scope,
|
||||
redirect_uri=redirect_uri, code_challenge_method="S256",
|
||||
transport=httpx.MockTransport(provider)) # fmt: skip
|
||||
|
||||
monkeypatch.setattr(sources, "_client", client_for)
|
||||
monkeypatch.setattr(sources, "PENDING", tmp_path / "pending")
|
||||
monkeypatch.setattr(sources, "account", lambda p, token, env: {
|
||||
"user": "ana@hospital.mx", "drive_id": "d1",
|
||||
"oauth2_client_params": {"client_id": env["client_id"], "token": token}}) # fmt: skip
|
||||
start = client.get("/ingest/sources/oauth/microsoft/start",
|
||||
params={"origin": "http://10.0.10.41:5710"}).json() # fmt: skip
|
||||
assert start["url"].startswith("https://login.microsoftonline.com/organizations/")
|
||||
assert "code_challenge=" in start["url"] and "client_id=app" in start["url"]
|
||||
back = client.get("/ingest/sources/oauth/microsoft/callback",
|
||||
params={"state": start["state"], "code": "c0de"}) # fmt: skip
|
||||
assert back.status_code == 200
|
||||
assert '"user": "ana@hospital.mx"' in back.text and '"http://10.0.10.41:5710"' in back.text
|
||||
assert "code_verifier=" in exchanged["body"] and "code=c0de" in exchanged["body"]
|
||||
again = client.get("/ingest/sources/oauth/microsoft/callback",
|
||||
params={"state": start["state"], "code": "c0de"}) # fmt: skip
|
||||
assert again.status_code == 400
|
||||
|
||||
|
||||
def test_a_saved_account_shows_who_but_never_its_tokens():
|
||||
from core.pipeline import MASK, Pipeline, redacted, restored
|
||||
|
||||
params = {"client_id": "app", "client_secret": "app-secret-xyz",
|
||||
"token": {"refresh_token": "refresh-xyz"}} # fmt: skip
|
||||
account = {"user": "ana@hospital.mx", "drive_id": "d1", "oauth2_client_params": params}
|
||||
saved = Pipeline(nodes=[{"id": "s", "kind": "source", "guided": {
|
||||
"type": "onedrive", "answers": {"account": account, "folder": "Reportes"}}}]) # fmt: skip
|
||||
shown = redacted(saved)
|
||||
answer = shown.nodes[0].guided.answers["account"]
|
||||
assert answer["user"] == "ana@hospital.mx"
|
||||
dumped = shown.model_dump_json()
|
||||
assert "refresh-xyz" not in dumped and "app-secret-xyz" not in dumped
|
||||
assert answer["oauth2_client_params"]["client_secret"] == MASK
|
||||
back = restored(Pipeline.model_validate(shown.model_dump()), saved).nodes[0]
|
||||
assert (
|
||||
back.args["storage_options"]["oauth2_client_params"]["token"]["refresh_token"]
|
||||
== "refresh-xyz"
|
||||
)
|
||||
@@ -1,96 +0,0 @@
|
||||
"""The SQL connector is the one import path where the client chooses what
|
||||
the server connects to; these tests pin its guard rails (see
|
||||
webapi.imports.connectors.sql_policy)."""
|
||||
import pytest
|
||||
import sqlalchemy as sa
|
||||
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
from webapi.imports.connectors.sql import SqlConnector
|
||||
from webapi.imports.connectors.sql_policy import SqlSourcePolicy
|
||||
|
||||
PRODUCTION_POLICY = SqlSourcePolicy(
|
||||
allowed_dialects=frozenset({"mysql", "mariadb", "postgresql", "mssql", "oracle"}), allowed_hosts=None
|
||||
)
|
||||
|
||||
|
||||
def test_sqlite_is_refused_by_default_policy(tmp_path):
|
||||
with pytest.raises(ConnectorError, match="dialect 'sqlite' is not allowed"):
|
||||
SqlConnector(f"sqlite:///{tmp_path / 'x.db'}", policy=PRODUCTION_POLICY)
|
||||
|
||||
|
||||
def test_host_allowlist_is_enforced():
|
||||
policy = SqlSourcePolicy(allowed_dialects=frozenset({"mysql"}), allowed_hosts=frozenset({"10.0.10.50"}))
|
||||
with pytest.raises(ConnectorError, match="not in the allowed"):
|
||||
policy.check_url("mysql+pymysql://u:p@evil.example.com/db")
|
||||
assert policy.check_url("mysql+pymysql://u:p@10.0.10.50/db").host == "10.0.10.50"
|
||||
|
||||
|
||||
def test_refuses_the_applications_own_database(monkeypatch, tmp_path):
|
||||
from persistance import settings as persistance_settings
|
||||
|
||||
own = tmp_path / "cacu.db"
|
||||
monkeypatch.setattr(persistance_settings.settings, "cacu_database_url", f"sqlite:///{own}")
|
||||
policy = SqlSourcePolicy(allowed_dialects=frozenset({"sqlite"}), allowed_hosts=None)
|
||||
with pytest.raises(ConnectorError, match="own database"):
|
||||
policy.check_url(f"sqlite:///{own}")
|
||||
|
||||
monkeypatch.setattr(persistance_settings.settings, "cama_database_url", "mysql+pymysql://app:pw@db.internal:3306/isss_cama")
|
||||
mysql_policy = SqlSourcePolicy(allowed_dialects=frozenset({"mysql"}), allowed_hosts=None)
|
||||
with pytest.raises(ConnectorError, match="own database"):
|
||||
mysql_policy.check_url("mysql+pymysql://someone_else:pw@DB.internal:3306/isss_cama")
|
||||
mysql_policy.check_url("mysql+pymysql://app:pw@db.internal:3306/hospital_legacy")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"query",
|
||||
[
|
||||
"DELETE FROM paciente",
|
||||
"select 1; drop table paciente",
|
||||
"UPDATE t SET a = 1",
|
||||
"-- harmless\nDROP TABLE t",
|
||||
"",
|
||||
],
|
||||
)
|
||||
def test_only_single_select_queries_pass(query):
|
||||
with pytest.raises(ConnectorError):
|
||||
SqlSourcePolicy.check_query(query)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("query", ["SELECT * FROM t;", " with x as (select 1 as a) select a from x", "/* c */ SELECT 1"])
|
||||
def test_select_queries_pass(query):
|
||||
assert SqlSourcePolicy.check_query(query)
|
||||
|
||||
|
||||
def test_connection_is_read_only_even_for_a_select_shaped_write(tmp_path):
|
||||
db = tmp_path / "src.db"
|
||||
engine = sa.create_engine(f"sqlite:///{db}")
|
||||
with engine.begin() as conn:
|
||||
conn.execute(sa.text("CREATE TABLE t (a INTEGER)"))
|
||||
conn.execute(sa.text("INSERT INTO t VALUES (1), (2)"))
|
||||
|
||||
connector = SqlConnector(f"sqlite:///{db}", policy=SqlSourcePolicy(frozenset({"sqlite"}), None))
|
||||
with pytest.raises(ConnectorError):
|
||||
# Passes the keyword check, but the read-only connection refuses it.
|
||||
connector.select_query("WITH d AS (DELETE FROM t RETURNING a) SELECT a FROM d").preview()
|
||||
with engine.connect() as conn:
|
||||
assert conn.execute(sa.text("SELECT COUNT(*) FROM t")).scalar_one() == 2
|
||||
|
||||
|
||||
def test_preview_only_fetches_the_limit_but_counts_everything(tmp_path):
|
||||
db = tmp_path / "big.db"
|
||||
engine = sa.create_engine(f"sqlite:///{db}")
|
||||
with engine.begin() as conn:
|
||||
conn.execute(sa.text("CREATE TABLE t (id INTEGER, cp TEXT)"))
|
||||
conn.execute(sa.text("INSERT INTO t VALUES " + ",".join(f"({i}, '0{i:04d}')" for i in range(500))))
|
||||
|
||||
connector = SqlConnector(f"sqlite:///{db}", policy=SqlSourcePolicy(frozenset({"sqlite"}), None)).select_table("t")
|
||||
preview = connector.preview(limit=5)
|
||||
assert len(preview.sample_rows) == 5
|
||||
assert preview.total_rows == 500
|
||||
assert {c.name: c.inferred_type for c in preview.columns} == {"id": "integer", "cp": "string"}
|
||||
|
||||
custom = SqlConnector(f"sqlite:///{db}", policy=SqlSourcePolicy(frozenset({"sqlite"}), None)).select_query(
|
||||
"SELECT id AS expediente FROM t WHERE id < 10"
|
||||
)
|
||||
assert custom.preview(limit=3).total_rows == 10
|
||||
assert list(custom.read_rows({"expediente": "pac_id_hospital"}))[:2] == [{"pac_id_hospital": 0}, {"pac_id_hospital": 1}]
|
||||
@@ -0,0 +1,110 @@
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
from pydantic import ValidationError
|
||||
|
||||
from core.domains import Domain
|
||||
from persistance.cluster import FolderTrainingSource
|
||||
from webapi import models
|
||||
from webapi.models import Training, train, training_config
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def sync_execution(monkeypatch):
|
||||
monkeypatch.setenv("EXECUTION_MODE", "sync")
|
||||
|
||||
|
||||
def test_tea_training_config_schema():
|
||||
config = training_config(Domain.TEA, "example").model_dump()
|
||||
assert (config["domain"], config["name"]) == ("tea", "example")
|
||||
schema = config["json_schema"]
|
||||
assert schema["title"] == "TrainingForm"
|
||||
assert set(schema["properties"]) == {"as_of", "execution", "source"}
|
||||
assert schema["properties"]["as_of"]["title"] == "Datos hasta"
|
||||
assert set(schema["$defs"]) == {
|
||||
"Execution",
|
||||
"TrainingSource",
|
||||
"SiteTrainingSource",
|
||||
"FolderTrainingSource",
|
||||
}
|
||||
execution = schema["$defs"]["Execution"]
|
||||
assert execution["title"] == "Ejecución"
|
||||
assert execution["properties"]["mode"]["title"] == "Modo"
|
||||
assert execution["properties"]["scheduler"]["title"] == "Planificador Dask"
|
||||
source = schema["$defs"]["TrainingSource"]
|
||||
assert source["discriminator"] == {
|
||||
"propertyName": "kind",
|
||||
"mapping": {
|
||||
"site": "#/$defs/SiteTrainingSource",
|
||||
"folder": "#/$defs/FolderTrainingSource",
|
||||
},
|
||||
}
|
||||
assert source["oneOf"] == [
|
||||
{"$ref": "#/$defs/SiteTrainingSource"},
|
||||
{"$ref": "#/$defs/FolderTrainingSource"},
|
||||
]
|
||||
site = schema["$defs"]["SiteTrainingSource"]
|
||||
assert set(site["properties"]) == {"kind"}
|
||||
folder = schema["$defs"]["FolderTrainingSource"]
|
||||
assert folder["properties"]["folder"]["title"] == "Carpeta"
|
||||
assert folder["properties"]["line_hz"]["enum"] == [50, 60]
|
||||
assert (site["title"], folder["title"]) == (
|
||||
"Niños del sitio sin el diagnóstico",
|
||||
"Carpeta de EDF con edades",
|
||||
)
|
||||
assert schema["properties"]["source"]["title"] == "Datos de entrenamiento"
|
||||
assert config["defaults"] == {
|
||||
"execution": {"mode": "sync", "scheduler": None},
|
||||
"source": {"kind": "site"},
|
||||
}
|
||||
|
||||
|
||||
def test_other_domains_have_no_training_source():
|
||||
for domain in ("cacu", "cama"):
|
||||
config = training_config(Domain(domain), "example").model_dump()
|
||||
assert (config["domain"], config["name"]) == (domain, "example")
|
||||
schema = config["json_schema"]
|
||||
assert set(schema["properties"]) == {"as_of", "execution"}
|
||||
assert set(schema["$defs"]) == {"Execution"}
|
||||
assert config["defaults"] == {"execution": {"mode": "sync", "scheduler": None}}
|
||||
|
||||
|
||||
def test_train_validates_the_training_source():
|
||||
with pytest.raises(HTTPException) as rejected:
|
||||
train(Domain.CACU, Training(source={"kind": "site"}))
|
||||
assert rejected.value.status_code == 422
|
||||
assert rejected.value.detail == "cacu models take no training source"
|
||||
|
||||
for source in (
|
||||
{"kind": "folder"},
|
||||
{"kind": "folder", "folder": "../x"},
|
||||
{"kind": "folder", "folder": "hel", "line_hz": 55},
|
||||
{"kind": "site", "folder": "hel"},
|
||||
{"kind": "site", "line_hz": 60},
|
||||
{"kind": "other"},
|
||||
):
|
||||
with pytest.raises(ValidationError):
|
||||
Training(source=source)
|
||||
assert Training(source={"kind": "site"}).model_dump()["source"] == {"kind": "site"}
|
||||
folder = Training(source={"kind": "folder", "folder": "hel"}).source
|
||||
assert isinstance(folder, FolderTrainingSource)
|
||||
assert folder.line_hz == 50
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"source",
|
||||
[
|
||||
{"kind": "site"},
|
||||
{"kind": "folder", "folder": "hel", "line_hz": 60},
|
||||
],
|
||||
)
|
||||
def test_train_submits_the_selected_source(monkeypatch, source):
|
||||
client = object()
|
||||
|
||||
def submit(actual_client, job, op, config, *, domain):
|
||||
assert actual_client is client
|
||||
assert (job, op, domain) == ("train", "train_models", "tea")
|
||||
assert config["source"] == source
|
||||
return {"run_id": "training"}
|
||||
|
||||
monkeypatch.setattr(models, "submit", submit)
|
||||
assert train(Domain.TEA, Training(source=source), client) == {"run_id": "training"}
|
||||
@@ -0,0 +1,46 @@
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from webapi.main import app
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(own_platform, monkeypatch):
|
||||
monkeypatch.setenv("AUTH_ADMIN_EMAIL", "admin@isssteleon.mx")
|
||||
monkeypatch.setenv("AUTH_ADMIN_PASSWORD", "una-clave-larga")
|
||||
with TestClient(app) as c:
|
||||
yield c
|
||||
|
||||
|
||||
def login(client, email, password):
|
||||
return client.post("/auth/login", data={"username": email, "password": password})
|
||||
|
||||
|
||||
def test_the_first_administrator_signs_in_and_adds_a_team(client):
|
||||
assert client.get("/users/me").status_code == 401
|
||||
assert login(client, "admin@isssteleon.mx", "mala").status_code == 400
|
||||
assert login(client, "admin@isssteleon.mx", "una-clave-larga").status_code == 204
|
||||
me = client.get("/users/me").json()
|
||||
assert me["is_superuser"] and me["domains"] == ["cacu", "cama", "tea"]
|
||||
team = {"email": "cacu@isssteleon.mx", "password": "equipo-cacu", "name": "Equipo CaCu",
|
||||
"domains": ["cacu"]} # fmt: skip
|
||||
assert client.post("/users/register", json=team).status_code == 201
|
||||
client.post("/auth/logout")
|
||||
assert login(client, "cacu@isssteleon.mx", "equipo-cacu").status_code == 204
|
||||
assert client.get("/users/me").json()["domains"] == ["cacu"]
|
||||
other = {"email": "x@isssteleon.mx", "password": "otra-clave"}
|
||||
assert client.post("/users/register", json=other).status_code == 403
|
||||
|
||||
|
||||
def test_the_api_answers_without_a_session(client):
|
||||
for path in ("/health", "/domains", "/ingest/schema", "/ingest/sources/types"):
|
||||
assert client.get(path).status_code == 200, path
|
||||
|
||||
|
||||
def test_a_restart_keeps_the_administrator_once_and_the_session_secret(client, own_platform):
|
||||
assert login(client, "admin@isssteleon.mx", "una-clave-larga").status_code == 204
|
||||
secret = (own_platform / "auth_secret").read_text()
|
||||
with TestClient(app):
|
||||
pass
|
||||
assert (own_platform / "auth_secret").read_text() == secret
|
||||
assert client.get("/users/me").status_code == 200
|
||||
@@ -0,0 +1,178 @@
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import socket
|
||||
import sqlite3
|
||||
import subprocess
|
||||
import time
|
||||
from contextlib import closing, contextmanager
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from models.tea.jobs import ASSOCIATION, MODELS
|
||||
from synthetic import tea
|
||||
|
||||
ROOT = Path(__file__).parents[2]
|
||||
FIXTURES = ROOT / "tests" / "fixtures"
|
||||
|
||||
|
||||
def _ok(response: httpx.Response):
|
||||
assert response.status_code == 200, response.text
|
||||
return response.json()
|
||||
|
||||
|
||||
def _port() -> int:
|
||||
with socket.socket() as s:
|
||||
s.bind(("127.0.0.1", 0))
|
||||
return s.getsockname()[1]
|
||||
|
||||
|
||||
def _until_up(url: str, process: subprocess.Popen, seconds: int = 180) -> None:
|
||||
deadline = time.monotonic() + seconds
|
||||
while time.monotonic() < deadline:
|
||||
assert process.poll() is None, f"{process.args[0]} exited with {process.returncode}"
|
||||
try:
|
||||
if httpx.get(url, timeout=2).status_code == 200:
|
||||
return
|
||||
except httpx.TransportError:
|
||||
pass
|
||||
time.sleep(1)
|
||||
raise TimeoutError(url)
|
||||
|
||||
|
||||
def _wait(api: httpx.Client, run_id: str, seconds: int = 1800) -> None:
|
||||
deadline = time.monotonic() + seconds
|
||||
while (run := _ok(api.get(f"/runs/{run_id}")))["state"] not in ("succeeded", "failed"):
|
||||
assert time.monotonic() < deadline, f"run {run_id} still {run['state']}"
|
||||
time.sleep(2)
|
||||
assert run["state"] == "succeeded", run.get("error")
|
||||
|
||||
|
||||
def _sensor_run(api: httpx.Client, seconds: int = 300) -> str:
|
||||
deadline = time.monotonic() + seconds
|
||||
while not (runs := _ok(api.get("/runs", params={"job": "tea_eeg", "domain": "tea"}))):
|
||||
assert time.monotonic() < deadline, "the sensor started no tea_eeg run"
|
||||
time.sleep(2)
|
||||
return runs[0]["id"]
|
||||
|
||||
|
||||
def _train_tea(api: httpx.Client) -> None:
|
||||
_wait(api, _ok(api.post("/tea/eegs/analyze", json={}))["run_id"])
|
||||
for names in (list(MODELS), [ASSOCIATION]):
|
||||
training = _ok(
|
||||
api.post(
|
||||
"/models/tea/train",
|
||||
json={
|
||||
"models": names,
|
||||
"source": {"kind": "site"},
|
||||
},
|
||||
)
|
||||
)
|
||||
_wait(api, training["run_id"])
|
||||
for name in names:
|
||||
versions = f"/models/tea/{name}/versions"
|
||||
version = _ok(api.get(versions))[-1]["version"]
|
||||
path = f"{versions}/{version}"
|
||||
_ok(
|
||||
api.post(
|
||||
f"{path}/reports/clinical_validation",
|
||||
files={
|
||||
"file": ("synthetic-validation.txt", b"Synthetic hospital test fixture")
|
||||
},
|
||||
)
|
||||
)
|
||||
_ok(api.post(f"{path}/promote"))
|
||||
assert any(
|
||||
v["version"] == version and v["status"] == "champion"
|
||||
for v in _ok(api.get(versions))
|
||||
), name
|
||||
_wait(api, _ok(api.post("/tea/eegs/analyze", json={}))["run_id"])
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _platform(data: Path):
|
||||
from mlflow.store.tracking.sqlalchemy_store import SqlAlchemyStore
|
||||
|
||||
(data / "dagster").mkdir(parents=True)
|
||||
(data / "reference").mkdir()
|
||||
shutil.copy(ROOT / "dagster.yaml", data / "dagster")
|
||||
tracking = f"sqlite:///{data / 'mlflow.db'}"
|
||||
SqlAlchemyStore(tracking, (data / "mlflow").as_uri()).engine.dispose()
|
||||
dagster_port, api_port = _port(), _port()
|
||||
env = {
|
||||
**os.environ,
|
||||
"ISSSTELEON_DATA": str(data),
|
||||
"DLT_DATA_DIR": str(data / "dlt"),
|
||||
"DAGSTER_HOME": str(data / "dagster"),
|
||||
"DAGSTER_HOST": "127.0.0.1",
|
||||
"DAGSTER_PORT": str(dagster_port),
|
||||
"MLFLOW_TRACKING_URI": tracking,
|
||||
"MLFLOW_DISABLE_AGENT_HINT": "1",
|
||||
"EXECUTION_MODE": "sync",
|
||||
"TEA_REFERENCE_ROOT": str(data / "reference"),
|
||||
"AUTH_ADMIN_EMAIL": "admin@isssteleon.mx",
|
||||
"AUTH_ADMIN_PASSWORD": "solo-para-pruebas",
|
||||
}
|
||||
webserver = subprocess.Popen(
|
||||
["dagster-webserver", "-m", "models.definitions", "-h", "127.0.0.1",
|
||||
"-p", str(dagster_port)], env=env, cwd=data,
|
||||
) # fmt: skip
|
||||
server = subprocess.Popen(
|
||||
["fastapi", "run", str(ROOT / "WebApi" / "webapi" / "main.py"), "--host", "127.0.0.1",
|
||||
"--port", str(api_port)], env=env, cwd=data,
|
||||
) # fmt: skip
|
||||
daemon = None
|
||||
try:
|
||||
_until_up(f"http://127.0.0.1:{dagster_port}/server_info", webserver)
|
||||
daemon = subprocess.Popen(
|
||||
["dagster-daemon", "run", "-m", "models.definitions"], env=env, cwd=data
|
||||
)
|
||||
_until_up(f"http://127.0.0.1:{api_port}/health", server)
|
||||
with httpx.Client(base_url=f"http://127.0.0.1:{api_port}", timeout=120) as client:
|
||||
yield client
|
||||
finally:
|
||||
for process in (server, daemon, webserver):
|
||||
if process is not None:
|
||||
process.terminate()
|
||||
process.wait(timeout=30)
|
||||
|
||||
|
||||
def _study_files(db: Path, out: Path) -> dict[str, str]:
|
||||
out.mkdir()
|
||||
with closing(sqlite3.connect(db)) as con:
|
||||
edf, report, birth = con.execute(
|
||||
"SELECT eeg_estudio, ord_pdf_blob, pac_fecha_nacimiento FROM eeg "
|
||||
"JOIN pacientes ON pac_id = eeg_pac_id "
|
||||
"JOIN ados2 ON ado_pac_id = eeg_pac_id "
|
||||
"JOIN ordenes_estudio ON ord_id = ado_ord_id ORDER BY eeg_id LIMIT 1"
|
||||
).fetchone()
|
||||
(out / "study.edf").write_bytes(edf)
|
||||
(out / "ados2.pdf").write_bytes(report)
|
||||
return {
|
||||
"TEA_EDF": str(out / "study.edf"),
|
||||
"TEA_ADOS2": str(out / "ados2.pdf"),
|
||||
"TEA_BIRTH": birth,
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.webapp
|
||||
def test_the_tea_pages_load_from_the_synthetic_hospital(tmp_path):
|
||||
hospital = tmp_path / "hospital"
|
||||
hospital.mkdir()
|
||||
tea.build(hospital / "hospital_tea.db")
|
||||
files = _study_files(hospital / "hospital_tea.db", tmp_path / "files")
|
||||
concept_map = json.loads((FIXTURES / "concept_maps" / "hospital_tea.json").read_text())
|
||||
drawn = (FIXTURES / "pipelines" / "hospital_tea.json").read_text()
|
||||
pipeline = json.loads(drawn.replace("{hospital}", str(hospital)))
|
||||
with _platform(tmp_path / "platform") as api:
|
||||
_ok(api.put("/ingest/concept-maps/hospital_tea", json=concept_map))
|
||||
_ok(api.put("/ingest/pipelines/tea", json=pipeline))
|
||||
_wait(api, _ok(api.post("/ingest/pipelines/tea/runs", json={}))["run_id"])
|
||||
_wait(api, _sensor_run(api))
|
||||
_train_tea(api)
|
||||
subprocess.run(
|
||||
["npx", "playwright", "test"], cwd=ROOT / "WebApp", check=True,
|
||||
env={**os.environ, **files, "API_URL": str(api.base_url).rstrip("/")},
|
||||
) # fmt: skip
|
||||
@@ -1,78 +0,0 @@
|
||||
import datetime as _dt
|
||||
import os
|
||||
from decimal import Decimal
|
||||
|
||||
from flask import Flask, jsonify
|
||||
from flask.json.provider import DefaultJSONProvider
|
||||
|
||||
from webapi.blueprints.cacu import cacu_bp
|
||||
from webapi.blueprints.cama import cama_bp
|
||||
from webapi.blueprints.data import data_bp
|
||||
from webapi.blueprints.governance import governance_bp
|
||||
from webapi.blueprints.imports import imports_bp
|
||||
from webapi.blueprints.tea import tea_bp
|
||||
|
||||
|
||||
class IsoJSONProvider(DefaultJSONProvider):
|
||||
"""ISO-8601 dates (Flask's default is RFC 822); files are never sent
|
||||
inline in JSON, only their size."""
|
||||
|
||||
@staticmethod
|
||||
def default(o):
|
||||
if isinstance(o, (_dt.datetime, _dt.date, _dt.time)):
|
||||
return o.isoformat()
|
||||
if isinstance(o, Decimal):
|
||||
return float(o)
|
||||
if isinstance(o, (bytes, bytearray)):
|
||||
return f"<{len(o)} bytes>"
|
||||
return DefaultJSONProvider.default(o)
|
||||
|
||||
|
||||
def create_app() -> Flask:
|
||||
app = Flask(__name__)
|
||||
app.json = IsoJSONProvider(app)
|
||||
# File sources travel inside the request; cap them per request.
|
||||
app.config["MAX_CONTENT_LENGTH"] = int(os.environ.get("WEBAPI_MAX_UPLOAD_MB", "200")) * 1024 * 1024
|
||||
|
||||
# The web client goes through a proxy; browser clients on other origins
|
||||
# are allowed with WEBAPI_CORS_ORIGINS (comma-separated).
|
||||
cors_origins = os.environ.get("WEBAPI_CORS_ORIGINS")
|
||||
if cors_origins:
|
||||
from flask_cors import CORS
|
||||
|
||||
CORS(app, origins=[origin.strip() for origin in cors_origins.split(",")])
|
||||
|
||||
@app.get("/health")
|
||||
def health():
|
||||
return {"status": "ok"}
|
||||
|
||||
@app.get("/api")
|
||||
def api_index():
|
||||
"""Every route with its methods and summary, for programmatic clients."""
|
||||
routes = []
|
||||
for rule in sorted(app.url_map.iter_rules(), key=lambda r: r.rule):
|
||||
if rule.endpoint == "static":
|
||||
continue
|
||||
doc = (app.view_functions[rule.endpoint].__doc__ or "").strip()
|
||||
routes.append(
|
||||
{
|
||||
"path": rule.rule,
|
||||
"methods": sorted(rule.methods - {"HEAD", "OPTIONS"}),
|
||||
"summary": " ".join(doc.split("\n\n")[0].split()),
|
||||
}
|
||||
)
|
||||
return jsonify({"routes": routes})
|
||||
|
||||
@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
|
||||
|
||||
app.register_blueprint(cacu_bp, url_prefix="/cacu")
|
||||
app.register_blueprint(cama_bp, url_prefix="/cama")
|
||||
app.register_blueprint(tea_bp, url_prefix="/tea")
|
||||
app.register_blueprint(imports_bp, url_prefix="/imports")
|
||||
app.register_blueprint(data_bp, url_prefix="/data")
|
||||
app.register_blueprint(governance_bp, url_prefix="/governance")
|
||||
|
||||
return app
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Caller:
|
||||
id: str = "anonymous"
|
||||
|
||||
|
||||
def caller() -> Caller:
|
||||
return Caller()
|
||||
@@ -1,41 +0,0 @@
|
||||
from flask import Blueprint, jsonify, request
|
||||
|
||||
from models.cacu import CaCuModel
|
||||
from models.prediction import ApplicabilityRejected, PredictionService
|
||||
from persistance.cacu import paciente_repository
|
||||
from persistance.db import get_cacu_session
|
||||
from webapi.indicadores import registrar_indicadores
|
||||
|
||||
cacu_bp = Blueprint("cacu", __name__)
|
||||
registrar_indicadores(cacu_bp, "cacu", get_cacu_session)
|
||||
|
||||
|
||||
@cacu_bp.get("/pacientes/<int:pac_id>")
|
||||
def get_paciente(pac_id: int):
|
||||
"""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 +0,0 @@
|
||||
from flask import Blueprint, jsonify, request
|
||||
|
||||
from models.cama import CaMaModel
|
||||
from models.prediction import ApplicabilityRejected, PredictionService
|
||||
from persistance.cama import paciente_repository
|
||||
from persistance.db import get_cama_session
|
||||
from webapi.indicadores import registrar_indicadores
|
||||
|
||||
cama_bp = Blueprint("cama", __name__)
|
||||
registrar_indicadores(cama_bp, "cama", get_cama_session)
|
||||
|
||||
|
||||
@cama_bp.get("/pacientes/<int:pac_id>")
|
||||
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())
|
||||
@@ -1,33 +0,0 @@
|
||||
"""Generic paginated read access to every importable table through its
|
||||
`Repository`, so clients can inspect what an import wrote."""
|
||||
from flask import Blueprint, jsonify, request
|
||||
|
||||
from webapi.imports.schemas.registry import ENTITY_REGISTRY
|
||||
|
||||
data_bp = Blueprint("data", __name__)
|
||||
|
||||
_MAX_PAGE = 500
|
||||
|
||||
|
||||
@data_bp.get("/<target>")
|
||||
def list_rows(target: str):
|
||||
spec = ENTITY_REGISTRY.get(target)
|
||||
if spec is None:
|
||||
return jsonify({"error": f"unknown target: {target!r}"}), 404
|
||||
try:
|
||||
limit = min(max(int(request.args.get("limit", 50)), 1), _MAX_PAGE)
|
||||
offset = max(int(request.args.get("offset", 0)), 0)
|
||||
except ValueError:
|
||||
return jsonify({"error": "limit/offset must be integers"}), 400
|
||||
rows = spec.repository.list(limit=limit, offset=offset)
|
||||
return jsonify(
|
||||
{
|
||||
"target": target,
|
||||
"total": spec.repository.count(),
|
||||
"limit": limit,
|
||||
"offset": offset,
|
||||
# Table order (JSON objects get their keys sorted on the way out).
|
||||
"columns": [column.name for column in spec.model.__table__.columns],
|
||||
"rows": [row.model_dump() for row in rows],
|
||||
}
|
||||
)
|
||||
@@ -1,355 +0,0 @@
|
||||
"""Model governance (ML, MLD, EL and VAR requirements): model versions and
|
||||
their promotion, cohorts, predictions, and the OCR extraction jobs with
|
||||
their manual review queue.
|
||||
|
||||
Training, versioning and artifact storage live in MLflow (`models.registry`
|
||||
is a thin layer over it); training runs anywhere, registering the result
|
||||
through `POST /model-versions`. Browsing/downloading a logged artifact goes
|
||||
straight to the MLflow tracking server's own UI/API, not through here.
|
||||
"""
|
||||
from dataclasses import asdict
|
||||
|
||||
from flask import Blueprint, Response, jsonify, request
|
||||
|
||||
from core.governance.enums import EstatusExtraccion
|
||||
from core.governance.models import ExtractionRun
|
||||
from core.ocr import OcrEstatus
|
||||
from models.cohort import COHORT_BUILDERS, describe_builder
|
||||
from models.ocr import OCR_JOBS, OcrColumnSpec, run_pending_extractions
|
||||
from models.registry import REPORT_TAGS, PromotionBlocked, registry
|
||||
from persistance.governance import (
|
||||
cohort_exclusion_count_repository,
|
||||
cohort_exclusion_repository,
|
||||
cohort_version_repository,
|
||||
extraction_run_repository,
|
||||
model_prediction_repository,
|
||||
)
|
||||
from persistance.repository import Repository
|
||||
|
||||
governance_bp = Blueprint("governance", __name__)
|
||||
|
||||
|
||||
@governance_bp.errorhandler(LookupError)
|
||||
def _not_found(exc: LookupError):
|
||||
return jsonify({"error": str(exc)}), 404
|
||||
|
||||
|
||||
@governance_bp.errorhandler(ValueError)
|
||||
def _bad_request(exc: ValueError):
|
||||
return jsonify({"error": str(exc)}), 400
|
||||
|
||||
|
||||
def _ocr_job_or_404(domain: str | None, entity: str | None) -> tuple[Repository, OcrColumnSpec] | None:
|
||||
job = OCR_JOBS.get((domain, entity))
|
||||
return (job.repository, job.columns) if job else None
|
||||
|
||||
|
||||
def _pk_name(repository: Repository) -> str:
|
||||
return next(iter(repository.model.__table__.primary_key.columns)).name
|
||||
|
||||
|
||||
# -- model versions ----------------------------------------------------------------
|
||||
|
||||
|
||||
@governance_bp.get("/model-versions")
|
||||
def list_model_versions():
|
||||
"""`?domain=` alone matches every scenario of that domain; `?domain=&scenario=`
|
||||
matches one; neither matches everything."""
|
||||
return jsonify({"model_versions": registry.versions(request.args.get("domain"), request.args.get("scenario"))})
|
||||
|
||||
|
||||
@governance_bp.post("/model-versions")
|
||||
def register_model_version():
|
||||
"""Registers a trained version: `{domain, scenario,
|
||||
environment: DEV|PROD, cohort_version_id?, metrics?, hyperparameters?,
|
||||
technical_validation_report_uri?, clinical_validation_report_uri?,
|
||||
interpretability_report_uri?}`."""
|
||||
body = request.get_json(silent=True) or {}
|
||||
missing = [k for k in ("domain", "scenario", "environment") if not body.get(k)]
|
||||
if missing:
|
||||
return jsonify({"error": f"faltan campos: {missing}"}), 400
|
||||
version = registry.register(
|
||||
domain=body["domain"],
|
||||
scenario=body["scenario"],
|
||||
environment=body["environment"],
|
||||
cohort_version_id=body.get("cohort_version_id"),
|
||||
metrics=body.get("metrics"),
|
||||
hyperparameters=body.get("hyperparameters"),
|
||||
**{k: body[k] for k in REPORT_TAGS if k in body},
|
||||
)
|
||||
return jsonify(registry.describe(body["domain"], body["scenario"], version)), 201
|
||||
|
||||
|
||||
@governance_bp.get("/model-versions/<domain>/<scenario>/<version>")
|
||||
def get_model_version(domain: str, scenario: str, version: str):
|
||||
return jsonify(registry.describe(domain, scenario, version))
|
||||
|
||||
|
||||
@governance_bp.patch("/model-versions/<domain>/<scenario>/<version>/reports")
|
||||
def attach_reports(domain: str, scenario: str, version: str):
|
||||
"""MLD-01/01b/03 documents, usually written after training."""
|
||||
body = request.get_json(silent=True) or {}
|
||||
registry.attach_reports(domain, scenario, version, **body)
|
||||
return jsonify(registry.describe(domain, scenario, version))
|
||||
|
||||
|
||||
@governance_bp.get("/model-versions/<domain>/<scenario>/<version>/lineage")
|
||||
def model_version_lineage(domain: str, scenario: str, version: str):
|
||||
return jsonify(registry.lineage(domain, scenario, version))
|
||||
|
||||
|
||||
@governance_bp.get("/model-versions/<domain>/<scenario>/<version>/checks")
|
||||
def model_version_checks(domain: str, scenario: str, version: str):
|
||||
checks = registry.checks(domain, scenario, version)
|
||||
return jsonify({"ready": all(c.passed for c in checks), "checks": [asdict(c) for c in checks]})
|
||||
|
||||
|
||||
@governance_bp.post("/model-versions/<domain>/<scenario>/<version>/promote")
|
||||
def promote_model_version(domain: str, scenario: str, version: str):
|
||||
"""Puts the version in production, tagging the previous one of its
|
||||
scenario `retirada_en`. 409 with the failing checks when it isn't ready."""
|
||||
try:
|
||||
registry.promote(domain, scenario, version)
|
||||
except PromotionBlocked as blocked:
|
||||
return jsonify({"error": str(blocked), "checks": [asdict(c) for c in blocked.checks]}), 409
|
||||
return jsonify(registry.describe(domain, scenario, version))
|
||||
|
||||
|
||||
@governance_bp.post("/model-versions/<domain>/<scenario>/<version>/retire")
|
||||
def retire_model_version(domain: str, scenario: str, version: str):
|
||||
registry.retire(domain, scenario, version)
|
||||
return jsonify(registry.describe(domain, scenario, version))
|
||||
|
||||
|
||||
@governance_bp.get("/model-versions/<domain>/<scenario>/compare")
|
||||
def compare_model_versions(domain: str, scenario: str):
|
||||
a, b = request.args.get("a"), request.args.get("b")
|
||||
if not a or not b:
|
||||
return jsonify({"error": "a y b deben ser versiones de MLflow"}), 400
|
||||
return jsonify(registry.compare(domain, scenario, a, b))
|
||||
|
||||
|
||||
@governance_bp.post("/model-versions/<domain>/<scenario>/<version>/artifacts")
|
||||
def upload_artifact(domain: str, scenario: str, version: str):
|
||||
"""Multipart: `file`, `kind` (ArtifactKind) — logs it to the version's
|
||||
MLflow run. Browse/download logged artifacts via the MLflow tracking
|
||||
server directly, not through here."""
|
||||
from core.governance.enums import ArtifactKind
|
||||
|
||||
upload = request.files.get("file")
|
||||
if upload is None:
|
||||
return jsonify({"error": "falta file"}), 400
|
||||
kinds = [k.value for k in ArtifactKind]
|
||||
if request.form.get("kind") not in kinds:
|
||||
return jsonify({"error": f"kind debe ser uno de {kinds}"}), 400
|
||||
registry.add_artifact(domain, scenario, version, kind=ArtifactKind(request.form["kind"]), filename=upload.filename or "artefacto", data=upload.read())
|
||||
return jsonify(registry.describe(domain, scenario, version)), 201
|
||||
|
||||
|
||||
# -- cohorts ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@governance_bp.get("/cohort-scenarios")
|
||||
def list_cohort_scenarios():
|
||||
"""Scenarios with a registered `CohortBuilder` (see models.cohort.register_cohort_builder)."""
|
||||
return jsonify({"scenarios": [describe_builder(cls) for cls in COHORT_BUILDERS.values()]})
|
||||
|
||||
|
||||
@governance_bp.post("/cohort-versions")
|
||||
def build_cohort_version():
|
||||
"""Builds and freezes a new cohort version: `{domain, scenario, description?}`."""
|
||||
body = request.get_json(silent=True) or {}
|
||||
builder = COHORT_BUILDERS.get((body.get("domain"), body.get("scenario")))
|
||||
if builder is None:
|
||||
return jsonify({"error": f"no hay un CohortBuilder registrado para ({body.get('domain')!r}, {body.get('scenario')!r})"}), 404
|
||||
return jsonify(builder().build(description=body.get("description")).model_dump()), 201
|
||||
|
||||
|
||||
@governance_bp.get("/cohort-versions")
|
||||
def list_cohort_versions():
|
||||
filters = {k: v for k, v in request.args.items() if k in {"domain", "scenario"}}
|
||||
versions = cohort_version_repository.list(limit=200, **filters)
|
||||
return jsonify({"cohort_versions": [v.model_dump() for v in versions]})
|
||||
|
||||
|
||||
@governance_bp.get("/cohort-versions/<int:cohort_version_id>/exclusions")
|
||||
def get_cohort_exclusions(cohort_version_id: int):
|
||||
"""EL-05/EL-07: per-criterion counts and the per-episode log behind them."""
|
||||
counts = cohort_exclusion_count_repository.list(limit=1000, cohort_version_id=cohort_version_id)
|
||||
detail = cohort_exclusion_repository.list(limit=1000, cohort_version_id=cohort_version_id)
|
||||
return jsonify({"counts": [c.model_dump() for c in counts], "detail": [d.model_dump() for d in detail]})
|
||||
|
||||
|
||||
# -- predictions and OCR -------------------------------------------------------------------
|
||||
|
||||
|
||||
@governance_bp.get("/predictions")
|
||||
def list_predictions():
|
||||
filters = {k: v for k, v in request.args.items() if k in {"domain", "pac_id_hospital", "mlflow_run_id", "modelo_nombre", "modelo_version"}}
|
||||
predictions = model_prediction_repository.list(limit=200, **filters)
|
||||
return jsonify({"predictions": [p.model_dump() for p in predictions]})
|
||||
|
||||
|
||||
@governance_bp.get("/ocr/jobs")
|
||||
def list_ocr_jobs():
|
||||
"""The configured OCR jobs, with the result columns each one fills."""
|
||||
jobs = [
|
||||
{
|
||||
"domain": job.domain,
|
||||
"entity": job.entity,
|
||||
"label": job.label,
|
||||
"result_fields": list(job.columns.result_field_map.values()),
|
||||
}
|
||||
for job in OCR_JOBS.values()
|
||||
]
|
||||
return jsonify({"jobs": jobs})
|
||||
|
||||
|
||||
@governance_bp.get("/ocr/<domain>/<entity>/rows")
|
||||
def list_ocr_rows(domain: str, entity: str):
|
||||
"""Rows of an OCR job filtered by `status`: `review` (the default, rows
|
||||
flagged `requiere_revision`), `pending`, `failed`, `done` or `all`.
|
||||
|
||||
Filtering happens in Python because `Repository.list` only supports
|
||||
equality filters; a review queue is small."""
|
||||
job = _ocr_job_or_404(domain, entity)
|
||||
if job is None:
|
||||
return jsonify({"error": f"no hay job de OCR registrado para (domain={domain!r}, entity={entity!r})"}), 404
|
||||
repository, spec = job
|
||||
|
||||
status = request.args.get("status", "review")
|
||||
limit = int(request.args.get("limit", 100))
|
||||
offset = int(request.args.get("offset", 0))
|
||||
pk_name = _pk_name(repository)
|
||||
|
||||
def matches(row) -> bool:
|
||||
if getattr(row, spec.blob_field, None) is None:
|
||||
return False
|
||||
estatus = getattr(row, spec.estatus_field, None)
|
||||
if status == "all":
|
||||
return True
|
||||
if status == "review":
|
||||
return bool(getattr(row, spec.requiere_revision_field, None))
|
||||
if status == "pending":
|
||||
return estatus in (None, OcrEstatus.PENDIENTE.value)
|
||||
if status == "failed":
|
||||
return estatus == OcrEstatus.FALLIDO.value
|
||||
if status == "done":
|
||||
return estatus == OcrEstatus.REALIZADO.value
|
||||
return True
|
||||
|
||||
candidates = [row for row in repository.list(limit=2000) if matches(row)]
|
||||
page = candidates[offset : offset + limit]
|
||||
rows = [
|
||||
{
|
||||
"id": getattr(row, pk_name),
|
||||
"pac_id_hospital": getattr(row, "pac_id_hospital", None),
|
||||
"values": {column: getattr(row, column, None) for column in spec.result_field_map.values()},
|
||||
"confianza": getattr(row, spec.confianza_field, None),
|
||||
"estatus": getattr(row, spec.estatus_field, None),
|
||||
"requiere_revision": getattr(row, spec.requiere_revision_field, None),
|
||||
"metodo_principal": getattr(row, spec.metodo_principal_field, None),
|
||||
"metodo_alternativo": getattr(row, spec.metodo_alternativo_field, None),
|
||||
}
|
||||
for row in page
|
||||
]
|
||||
return jsonify({"rows": rows, "total": len(candidates)})
|
||||
|
||||
|
||||
@governance_bp.get("/ocr/<domain>/<entity>/<int:pk>/blob")
|
||||
def get_ocr_blob(domain: str, entity: str, pk: int):
|
||||
"""Raw bytes of the row's stored PDF, for the review UI's page viewer."""
|
||||
job = _ocr_job_or_404(domain, entity)
|
||||
if job is None:
|
||||
return jsonify({"error": f"no hay job de OCR registrado para (domain={domain!r}, entity={entity!r})"}), 404
|
||||
repository, spec = job
|
||||
row = repository.get(pk)
|
||||
if row is None:
|
||||
return jsonify({"error": "not found"}), 404
|
||||
blob = getattr(row, spec.blob_field, None)
|
||||
if blob is None:
|
||||
return jsonify({"error": "esta fila no tiene un PDF almacenado"}), 404
|
||||
return Response(blob, mimetype="application/pdf")
|
||||
|
||||
|
||||
@governance_bp.post("/ocr/<domain>/<entity>/<int:pk>/correct")
|
||||
def correct_ocr_row(domain: str, entity: str, pk: int):
|
||||
"""Stores values entered by a reviewer for an OCR row. Marks the row
|
||||
done with method "manual" (VAR-03), clears `requiere_revision`, and logs
|
||||
an `ExtractionRun` like an automated run (VAR-07/08)."""
|
||||
job = _ocr_job_or_404(domain, entity)
|
||||
if job is None:
|
||||
return jsonify({"error": f"no hay job de OCR registrado para (domain={domain!r}, entity={entity!r})"}), 404
|
||||
repository, spec = job
|
||||
|
||||
body = request.get_json(silent=True) or {}
|
||||
values = body.get("values")
|
||||
if not isinstance(values, dict) or not values:
|
||||
return jsonify({"error": "'values' es requerido y debe tener al menos un campo"}), 400
|
||||
allowed = set(spec.result_field_map.values())
|
||||
unknown = set(values) - allowed
|
||||
if unknown:
|
||||
return jsonify({"error": f"columnas no permitidas para esta entidad: {sorted(unknown)}"}), 400
|
||||
|
||||
with repository.open_session() as session:
|
||||
tracked = session.get(repository.model, pk)
|
||||
if tracked is None:
|
||||
return jsonify({"error": "not found"}), 404
|
||||
for column, value in values.items():
|
||||
setattr(tracked, column, value)
|
||||
setattr(tracked, spec.estatus_field, OcrEstatus.REALIZADO.value)
|
||||
setattr(tracked, spec.requiere_revision_field, False)
|
||||
setattr(tracked, spec.metodo_principal_field, "manual")
|
||||
setattr(tracked, spec.metodo_alternativo_field, None)
|
||||
setattr(tracked, spec.confianza_field, float(body["confianza"]) if "confianza" in body else 1.0)
|
||||
session.add(tracked)
|
||||
session.commit()
|
||||
session.refresh(tracked)
|
||||
updated = tracked.model_dump()
|
||||
|
||||
extraction_run_repository.create(
|
||||
ExtractionRun(
|
||||
domain=domain,
|
||||
entity=entity,
|
||||
entity_pk=str(pk),
|
||||
column_extracted=",".join(sorted(values)),
|
||||
transform_description="Corrección manual vía UI de gobernanza — usuario revisó el PDF y escribió el valor directamente.",
|
||||
estatus=EstatusExtraccion.COMPLETADA,
|
||||
)
|
||||
)
|
||||
return jsonify(updated)
|
||||
|
||||
|
||||
@governance_bp.post("/ocr/run")
|
||||
def run_ocr():
|
||||
"""Runs an OCR job over pending rows. Rows already `REALIZADO` are
|
||||
skipped, so repeated calls are safe (VAR-09)."""
|
||||
body = request.get_json(silent=True) or {}
|
||||
domain = body.get("domain")
|
||||
entity = body.get("entity")
|
||||
job = OCR_JOBS.get((domain, entity))
|
||||
if job is None:
|
||||
return jsonify({"error": f"no hay job de OCR registrado para (domain={domain!r}, entity={entity!r})"}), 400
|
||||
|
||||
try:
|
||||
summary = run_pending_extractions(
|
||||
job.repository,
|
||||
job.columns,
|
||||
job.extractor(),
|
||||
domain=domain,
|
||||
entity=entity,
|
||||
governance_repository=extraction_run_repository,
|
||||
source_description=body.get("source_description"),
|
||||
limit=int(body.get("limit", 500)),
|
||||
)
|
||||
except NotImplementedError as exc:
|
||||
return jsonify({"error": str(exc)}), 501
|
||||
|
||||
return jsonify(
|
||||
{
|
||||
"processed": summary.processed,
|
||||
"skipped_already_done": summary.skipped_already_done,
|
||||
"failed": summary.failed,
|
||||
"needs_review": summary.needs_review,
|
||||
}
|
||||
)
|
||||
@@ -1,311 +0,0 @@
|
||||
"""Import routes. They only parse the request and shape the response; the
|
||||
work happens in `webapi.imports`. Errors map to HTTP 400 in one place."""
|
||||
import json
|
||||
|
||||
from flask import Blueprint, Response, jsonify, request
|
||||
|
||||
from extraction import BBox, ExtractionError
|
||||
from extraction.readers import reader_for
|
||||
from webapi.imports.connectors import ConnectorError, build_connector, catalog, connector_class, kind_for_filename
|
||||
from webapi.imports.connectors.base import decode_file
|
||||
from webapi.imports.connectors.pdf import PdfConnector
|
||||
from webapi.imports.connectors.sql import SqlConnector
|
||||
from webapi.imports.connectors.tabular import FileConnector
|
||||
from webapi.imports.schemas.registry import ENTITY_REGISTRY
|
||||
from webapi.imports.services.import_service import (
|
||||
ImportRequestError,
|
||||
commit_sources,
|
||||
serialize_errors,
|
||||
validate_source,
|
||||
)
|
||||
from webapi.imports.services.introspection_service import (
|
||||
detect_pdf,
|
||||
document_report,
|
||||
extract_pdf_regions,
|
||||
preview_with_suggestions,
|
||||
)
|
||||
|
||||
imports_bp = Blueprint("imports", __name__)
|
||||
|
||||
|
||||
class BadRequest(Exception):
|
||||
"""Missing or malformed request parameter."""
|
||||
|
||||
|
||||
@imports_bp.errorhandler(BadRequest)
|
||||
@imports_bp.errorhandler(ConnectorError)
|
||||
@imports_bp.errorhandler(ExtractionError)
|
||||
@imports_bp.errorhandler(ImportRequestError)
|
||||
def _bad_request(exc: Exception):
|
||||
return jsonify({"error": str(exc)}), 400
|
||||
|
||||
|
||||
def _json_body() -> dict:
|
||||
body = request.get_json(silent=True)
|
||||
if not isinstance(body, dict):
|
||||
raise BadRequest("request body must be a JSON object")
|
||||
return body
|
||||
|
||||
|
||||
def _require(mapping: dict, key: str):
|
||||
value = mapping.get(key)
|
||||
if value in (None, ""):
|
||||
raise BadRequest(f"missing {key}")
|
||||
return value
|
||||
|
||||
|
||||
def _uploaded_file() -> tuple[str, bytes]:
|
||||
if "file" not in request.files:
|
||||
raise BadRequest("missing file")
|
||||
upload = request.files["file"]
|
||||
return upload.filename or "", upload.read()
|
||||
|
||||
|
||||
def _form_int(key: str, default: int | None = None) -> int:
|
||||
raw = request.form.get(key)
|
||||
if raw is None:
|
||||
if default is None:
|
||||
raise BadRequest(f"missing {key}")
|
||||
return default
|
||||
try:
|
||||
return int(raw)
|
||||
except ValueError as exc:
|
||||
raise BadRequest(f"{key} must be an integer") from exc
|
||||
|
||||
|
||||
def _form_json(key: str, default=None):
|
||||
raw = request.form.get(key)
|
||||
if raw in (None, ""):
|
||||
return default
|
||||
try:
|
||||
return json.loads(raw)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise BadRequest(f"{key} must be JSON: {exc}") from exc
|
||||
|
||||
|
||||
# -- catalog -------------------------------------------------------------------
|
||||
|
||||
|
||||
@imports_bp.get("/connectors")
|
||||
def get_connectors():
|
||||
"""Every source kind the server can read, with what the client needs to
|
||||
offer it (accepted extensions, SQL engines and whether their driver is
|
||||
installed, document segmentation strategies)."""
|
||||
return jsonify({"connectors": catalog()})
|
||||
|
||||
|
||||
@imports_bp.get("/targets")
|
||||
def get_targets():
|
||||
targets = []
|
||||
for key, spec in ENTITY_REGISTRY.items():
|
||||
schema_json = spec.schema.model_json_schema()
|
||||
required = set(schema_json.get("required", []))
|
||||
fields = [
|
||||
{"name": name, "required": name in required, "type": _json_schema_type(prop)}
|
||||
for name, prop in schema_json.get("properties", {}).items()
|
||||
]
|
||||
domain, _, table = key.partition(".")
|
||||
targets.append(
|
||||
{
|
||||
"key": key,
|
||||
"domain": domain,
|
||||
"table": table,
|
||||
"conflict_fields": list(spec.conflict_fields) if spec.conflict_fields else None,
|
||||
"fields": fields,
|
||||
}
|
||||
)
|
||||
return jsonify({"targets": targets})
|
||||
|
||||
|
||||
def _json_schema_type(prop: dict) -> str:
|
||||
"""`Optional[X]` renders as `anyOf: [X, null]`: report X and its format."""
|
||||
candidates = prop.get("anyOf") or [prop]
|
||||
for candidate in candidates:
|
||||
if candidate.get("type") and candidate["type"] != "null":
|
||||
return candidate.get("format") or candidate["type"]
|
||||
return "string"
|
||||
|
||||
|
||||
# -- generic preview --------------------------------------------------------------
|
||||
|
||||
|
||||
@imports_bp.post("/sources/file/preview")
|
||||
def preview_file():
|
||||
"""Multipart upload of any file connector (`source_kind` may be omitted
|
||||
and is then inferred from the file name)."""
|
||||
name, raw = _uploaded_file()
|
||||
kind = request.form.get("source_kind") or kind_for_filename(name)
|
||||
cls = connector_class(kind)
|
||||
if not issubclass(cls, FileConnector):
|
||||
raise BadRequest(f"{kind!r} is not a file source")
|
||||
options = _form_json("options", {}) or {}
|
||||
if "file_name" in cls.option_names:
|
||||
options.setdefault("file_name", name)
|
||||
connector = cls.from_bytes(raw, options)
|
||||
return jsonify(preview_with_suggestions(connector, request.form.get("target")))
|
||||
|
||||
|
||||
@imports_bp.post("/sources/<kind>/preview")
|
||||
def preview_source(kind: str):
|
||||
"""JSON preview for any connector: `{"payload": {...}, "target": "cacu.Paciente"}`,
|
||||
the same payload an import source carries."""
|
||||
body = _json_body()
|
||||
payload = _require(body, "payload")
|
||||
if kind == "document":
|
||||
payload = {**payload, "target": payload.get("target") or body.get("target")}
|
||||
return jsonify(preview_with_suggestions(build_connector(kind, payload), body.get("target")))
|
||||
|
||||
|
||||
# -- SQL browsing -------------------------------------------------------------------
|
||||
|
||||
|
||||
@imports_bp.post("/sources/sql/test-connection")
|
||||
def sql_test_connection():
|
||||
connector = SqlConnector.connect(_json_body())
|
||||
connector.test_connection()
|
||||
return jsonify({"ok": True, "dialect": connector.get_dialect()})
|
||||
|
||||
|
||||
@imports_bp.post("/sources/sql/schemas")
|
||||
def sql_schemas():
|
||||
return jsonify({"schemas": SqlConnector.connect(_json_body()).list_schemas()})
|
||||
|
||||
|
||||
@imports_bp.post("/sources/sql/tables")
|
||||
def sql_tables():
|
||||
body = _json_body()
|
||||
return jsonify({"tables": SqlConnector.connect(body).list_tables(schema=body.get("schema"))})
|
||||
|
||||
|
||||
@imports_bp.post("/sources/sql/columns")
|
||||
def sql_columns():
|
||||
body = _json_body()
|
||||
columns = SqlConnector.connect(body).list_columns(_require(body, "table"), schema=body.get("schema"))
|
||||
return jsonify({"columns": [{"name": c.name, "inferred_type": c.inferred_type} for c in columns]})
|
||||
|
||||
|
||||
@imports_bp.post("/sources/sql/preview")
|
||||
def sql_preview():
|
||||
body = _json_body()
|
||||
connector = SqlConnector.connect(body)
|
||||
if body.get("query"):
|
||||
connector.select_query(body["query"])
|
||||
else:
|
||||
connector.select_table(_require(body, "table"), schema=body.get("schema"))
|
||||
return jsonify(preview_with_suggestions(connector, body.get("target")))
|
||||
|
||||
|
||||
# -- PDF tables -------------------------------------------------------------------------
|
||||
|
||||
|
||||
@imports_bp.post("/sources/pdf/detect")
|
||||
def pdf_detect():
|
||||
return jsonify(detect_pdf(_uploaded_file()[1]))
|
||||
|
||||
|
||||
@imports_bp.post("/sources/pdf/page-image")
|
||||
def pdf_page_image():
|
||||
png = PdfConnector(_uploaded_file()[1]).render_page_image(_form_int("page_number"), dpi=_form_int("dpi", 150))
|
||||
return Response(png, mimetype="image/png")
|
||||
|
||||
|
||||
@imports_bp.post("/sources/pdf/table/preview")
|
||||
def pdf_table_preview():
|
||||
raw = _uploaded_file()[1]
|
||||
page_number = _form_int("page_number")
|
||||
bbox = _form_json("bbox")
|
||||
if not isinstance(bbox, list) or len(bbox) != 4:
|
||||
raise BadRequest("missing page_number or bbox")
|
||||
connector = PdfConnector(raw)
|
||||
connector.select_table(page_number, tuple(float(v) for v in bbox))
|
||||
return jsonify(preview_with_suggestions(connector, request.form.get("target")))
|
||||
|
||||
|
||||
@imports_bp.post("/sources/pdf/regions/extract")
|
||||
def pdf_regions_extract():
|
||||
body = _json_body()
|
||||
raw = decode_file(body)
|
||||
regions = _require(body, "regions")
|
||||
return jsonify(extract_pdf_regions(raw, regions, dpi=int(body.get("dpi", 150)), target_key=body.get("target")))
|
||||
|
||||
|
||||
# -- documents ------------------------------------------------------------------------------
|
||||
|
||||
|
||||
@imports_bp.post("/sources/document/extract")
|
||||
def document_extract():
|
||||
"""Reads the documents, splits them into patient records and extracts
|
||||
the target's fields: `{files: [{name, file_base64}], target,
|
||||
segmentation?, pages_per_record?, ocr_mode?, key_pattern?, overrides?}`.
|
||||
Each record comes back with per-field confidence and evidence, conflicts
|
||||
between sources, and the images found on its pages."""
|
||||
body = _json_body()
|
||||
_require(body, "target")
|
||||
if not body.get("files"):
|
||||
raise BadRequest("missing files")
|
||||
return jsonify(document_report(body))
|
||||
|
||||
|
||||
@imports_bp.post("/sources/document/page-image")
|
||||
def document_page_image():
|
||||
"""PNG of one page of any supported document; with `bbox` (normalized,
|
||||
JSON list) only that region, e.g. an embedded image."""
|
||||
name, raw = _uploaded_file()
|
||||
reader = reader_for(name, raw)
|
||||
page_number = _form_int("page_number")
|
||||
dpi = min(max(_form_int("dpi", 150), 50), 300)
|
||||
bbox = _form_json("bbox")
|
||||
if bbox is None:
|
||||
return Response(reader.render_page(raw, page_number, dpi=dpi), mimetype="image/png")
|
||||
if not isinstance(bbox, list) or len(bbox) != 4:
|
||||
raise BadRequest("bbox must be [x0, y0, x1, y1]")
|
||||
return Response(reader.render_region(raw, page_number, BBox(*map(float, bbox)), dpi=dpi), mimetype="image/png")
|
||||
|
||||
|
||||
# -- validate and load -------------------------------------------------------------------------
|
||||
|
||||
|
||||
@imports_bp.post("/validate")
|
||||
def validate():
|
||||
result = validate_source(_require(_json_body(), "source"))
|
||||
return jsonify(
|
||||
{
|
||||
"total_rows": result.total_rows,
|
||||
"valid_count": result.valid_count,
|
||||
"error_count": result.error_count,
|
||||
"errors": serialize_errors(result),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@imports_bp.post("/commit")
|
||||
def commit():
|
||||
"""`{sources: [...], on_conflict: "reject"|"upsert", merge_duplicates: bool}`.
|
||||
With `merge_duplicates`, rows of different sources sharing a natural key
|
||||
are combined into one record before writing."""
|
||||
body = _json_body()
|
||||
results = commit_sources(
|
||||
_require(body, "sources"),
|
||||
on_conflict=body.get("on_conflict", "reject"),
|
||||
merge=bool(body.get("merge_duplicates", False)),
|
||||
)
|
||||
return jsonify(
|
||||
{
|
||||
"ok": all(r.rejected == 0 for r in results),
|
||||
"results": [
|
||||
{
|
||||
"target": r.target,
|
||||
"label": r.label,
|
||||
"total": r.total,
|
||||
"created": r.created,
|
||||
"updated": r.updated,
|
||||
"rejected": r.rejected,
|
||||
"merged": r.merged,
|
||||
"errors": r.errors,
|
||||
"warnings": r.warnings,
|
||||
"linked": r.linked,
|
||||
}
|
||||
for r in results
|
||||
],
|
||||
}
|
||||
)
|
||||
@@ -1,40 +0,0 @@
|
||||
from flask import Blueprint, jsonify, request
|
||||
|
||||
from models.prediction import ApplicabilityRejected, PredictionService
|
||||
from models.tea import TeaModel
|
||||
from persistance.db import get_tea_session
|
||||
from persistance.tea import pacientes_repository
|
||||
from webapi.indicadores import registrar_indicadores
|
||||
|
||||
tea_bp = Blueprint("tea", __name__)
|
||||
registrar_indicadores(tea_bp, "tea", get_tea_session)
|
||||
|
||||
|
||||
@tea_bp.get("/pacientes/<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())
|
||||
@@ -0,0 +1,70 @@
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel
|
||||
|
||||
from persistance import eeg
|
||||
from persistance.cluster import Execution
|
||||
from persistance.eeg import Scope
|
||||
from webapi.runs import dagster, execution_config, submit
|
||||
|
||||
router = APIRouter(prefix="/tea/eegs", tags=["eeg"])
|
||||
|
||||
|
||||
class Study(BaseModel):
|
||||
id: str
|
||||
person_id: str
|
||||
study_date: str
|
||||
lab_record_id: str | None
|
||||
analysed: bool
|
||||
valid: bool | None
|
||||
level: str | None
|
||||
|
||||
|
||||
class Metric(BaseModel):
|
||||
code: str
|
||||
value: float
|
||||
z: float | None
|
||||
outside: float | None
|
||||
model: str | None
|
||||
|
||||
|
||||
class Analysis(BaseModel):
|
||||
id: str
|
||||
valid: bool | None
|
||||
level: str | None
|
||||
age_months: float | None
|
||||
metrics: list[Metric]
|
||||
checks: list[dict[str, Any]]
|
||||
regions: list[dict[str, Any]]
|
||||
|
||||
|
||||
class AnalyzeRequest(BaseModel):
|
||||
scope: Scope = Scope()
|
||||
execution: Execution | None = None
|
||||
|
||||
|
||||
@router.get("")
|
||||
def studies() -> list[Study]:
|
||||
return [Study(**s) for s in eeg.studies()]
|
||||
|
||||
|
||||
@router.post(
|
||||
"/analyze",
|
||||
description="Starts `tea_eeg`: analyse the EEGs in scope, score the curves, rebuild gold.",
|
||||
)
|
||||
def analyze_eegs(request: AnalyzeRequest, client=Depends(dagster)) -> dict[str, str]:
|
||||
config = {"scope": request.scope.model_dump(), "execution": execution_config(request.execution)}
|
||||
return submit(client, "tea_eeg", "tea_analyze_studies", config, domain="tea")
|
||||
|
||||
|
||||
@router.get("/summary")
|
||||
def eeg_studies_summary() -> dict[str, int]:
|
||||
return eeg.summary()
|
||||
|
||||
|
||||
@router.get("/{eeg_id}")
|
||||
def study(eeg_id: str) -> Analysis:
|
||||
if (found := eeg.study(eeg_id)) is None:
|
||||
raise HTTPException(404, detail=f"no analysed EEG {eeg_id}")
|
||||
return Analysis(**found)
|
||||
@@ -0,0 +1,21 @@
|
||||
from fastapi import APIRouter, HTTPException
|
||||
|
||||
from persistance import cluster
|
||||
from persistance.cluster import Execution, Health, Mode, Options
|
||||
|
||||
router = APIRouter(prefix="/execution", tags=["execution"])
|
||||
|
||||
|
||||
@router.get("/options")
|
||||
def execution_options() -> Options:
|
||||
return cluster.options()
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
def execution_health(
|
||||
mode: Mode | None = None, scheduler: str | None = None, reference: str | None = None
|
||||
) -> Health:
|
||||
try:
|
||||
return cluster.health(Execution(mode=mode, scheduler=scheduler), reference)
|
||||
except cluster.ExecutionError as e:
|
||||
raise HTTPException(422, detail=str(e)) from e
|
||||
+716
@@ -0,0 +1,716 @@
|
||||
import unicodedata
|
||||
from collections import defaultdict
|
||||
from datetime import date, datetime
|
||||
from typing import Annotated, Any
|
||||
from urllib.parse import urlencode
|
||||
|
||||
from dagster_graphql import DagsterGraphQLClient
|
||||
from fastapi import APIRouter, Body, Depends, HTTPException, Query, Request
|
||||
from fastapi.responses import Response
|
||||
from fhir.resources.R4B.bundle import Bundle
|
||||
from fhir.resources.R4B.capabilitystatement import CapabilityStatement
|
||||
from fhir.resources.R4B.operationoutcome import OperationOutcome
|
||||
from fhir.resources.R4B.parameters import Parameters
|
||||
from fhir.resources.R4B.resource import Resource
|
||||
|
||||
from core import catalog
|
||||
from core import fhir as f
|
||||
from core import measures as m
|
||||
from core.domains import Domain, measures, part
|
||||
from core.follow_up import window_start
|
||||
from core.pipeline import ID_PATTERN
|
||||
from core.tea import fhir as tea_fhir
|
||||
from core.tea.follow_up import FILTERS as TEA_FILTERS
|
||||
from persistance import config_log, readers
|
||||
from persistance import fhir as reads
|
||||
from persistance import measures as measure_reads
|
||||
from webapi.ingest import submit
|
||||
from webapi.runs import dagster
|
||||
|
||||
FHIR_JSON = "application/fhir+json"
|
||||
PAGE, MAX_PAGE = 50, 200
|
||||
REVINCLUDES = ("DiagnosticReport:subject", "RiskAssessment:subject", "Observation:subject")
|
||||
|
||||
router = APIRouter(prefix="/{domain}/fhir", tags=["fhir"])
|
||||
_OK = {200: {"content": {FHIR_JSON: {"schema": {"type": "object"}}}, "description": "FHIR"}}
|
||||
|
||||
|
||||
def fhir(resource: Resource) -> Response:
|
||||
return Response(resource.model_dump_json(exclude_none=True), media_type=FHIR_JSON)
|
||||
|
||||
|
||||
def outcome(status: int, text: str) -> Response:
|
||||
issue = {"severity": "error", "code": "not-found" if status == 404 else "invalid",
|
||||
"diagnostics": text} # fmt: skip
|
||||
return Response(OperationOutcome(issue=[issue]).model_dump_json(exclude_none=True),
|
||||
status_code=status, media_type=FHIR_JSON) # fmt: skip
|
||||
|
||||
|
||||
def _clinical(domain: Domain):
|
||||
if (found := part(domain, "follow_up")) is None:
|
||||
raise HTTPException(404, f"no clinical resources for {domain.value} yet")
|
||||
return found
|
||||
|
||||
|
||||
def _cutoff(domain: Domain, asked: date | None) -> date:
|
||||
if asked is not None:
|
||||
return asked
|
||||
return reads.last_data_day(domain.value) or date.today()
|
||||
|
||||
|
||||
def _page(count: int | None, offset: int) -> tuple[int, int]:
|
||||
count = PAGE if count is None else count
|
||||
if not 0 <= count <= MAX_PAGE or offset < 0:
|
||||
raise HTTPException(422, f"_count goes from 0 to {MAX_PAGE}; _offset from 0")
|
||||
return count, offset
|
||||
|
||||
|
||||
def bundle(request: Request, matches: list[Resource], total: int, count: int, offset: int,
|
||||
included: list[Resource] = (), applied: dict | None = None) -> Response: # fmt: skip
|
||||
base = str(request.base_url).rstrip("/") + request.url.path.rsplit("/", 1)[0]
|
||||
|
||||
def link(relation: str, at: int) -> dict:
|
||||
params = {**(applied or {}), "_offset": at, "_count": count}
|
||||
query = [(k, v) for k, v in request.query_params.multi_items() if k not in params]
|
||||
url = request.url.replace(query=urlencode([*query, *params.items()], doseq=True))
|
||||
return {"relation": relation, "url": str(url)}
|
||||
|
||||
links = [link("self", offset)]
|
||||
if offset + count < total:
|
||||
links.append(link("next", offset + count))
|
||||
if offset > 0:
|
||||
links.append(link("previous", max(offset - count, 0)))
|
||||
groups = (("match", matches), ("include", included))
|
||||
entries = [{"fullUrl": f"{base}/{r.get_resource_type()}/{r.id}", "resource": r,
|
||||
"search": {"mode": mode}} for mode, group in groups for r in group] # fmt: skip
|
||||
found = Bundle(type="searchset", total=total, link=links, entry=entries or None)
|
||||
return fhir(found)
|
||||
|
||||
|
||||
def _sliced(found: list, count: int, offset: int) -> list:
|
||||
return found[offset:offset + count] # fmt: skip
|
||||
|
||||
|
||||
_WINDOW = Query(
|
||||
None,
|
||||
alias="follow-up-window",
|
||||
description="months: the domain's follow-up list over that window up to the cut-off",
|
||||
)
|
||||
_START = Query(
|
||||
None,
|
||||
alias="follow-up-start",
|
||||
description="explicit window start that overrides follow-up-window",
|
||||
)
|
||||
_CUTOFF = Query(None, alias="follow-up-cutoff", description="default: the last day with data")
|
||||
_STATUS = Query(None, alias="follow-up-status")
|
||||
|
||||
|
||||
@router.get(
|
||||
"/Patient/$eeg-summary",
|
||||
responses=_OK,
|
||||
response_class=Response,
|
||||
description="EEG counts for the follow-up list. Without a window or start, "
|
||||
"use the whole history.",
|
||||
)
|
||||
def eeg_summary(
|
||||
request: Request,
|
||||
domain: Domain,
|
||||
window: int | None = _WINDOW,
|
||||
start: date | None = _START,
|
||||
cutoff: date | None = _CUTOFF,
|
||||
status: str | None = _STATUS,
|
||||
) -> Response:
|
||||
fu = _clinical(domain)
|
||||
if not hasattr(fu, "summary"):
|
||||
return outcome(404, f"no EEG summary for {domain.value}")
|
||||
at = _cutoff(domain, cutoff)
|
||||
try:
|
||||
rows, _, _ = _patient_rows(request, domain, fu, at, window, start, cutoff, status,
|
||||
whole_history=True) # fmt: skip
|
||||
except ValueError as exc:
|
||||
return outcome(422, str(exc))
|
||||
counts = fu.summary(rows)
|
||||
parameters = [
|
||||
{"name": name, "valueInteger": counts[name]}
|
||||
for name in ("valid", "not_valid", "normal", "abnormal")
|
||||
]
|
||||
for entry in counts["by_alteration"]:
|
||||
parameters.append({"name": "by_alteration", "part": [
|
||||
{"name": "alteration", "valueCode": entry["alteration"]},
|
||||
{"name": "patients", "valueInteger": entry["patients"]},
|
||||
]}) # fmt: skip
|
||||
return fhir(Parameters(parameter=parameters))
|
||||
|
||||
|
||||
@router.get("/Patient/{id}", responses=_OK, response_class=Response)
|
||||
def read_patient(domain: Domain, id: str) -> Response:
|
||||
fu = _clinical(domain)
|
||||
(row,) = reads.rows(domain.value, "person", id=id) or [None]
|
||||
if row is None:
|
||||
(link,) = reads.rows(domain.value, "replaced", id=id) or [None]
|
||||
if link is None:
|
||||
raise HTTPException(404, f"no Patient/{id}")
|
||||
return fhir(f.replaced_patient(id, link["replaced_by"]))
|
||||
status = fu.status(row, _cutoff(domain, None))
|
||||
(found,) = _with_identity(domain, [{**row, "status": status}])
|
||||
return fhir(f.patient(found, fu.STATUS_SYSTEM))
|
||||
|
||||
|
||||
def _with_identity(domain: Domain, rows: list[dict]) -> list[dict]:
|
||||
persons = [r["person_id"] for r in rows]
|
||||
names, ids, replaces = {}, {}, {}
|
||||
for r in reads.rows(domain.value, "names", persons=persons):
|
||||
names.setdefault(r["person_id"], []).append(r["text"])
|
||||
for r in reads.rows(domain.value, "identifiers", persons=persons):
|
||||
ids.setdefault(r["person_id"], []).append((r["system"], r["value"]))
|
||||
for r in reads.rows(domain.value, "replaces", persons=persons):
|
||||
replaces.setdefault(r["replaced_by"], []).append(r["person_id"])
|
||||
return [
|
||||
{**r, "names": names.get(p, []), "identifiers": ids.get(p, []),
|
||||
"replaces": replaces.get(p, [])}
|
||||
for r in rows if (p := r["person_id"])
|
||||
] # fmt: skip
|
||||
|
||||
|
||||
def _folded(text: str) -> str:
|
||||
return "".join(c for c in unicodedata.normalize("NFKD", text.casefold())
|
||||
if not unicodedata.combining(c)) # fmt: skip
|
||||
|
||||
|
||||
def _matches(row: dict, name: str | None, identifier: str | None) -> bool:
|
||||
if name:
|
||||
words = _folded(name).split()
|
||||
if not any(all(any(w.startswith(q) for w in _folded(n).split()) for q in words)
|
||||
for n in row["names"]): # fmt: skip
|
||||
return False
|
||||
if identifier:
|
||||
system, _, value = identifier.rpartition("|")
|
||||
if not any((not system or s == system) and v.casefold() == value.strip().casefold()
|
||||
for s, v in row["identifiers"]): # fmt: skip
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
@router.get(
|
||||
"/Patient",
|
||||
responses=_OK,
|
||||
response_class=Response,
|
||||
description=(
|
||||
"Patients, or the domain's follow-up list selected by window or start.\n\n"
|
||||
"For TEA, a cutoff or a TEA filter also selects the follow-up list. Patients without\n"
|
||||
"follow-up episodes appear only in the plain search."
|
||||
),
|
||||
)
|
||||
def search_patient(
|
||||
request: Request,
|
||||
domain: Domain,
|
||||
_id: str | None = Query(None, alias="_id"),
|
||||
window: int | None = _WINDOW,
|
||||
start: date | None = _START,
|
||||
cutoff: date | None = _CUTOFF,
|
||||
status: str | None = _STATUS,
|
||||
name: str | None = Query(
|
||||
None, description="each word starts a word of her name (case and accents ignored)"
|
||||
),
|
||||
identifier: str | None = Query(
|
||||
None, description="[system|]value: a CURP or record number (case ignored)"
|
||||
),
|
||||
sort: str = Query("-recent", alias="_sort", description="-recent or -risk-<outcome>"),
|
||||
horizon: float | None = Query(None, alias="risk-horizon", description="years"),
|
||||
revinclude: list[str] = Query([], alias="_revinclude", description=f"any of {REVINCLUDES}"),
|
||||
include: list[str] = Query([], alias="_include:iterate", description="DiagnosticReport:result"),
|
||||
_count: int | None = Query(None),
|
||||
_offset: int = Query(0),
|
||||
) -> Response:
|
||||
fu = _clinical(domain)
|
||||
count, offset = _page(_count, _offset)
|
||||
at = _cutoff(domain, cutoff)
|
||||
horizon = fu.DEFAULT_HORIZON if horizon is None else horizon
|
||||
try:
|
||||
rows, listed, applied = _patient_rows(
|
||||
request, domain, fu, at, window, start, cutoff, status, sort, _id
|
||||
)
|
||||
except ValueError as exc:
|
||||
return outcome(422, str(exc))
|
||||
if name or identifier:
|
||||
found = {r["person_id"] for r in _with_identity(domain, rows)
|
||||
if _matches(r, name, identifier)} # fmt: skip
|
||||
rows = [r for r in rows if r["person_id"] in found]
|
||||
persons = [r["person_id"] for r in rows]
|
||||
risks: dict[str, list[dict]] = {}
|
||||
if domain != Domain.TEA and (listed and sort != "-recent" or
|
||||
"RiskAssessment:subject" in revinclude): # fmt: skip
|
||||
for r in reads.rows(domain.value, "risk", persons=persons):
|
||||
risks.setdefault(r["person_id"], []).append(r)
|
||||
if listed:
|
||||
rows = fu.ordered(rows, sort, risks, horizon)
|
||||
page = _sliced(rows, count, offset)
|
||||
mine = {r["person_id"] for r in page}
|
||||
included = _included(domain, revinclude, include, sorted(mine), at,
|
||||
{p: v for p, v in risks.items() if p in mine}) # fmt: skip
|
||||
patients = [f.patient(r, fu.STATUS_SYSTEM) for r in _with_identity(domain, page)]
|
||||
return bundle(request, patients, len(rows), count, offset, included,
|
||||
applied) # fmt: skip
|
||||
|
||||
|
||||
def _patient_rows(
|
||||
request: Request,
|
||||
domain: Domain,
|
||||
fu,
|
||||
at: date,
|
||||
window: int | None,
|
||||
start: date | None,
|
||||
cutoff: date | None,
|
||||
status: str | None,
|
||||
sort: str = "-recent",
|
||||
_id: str | None = None,
|
||||
*,
|
||||
whole_history: bool = False,
|
||||
) -> tuple[list[dict], bool, dict]:
|
||||
filters = {
|
||||
name: request.query_params.getlist(name)
|
||||
for name in (TEA_FILTERS if domain == Domain.TEA else ())
|
||||
if name in request.query_params
|
||||
}
|
||||
if filters:
|
||||
fu.matches({}, filters)
|
||||
listed = (
|
||||
whole_history
|
||||
or start is not None
|
||||
or window is not None
|
||||
or bool(filters)
|
||||
or (hasattr(fu, "FILTERS") and cutoff is not None)
|
||||
)
|
||||
persons = reads.rows(domain.value, "persons")
|
||||
applied = {}
|
||||
if listed:
|
||||
if sort not in fu.SORTS:
|
||||
raise HTTPException(422, f"_sort is one of {fu.SORTS}")
|
||||
if start is None and window is not None:
|
||||
if window not in fu.WINDOWS:
|
||||
raise HTTPException(422, f"follow-up-window is one of {fu.WINDOWS}")
|
||||
start = window_start(at, window)
|
||||
start = start or date.min
|
||||
params = {"start": start.isoformat(), "cutoff": at.isoformat()}
|
||||
person = {r["person_id"]: r for r in persons}
|
||||
rows = [
|
||||
{**person[r["person_id"]], **r}
|
||||
for r in fu.listed(reads.rows(domain.value, "follow_up", **params), start, at)
|
||||
]
|
||||
applied = {"follow-up-cutoff": at.isoformat(), **filters}
|
||||
else:
|
||||
rows = [{**r, "status": fu.status(r, at)} for r in persons]
|
||||
if _id and (not listed or domain == Domain.TEA):
|
||||
ids = set(_id.split(","))
|
||||
rows = [r for r in rows if r["person_id"] in ids]
|
||||
if status:
|
||||
rows = [r for r in rows if r["status"] in status.split(",")]
|
||||
if filters:
|
||||
rows = [r for r in rows if fu.matches(r, filters)]
|
||||
return rows, listed, applied
|
||||
|
||||
|
||||
def _included(domain: Domain, revinclude: list[str], include: list[str], persons: list[str],
|
||||
at: date, risks: dict[str, list[dict]]) -> list[Resource]: # fmt: skip
|
||||
allowed = _revincludes(domain)
|
||||
unknown = set(revinclude) - set(allowed) | set(include) - {"DiagnosticReport:result"}
|
||||
if unknown:
|
||||
raise HTTPException(422, f"cannot include {sorted(unknown)}")
|
||||
found: list[Resource] = []
|
||||
reports = "DiagnosticReport:subject" in revinclude
|
||||
observations = "Observation:subject" in revinclude or (
|
||||
reports and "DiagnosticReport:result" in include
|
||||
)
|
||||
if reports or observations:
|
||||
for r in _studies(domain, persons, at.isoformat()):
|
||||
kind = r.get_resource_type()
|
||||
if (kind == "DiagnosticReport" and reports) or (kind == "Observation" and observations):
|
||||
found.append(r)
|
||||
if "Condition:subject" in revinclude:
|
||||
found += [f.condition(r) for r in reads.rows(domain.value, "condition", persons=persons,
|
||||
cutoff=at.isoformat())] # fmt: skip
|
||||
if "RiskAssessment:subject" in revinclude:
|
||||
if domain == Domain.TEA:
|
||||
found += _tea_risks(persons, at.isoformat())
|
||||
else:
|
||||
found += _risk_assessments([r for p in persons for r in risks.get(p, [])])
|
||||
return found
|
||||
|
||||
|
||||
def _revincludes(domain: Domain) -> tuple[str, ...]:
|
||||
return (*REVINCLUDES, "Condition:subject") if domain == Domain.TEA else REVINCLUDES
|
||||
|
||||
|
||||
def _subjects(subject: str | None) -> list[str]:
|
||||
if not subject:
|
||||
raise HTTPException(422, "subject is required (Patient/<id>, comma-separated)")
|
||||
return [s.removeprefix("Patient/") for s in subject.split(",")]
|
||||
|
||||
|
||||
def _studies(domain: Domain, persons: list[str], at: str) -> list[Resource]:
|
||||
found: list[Resource] = []
|
||||
report_facts = _clinical(domain).REPORT_FACTS
|
||||
if domain == Domain.TEA:
|
||||
births = {
|
||||
r["person_id"]: date.fromisoformat(f._day(r["birth_date"])) if r["birth_date"] else None
|
||||
for r in reads.rows(domain.value, "births", persons=persons)
|
||||
}
|
||||
for study in catalog.of_domain(domain.value):
|
||||
spec = catalog.studies()[study]
|
||||
facts = {}
|
||||
if kind := report_facts.get(study):
|
||||
found_facts = reads.rows(domain.value, kind, persons=persons, cutoff=at)
|
||||
facts = {(r["person_id"], str(r["sample_date"])[:10]): r["days"]
|
||||
for r in found_facts} # fmt: skip
|
||||
first = next(e.date for e in spec.events.values() if e.parent is None)
|
||||
for row in reads.instances(study, persons, at):
|
||||
days = facts.get((row["person_id"], str(row[first])[:10]))
|
||||
extra = [] if days is None else [f.ext("days-to-diagnosis", "integer", int(days))]
|
||||
known = f.known(study, row, at)
|
||||
found += f.instance(study, known, extra)
|
||||
if domain == Domain.TEA and study == "ados2":
|
||||
known["evaluation_date"] = date.fromisoformat(f._day(known["evaluation_date"]))
|
||||
found.append(tea_fhir.ados2_observation(known, births.get(row["person_id"])))
|
||||
if domain == Domain.TEA:
|
||||
found += _tea_eeg_studies(persons, at)
|
||||
return found
|
||||
|
||||
|
||||
def _tea_eeg_studies(persons: list[str], at: str) -> list[Resource]:
|
||||
def rows(kind):
|
||||
return reads.rows("tea", kind, persons=persons, cutoff=at)
|
||||
|
||||
def key(row):
|
||||
return row["person_id"], row["study_date"], row["edf"]
|
||||
|
||||
regions, results = defaultdict(list), defaultdict(list)
|
||||
for row in rows("regions"):
|
||||
regions[(*key(row), row["code"])].append(row)
|
||||
for row in rows("checks"):
|
||||
results[key(row)].append(tea_fhir.eeg_check(row))
|
||||
for row in rows("metrics"):
|
||||
results[key(row)].append(tea_fhir.eeg_metric(row, regions[(*key(row), row["code"])]))
|
||||
found = []
|
||||
for row in rows("eegs"):
|
||||
observations = results[key(row)]
|
||||
found.extend((tea_fhir.eeg_report(row, observations), *observations))
|
||||
return found
|
||||
|
||||
|
||||
def _tea_risks(persons: list[str], at: str) -> list[Resource]:
|
||||
groups = defaultdict(list)
|
||||
for row in reads.rows("tea", "association_scores", persons=persons, cutoff=at):
|
||||
group = groups[row["person_id"]]
|
||||
if (
|
||||
not group
|
||||
or row["edf"] == group[0]["edf"]
|
||||
and row["study_date"] == group[0]["study_date"]
|
||||
):
|
||||
group.append(row)
|
||||
return [tea_fhir.association_risk(group) for group in groups.values()]
|
||||
|
||||
|
||||
def _risk_assessments(rows: list[dict]) -> list[Resource]:
|
||||
groups: dict[tuple, list[dict]] = {}
|
||||
for r in rows:
|
||||
groups.setdefault((r["model"], r["version"], r["person_id"], str(r["index_date"])),
|
||||
[]).append(r) # fmt: skip
|
||||
return [f.risk_assessment(g[0], g) for g in groups.values()]
|
||||
|
||||
|
||||
def _clinical_search(kind: str, build, request, domain, subject, count, offset):
|
||||
fu = _clinical(domain)
|
||||
count, offset = _page(count, offset)
|
||||
params: dict = {"persons": _subjects(subject)}
|
||||
if kind != "risk":
|
||||
params["cutoff"] = _cutoff(domain, None).isoformat()
|
||||
if kind == "procedure":
|
||||
params["types"] = list(fu.PROCEDURES)
|
||||
if kind == "risk" and domain == Domain.TEA:
|
||||
found = _tea_risks(params["persons"], _cutoff(domain, None).isoformat())
|
||||
else:
|
||||
found = build(reads.rows(domain.value, kind, **params))
|
||||
return bundle(request, _sliced(found, count, offset), len(found), count, offset)
|
||||
|
||||
|
||||
SUBJECT = "Patient/<id>, comma-separated"
|
||||
|
||||
|
||||
@router.get(
|
||||
"/DiagnosticReport",
|
||||
responses=_OK,
|
||||
response_class=Response,
|
||||
description=(
|
||||
"The domain's reports (each study of the catalog with a report), "
|
||||
"as known by the last\n"
|
||||
"day with data."
|
||||
),
|
||||
)
|
||||
def search_diagnostic_report(request: Request, domain: Domain,
|
||||
subject: str | None = Query(None, description=SUBJECT),
|
||||
_count: int | None = Query(None),
|
||||
_offset: int = Query(0)) -> Response: # fmt: skip
|
||||
return _study_search("DiagnosticReport", request, domain, subject, _count, _offset)
|
||||
|
||||
|
||||
def _study_search(kind: str, request, domain, subject, count, offset) -> Response:
|
||||
_clinical(domain)
|
||||
count, offset = _page(count, offset)
|
||||
persons, at = _subjects(subject), _cutoff(domain, None).isoformat()
|
||||
found = [r for r in _studies(domain, persons, at) if r.get_resource_type() == kind]
|
||||
return bundle(request, _sliced(found, count, offset), len(found), count, offset)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/Encounter",
|
||||
responses=_OK,
|
||||
response_class=Response,
|
||||
description="Consultations: each study of the catalog without a report, as an encounter.",
|
||||
)
|
||||
def search_encounter(request: Request, domain: Domain,
|
||||
subject: str | None = Query(None, description=SUBJECT),
|
||||
_count: int | None = Query(None),
|
||||
_offset: int = Query(0)) -> Response: # fmt: skip
|
||||
return _study_search("Encounter", request, domain, subject, _count, _offset)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/Observation",
|
||||
responses=_OK,
|
||||
response_class=Response,
|
||||
description="Every result of the domain's reports, one per field of the catalog.",
|
||||
)
|
||||
def search_observation(request: Request, domain: Domain,
|
||||
subject: str | None = Query(None, description=SUBJECT),
|
||||
_count: int | None = Query(None),
|
||||
_offset: int = Query(0)) -> Response: # fmt: skip
|
||||
return _study_search("Observation", request, domain, subject, _count, _offset)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/Condition",
|
||||
responses=_OK,
|
||||
response_class=Response,
|
||||
description="What clinical notes diagnosed (CaMa: and each recurrence).",
|
||||
)
|
||||
def search_condition(request: Request, domain: Domain,
|
||||
subject: str | None = Query(None, description=SUBJECT),
|
||||
_count: int | None = Query(None),
|
||||
_offset: int = Query(0)) -> Response: # fmt: skip
|
||||
|
||||
def build(rows):
|
||||
return [f.condition(r) for r in rows]
|
||||
|
||||
return _clinical_search("condition", build, request, domain, subject, _count, _offset)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/Procedure",
|
||||
responses=_OK,
|
||||
response_class=Response,
|
||||
description=(
|
||||
"The procedures the domain's timeline infers (CaCu: colposcopies "
|
||||
"and treatments;\n"
|
||||
"CaMa: each treatment, by its kind)."
|
||||
),
|
||||
)
|
||||
def search_procedure(request: Request, domain: Domain,
|
||||
subject: str | None = Query(None, description=SUBJECT),
|
||||
_count: int | None = Query(None),
|
||||
_offset: int = Query(0)) -> Response: # fmt: skip
|
||||
|
||||
def build(rows):
|
||||
return [f.procedure(r, domain.value) for r in rows]
|
||||
|
||||
return _clinical_search("procedure", build, request, domain, subject, _count, _offset)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/RiskAssessment",
|
||||
responses=_OK,
|
||||
response_class=Response,
|
||||
description="The champion models' risks, one per model and index date.",
|
||||
)
|
||||
def search_risk_assessment(request: Request, domain: Domain,
|
||||
subject: str | None = Query(None, description=SUBJECT),
|
||||
_count: int | None = Query(None),
|
||||
_offset: int = Query(0)) -> Response: # fmt: skip
|
||||
return _clinical_search("risk", _risk_assessments, request, domain, subject, _count, _offset)
|
||||
|
||||
|
||||
def _measure(domain: Domain, key: str) -> m.Measure:
|
||||
found = measures(domain)
|
||||
for code, measure in found.items():
|
||||
if key in (code, f.measure_id(code), f.measure_url(code)):
|
||||
return measure
|
||||
raise HTTPException(404, f"no {domain.value} Measure {key}")
|
||||
|
||||
|
||||
@router.get("/Measure/{id}", responses=_OK, response_class=Response)
|
||||
def read_measure(domain: Domain, id: str) -> Response:
|
||||
return fhir(f.measure(_measure(domain, id), domain.value))
|
||||
|
||||
|
||||
@router.get(
|
||||
"/Measure",
|
||||
responses=_OK,
|
||||
response_class=Response,
|
||||
description="Every measure of the domain (none for a domain without them yet).",
|
||||
)
|
||||
def search_measure(request: Request, domain: Domain, _count: int | None = Query(None),
|
||||
_offset: int = Query(0)) -> Response: # fmt: skip
|
||||
count, offset = _page(_count, _offset)
|
||||
found = [f.measure(x, domain.value) for x in measures(domain).values()]
|
||||
return bundle(request, _sliced(found, count, offset), len(found), count, offset)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/MeasureReport",
|
||||
responses=_OK,
|
||||
response_class=Response,
|
||||
description="The measure's summary report for each period asked for, evaluated over gold.",
|
||||
)
|
||||
def search_measure_report(
|
||||
request: Request,
|
||||
domain: Domain,
|
||||
measure: str = Query(alias="measure", description="the Measure's id or canonical URL"),
|
||||
periods: str = Query(
|
||||
alias="reporting-period",
|
||||
description="semesters (2025-S1) or months (2025-03), comma-separated",
|
||||
),
|
||||
as_of: datetime | None = Query(
|
||||
None, alias="as-of", description="count only what was known by then"
|
||||
),
|
||||
event_cutoff: date | None = Query(
|
||||
None, alias="event-cutoff", description="durations count to this day"
|
||||
),
|
||||
_count: int | None = Query(None),
|
||||
_offset: int = Query(0),
|
||||
) -> Response:
|
||||
found = _measure(domain, measure.split("|")[0])
|
||||
count, offset = _page(_count, _offset)
|
||||
try:
|
||||
asked = [(p.strip(), m.Period.parse(p.strip())) for p in periods.split(",") if p.strip()]
|
||||
except ValueError as e:
|
||||
raise HTTPException(422, f"reporting-period: {e}") from e
|
||||
rows = measure_reads.rows(domain.value, found.rows, **found.params)
|
||||
reports = []
|
||||
page = _sliced(asked, count, offset)
|
||||
results = m.evaluate_periods(found, rows, [p for _, p in page], as_of, event_cutoff)
|
||||
for (text, period), result in zip(page, results, strict=True):
|
||||
report = m.report(found, period, result, as_of)
|
||||
report.id = f"{f.measure_id(found.id)}-{text.lower()}"
|
||||
reports.append(report)
|
||||
return bundle(request, reports, len(asked), count, offset)
|
||||
|
||||
|
||||
@router.post(
|
||||
"",
|
||||
responses=_OK,
|
||||
response_class=Response,
|
||||
status_code=202,
|
||||
description=(
|
||||
"A standard hospital's Bundle: checked as FHIR, kept as sent in "
|
||||
"the sender's inbox,\n"
|
||||
"and placed by the sender's pipeline (a run starts; follow it at "
|
||||
"the Location)."
|
||||
),
|
||||
)
|
||||
def post_bundle(
|
||||
domain: Domain,
|
||||
bundle: Annotated[dict[str, Any], Body(description="a FHIR R4 batch or transaction Bundle")],
|
||||
sender: str = Query(
|
||||
pattern=ID_PATTERN,
|
||||
max_length=40,
|
||||
description="the sender's pipeline (its fhir nodes read this inbox)",
|
||||
),
|
||||
client: DagsterGraphQLClient = Depends(dagster),
|
||||
) -> Response:
|
||||
try:
|
||||
parsed = Bundle.model_validate(bundle)
|
||||
except ValueError as e:
|
||||
raise HTTPException(422, f"not a valid R4 Bundle: {e}") from e
|
||||
if parsed.type not in ("batch", "transaction", "collection"):
|
||||
raise HTTPException(422, "send a batch, transaction or collection Bundle")
|
||||
if not config_log.latest_version(sender):
|
||||
raise HTTPException(404, f"no pipeline {sender} to place what it sends")
|
||||
readers.receive(sender, bundle)
|
||||
run_id = submit(client, sender)
|
||||
entries = [{"response": {"status": "202 Accepted", "location":
|
||||
f"{e.resource.get_resource_type()}/{e.resource.id}"}}
|
||||
for e in parsed.entry or [] if e.resource is not None] # fmt: skip
|
||||
answer = Bundle(type="batch-response", entry=entries or None)
|
||||
found = fhir(answer)
|
||||
found.status_code = 202
|
||||
found.headers["Location"] = f"/runs/{run_id}"
|
||||
return found
|
||||
|
||||
|
||||
@router.get(
|
||||
"/metadata",
|
||||
responses=_OK,
|
||||
response_class=Response,
|
||||
description=(
|
||||
"What this base serves: built from the routes above, so it cannot drift from them."
|
||||
),
|
||||
)
|
||||
def metadata(request: Request, domain: Domain) -> Response:
|
||||
resources: dict[str, dict] = {}
|
||||
system: list[dict] = []
|
||||
fu = part(domain, "follow_up")
|
||||
clinical = fu is not None
|
||||
for route in router.routes:
|
||||
path = route.path.removeprefix(router.prefix)
|
||||
if not path:
|
||||
if clinical:
|
||||
system = [{"code": "batch"}, {"code": "transaction"}]
|
||||
continue
|
||||
_, kind, *rest = path.split("/")
|
||||
if kind == "metadata" or (kind != "Measure" and kind != "MeasureReport"
|
||||
and not clinical): # fmt: skip
|
||||
continue
|
||||
if rest and rest[0].startswith("$"):
|
||||
continue
|
||||
entry = resources.setdefault(kind, {"type": kind, "interaction": [], "searchParam": []})
|
||||
if kind == "Patient" and not rest:
|
||||
entry |= {"searchInclude": ["DiagnosticReport:result"],
|
||||
"searchRevInclude": list(_revincludes(domain))} # fmt: skip
|
||||
if domain == Domain.TEA:
|
||||
entry["searchParam"] += [
|
||||
{"name": name, "type": spec[0]} for name, spec in TEA_FILTERS.items()
|
||||
]
|
||||
entry["interaction"].append({"code": "read" if rest else "search-type"})
|
||||
for param in route.dependant.query_params:
|
||||
name = param.alias
|
||||
if name.startswith("_") and name != "_id":
|
||||
continue
|
||||
declared = f.SEARCH_PARAMETERS.get(name)
|
||||
entry["searchParam"].append({
|
||||
"name": name,
|
||||
"type": declared[1] if declared else _STANDARD[name],
|
||||
**({"definition": f"{f.BASE}/SearchParameter/{name}"} if declared else {}),
|
||||
}) # fmt: skip
|
||||
statement = CapabilityStatement.model_validate({
|
||||
"resourceType": "CapabilityStatement",
|
||||
"status": "active",
|
||||
"date": date.today().isoformat(),
|
||||
"kind": "instance",
|
||||
"fhirVersion": f.FHIR_VERSION,
|
||||
"format": ["json"],
|
||||
"implementation": {"description": f"ISSSTELEON {domain.value}",
|
||||
"url": str(request.base_url).rstrip("/") + f"/{domain.value}/fhir"},
|
||||
"rest": [{"mode": "server",
|
||||
"resource": [{k: v for k, v in r.items() if v} for r in resources.values()],
|
||||
**({"interaction": system} if system else {})}],
|
||||
}) # fmt: skip
|
||||
return fhir(statement)
|
||||
|
||||
|
||||
_STANDARD = {
|
||||
"_id": "token",
|
||||
"subject": "reference",
|
||||
"measure": "reference",
|
||||
"follow-up-start": "date",
|
||||
"name": "string",
|
||||
"identifier": "token",
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
"""Import sources. Each module registers its connector class on import;
|
||||
the order here is the order the catalog lists them in."""
|
||||
from webapi.imports.connectors import csv_, excel, json_, pdf, document, edf, sql # noqa: F401 (catalog order)
|
||||
from webapi.imports.connectors.base import Connector, PreviewResult, SourceColumn, SourceTable
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
from webapi.imports.connectors.registry import (
|
||||
CONNECTORS,
|
||||
build_connector,
|
||||
catalog,
|
||||
connector_class,
|
||||
kind_for_filename,
|
||||
register_connector,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"CONNECTORS",
|
||||
"Connector",
|
||||
"ConnectorError",
|
||||
"PreviewResult",
|
||||
"SourceColumn",
|
||||
"SourceTable",
|
||||
"build_connector",
|
||||
"catalog",
|
||||
"connector_class",
|
||||
"kind_for_filename",
|
||||
"register_connector",
|
||||
]
|
||||
@@ -1,93 +0,0 @@
|
||||
import base64
|
||||
import binascii
|
||||
from abc import ABC, abstractmethod
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, ClassVar, Iterator
|
||||
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SourceColumn:
|
||||
name: str
|
||||
inferred_type: str # "string" | "integer" | "float" | "boolean" | "date" | "datetime" | "binary" | "unknown"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PreviewResult:
|
||||
columns: list[SourceColumn]
|
||||
sample_rows: list[dict[str, Any]]
|
||||
total_rows: int | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SourceTable:
|
||||
"""One table a source offers: an Excel sheet, a section of an EDF
|
||||
file. `options` is what to send back to read that table."""
|
||||
|
||||
name: str
|
||||
options: dict[str, Any] = field(default_factory=dict)
|
||||
kind: str = "table"
|
||||
|
||||
|
||||
class Connector(ABC):
|
||||
"""A data source that can be read as columns and rows.
|
||||
|
||||
Adding a source means subclassing this (or `FileConnector` for an
|
||||
uploaded file), setting the class attributes below, implementing
|
||||
`from_payload`, and decorating the class with `@register_connector`.
|
||||
The import pipeline, the `/imports/connectors` catalog and the web
|
||||
client pick it up from there.
|
||||
"""
|
||||
|
||||
kind: ClassVar[str]
|
||||
label: ClassVar[str]
|
||||
description: ClassVar[str] = ""
|
||||
category: ClassVar[str] # "file" | "database" | "document" | "signal"
|
||||
icon: ClassVar[str] = "table_view"
|
||||
extensions: ClassVar[tuple[str, ...]] = ()
|
||||
|
||||
@classmethod
|
||||
@abstractmethod
|
||||
def from_payload(cls, payload: dict[str, Any]) -> "Connector":
|
||||
"""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: ...
|
||||
|
||||
@abstractmethod
|
||||
def read_rows(self, column_mapping: dict[str, str]) -> Iterator[dict[str, Any]]:
|
||||
"""`column_mapping`: source column -> target field. Yields one dict
|
||||
per row keyed by target field. Values are not validated here."""
|
||||
|
||||
def tables(self) -> list[SourceTable]:
|
||||
"""The tables this source offers, when it has more than one."""
|
||||
return []
|
||||
|
||||
def metadata(self) -> dict[str, Any]:
|
||||
"""Source-specific facts worth showing (a CSV's delimiter, ...)."""
|
||||
return {}
|
||||
|
||||
@classmethod
|
||||
def describe(cls) -> dict[str, Any]:
|
||||
return {
|
||||
"kind": cls.kind,
|
||||
"label": cls.label,
|
||||
"description": cls.description,
|
||||
"category": cls.category,
|
||||
"icon": cls.icon,
|
||||
"extensions": list(cls.extensions),
|
||||
}
|
||||
|
||||
|
||||
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
|
||||
except (binascii.Error, ValueError, TypeError) as exc:
|
||||
raise ConnectorError(f"{key} is not valid base64: {exc}") from exc
|
||||
@@ -1,72 +0,0 @@
|
||||
import csv
|
||||
import io
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
from webapi.imports.connectors.registry import register_connector
|
||||
from webapi.imports.connectors.tabular import FileConnector
|
||||
|
||||
_CANDIDATE_DELIMITERS = ",;\t|"
|
||||
# utf-8-sig strips the BOM Excel prepends when it exports "CSV UTF-8" (it
|
||||
# would otherwise end up glued to the first column's name); cp1252 is what
|
||||
# Excel on Windows writes for plain "CSV" in a Spanish locale.
|
||||
_FALLBACK_ENCODINGS = ("utf-8-sig", "cp1252")
|
||||
|
||||
|
||||
@register_connector
|
||||
class CsvConnector(FileConnector):
|
||||
"""Every cell is read as text: pandas' type guessing would turn the
|
||||
postal code `01000` into `1000` before validation sees it."""
|
||||
|
||||
kind = "csv"
|
||||
label = "Texto / CSV"
|
||||
description = "Archivos delimitados por comas, punto y coma o tabuladores"
|
||||
category = "file"
|
||||
icon = "table_view"
|
||||
extensions = ("csv", "txt", "tsv")
|
||||
option_names = ("delimiter", "encoding")
|
||||
|
||||
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")
|
||||
self._delimiter = delimiter or _sniff_delimiter(text)
|
||||
try:
|
||||
self._df = pd.read_csv(
|
||||
io.StringIO(text),
|
||||
sep=self._delimiter,
|
||||
dtype=str,
|
||||
keep_default_na=False,
|
||||
na_values=[""],
|
||||
skipinitialspace=True,
|
||||
)
|
||||
except Exception as exc: # pandas raises a variety of error types
|
||||
raise ConnectorError(f"could not parse CSV: {exc}") from exc
|
||||
self._df.columns = [str(c).strip() for c in self._df.columns]
|
||||
|
||||
def _dataframe(self) -> pd.DataFrame:
|
||||
return self._df
|
||||
|
||||
def metadata(self) -> dict:
|
||||
return {"delimiter": self._delimiter, "encoding": self._encoding}
|
||||
|
||||
|
||||
def _decode(raw: bytes, encoding: str | None) -> tuple[str, str]:
|
||||
for candidate in (encoding,) if encoding else _FALLBACK_ENCODINGS:
|
||||
try:
|
||||
return candidate, raw.decode(candidate)
|
||||
except (UnicodeDecodeError, LookupError):
|
||||
continue
|
||||
raise ConnectorError(f"could not decode CSV as {encoding or ' / '.join(_FALLBACK_ENCODINGS)}")
|
||||
|
||||
|
||||
def _sniff_delimiter(text: str) -> str:
|
||||
"""`csv.Sniffer` restricted to real delimiters. pandas' own `sep=None`
|
||||
sniffing picks letters as delimiters on single-column files (`id\\nH3`
|
||||
parsed as columns `['Unnamed: 0', 'd']`)."""
|
||||
sample = "\n".join(text.splitlines()[:50])
|
||||
try:
|
||||
return csv.Sniffer().sniff(sample, delimiters=_CANDIDATE_DELIMITERS).delimiter
|
||||
except csv.Error:
|
||||
return ","
|
||||
@@ -1,229 +0,0 @@
|
||||
import hashlib
|
||||
import json
|
||||
import threading
|
||||
from collections import OrderedDict
|
||||
from typing import Any, ClassVar
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from extraction import DocumentExtractor, ExtractedRecord, ExtractionError, make_segmenter, read_document, reader_for
|
||||
from extraction.readers import PdfReader, combine_pages, supported_extensions
|
||||
from extraction.segmentation import SEGMENTERS
|
||||
from webapi.imports.connectors.base import decode_file
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
from webapi.imports.connectors.registry import register_connector
|
||||
from webapi.imports.connectors.tabular import DataFrameConnector
|
||||
from webapi.imports.schemas.field_specs import field_specs_for, key_field_for
|
||||
from webapi.imports.schemas.registry import ENTITY_REGISTRY
|
||||
|
||||
DOCUMENT_COLUMN = "documento"
|
||||
IMAGE_COLUMN = "imagen"
|
||||
CONFIDENCE_COLUMN = "confianza_extraccion"
|
||||
SOURCES_COLUMN = "origen"
|
||||
|
||||
|
||||
class _ResultCache:
|
||||
"""OCR over a stack of scans is slow, and the stateless API runs the
|
||||
same extraction for preview, validation and commit. Results are kept
|
||||
per worker for the last few distinct requests."""
|
||||
|
||||
def __init__(self, size: int = 8):
|
||||
self._items: OrderedDict[str, list[ExtractedRecord]] = OrderedDict()
|
||||
self._size = size
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def get_or_compute(self, key: str, compute) -> list[ExtractedRecord]:
|
||||
with self._lock:
|
||||
if key in self._items:
|
||||
self._items.move_to_end(key)
|
||||
return self._items[key]
|
||||
value = compute()
|
||||
with self._lock:
|
||||
self._items[key] = value
|
||||
while len(self._items) > self._size:
|
||||
self._items.popitem(last=False)
|
||||
return value
|
||||
|
||||
|
||||
_CACHE = _ResultCache()
|
||||
|
||||
|
||||
@register_connector
|
||||
class DocumentConnector(DataFrameConnector):
|
||||
"""Clinical documents that are not tables: one report per patient,
|
||||
several pages per patient, many patients per file, scans, free text.
|
||||
|
||||
Every file is read page by page (text layer or OCR), split into
|
||||
per-patient records, and the target entity's fields are extracted from
|
||||
labels and narrative text. Records of the same patient found in other
|
||||
pages or files are merged. Each row also carries the record's pages as
|
||||
a PDF (`documento`), mappable to the entity's file column.
|
||||
|
||||
Corrections made while reviewing travel in `overrides`
|
||||
(`{"<row>": {"field": value}}`) and win over the extracted value.
|
||||
"""
|
||||
|
||||
kind = "document"
|
||||
label = "Documentos clínicos"
|
||||
description = "Reportes, formatos y notas en PDF o imagen; los campos se extraen del texto libre"
|
||||
category = "document"
|
||||
icon = "document_scanner"
|
||||
extensions: ClassVar[tuple[str, ...]] = tuple(supported_extensions())
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
files: list[tuple[str, bytes]],
|
||||
*,
|
||||
target: str,
|
||||
segmentation: str = "auto",
|
||||
pages_per_record: int = 1,
|
||||
ocr_mode: str = "auto",
|
||||
key_pattern: str | None = None,
|
||||
overrides: dict[str, dict[str, Any]] | None = None,
|
||||
):
|
||||
if not files:
|
||||
raise ConnectorError("no documents given")
|
||||
entity = ENTITY_REGISTRY.get(target)
|
||||
if entity is None:
|
||||
raise ConnectorError(f"unknown target: {target!r}")
|
||||
if segmentation not in SEGMENTERS:
|
||||
raise ConnectorError(f"unknown segmentation {segmentation!r} (available: {', '.join(SEGMENTERS)})")
|
||||
if ocr_mode not in ("auto", "always", "never"):
|
||||
raise ConnectorError(f"unknown ocr_mode {ocr_mode!r}")
|
||||
self.files = files
|
||||
self.target = target
|
||||
self.specs = field_specs_for(entity, key_pattern=key_pattern)
|
||||
self.key_field = key_field_for(entity)
|
||||
self.segmentation = segmentation
|
||||
self.pages_per_record = max(1, int(pages_per_record))
|
||||
self.ocr_mode = ocr_mode
|
||||
self.key_pattern = key_pattern
|
||||
self.overrides = {str(k): v for k, v in (overrides or {}).items()}
|
||||
self._df: pd.DataFrame | None = None
|
||||
|
||||
@classmethod
|
||||
def from_payload(cls, payload: dict[str, Any]) -> "DocumentConnector":
|
||||
files = [(f.get("name") or f"documento_{i}", decode_file(f)) for i, f in enumerate(payload.get("files") or [], 1)]
|
||||
return cls(
|
||||
files,
|
||||
target=payload["target"],
|
||||
segmentation=payload.get("segmentation", "auto"),
|
||||
pages_per_record=payload.get("pages_per_record", 1),
|
||||
ocr_mode=payload.get("ocr_mode", "auto"),
|
||||
key_pattern=payload.get("key_pattern") or None,
|
||||
overrides=payload.get("overrides"),
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def describe(cls) -> dict[str, Any]:
|
||||
segmentations = [{"id": name, "label": segmenter.label} for name, segmenter in SEGMENTERS.items()]
|
||||
return {**super().describe(), "segmentations": segmentations}
|
||||
|
||||
# -- extraction -----------------------------------------------------------
|
||||
|
||||
@property
|
||||
def records(self) -> list[ExtractedRecord]:
|
||||
return _CACHE.get_or_compute(self._cache_key(), self._extract)
|
||||
|
||||
def _extract(self) -> list[ExtractedRecord]:
|
||||
try:
|
||||
documents = [read_document(name, raw, ocr_mode=self.ocr_mode) for name, raw in self.files]
|
||||
except ExtractionError as exc:
|
||||
raise ConnectorError(str(exc)) from exc
|
||||
segmenter = make_segmenter(
|
||||
self.segmentation,
|
||||
key=next((s for s in self.specs if s.name == self.key_field), None),
|
||||
pages_per_record=self.pages_per_record,
|
||||
)
|
||||
return DocumentExtractor(self.specs, key_field=self.key_field, segmenter=segmenter).extract(documents)
|
||||
|
||||
def _cache_key(self) -> str:
|
||||
digest = hashlib.sha256()
|
||||
for name, raw in self.files:
|
||||
digest.update(name.encode())
|
||||
digest.update(hashlib.sha256(raw).digest())
|
||||
config = [self.target, self.segmentation, self.pages_per_record, self.ocr_mode, self.key_pattern]
|
||||
digest.update(json.dumps(config).encode())
|
||||
return digest.hexdigest()
|
||||
|
||||
# -- rows -----------------------------------------------------------------
|
||||
|
||||
def _dataframe(self) -> pd.DataFrame:
|
||||
if self._df is None:
|
||||
columns = [spec.name for spec in self.specs] + [DOCUMENT_COLUMN, IMAGE_COLUMN, CONFIDENCE_COLUMN, SOURCES_COLUMN]
|
||||
rows = [self._row(index, record) for index, record in enumerate(self.records)]
|
||||
self._df = pd.DataFrame(rows, columns=columns, dtype=object)
|
||||
return self._df
|
||||
|
||||
def _row(self, index: int, record: ExtractedRecord) -> dict[str, Any]:
|
||||
row: dict[str, Any] = record.row()
|
||||
row.update(self.overrides.get(str(index), {}))
|
||||
row[DOCUMENT_COLUMN] = self._record_pdf(record)
|
||||
row[IMAGE_COLUMN] = self._record_image(record)
|
||||
row[CONFIDENCE_COLUMN] = round(record.confidence, 3)
|
||||
row[SOURCES_COLUMN] = "; ".join(f"{s.document} p. {', '.join(map(str, s.page_numbers))}" for s in record.sources)
|
||||
return row
|
||||
|
||||
def _record_pdf(self, record: ExtractedRecord) -> bytes | None:
|
||||
"""The record's pages from every PDF it was found in, as one PDF."""
|
||||
by_name = dict(self.files)
|
||||
parts = [
|
||||
(by_name[source.document], source.page_numbers)
|
||||
for source in record.sources
|
||||
if source.document in by_name and PdfReader.accepts(source.document, by_name[source.document][:8])
|
||||
]
|
||||
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."""
|
||||
by_name = dict(self.files)
|
||||
candidates = [(document, image) for document, image in record.images if document in by_name]
|
||||
if not candidates:
|
||||
return None
|
||||
figures = [c for c in candidates if c[1].kind == "figure"]
|
||||
document, image = figures[0] if figures else candidates[0]
|
||||
raw = by_name[document]
|
||||
try:
|
||||
return reader_for(document, raw).render_region(raw, image.page_number, image.bbox)
|
||||
except ExtractionError:
|
||||
return None
|
||||
|
||||
# -- review ---------------------------------------------------------------
|
||||
|
||||
def report(self) -> list[dict[str, Any]]:
|
||||
"""Per record: every extracted value with its confidence, method and
|
||||
the line it was read from, conflicts between sources, and the
|
||||
images found on its pages."""
|
||||
report = []
|
||||
for index, record in enumerate(self.records):
|
||||
overrides = self.overrides.get(str(index), {})
|
||||
fields = {name: value.to_dict() for name, value in record.values.items()}
|
||||
for name, value in overrides.items():
|
||||
fields[name] = {**fields.get(name, {}), "value": value, "method": "manual", "confidence": 1.0}
|
||||
report.append(
|
||||
{
|
||||
"index": index,
|
||||
"key": record.key,
|
||||
"confidence": round(record.confidence, 3),
|
||||
"fields": fields,
|
||||
"missing": [s.name for s in self.specs if s.required and s.name not in fields],
|
||||
"conflicts": [
|
||||
{"field": c.field, "kept": c.kept.to_dict(), "discarded": c.discarded.to_dict()}
|
||||
for c in record.conflicts
|
||||
],
|
||||
"sources": [{"document": s.document, "page_numbers": s.page_numbers} for s in record.sources],
|
||||
"images": [
|
||||
{"document": name, "page_number": image.page_number, "bbox": image.bbox.as_list(), "kind": image.kind}
|
||||
for name, image in record.images
|
||||
],
|
||||
}
|
||||
)
|
||||
return report
|
||||
|
||||
def metadata(self) -> dict[str, Any]:
|
||||
return {"records": len(self.records), "key_field": self.key_field, "documents": [name for name, _ in self.files]}
|
||||
@@ -1,104 +0,0 @@
|
||||
from datetime import date, timedelta
|
||||
from pathlib import PurePath
|
||||
from typing import Any
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from extraction import ExtractionError
|
||||
from extraction.signals import EegRecording
|
||||
from webapi.imports.connectors.base import decode_file
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
from webapi.imports.connectors.registry import register_connector
|
||||
from webapi.imports.connectors.tabular import FileConnector
|
||||
|
||||
MAX_LISTED_EVENTS = 20
|
||||
|
||||
|
||||
@register_connector
|
||||
class EdfConnector(FileConnector):
|
||||
"""EEG recordings (`.edf`), one row per file, shaped for `tea.EegEstudio`:
|
||||
patient and dates from the header, an estimated background rhythm from
|
||||
the posterior channels, a text summary of the recording, and the file
|
||||
itself (column `estudio`, stored in `eeg_estudio.eeg_estudio`)."""
|
||||
|
||||
kind = "edf"
|
||||
label = "EEG (EDF)"
|
||||
description = "Registros de electroencefalografía en European Data Format"
|
||||
category = "signal"
|
||||
icon = "monitor_heart"
|
||||
extensions = ("edf",)
|
||||
option_names = ("file_name",)
|
||||
|
||||
def __init__(self, raw: bytes, *, file_name: str = "registro.edf"):
|
||||
self.files = [(file_name, raw)]
|
||||
self._df: pd.DataFrame | None = None
|
||||
|
||||
@classmethod
|
||||
def from_payload(cls, payload: dict[str, Any]) -> "EdfConnector":
|
||||
"""Accepts 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
|
||||
|
||||
def metadata(self) -> dict[str, Any]:
|
||||
return {"files": [name for name, _ in self.files]}
|
||||
|
||||
def _dataframe(self) -> pd.DataFrame:
|
||||
if self._df is None:
|
||||
self._df = pd.DataFrame([self._row(name, raw) for name, raw in self.files], dtype=object)
|
||||
return self._df
|
||||
|
||||
def _row(self, name: str, raw: bytes) -> dict[str, Any]:
|
||||
try:
|
||||
eeg = EegRecording.read(raw)
|
||||
except ExtractionError as exc:
|
||||
raise ConnectorError(f"{name}: {exc}") from exc
|
||||
patient = eeg.patient
|
||||
study_date = eeg.start.date() if eeg.start else None
|
||||
rhythm = eeg.background_rhythm()
|
||||
return {
|
||||
"id_registro_laboratorio": eeg.recording_fields["admin_code"] or PurePath(name).stem,
|
||||
"paciente": patient.code,
|
||||
"sexo": patient.sex,
|
||||
"fecha_nacimiento_declarada": patient.birthdate,
|
||||
"edad_meses": age_in_months(patient.birthdate, study_date),
|
||||
"fecha_estudio": study_date,
|
||||
"duracion_min": round(eeg.duration_seconds / 60) if eeg.duration_seconds else None,
|
||||
"ritmo_base_frecuencia": rhythm["frequency_hz"],
|
||||
"ritmo_base_amplitud": rhythm["amplitude_uv"],
|
||||
"descripcion_senal": describe(eeg),
|
||||
"archivo": name,
|
||||
"estudio": raw,
|
||||
}
|
||||
|
||||
|
||||
def describe(eeg: EegRecording) -> str:
|
||||
channels = eeg.channels
|
||||
parts = [
|
||||
f"{eeg.variant}, {len(channels)} canales a {channels[0].sample_rate:g} Hz" if channels else eeg.variant,
|
||||
f"duración {timedelta(seconds=round(eeg.duration_seconds))}",
|
||||
"montaje: " + ", ".join(c.label for c in channels),
|
||||
]
|
||||
fields = eeg.recording_fields
|
||||
if fields["equipment"]:
|
||||
parts.append(f"equipo: {fields['equipment']}")
|
||||
if fields["technician"]:
|
||||
parts.append(f"técnico: {fields['technician']}")
|
||||
events = eeg.annotations()
|
||||
if events:
|
||||
listed = "; ".join(f"{timedelta(seconds=round(e.onset_seconds))} {e.text}" for e in events[:MAX_LISTED_EVENTS])
|
||||
more = f" (+{len(events) - MAX_LISTED_EVENTS})" if len(events) > MAX_LISTED_EVENTS else ""
|
||||
parts.append(f"eventos: {listed}{more}")
|
||||
return ". ".join(parts) + "."
|
||||
|
||||
|
||||
def age_in_months(birthdate: date | None, on: date | None) -> float | None:
|
||||
if birthdate is None or on is None or on < birthdate:
|
||||
return None
|
||||
months = (on.year - birthdate.year) * 12 + (on.month - birthdate.month)
|
||||
if on.day < birthdate.day:
|
||||
months -= 1
|
||||
return float(months)
|
||||
@@ -1,3 +0,0 @@
|
||||
class ConnectorError(Exception):
|
||||
"""Raised by any `Connector` subclass for malformed input, a bad
|
||||
connection string, an unreadable file, etc."""
|
||||
@@ -1,49 +0,0 @@
|
||||
import io
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
from webapi.imports.connectors.base import SourceTable
|
||||
from webapi.imports.connectors.registry import register_connector
|
||||
from webapi.imports.connectors.tabular import FileConnector
|
||||
|
||||
|
||||
@register_connector
|
||||
class ExcelConnector(FileConnector):
|
||||
"""`dtype=object` keeps each cell as the value openpyxl read; column
|
||||
typing would turn an integer column with a blank cell into floats."""
|
||||
|
||||
kind = "excel"
|
||||
label = "Libro de Excel"
|
||||
description = "Cada hoja del libro se ofrece como tabla"
|
||||
category = "file"
|
||||
icon = "grid_on"
|
||||
extensions = ("xlsx", "xlsm")
|
||||
option_names = ("sheet_name",)
|
||||
|
||||
def __init__(self, raw: bytes, *, sheet_name: str | int | None = None):
|
||||
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
|
||||
|
||||
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}")
|
||||
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
|
||||
self._df.columns = [str(c).strip() for c in self._df.columns]
|
||||
|
||||
def list_sheets(self) -> list[str]:
|
||||
return list(self._workbook.sheet_names)
|
||||
|
||||
def tables(self) -> list[SourceTable]:
|
||||
return [SourceTable(name, {"sheet_name": name}, kind="sheet") for name in self.list_sheets()]
|
||||
|
||||
def _dataframe(self) -> pd.DataFrame:
|
||||
return self._df
|
||||
|
||||
def metadata(self) -> dict:
|
||||
return {"sheets": self.list_sheets(), "sheet_name": self._sheet}
|
||||
@@ -1,61 +0,0 @@
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
from webapi.imports.connectors.registry import register_connector
|
||||
from webapi.imports.connectors.tabular import FileConnector
|
||||
|
||||
|
||||
@register_connector
|
||||
class JsonConnector(FileConnector):
|
||||
"""Nested objects are flattened to dotted column names
|
||||
(`paciente.sexo`) into an object-dtype DataFrame, so JSON's own types
|
||||
survive (`json_normalize` turns a sometimes-missing integer into floats)."""
|
||||
|
||||
kind = "json"
|
||||
label = "JSON"
|
||||
description = "Lista de registros; los objetos anidados se aplanan"
|
||||
category = "file"
|
||||
icon = "data_object"
|
||||
extensions = ("json",)
|
||||
option_names = ("record_path",)
|
||||
|
||||
def __init__(self, raw: bytes, *, record_path: str | None = None):
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not parse 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
|
||||
|
||||
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")
|
||||
|
||||
self._record_path = record_path
|
||||
self._df = pd.DataFrame([_flatten(record) for record in data], dtype=object)
|
||||
|
||||
def _dataframe(self) -> pd.DataFrame:
|
||||
return self._df
|
||||
|
||||
def metadata(self) -> dict:
|
||||
return {"record_path": self._record_path}
|
||||
|
||||
|
||||
def _flatten(record: dict[str, Any], prefix: str = "") -> dict[str, Any]:
|
||||
flat: dict[str, Any] = {}
|
||||
for key, value in record.items():
|
||||
name = f"{prefix}{key}"
|
||||
if isinstance(value, dict):
|
||||
flat.update(_flatten(value, f"{name}."))
|
||||
else:
|
||||
flat[name] = value
|
||||
return flat
|
||||
@@ -1,353 +0,0 @@
|
||||
"""PDF tables. Two ways to turn a PDF into rows:
|
||||
|
||||
- `select_table`: a ruled table found by pdfplumber in the text layer;
|
||||
- `extract_regions`: one drawn box per column over the rendered page. Each
|
||||
box is read from the text layer or OCR'd, and lines from all boxes on a
|
||||
page are aligned into rows by their vertical position.
|
||||
|
||||
Documents that are not tables (one report per patient, free text) go
|
||||
through `DocumentConnector` instead.
|
||||
"""
|
||||
import io
|
||||
import statistics
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
import pandas as pd
|
||||
import pdfplumber
|
||||
import pytesseract
|
||||
from pytesseract import Output
|
||||
|
||||
from extraction.ocr import DEFAULT_LANG, group_words
|
||||
from webapi.imports.connectors.base import decode_file
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
from webapi.imports.connectors.registry import register_connector
|
||||
from webapi.imports.connectors.tabular import DataFrameConnector
|
||||
|
||||
_DEFAULT_SAMPLE_PAGES = 3
|
||||
_DEFAULT_CHAR_THRESHOLD = 20
|
||||
_DEFAULT_DPI = 150
|
||||
# Rendering memory grows with dpi². Past ~300 dpi OCR gains nothing and a
|
||||
# single request could exhaust the worker.
|
||||
_MIN_DPI, _MAX_DPI = 50, 300
|
||||
# PSM 6 (one uniform block): a region is a narrow column of stacked lines;
|
||||
# full-page segmentation (PSM 3) drops short crops such as a lone "F".
|
||||
_OCR_CONFIG = "--psm 6"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TableCandidate:
|
||||
page_number: int # 1-indexed
|
||||
bbox: tuple[float, float, float, float] # PDF points, pdfplumber's native space
|
||||
grid: list[list[str | None]] # header row + data rows
|
||||
confidence: float # ranking heuristic only, not ML
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RegionSpec:
|
||||
target_field: str
|
||||
page_numbers: list[int] # 1-indexed
|
||||
bbox: tuple[float, float, float, float] # normalized 0..1 over the rendered page
|
||||
|
||||
@classmethod
|
||||
def parse(cls, raw: dict[str, Any]) -> "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
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ExtractionWarning:
|
||||
page_number: int
|
||||
message: str
|
||||
|
||||
|
||||
@register_connector
|
||||
class PdfConnector(DataFrameConnector):
|
||||
kind = "pdf"
|
||||
label = "PDF (tablas)"
|
||||
description = "Tablas detectadas o columnas dibujadas sobre la página (OCR para escaneos)"
|
||||
category = "document"
|
||||
icon = "picture_as_pdf"
|
||||
extensions = ("pdf",)
|
||||
|
||||
@classmethod
|
||||
def from_payload(cls, payload: dict[str, Any]) -> "PdfConnector":
|
||||
connector = cls(decode_file(payload))
|
||||
mode = payload.get("mode", "table")
|
||||
if mode == "table":
|
||||
connector.select_table(int(payload["page_number"]), tuple(float(v) for v in payload["bbox"]))
|
||||
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}")
|
||||
return connector
|
||||
|
||||
def __init__(self, file_bytes: bytes):
|
||||
self.file_bytes = file_bytes
|
||||
try:
|
||||
self._pdf = pdfplumber.open(io.BytesIO(file_bytes))
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not open PDF: {exc}") from exc
|
||||
|
||||
self._table_grid: list[list[str | None]] | None = None
|
||||
self._region_rows: dict[str, list[str | None]] | None = None
|
||||
self.warnings: list[ExtractionWarning] = []
|
||||
|
||||
@property
|
||||
def page_count(self) -> int:
|
||||
return len(self._pdf.pages)
|
||||
|
||||
def has_text_layer(self, sample_pages: int = _DEFAULT_SAMPLE_PAGES, char_threshold: int = _DEFAULT_CHAR_THRESHOLD) -> bool:
|
||||
return any(self._page_has_text(page, char_threshold) for page in self._pdf.pages[:sample_pages])
|
||||
|
||||
@staticmethod
|
||||
def _page_has_text(page, char_threshold: int = _DEFAULT_CHAR_THRESHOLD) -> bool:
|
||||
try:
|
||||
text = page.extract_text() or ""
|
||||
except Exception:
|
||||
return False
|
||||
return len(text.strip()) >= char_threshold
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Ruled tables found by pdfplumber in the text layer
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def detect_tables(self) -> list[TableCandidate]:
|
||||
candidates: list[TableCandidate] = []
|
||||
for page in self._pdf.pages:
|
||||
try:
|
||||
tables = page.find_tables()
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not detect tables on page {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
|
||||
if len(grid) < 2:
|
||||
continue # header + >=1 data row required
|
||||
candidates.append(
|
||||
TableCandidate(
|
||||
page_number=page.page_number,
|
||||
bbox=tuple(table.bbox),
|
||||
grid=grid,
|
||||
confidence=_table_confidence(grid),
|
||||
)
|
||||
)
|
||||
candidates.sort(key=lambda c: c.confidence, reverse=True)
|
||||
return candidates
|
||||
|
||||
def select_table(self, page_number: int, bbox: tuple[float, float, float, float]) -> None:
|
||||
page = self._page(page_number)
|
||||
try:
|
||||
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
|
||||
if not grid or len(grid) < 2:
|
||||
raise ConnectorError(f"no usable table found at {bbox} on page {page_number}")
|
||||
self._table_grid = grid
|
||||
self._region_rows = None
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Drawn regions over the rendered page, read from text or OCR, then aligned
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def render_page_image(self, page_number: int, dpi: int = _DEFAULT_DPI) -> bytes:
|
||||
_check_dpi(dpi)
|
||||
page = self._page(page_number)
|
||||
try:
|
||||
image = page.to_image(resolution=dpi).original
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not render page {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")
|
||||
_check_dpi(dpi)
|
||||
|
||||
by_page: dict[int, list[RegionSpec]] = {}
|
||||
for region in regions:
|
||||
for page_number in region.page_numbers:
|
||||
by_page.setdefault(page_number, []).append(region)
|
||||
|
||||
self.warnings = []
|
||||
result: dict[str, list[str | None]] = {region.target_field: [] for region in regions}
|
||||
|
||||
for page_number in sorted(by_page):
|
||||
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))
|
||||
|
||||
self._region_rows = result
|
||||
self._table_grid = None
|
||||
return result
|
||||
|
||||
def _lines_for_page(self, page, regions_on_page: list[RegionSpec], dpi: int) -> list[dict[str, Any]]:
|
||||
"""Collect `(target_field, y, height, text)` lines for every region
|
||||
on one page. Y is in page pixels at `dpi` whether the region was read
|
||||
from the text layer or OCR'd, so lines from all regions can be aligned."""
|
||||
scale = dpi / 72.0
|
||||
use_text_layer = self._page_has_text(page)
|
||||
rendered_image = None
|
||||
lines: list[dict[str, Any]] = []
|
||||
|
||||
for region in regions_on_page:
|
||||
x0n, y0n, x1n, y1n = region.bbox
|
||||
|
||||
if use_text_layer:
|
||||
point_bbox = self._clamp_to_page(
|
||||
(x0n * page.width, y0n * page.height, x1n * page.width, y1n * page.height),
|
||||
page,
|
||||
)
|
||||
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
|
||||
for line in region_lines:
|
||||
text = (line.get("text") or "").strip()
|
||||
if not text:
|
||||
continue
|
||||
lines.append(
|
||||
{
|
||||
"target_field": region.target_field,
|
||||
"y": ((line["top"] + line["bottom"]) / 2) * scale,
|
||||
"height": (line["bottom"] - line["top"]) * scale,
|
||||
"text": text,
|
||||
}
|
||||
)
|
||||
else:
|
||||
if rendered_image is None:
|
||||
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
|
||||
img_w, img_h = rendered_image.size
|
||||
crop_box = (
|
||||
max(0, round(x0n * img_w)),
|
||||
max(0, round(y0n * img_h)),
|
||||
min(img_w, round(x1n * img_w)),
|
||||
min(img_h, round(y1n * img_h)),
|
||||
)
|
||||
if crop_box[2] <= crop_box[0] or crop_box[3] <= crop_box[1]:
|
||||
continue
|
||||
cropped = rendered_image.crop(crop_box)
|
||||
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
|
||||
for words in group_words(data):
|
||||
text = " ".join(w["text"] for w in words).strip()
|
||||
if not text:
|
||||
continue
|
||||
top_local = min(w["top"] for w in words)
|
||||
bottom_local = max(w["top"] + w["height"] for w in words)
|
||||
lines.append(
|
||||
{
|
||||
"target_field": region.target_field,
|
||||
"y": crop_box[1] + (top_local + bottom_local) / 2,
|
||||
"height": bottom_local - top_local,
|
||||
"text": text,
|
||||
}
|
||||
)
|
||||
return lines
|
||||
|
||||
def _cluster_rows(self, lines: list[dict[str, Any]], page_number: int) -> list[dict[str, str]]:
|
||||
if not lines:
|
||||
return []
|
||||
heights = [line["height"] for line in lines if line["height"] > 0]
|
||||
median_height = statistics.median(heights) if heights else 10.0
|
||||
gap_tolerance = 0.6 * median_height
|
||||
|
||||
ordered = sorted(lines, key=lambda line: line["y"])
|
||||
clusters: list[list[dict[str, Any]]] = [[ordered[0]]]
|
||||
for line in ordered[1:]:
|
||||
if line["y"] - clusters[-1][-1]["y"] <= gap_tolerance:
|
||||
clusters[-1].append(line)
|
||||
else:
|
||||
clusters.append([line])
|
||||
|
||||
resolved: list[list[dict[str, Any]]] = []
|
||||
for cluster in clusters:
|
||||
resolved.extend(self._split_conflicts(cluster, page_number))
|
||||
|
||||
rows = []
|
||||
for cluster in resolved:
|
||||
row: dict[str, str] = {}
|
||||
for line in cluster:
|
||||
if line["target_field"] in row:
|
||||
row[line["target_field"]] = f"{row[line['target_field']]} {line['text']}".strip()
|
||||
else:
|
||||
row[line["target_field"]] = line["text"]
|
||||
rows.append(row)
|
||||
return rows
|
||||
|
||||
def _split_conflicts(self, cluster: list[dict[str, Any]], page_number: int) -> list[list[dict[str, Any]]]:
|
||||
"""A row cluster holds at most one line per target field. When two
|
||||
lines of the same region land in one cluster, split it at its largest
|
||||
internal gap (recursively) and record a warning rather than drop data."""
|
||||
fields = [line["target_field"] for line in cluster]
|
||||
if len(fields) == len(set(fields)) or len(cluster) < 2:
|
||||
return [cluster]
|
||||
|
||||
ordered = sorted(cluster, key=lambda line: line["y"])
|
||||
gaps = [(ordered[i + 1]["y"] - ordered[i]["y"], i) for i in range(len(ordered) - 1)]
|
||||
_, split_at = max(gaps, key=lambda g: g[0])
|
||||
left, right = ordered[: split_at + 1], ordered[split_at + 1 :]
|
||||
|
||||
duplicated = sorted({f for f in fields if fields.count(f) > 1})
|
||||
self.warnings.append(
|
||||
ExtractionWarning(
|
||||
page_number=page_number,
|
||||
message=f"alignment conflict on field(s) {duplicated}: cluster split at largest internal gap",
|
||||
)
|
||||
)
|
||||
return self._split_conflicts(left, page_number) + self._split_conflicts(right, page_number)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Connector interface, usable once select_table() or extract_regions() ran
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _dataframe(self) -> pd.DataFrame:
|
||||
if self._table_grid is not None:
|
||||
header, *data_rows = self._table_grid
|
||||
columns = [name if name else f"column_{i}" for i, name in enumerate(header)]
|
||||
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")
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _page(self, page_number: int):
|
||||
if not (1 <= page_number <= self.page_count):
|
||||
raise ConnectorError(f"page_number out of range: {page_number}")
|
||||
return self._pdf.pages[page_number - 1]
|
||||
|
||||
@staticmethod
|
||||
def _clamp_to_page(bbox: tuple[float, float, float, float], page) -> tuple[float, float, float, float]:
|
||||
x0, top, x1, bottom = bbox
|
||||
px0, ptop, px1, pbottom = page.bbox
|
||||
return (max(x0, px0), max(top, ptop), min(x1, px1), min(bottom, pbottom))
|
||||
|
||||
|
||||
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}")
|
||||
|
||||
|
||||
def _table_confidence(grid: list[list[str | None]]) -> float:
|
||||
"""Ranking heuristic for the UI: capped row count plus non-empty cell rate."""
|
||||
data_rows = len(grid) - 1
|
||||
total_cells = sum(len(row) for row in grid) or 1
|
||||
filled_cells = sum(1 for row in grid for cell in row if cell not in (None, ""))
|
||||
fill_rate = filled_cells / total_cells
|
||||
row_score = min(data_rows / 5, 1.0)
|
||||
return round(0.5 * row_score + 0.5 * fill_rate, 4)
|
||||
@@ -1,38 +0,0 @@
|
||||
from typing import Any
|
||||
|
||||
from webapi.imports.connectors.base import Connector
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
|
||||
CONNECTORS: dict[str, type[Connector]] = {}
|
||||
|
||||
|
||||
def register_connector(cls: type[Connector]) -> type[Connector]:
|
||||
if cls.kind in CONNECTORS:
|
||||
raise ValueError(f"connector kind {cls.kind!r} is already registered by {CONNECTORS[cls.kind].__name__}")
|
||||
CONNECTORS[cls.kind] = cls
|
||||
return cls
|
||||
|
||||
|
||||
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))})")
|
||||
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")
|
||||
try:
|
||||
return connector_class(kind).from_payload(payload)
|
||||
except KeyError as exc:
|
||||
raise ConnectorError(f"missing field in payload: {exc}") from exc
|
||||
|
||||
|
||||
def kind_for_filename(filename: str) -> str | None:
|
||||
extension = filename.lower().rsplit(".", 1)[-1]
|
||||
return next((kind for kind, cls in CONNECTORS.items() if extension in cls.extensions), None)
|
||||
|
||||
|
||||
def catalog() -> list[dict[str, Any]]:
|
||||
return [cls.describe() for cls in CONNECTORS.values()]
|
||||
@@ -1,262 +0,0 @@
|
||||
import datetime as _dt
|
||||
import importlib.util
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, ClassVar, Iterator
|
||||
|
||||
import pandas as pd
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.pool import NullPool
|
||||
|
||||
from webapi.imports.connectors.base import Connector, PreviewResult, SourceColumn
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
from webapi.imports.connectors.registry import register_connector
|
||||
from webapi.imports.connectors.sql_policy import SqlSourcePolicy
|
||||
from webapi.imports.connectors.tabular import infer_type
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SqlEngine:
|
||||
"""A database server the connection form offers. Supporting another
|
||||
server is one entry in `SqlConnector.ENGINES` plus its driver package."""
|
||||
|
||||
id: str
|
||||
label: str
|
||||
drivername: str
|
||||
default_port: int
|
||||
driver_module: str
|
||||
description: str = ""
|
||||
default_schema: str | None = None
|
||||
|
||||
@property
|
||||
def available(self) -> bool:
|
||||
return importlib.util.find_spec(self.driver_module) is not None
|
||||
|
||||
def describe(self) -> dict[str, Any]:
|
||||
return {
|
||||
"id": self.id,
|
||||
"label": self.label,
|
||||
"description": self.description,
|
||||
"default_port": self.default_port,
|
||||
"default_schema": self.default_schema,
|
||||
"available": self.available,
|
||||
}
|
||||
|
||||
|
||||
@register_connector
|
||||
class SqlConnector(Connector):
|
||||
"""Reads a table or a SELECT from a client's database server.
|
||||
|
||||
Browsing (`list_schemas`/`list_tables`/`list_columns`) lives here only;
|
||||
the import pipeline uses the `Connector` methods once `select_table` or
|
||||
`select_query` has been called. Rows come straight from SQLAlchemy, so
|
||||
they keep the driver's types, previews fetch only `limit` rows and
|
||||
`read_rows` streams. Connections are read-only (see `_reading`) and
|
||||
unpooled, since every request builds its own connector.
|
||||
"""
|
||||
|
||||
kind = "sql"
|
||||
label = "Base de datos"
|
||||
description = "Tabla o consulta de un servidor SQL"
|
||||
category = "database"
|
||||
icon = "storage"
|
||||
|
||||
ENGINES: ClassVar[dict[str, SqlEngine]] = {
|
||||
engine.id: engine
|
||||
for engine in (
|
||||
SqlEngine("mysql", "MySQL", "mysql+pymysql", 3306, "pymysql", "Servidor MySQL 5.7+ / 8"),
|
||||
SqlEngine("mariadb", "MariaDB", "mariadb+pymysql", 3306, "pymysql", "Servidor MariaDB"),
|
||||
SqlEngine("postgresql", "PostgreSQL", "postgresql+psycopg2", 5432, "psycopg2", "Servidor PostgreSQL", "public"),
|
||||
SqlEngine("mssql", "SQL Server", "mssql+pymssql", 1433, "pymssql", "Microsoft SQL Server 2017+ / Azure SQL", "dbo"),
|
||||
)
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def describe(cls) -> dict[str, Any]:
|
||||
return {**super().describe(), "engines": [engine.describe() for engine in cls.ENGINES.values()]}
|
||||
|
||||
@classmethod
|
||||
def from_payload(cls, payload: dict[str, Any]) -> "SqlConnector":
|
||||
connector = cls.connect(payload)
|
||||
if payload.get("query"):
|
||||
return connector.select_query(payload["query"])
|
||||
return connector.select_table(payload["table"], schema=payload.get("schema"))
|
||||
|
||||
@classmethod
|
||||
def connect(cls, payload: dict[str, Any]) -> "SqlConnector":
|
||||
"""A connector without a table selected yet, for browsing. Takes
|
||||
either `server` (engine, host, port, database, user, password) or a
|
||||
raw SQLAlchemy `connection_string`."""
|
||||
if payload.get("server"):
|
||||
return cls(cls.server_url(payload["server"]))
|
||||
if payload.get("connection_string"):
|
||||
return cls(payload["connection_string"])
|
||||
raise ConnectorError("missing server or 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)})")
|
||||
if not engine.available:
|
||||
raise ConnectorError(f"the {engine.label} driver ({engine.driver_module}) is not installed on the server")
|
||||
if not server.get("host") or not server.get("database"):
|
||||
raise ConnectorError("host and database are required")
|
||||
try:
|
||||
port = int(server.get("port") or engine.default_port)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ConnectorError("port must be a number") from exc
|
||||
return sa.engine.URL.create(
|
||||
engine.drivername,
|
||||
username=server.get("user") or None,
|
||||
password=server.get("password") or None,
|
||||
host=server["host"],
|
||||
port=port,
|
||||
database=server["database"],
|
||||
)
|
||||
|
||||
def __init__(self, connection: str | sa.engine.URL, *, policy: SqlSourcePolicy | None = None):
|
||||
self._policy = policy or SqlSourcePolicy.from_env()
|
||||
url = self._policy.check_url(connection)
|
||||
try:
|
||||
self._engine = sa.create_engine(url, poolclass=NullPool)
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"invalid connection string: {exc}") from exc
|
||||
self._table: sa.Table | None = None
|
||||
self._query: str | None = None
|
||||
|
||||
# -- browsing ---------------------------------------------------------
|
||||
|
||||
def test_connection(self) -> None:
|
||||
try:
|
||||
with self._reading() as conn:
|
||||
conn.execute(sa.text("SELECT 1"))
|
||||
except ConnectorError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not connect: {exc}") from exc
|
||||
|
||||
def get_dialect(self) -> str:
|
||||
return self._engine.dialect.name
|
||||
|
||||
def list_schemas(self) -> list[str]:
|
||||
try:
|
||||
return sa.inspect(self._engine).get_schema_names()
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not list schemas: {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
|
||||
|
||||
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
|
||||
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
|
||||
self._query = None
|
||||
return self
|
||||
|
||||
def select_query(self, query: str) -> "SqlConnector":
|
||||
self._query, self._table = self._policy.check_query(query), None
|
||||
return self
|
||||
|
||||
# -- Connector ----------------------------------------------------------
|
||||
|
||||
def get_columns(self) -> list[SourceColumn]:
|
||||
return self.preview(limit=200).columns
|
||||
|
||||
def preview(self, *, limit: int = 20) -> PreviewResult:
|
||||
statement = self._selectable()
|
||||
try:
|
||||
with self._reading() as conn:
|
||||
result = conn.execute(sa.select(statement).limit(limit))
|
||||
names = list(result.keys())
|
||||
rows = [dict(row) for row in result.mappings()]
|
||||
total = conn.execute(sa.select(sa.func.count()).select_from(statement)).scalar_one()
|
||||
except ConnectorError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not read rows: {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]]:
|
||||
statement = sa.select(self._selectable())
|
||||
try:
|
||||
with self._reading() as conn:
|
||||
result = conn.execution_options(stream_results=True, yield_per=1000).execute(statement)
|
||||
for row in result.mappings():
|
||||
yield {target: row.get(source) for source, target in column_mapping.items()}
|
||||
except ConnectorError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not read rows: {exc}") from exc
|
||||
|
||||
# -- internals ----------------------------------------------------------
|
||||
|
||||
def _selectable(self) -> sa.Subquery:
|
||||
if self._table is not None:
|
||||
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")
|
||||
|
||||
def _columns(self, names: list[str], rows: list[dict[str, Any]]) -> list[SourceColumn]:
|
||||
if self._table is not None:
|
||||
by_name = {c.name: c for c in self._table.columns}
|
||||
return [SourceColumn(n, _sa_type_to_kind(by_name[n].type) if n in by_name else "string") for n in names]
|
||||
return [SourceColumn(n, infer_type(pd.Series([r.get(n) for r in rows], dtype=object))) for n in names]
|
||||
|
||||
@contextmanager
|
||||
def _reading(self):
|
||||
"""A connection that can't write: read-only mode where the dialect
|
||||
has one, and an unconditional rollback, so not even a SELECT calling
|
||||
a side-effecting function can commit anything. SQL Server has no
|
||||
read-only session mode; the rollback and `SqlSourcePolicy`'s
|
||||
single-SELECT rule cover it."""
|
||||
with self._engine.connect() as conn:
|
||||
dialect = conn.dialect.name
|
||||
if dialect in ("mysql", "mariadb"):
|
||||
conn.exec_driver_sql("SET SESSION TRANSACTION READ ONLY")
|
||||
elif dialect == "postgresql":
|
||||
conn.exec_driver_sql("SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY")
|
||||
elif dialect == "sqlite":
|
||||
conn.exec_driver_sql("PRAGMA query_only = ON")
|
||||
try:
|
||||
yield conn
|
||||
finally:
|
||||
conn.rollback()
|
||||
|
||||
|
||||
def _text_subquery(query: str) -> sa.Subquery:
|
||||
"""Wraps policy-checked SELECT text as a derived table, so SQLAlchemy
|
||||
composes LIMIT/TOP and COUNT(*) for whichever dialect the source speaks."""
|
||||
return sa.select(sa.literal_column("*")).select_from(sa.text(f"({query}) AS source_query")).subquery("source")
|
||||
|
||||
|
||||
def _sa_type_to_kind(sa_type: sa.types.TypeEngine) -> str:
|
||||
try:
|
||||
python_type = sa_type.python_type
|
||||
except (NotImplementedError, AttributeError):
|
||||
return "string"
|
||||
if python_type is bool:
|
||||
return "boolean"
|
||||
if python_type is int:
|
||||
return "integer"
|
||||
if python_type is float:
|
||||
return "float"
|
||||
if python_type is _dt.datetime:
|
||||
return "datetime"
|
||||
if python_type is _dt.date:
|
||||
return "date"
|
||||
return "string"
|
||||
@@ -1,90 +0,0 @@
|
||||
"""What a client-supplied connection or query may reach. The SQL
|
||||
connector is the one place where the client picks what the server connects
|
||||
to, so:
|
||||
|
||||
- dialects are allowlisted (`WEBAPI_SQL_ALLOWED_DIALECTS`); sqlite is off
|
||||
by default because its URL is a path on this server's filesystem;
|
||||
- hosts can be allowlisted (`WEBAPI_SQL_ALLOWED_HOSTS`, comma-separated);
|
||||
- the application's own databases are never a valid source;
|
||||
- custom SQL must be a single SELECT/WITH statement (on top of the
|
||||
read-only connection, not instead of it).
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
|
||||
from sqlalchemy.engine import URL, make_url
|
||||
from sqlalchemy.exc import ArgumentError
|
||||
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
|
||||
_DEFAULT_DIALECTS = "mysql,mariadb,postgresql,mssql,oracle"
|
||||
_LEADING_COMMENTS = re.compile(r"^\s*((--[^\n]*\n)|(/\*.*?\*/)|\s)*", re.S)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SqlSourcePolicy:
|
||||
allowed_dialects: frozenset[str]
|
||||
allowed_hosts: frozenset[str] | None
|
||||
|
||||
@classmethod
|
||||
def from_env(cls) -> "SqlSourcePolicy":
|
||||
dialects = os.environ.get("WEBAPI_SQL_ALLOWED_DIALECTS", _DEFAULT_DIALECTS)
|
||||
hosts = os.environ.get("WEBAPI_SQL_ALLOWED_HOSTS")
|
||||
return cls(
|
||||
allowed_dialects=frozenset(d.strip().lower() for d in dialects.split(",") if d.strip()),
|
||||
allowed_hosts=frozenset(h.strip().lower() for h in hosts.split(",") if h.strip()) if hosts else None,
|
||||
)
|
||||
|
||||
def check_url(self, connection: "str | URL") -> URL:
|
||||
try:
|
||||
url = connection if isinstance(connection, URL) else make_url(connection)
|
||||
except ArgumentError as exc:
|
||||
raise ConnectorError(f"invalid connection string: {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))})"
|
||||
)
|
||||
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")
|
||||
if _same_database(url, _own_database_urls()):
|
||||
raise ConnectorError("this connection points at the application's own database — not a valid import source")
|
||||
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")
|
||||
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")
|
||||
return statement
|
||||
|
||||
|
||||
def _own_database_urls() -> list[URL]:
|
||||
from persistance.settings import settings
|
||||
|
||||
urls = []
|
||||
for raw in (
|
||||
settings.cacu_database_url,
|
||||
settings.cama_database_url,
|
||||
settings.tea_database_url,
|
||||
settings.governance_database_url,
|
||||
):
|
||||
try:
|
||||
urls.append(make_url(raw))
|
||||
except ArgumentError:
|
||||
continue
|
||||
return urls
|
||||
|
||||
|
||||
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())
|
||||
|
||||
return key(candidate) in {key(url) for url in own}
|
||||
@@ -1,122 +0,0 @@
|
||||
"""Connectors whose rows fit in one pandas DataFrame (CSV, Excel, JSON,
|
||||
PDF, EDF, documents): they only have to build the DataFrame."""
|
||||
|
||||
import datetime as _dt
|
||||
import math
|
||||
import re
|
||||
from abc import abstractmethod
|
||||
from typing import Any, ClassVar, Iterator
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from webapi.imports.connectors.base import Connector, PreviewResult, SourceColumn, decode_file
|
||||
|
||||
|
||||
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(
|
||||
columns=columns_from_dataframe(df),
|
||||
sample_rows=rows_from_dataframe(df.head(limit)),
|
||||
total_rows=len(df),
|
||||
)
|
||||
|
||||
def read_rows(self, column_mapping: dict[str, str]) -> Iterator[dict[str, Any]]:
|
||||
for row in rows_from_dataframe(self._dataframe()):
|
||||
yield {target: row.get(source) for source, target in column_mapping.items()}
|
||||
|
||||
|
||||
class FileConnector(DataFrameConnector):
|
||||
"""An uploaded file. Subclasses implement `__init__(raw, **options)`
|
||||
and list the keyword options a client may pass in `option_names`."""
|
||||
|
||||
option_names: ClassVar[tuple[str, ...]] = ()
|
||||
|
||||
@classmethod
|
||||
def from_bytes(cls, raw: bytes, options: dict[str, Any] | None = None) -> "FileConnector":
|
||||
options = {k: v for k, v in (options or {}).items() if k in cls.option_names and v not in (None, "")}
|
||||
return cls(raw, **options)
|
||||
|
||||
@classmethod
|
||||
def from_payload(cls, payload: dict[str, Any]) -> "FileConnector":
|
||||
return cls.from_bytes(decode_file(payload), payload.get("options") or {})
|
||||
|
||||
|
||||
def columns_from_dataframe(df: pd.DataFrame) -> list[SourceColumn]:
|
||||
return [SourceColumn(name=str(name), inferred_type=infer_type(df[name])) for name in df.columns]
|
||||
|
||||
|
||||
_INT_RE = re.compile(r"^[+-]?\d+$")
|
||||
_FLOAT_RE = re.compile(r"^[+-]?(\d+\.\d*|\.\d+|\d+)([eE][+-]?\d+)?$")
|
||||
_DATE_RE = re.compile(r"^(\d{4}-\d{2}-\d{2}|\d{1,2}/\d{1,2}/\d{4})$")
|
||||
_DATETIME_RE = re.compile(r"^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}(:\d{2})?")
|
||||
_BOOL_VALUES = {"true", "false", "si", "sí", "no", "verdadero", "falso"}
|
||||
|
||||
|
||||
def infer_type(series: "pd.Series") -> str:
|
||||
"""Display hint for the UI only; values are never converted here."""
|
||||
kind = series.dtype.kind
|
||||
if kind in ("i", "u"):
|
||||
return "integer"
|
||||
if kind == "f":
|
||||
return "float"
|
||||
if kind == "b":
|
||||
return "boolean"
|
||||
if kind == "M":
|
||||
return "datetime"
|
||||
values = [v for v in series.head(500).tolist() if v is not None and not (isinstance(v, float) and math.isnan(v))]
|
||||
if not values:
|
||||
return "string"
|
||||
return _infer_from_values(values)
|
||||
|
||||
|
||||
def _infer_from_values(values: list[Any]) -> str:
|
||||
if all(isinstance(v, bool) for v in values):
|
||||
return "boolean"
|
||||
if all(isinstance(v, int) and not isinstance(v, bool) for v in values):
|
||||
return "integer"
|
||||
if all(isinstance(v, (int, float)) and not isinstance(v, bool) for v in values):
|
||||
return "float"
|
||||
if all(isinstance(v, _dt.datetime) for v in values):
|
||||
return "datetime"
|
||||
if all(isinstance(v, _dt.date) for v in values):
|
||||
return "date"
|
||||
if all(isinstance(v, (bytes, bytearray)) for v in values):
|
||||
return "binary"
|
||||
if not all(isinstance(v, str) for v in values):
|
||||
return "string"
|
||||
texts = [v.strip() for v in values]
|
||||
# A leading zero ("01000", "007") means the value is a code, not a number.
|
||||
if all(_INT_RE.match(t) for t in texts) and not any(len(t.lstrip("+-")) > 1 and t.lstrip("+-").startswith("0") for t in texts):
|
||||
return "integer"
|
||||
if all(_FLOAT_RE.match(t) for t in texts) and any("." in t or "e" in t.lower() for t in texts):
|
||||
return "float"
|
||||
if all(_DATETIME_RE.match(t) for t in texts):
|
||||
return "datetime"
|
||||
if all(_DATE_RE.match(t) for t in texts):
|
||||
return "date"
|
||||
if all(t.lower() in _BOOL_VALUES for t in texts):
|
||||
return "boolean"
|
||||
return "string"
|
||||
|
||||
|
||||
def rows_from_dataframe(df: pd.DataFrame) -> list[dict[str, Any]]:
|
||||
return [{key: clean_value(value) for key, value in row.items()} for row in df.to_dict(orient="records")]
|
||||
|
||||
|
||||
def clean_value(value: Any) -> Any:
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, float) and math.isnan(value):
|
||||
return None
|
||||
if value is pd.NaT:
|
||||
return None
|
||||
if hasattr(value, "to_pydatetime"): # pandas.Timestamp
|
||||
return value.to_pydatetime()
|
||||
return value
|
||||
@@ -1,164 +0,0 @@
|
||||
"""Auto-match suggestions for the column-mapping UI, based on stdlib `difflib`."""
|
||||
|
||||
import difflib
|
||||
import re
|
||||
import unicodedata
|
||||
from dataclasses import dataclass
|
||||
|
||||
# Keys are target fields; values are normalized source-column names (see
|
||||
# `_normalize`: lowercase, no accents, spaces/dashes/dots -> "_").
|
||||
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",
|
||||
},
|
||||
"pac_fecha_nacimiento": {"fecha_nacimiento", "dob", "birth_date", "fecha_nac", "fec_nac", "f_nac", "f_nacimiento", "nacimiento"},
|
||||
"pac_sexo": {"sexo", "genero", "gender", "sex"},
|
||||
"pac_codigo_postal": {"codigo_postal", "cod_postal", "cp", "c_p", "zip", "zip_code"},
|
||||
"pac_dependencia": {"dependencia", "tipo_derechohabiente", "derechohabiencia", "afiliacion"},
|
||||
"pac_parentesco": {"parentesco", "relacion"},
|
||||
"ord_numero_hospital": {"folio", "folio_orden", "numero_orden", "no_orden", "orden", "num_orden"},
|
||||
"ord_tipo_estudio": {"estudio", "tipo_estudio", "estudio_solicitado"},
|
||||
"ord_medico_solicitante": {"medico", "medico_solicitante", "solicitante"},
|
||||
"nm_id_hospital": {"folio_nota", "id_nota", "numero_nota", "no_nota"},
|
||||
"nm_fecha": {"fecha", "fecha_consulta", "fecha_nota"},
|
||||
"nm_especialidad": {"servicio", "especialidad"},
|
||||
"nm_motivo_consulta": {"motivo", "motivo_consulta"},
|
||||
"nm_diagnostico_texto": {"dx", "diagnostico"},
|
||||
"nm_masa_corporal": {"peso", "peso_kg", "peso_(kg)"},
|
||||
"nm_talla": {"talla", "talla_m", "talla_(m)", "estatura"},
|
||||
"nm_medico_tratante": {"medico", "medico_tratante"},
|
||||
"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").
|
||||
_STOPWORDS = {"de", "del", "la", "el", "los", "las", "en", "por", "para", "con"}
|
||||
_NEAR_WORD = 0.8
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MatchSuggestion:
|
||||
source_column: str
|
||||
target_field: str | None
|
||||
confidence: float
|
||||
reason: str # "exact" | "normalized" | "synonym" | "unprefixed" | "fuzzy" | "none"
|
||||
|
||||
|
||||
def _normalize(name: str) -> str:
|
||||
without_accents = "".join(
|
||||
c for c in unicodedata.normalize("NFKD", name) if not unicodedata.combining(c)
|
||||
)
|
||||
cleaned = without_accents.strip().lower()
|
||||
for separator in ("-", ".", "/"):
|
||||
cleaned = cleaned.replace(separator, " ")
|
||||
return "_".join(cleaned.split())
|
||||
|
||||
|
||||
def _words(normalized: str) -> list[str]:
|
||||
return [w for w in re.split(r"[^a-z0-9]+", normalized) if len(w) > 2 and w not in _STOPWORDS]
|
||||
|
||||
|
||||
def _word_score(source_words: list[str], target_words: list[str]) -> float:
|
||||
"""Word-level similarity: each source word scores its best match among
|
||||
the target words (exact 1.0, near-miss spellings ≥0.8, else 0), divided
|
||||
by the longer word list. Comparing words rather than whole strings
|
||||
rewards shared meaning ("estudio solicitado" ~ "tipo_estudio") instead of
|
||||
shared suffixes ("estudio_solicitado" ~ "medico_solicitante")."""
|
||||
if not source_words or not target_words:
|
||||
return 0.0
|
||||
total = 0.0
|
||||
for word in source_words:
|
||||
best = max(difflib.SequenceMatcher(None, word, other).ratio() for other in target_words)
|
||||
if best >= _NEAR_WORD:
|
||||
total += best
|
||||
return total / max(len(source_words), len(target_words))
|
||||
|
||||
|
||||
def _unprefixed(target: str) -> str:
|
||||
"""`pac_sexo` -> `sexo`: Core's field names carry a table prefix that
|
||||
source systems never use."""
|
||||
head, _, rest = target.partition("_")
|
||||
return rest if rest else head
|
||||
|
||||
|
||||
class ColumnMatcher:
|
||||
"""Exact name -> normalized (case/accents/separators) -> static synonym
|
||||
table -> name without the table prefix -> word-level similarity -> no
|
||||
match.
|
||||
|
||||
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."""
|
||||
|
||||
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)
|
||||
|
||||
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
|
||||
|
||||
@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
|
||||
@@ -1,21 +0,0 @@
|
||||
"""Common base for every import schema."""
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
|
||||
from webapi.imports.schemas.coercion import Catalog
|
||||
|
||||
|
||||
class ImportSchema(BaseModel):
|
||||
"""Shared pydantic config for all import schemas.
|
||||
|
||||
`coerce_numbers_to_str`: a numeric source column (SQL INT, Excel number,
|
||||
JSON number) feeding a text field is legitimate: expediente `12345` is "12345".
|
||||
"""
|
||||
|
||||
model_config = ConfigDict(coerce_numbers_to_str=True)
|
||||
|
||||
@classmethod
|
||||
def catalog_for(cls, field_name: str) -> Catalog | None:
|
||||
field = cls.model_fields.get(field_name)
|
||||
if field is None:
|
||||
return None
|
||||
return next((m for m in field.metadata if isinstance(m, Catalog)), None)
|
||||
@@ -1,47 +0,0 @@
|
||||
"""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
|
||||
|
||||
|
||||
class BiometriaHematicaImportSchema(ImportSchema):
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
ord_numero_hospital: Optional[int] = None
|
||||
bh_fecha: Optional[date] = None
|
||||
|
||||
eritrocitos_mill_ul: Optional[float] = None
|
||||
hemoglobina_g_dl: Optional[float] = None
|
||||
hematocrito_pct: Optional[float] = None
|
||||
vcm_fl: Optional[float] = None
|
||||
hcm_pg: Optional[float] = None
|
||||
chcm_g_dl: Optional[float] = None
|
||||
rdw_pct: Optional[float] = None
|
||||
leucocitos_mil_ul: Optional[float] = None
|
||||
|
||||
linfocitos_pct: Optional[float] = None
|
||||
monocitos_pct: Optional[float] = None
|
||||
basofilos_pct: Optional[float] = None
|
||||
eosinofilos_pct: Optional[float] = None
|
||||
neutrofilos_pct: Optional[float] = None
|
||||
mielocitos_pct: Optional[float] = None
|
||||
metamielocitos_pct: Optional[float] = None
|
||||
neutrofilos_banda_pct: Optional[float] = None
|
||||
neutrofilos_segmentados_pct: Optional[float] = None
|
||||
|
||||
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 +0,0 @@
|
||||
"""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
|
||||
|
||||
_GRADO_CIN_CATALOG = Catalog(GradoCIN, GRADO_CIN_ALIAS)
|
||||
|
||||
|
||||
class BiopsiaCervicalImportSchema(ImportSchema):
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
ord_numero_hospital: Optional[int] = None
|
||||
cit_id: Optional[int] = None
|
||||
bx_fecha_solicitud: Optional[date] = None
|
||||
bx_fecha_reporte: Optional[date] = 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)
|
||||
@@ -1,48 +0,0 @@
|
||||
"""Import schema for `core.cacu.models.CitologiaCervical`.
|
||||
|
||||
`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
|
||||
|
||||
_CELULAS_ESCAMOSAS_CATALOG = Catalog(CelulasEscamosas, CELULAS_ESCAMOSAS_ALIAS)
|
||||
_RESULTADO_VPH_CATALOG = Catalog(ResultadoVPH)
|
||||
|
||||
|
||||
class CitologiaCervicalImportSchema(ImportSchema):
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
ord_numero_hospital: Optional[int] = None
|
||||
cit_fecha_toma: Optional[date] = None
|
||||
cit_fecha_reporte: Optional[date] = None
|
||||
cit_calidad_especimen: Optional[str] = None
|
||||
cit_pdf_blob: Optional[bytes] = None
|
||||
cit_observaciones: Optional[str] = None
|
||||
cit_condiciones_ginecoobs: Optional[str] = None
|
||||
cit_exploracion: Optional[str] = None
|
||||
cit_dx_lesion: Optional[str] = None
|
||||
cit_celulas_glandulares: Optional[str] = None
|
||||
cit_carcinoma_invasor: Optional[str] = None
|
||||
cit_celulas_escamosas: CatalogValue(_CELULAS_ESCAMOSAS_CATALOG) = None
|
||||
cit_vph_pdf_blob: Optional[bytes] = None
|
||||
cit_vph_ocr_confianza: Optional[float] = None
|
||||
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)
|
||||
@@ -1,56 +0,0 @@
|
||||
"""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
|
||||
|
||||
_ESPECIALIDAD_CATALOG = Catalog(Especialidad, ESPECIALIDAD_ALIAS)
|
||||
_TIPO_NOTA_CATALOG = Catalog(TipoNota, TIPO_NOTA_ALIAS)
|
||||
|
||||
|
||||
class NotaMedicaImportSchema(ImportSchema):
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
nm_id_hospital: str
|
||||
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_medico_tratante: Optional[str] = None
|
||||
nm_motivo_consulta: Optional[str] = None
|
||||
nm_interrogatorio: Optional[str] = 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_pronostico: Optional[str] = None
|
||||
nm_observaciones: Optional[str] = None
|
||||
nm_masa_corporal: Optional[float] = None
|
||||
nm_talla: Optional[float] = None
|
||||
nm_imc_visita: Optional[float] = None
|
||||
nm_frecuencia_cardiaca: Optional[int] = None
|
||||
nm_frecuencia_respiratoria: Optional[int] = None
|
||||
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,36 +0,0 @@
|
||||
"""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
|
||||
|
||||
_TIPO_ESTUDIO_CATALOG = Catalog(TipoEstudio, TIPO_ESTUDIO_ALIAS)
|
||||
|
||||
|
||||
class OrdenesEstudioImportSchema(ImportSchema):
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
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_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,39 +0,0 @@
|
||||
"""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
|
||||
|
||||
# Dependencia/Parentesco: Core marks both catalogs as tentative.
|
||||
_DEPENDENCIA_CATALOG = Catalog(Dependencia, DEPENDENCIA_ALIAS, strict=False)
|
||||
_PARENTESCO_CATALOG = Catalog(Parentesco, PARENTESCO_ALIAS, strict=False)
|
||||
_SEXO_BIOLOGICO_CATALOG = Catalog(SexoBiologico, SEXO_BIOLOGICO_ALIAS)
|
||||
|
||||
|
||||
class PacienteImportSchema(ImportSchema):
|
||||
pac_id_hospital: HospitalId
|
||||
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_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,47 +0,0 @@
|
||||
"""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
|
||||
|
||||
|
||||
class BiometriaHematicaImportSchema(ImportSchema):
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
ord_numero_hospital: Optional[int] = None
|
||||
bh_fecha: Optional[date] = None
|
||||
|
||||
eritrocitos_mill_ul: Optional[float] = None
|
||||
hemoglobina_g_dl: Optional[float] = None
|
||||
hematocrito_pct: Optional[float] = None
|
||||
vcm_fl: Optional[float] = None
|
||||
hcm_pg: Optional[float] = None
|
||||
chcm_g_dl: Optional[float] = None
|
||||
rdw_pct: Optional[float] = None
|
||||
leucocitos_mil_ul: Optional[float] = None
|
||||
|
||||
linfocitos_pct: Optional[float] = None
|
||||
monocitos_pct: Optional[float] = None
|
||||
basofilos_pct: Optional[float] = None
|
||||
eosinofilos_pct: Optional[float] = None
|
||||
neutrofilos_pct: Optional[float] = None
|
||||
mielocitos_pct: Optional[float] = None
|
||||
metamielocitos_pct: Optional[float] = None
|
||||
neutrofilos_banda_pct: Optional[float] = None
|
||||
neutrofilos_segmentados_pct: Optional[float] = None
|
||||
|
||||
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 +0,0 @@
|
||||
"""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
|
||||
|
||||
_GRADO_HISTOLOGICO_MAMA_CATALOG = Catalog(GradoHistologicoMama)
|
||||
|
||||
|
||||
class BiopsiaMamaImportSchema(ImportSchema):
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
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_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)
|
||||
@@ -1,34 +0,0 @@
|
||||
"""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
|
||||
|
||||
_BIRADS_CATALOG = Catalog(BIRADS, BIRADS_ALIAS)
|
||||
|
||||
|
||||
class MastografiaImportSchema(ImportSchema):
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
ord_id: Optional[int] = None
|
||||
ord_numero_hospital: Optional[int] = None
|
||||
mast_fecha_toma: Optional[date] = None
|
||||
mast_fecha_reporte: Optional[date] = 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,56 +0,0 @@
|
||||
"""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
|
||||
|
||||
_ESPECIALIDAD_CATALOG = Catalog(Especialidad, ESPECIALIDAD_ALIAS)
|
||||
_TIPO_NOTA_CATALOG = Catalog(TipoNota, TIPO_NOTA_ALIAS)
|
||||
|
||||
|
||||
class NotaMedicaImportSchema(ImportSchema):
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
nm_id_hospital: str
|
||||
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_medico_tratante: Optional[str] = None
|
||||
nm_motivo_consulta: Optional[str] = None
|
||||
nm_interrogatorio: Optional[str] = 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_pronostico: Optional[str] = None
|
||||
nm_observaciones: Optional[str] = None
|
||||
nm_masa_corporal: Optional[float] = None
|
||||
nm_talla: Optional[float] = None
|
||||
nm_imc_visita: Optional[float] = None
|
||||
nm_frecuencia_cardiaca: Optional[int] = None
|
||||
nm_frecuencia_respiratoria: Optional[int] = None
|
||||
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,36 +0,0 @@
|
||||
"""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
|
||||
|
||||
_TIPO_ESTUDIO_CATALOG = Catalog(TipoEstudio, TIPO_ESTUDIO_ALIAS)
|
||||
|
||||
|
||||
class OrdenesEstudioImportSchema(ImportSchema):
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
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_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,39 +0,0 @@
|
||||
"""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
|
||||
|
||||
# Dependencia/Parentesco: Core marks both catalogs as tentative.
|
||||
_DEPENDENCIA_CATALOG = Catalog(Dependencia, DEPENDENCIA_ALIAS, strict=False)
|
||||
_PARENTESCO_CATALOG = Catalog(Parentesco, PARENTESCO_ALIAS, strict=False)
|
||||
_SEXO_BIOLOGICO_CATALOG = Catalog(SexoBiologico, SEXO_BIOLOGICO_ALIAS)
|
||||
|
||||
|
||||
class PacienteImportSchema(ImportSchema):
|
||||
pac_id_hospital: HospitalId
|
||||
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_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")
|
||||
@@ -1,76 +0,0 @@
|
||||
"""Classifies pydantic validation errors into a few report categories using
|
||||
only each error's `type` and message, so no per-field rules are needed."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from enum import Enum
|
||||
from typing import Any
|
||||
|
||||
|
||||
class ErrorCategory(str, Enum):
|
||||
MISSING = "missing"
|
||||
OUT_OF_CATALOG = "out_of_catalog"
|
||||
TYPE_INVALID = "type_invalid"
|
||||
UNKNOWN = "unknown"
|
||||
|
||||
|
||||
_BY_PYDANTIC_TYPE: dict[str, ErrorCategory] = {
|
||||
"missing": ErrorCategory.MISSING,
|
||||
"enum": ErrorCategory.OUT_OF_CATALOG,
|
||||
"int_parsing": ErrorCategory.TYPE_INVALID,
|
||||
"int_type": ErrorCategory.TYPE_INVALID,
|
||||
"float_parsing": ErrorCategory.TYPE_INVALID,
|
||||
"float_type": ErrorCategory.TYPE_INVALID,
|
||||
"bool_parsing": ErrorCategory.TYPE_INVALID,
|
||||
"bool_type": ErrorCategory.TYPE_INVALID,
|
||||
"date_parsing": ErrorCategory.TYPE_INVALID,
|
||||
"date_type": ErrorCategory.TYPE_INVALID,
|
||||
"datetime_parsing": ErrorCategory.TYPE_INVALID,
|
||||
"datetime_type": ErrorCategory.TYPE_INVALID,
|
||||
"string_type": ErrorCategory.TYPE_INVALID,
|
||||
"string_too_long": ErrorCategory.TYPE_INVALID,
|
||||
"string_pattern_mismatch": ErrorCategory.TYPE_INVALID,
|
||||
}
|
||||
|
||||
_BY_MESSAGE_SUBSTRING: tuple[tuple[str, ErrorCategory], ...] = (
|
||||
("no está en el catálogo", ErrorCategory.OUT_OF_CATALOG),
|
||||
("es requerido", ErrorCategory.MISSING),
|
||||
("required", ErrorCategory.MISSING),
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ValidationError:
|
||||
field: str
|
||||
category: ErrorCategory
|
||||
message: str
|
||||
raw_value: Any = None
|
||||
|
||||
|
||||
def classify_error(error: dict) -> ValidationError:
|
||||
"""`error` is one entry of pydantic's `ValidationError.errors()`."""
|
||||
loc = error.get("loc") or ()
|
||||
field = str(loc[0]) if loc else "<entre campos>"
|
||||
etype = error.get("type", "")
|
||||
# pydantic prefixes errors raised inside validators with "Value error, ",
|
||||
# which is noise in the report.
|
||||
message = str(error.get("msg", "")).removeprefix("Value error, ")
|
||||
raw_value = error.get("input")
|
||||
|
||||
category = _BY_PYDANTIC_TYPE.get(etype)
|
||||
if category is None:
|
||||
category = _classify_by_message(message, etype)
|
||||
|
||||
return ValidationError(field=field, category=category, message=message, raw_value=raw_value)
|
||||
|
||||
|
||||
def _classify_by_message(message: str, etype: str) -> ErrorCategory:
|
||||
lowered = message.lower()
|
||||
for fragment, mapped in _BY_MESSAGE_SUBSTRING:
|
||||
if fragment in lowered:
|
||||
return mapped
|
||||
# "value_error" is what pydantic reports for errors raised by our own
|
||||
# validators (e.g. a bad date string). If it is not a missing value, it
|
||||
# is almost always a format problem.
|
||||
if etype == "value_error":
|
||||
return ErrorCategory.TYPE_INVALID
|
||||
return ErrorCategory.UNKNOWN
|
||||
@@ -1,180 +0,0 @@
|
||||
"""Shared coercion helpers and field types for the import schemas: raw-value
|
||||
shapes (Excel/SQL datetimes, ISO strings, empty CSV cells) and catalogs."""
|
||||
|
||||
import base64
|
||||
import binascii
|
||||
from datetime import date, datetime
|
||||
from enum import Enum
|
||||
from typing import Annotated, Any, Optional, Type
|
||||
|
||||
from pydantic import BeforeValidator, StringConstraints
|
||||
|
||||
from core.columns import HOSPITAL_ID_LENGTH
|
||||
from extraction import ExtractionError
|
||||
from extraction.signals import EegRecording
|
||||
|
||||
# Same bound as Core's VARCHAR column, so an over-long id is a validation
|
||||
# error here rather than a `Data too long` failure at insert on MySQL/Postgres.
|
||||
HospitalId = Annotated[str, StringConstraints(max_length=HOSPITAL_ID_LENGTH)]
|
||||
|
||||
|
||||
def required_str(v: Any, *, field_name: str) -> str:
|
||||
if v is None or str(v).strip() == "":
|
||||
raise ValueError(f"{field_name} es requerido")
|
||||
return str(v).strip()
|
||||
|
||||
|
||||
def optional_str(v: Any) -> Any:
|
||||
if v is None:
|
||||
return None
|
||||
text = str(v).strip()
|
||||
return text or None
|
||||
|
||||
|
||||
def rounded_int(v: Any) -> Any:
|
||||
"""A minutes/count field stored as an `int` column, whose source may
|
||||
report a float (e.g. a duration measured to tenths of a minute)."""
|
||||
if v is None or (isinstance(v, str) and v.strip() == ""):
|
||||
return None
|
||||
return round(float(v))
|
||||
|
||||
|
||||
_DAY_FIRST_FORMATS = ("%d/%m/%Y", "%d-%m-%Y", "%d.%m.%Y", "%Y/%m/%d")
|
||||
|
||||
|
||||
def required_date(v: Any, *, field_name: str) -> Any:
|
||||
coerced = coerce_date(v)
|
||||
if coerced is None:
|
||||
raise ValueError(f"{field_name} es requerido")
|
||||
return coerced
|
||||
|
||||
|
||||
def coerce_date(v: Any) -> Any:
|
||||
"""Accepts a `date`, a `datetime` (Excel and SQL often return one for a
|
||||
date-only column), an ISO-8601 string, or a day-first string such as
|
||||
`15/01/1990`. Month-first is not supported because Mexican source systems
|
||||
write dates day-first."""
|
||||
if v is None or (isinstance(v, str) and not v.strip()):
|
||||
return None
|
||||
if isinstance(v, datetime):
|
||||
return v.date()
|
||||
if isinstance(v, date):
|
||||
return v
|
||||
if isinstance(v, str):
|
||||
text = v.strip()
|
||||
try:
|
||||
return datetime.fromisoformat(text).date() if len(text) > 10 else date.fromisoformat(text)
|
||||
except ValueError:
|
||||
pass
|
||||
for fmt in _DAY_FIRST_FORMATS:
|
||||
try:
|
||||
return datetime.strptime(text, fmt).date()
|
||||
except ValueError:
|
||||
continue
|
||||
raise ValueError(f"'{text}' no es una fecha válida (use AAAA-MM-DD o DD/MM/AAAA)")
|
||||
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
|
||||
several alias dicts only list the exceptions (`PARENTESCO_ALIAS` has one entry)."""
|
||||
|
||||
def __init__(self, enum_cls: Type[Enum], aliases: dict[str, str] | None = None, *, strict: bool = True):
|
||||
self.name = enum_cls.__name__
|
||||
# strict=False only for catalogs Core marks as tentative: known values are
|
||||
# still normalized, unknown ones pass through instead of rejecting real data.
|
||||
self.strict = strict
|
||||
self._lookup: dict[str, str] = {}
|
||||
for member in enum_cls:
|
||||
self._lookup[member.value.upper()] = member.value
|
||||
self._lookup.setdefault(member.name.upper(), member.value)
|
||||
for raw, canonical in (aliases or {}).items():
|
||||
self._lookup[str(raw).strip().upper()] = canonical
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"Catalog({self.name}{'' if self.strict else ', strict=False'})"
|
||||
|
||||
@property
|
||||
def values(self) -> list[str]:
|
||||
return sorted(set(self._lookup.values()))
|
||||
|
||||
@property
|
||||
def choices(self) -> dict[str, str]:
|
||||
"""Every accepted surface form (uppercased) mapped to its canonical value."""
|
||||
return dict(self._lookup)
|
||||
|
||||
def resolve(self, raw: str) -> str | None:
|
||||
return self._lookup.get(raw.strip().upper())
|
||||
|
||||
def coerce(self, v: Any) -> Any:
|
||||
"""Normalizes a raw value to its canonical form. An unknown value is an
|
||||
`out_of_catalog` error, never silently stored: the target columns are plain
|
||||
text, so nothing downstream would catch it."""
|
||||
if v is None:
|
||||
return None
|
||||
text = str(v).strip()
|
||||
if not text:
|
||||
return None
|
||||
resolved = self.resolve(text)
|
||||
if resolved is not None:
|
||||
return resolved
|
||||
if not self.strict:
|
||||
return text
|
||||
raise ValueError(f"'{text}' no está en el catálogo (válidos: {', '.join(map(str, self.values))})")
|
||||
|
||||
|
||||
def CatalogValue(catalog: Catalog): # noqa: N802 (used in annotations, like a type)
|
||||
"""Field type for a catalog-backed column; the Catalog stays in
|
||||
`FieldInfo.metadata` so `ImportSchema.catalog_for` can find it."""
|
||||
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."""
|
||||
if v is None or (isinstance(v, str) and not v.strip()):
|
||||
return None
|
||||
if isinstance(v, bool):
|
||||
return v
|
||||
if isinstance(v, int) or (isinstance(v, float) and v.is_integer()):
|
||||
return f"{int(v):05d}"
|
||||
return str(v).strip()
|
||||
|
||||
|
||||
# Same shape as Core's CHAR(5) column. CaMa's REGEXP CHECK can't run on
|
||||
# SQLite and is not in the migrations, so the format is enforced here.
|
||||
CodigoPostal = Annotated[str, StringConstraints(pattern=r"^[0-9]{5}$")]
|
||||
|
||||
|
||||
def edf_file(v: Any) -> Any:
|
||||
"""`eeg_estudio.eeg_estudio`: an EDF file MNE can open (TEA amendment).
|
||||
JSON sources may carry it base64-encoded."""
|
||||
if v is None or (isinstance(v, str) and not v.strip()):
|
||||
return None
|
||||
if isinstance(v, str):
|
||||
try:
|
||||
v = base64.b64decode(v, validate=True)
|
||||
except (binascii.Error, ValueError) as exc:
|
||||
raise ValueError("el archivo EDF debe venir como bytes o base64") from exc
|
||||
if not isinstance(v, (bytes, bytearray)):
|
||||
raise ValueError("el archivo EDF debe venir como bytes o base64")
|
||||
try:
|
||||
EegRecording.validate_edf(bytes(v))
|
||||
except ExtractionError as exc:
|
||||
raise ValueError(f"no es un archivo EDF válido: {exc}") from exc
|
||||
return bytes(v)
|
||||
@@ -1,91 +0,0 @@
|
||||
"""What the document extractor should look for to fill a target entity,
|
||||
derived from the entity's import schema: the field's type decides how a
|
||||
value is parsed, its catalog becomes the accepted terms, and the captions
|
||||
and clinical synonyms come from `extraction.nlp.vocabulary`."""
|
||||
import re
|
||||
import types
|
||||
import typing
|
||||
from datetime import date, datetime
|
||||
|
||||
from extraction.nlp import FieldKind, FieldSpec
|
||||
from extraction.nlp.vocabulary import CLINICAL_TERMS, FREE_TEXT_FIELDS, PATTERNS, labels_for
|
||||
from webapi.imports.schemas.registry import EntitySpec
|
||||
|
||||
# Surrogate keys, stored files and OCR bookkeeping are never read from a document.
|
||||
_NOT_IN_DOCUMENTS = re.compile(r"(_id$|_blob$|_ocr_|_created_at$|_updated_at$|^eeg_estudio$|_pdf_ruta$|_nlp_version$)")
|
||||
_IDENTIFIERS = re.compile(r"(_id_hospital$|_id_registro_laboratorio$)")
|
||||
_LONG_TEXT = re.compile(r"(observaciones|_texto$|interpretacion|descripcion|motivo|interrogatorio|plan_|tratamiento|exploracion|receta|pronostico)")
|
||||
|
||||
|
||||
def field_specs_for(entity: EntitySpec, *, key_pattern: str | None = None) -> list[FieldSpec]:
|
||||
specs = []
|
||||
for name, info in entity.schema.model_fields.items():
|
||||
if _NOT_IN_DOCUMENTS.search(name):
|
||||
continue
|
||||
kind = _kind(name, info.annotation, entity)
|
||||
choices: dict = {}
|
||||
if kind is FieldKind.CHOICE:
|
||||
catalog = entity.schema.catalog_for(name)
|
||||
if catalog is not None:
|
||||
choices.update(catalog.choices)
|
||||
choices.update(CLINICAL_TERMS.get(name, {}))
|
||||
pattern = PATTERNS.get(name)
|
||||
if key_pattern and name == key_field_for(entity):
|
||||
pattern = key_pattern
|
||||
specs.append(
|
||||
FieldSpec(
|
||||
name=name,
|
||||
kind=kind,
|
||||
labels=labels_for(name, _description(entity, name)),
|
||||
choices=choices,
|
||||
pattern=pattern,
|
||||
scan_free_text=name in FREE_TEXT_FIELDS or (pattern is not None and pattern == key_pattern),
|
||||
multiline=kind is FieldKind.TEXT and bool(_LONG_TEXT.search(name)),
|
||||
required=info.is_required(),
|
||||
)
|
||||
)
|
||||
return specs
|
||||
|
||||
|
||||
def key_field_for(entity: EntitySpec) -> str | None:
|
||||
"""The field that identifies whose record a page belongs to."""
|
||||
fields = entity.schema.model_fields
|
||||
for candidate in ("pac_id_hospital", "eeg_id_registro_laboratorio"):
|
||||
if candidate in fields:
|
||||
return candidate
|
||||
return entity.conflict_fields[0] if entity.conflict_fields else None
|
||||
|
||||
|
||||
def _kind(name: str, annotation, entity: EntitySpec) -> FieldKind:
|
||||
if entity.schema.catalog_for(name) is not None or name in CLINICAL_TERMS:
|
||||
return FieldKind.CHOICE
|
||||
if _IDENTIFIERS.search(name):
|
||||
return FieldKind.IDENTIFIER
|
||||
base = _unwrap(annotation)
|
||||
if base in (date, datetime):
|
||||
return FieldKind.DATE
|
||||
if base is bool or base is int:
|
||||
return FieldKind.INTEGER
|
||||
if base is float:
|
||||
return FieldKind.DECIMAL
|
||||
return FieldKind.TEXT
|
||||
|
||||
|
||||
def _unwrap(annotation):
|
||||
"""`Optional[Annotated[str, ...]]` -> `str`."""
|
||||
while True:
|
||||
origin = typing.get_origin(annotation)
|
||||
if origin is typing.Annotated:
|
||||
annotation = typing.get_args(annotation)[0]
|
||||
elif origin in (typing.Union, types.UnionType):
|
||||
args = [a for a in typing.get_args(annotation) if a is not type(None)]
|
||||
annotation = args[0] if args else annotation
|
||||
if not args:
|
||||
return annotation
|
||||
else:
|
||||
return annotation
|
||||
|
||||
|
||||
def _description(entity: EntitySpec, name: str) -> str | None:
|
||||
field = entity.model.model_fields.get(name)
|
||||
return field.description if field is not None else None
|
||||
@@ -1,244 +0,0 @@
|
||||
"""Per importable Core entity: its import schema, its `Repository`, and the
|
||||
natural-key fields used for `on_conflict=upsert`. Field metadata for the UI
|
||||
comes from each schema's `model_json_schema()`.
|
||||
|
||||
Keys are `"<domain>.<ModelName>"`, since some names (`NotaMedica`) repeat
|
||||
across domains.
|
||||
"""
|
||||
from dataclasses import dataclass
|
||||
from typing import Sequence, Type
|
||||
|
||||
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 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 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
|
||||
from persistance.cacu import nota_medica_repository as cacu_nota_medica_repository
|
||||
from persistance.cacu import ordenes_estudio_repository as cacu_ordenes_estudio_repository
|
||||
from persistance.cacu import paciente_repository as cacu_paciente_repository
|
||||
from persistance.cama import biometria_hematica_repository as cama_biometria_hematica_repository
|
||||
from persistance.cama import biopsia_mama_repository as cama_biopsia_mama_repository
|
||||
from persistance.cama import mastografia_repository as cama_mastografia_repository
|
||||
from persistance.cama import nota_medica_repository as cama_nota_medica_repository
|
||||
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 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
|
||||
from persistance.tea import evaluacion_psicologica_repository as tea_evaluacion_psicologica_repository
|
||||
from persistance.tea import instrumento_aplicado_repository as tea_instrumento_aplicado_repository
|
||||
from persistance.tea import nota_medica_repository as tea_nota_medica_repository
|
||||
from persistance.tea import ordenes_estudio_repository as tea_ordenes_estudio_repository
|
||||
from persistance.tea import pacientes_repository as tea_pacientes_repository
|
||||
from persistance.tea import parto_neonatal_repository as tea_parto_neonatal_repository
|
||||
from persistance.tea import (
|
||||
potenciales_evocados_auditivos_repository as tea_potenciales_evocados_auditivos_repository,
|
||||
)
|
||||
from webapi.imports.schemas.cacu.biometria_hematica import (
|
||||
BiometriaHematicaImportSchema as CacuBiometriaHematicaImportSchema,
|
||||
)
|
||||
from webapi.imports.schemas.cacu.biopsia_cervical import BiopsiaCervicalImportSchema
|
||||
from webapi.imports.schemas.cacu.citologia_cervical import CitologiaCervicalImportSchema
|
||||
from webapi.imports.schemas.cacu.nota_medica import NotaMedicaImportSchema as CacuNotaMedicaImportSchema
|
||||
from webapi.imports.schemas.cacu.ordenes_estudio import (
|
||||
OrdenesEstudioImportSchema as CacuOrdenesEstudioImportSchema,
|
||||
)
|
||||
from webapi.imports.schemas.cacu.paciente import PacienteImportSchema as CacuPacienteImportSchema
|
||||
from webapi.imports.schemas.cama.biometria_hematica import (
|
||||
BiometriaHematicaImportSchema as CamaBiometriaHematicaImportSchema,
|
||||
)
|
||||
from webapi.imports.schemas.cama.biopsia_mama import BiopsiaMamaImportSchema
|
||||
from webapi.imports.schemas.cama.mastografia import MastografiaImportSchema
|
||||
from webapi.imports.schemas.cama.nota_medica import NotaMedicaImportSchema as CamaNotaMedicaImportSchema
|
||||
from webapi.imports.schemas.cama.ordenes_estudio import (
|
||||
OrdenesEstudioImportSchema as CamaOrdenesEstudioImportSchema,
|
||||
)
|
||||
from webapi.imports.schemas.cama.paciente import PacienteImportSchema as CamaPacienteImportSchema
|
||||
from webapi.imports.schemas.tea.antecedentes_maternos_gestacion import (
|
||||
AntecedentesMaternosGestacionImportSchema,
|
||||
)
|
||||
from webapi.imports.schemas.tea.eeg_estudio import EegEstudioImportSchema
|
||||
from webapi.imports.schemas.tea.eeg_segmento import EegSegmentoImportSchema
|
||||
from webapi.imports.schemas.tea.evaluacion_psicologica import EvaluacionPsicologicaImportSchema
|
||||
from webapi.imports.schemas.tea.instrumento_aplicado import InstrumentoAplicadoImportSchema
|
||||
from webapi.imports.schemas.tea.nota_medica import NotaMedicaImportSchema as TeaNotaMedicaImportSchema
|
||||
from webapi.imports.schemas.tea.ordenes_estudio import (
|
||||
OrdenesEstudioImportSchema as TeaOrdenesEstudioImportSchema,
|
||||
)
|
||||
from webapi.imports.schemas.tea.pacientes import PacientesImportSchema
|
||||
from webapi.imports.schemas.tea.parto_neonatal import PartoNeonatalImportSchema
|
||||
from webapi.imports.schemas.tea.potenciales_evocados_auditivos import (
|
||||
PotencialesEvocadosAuditivosImportSchema,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class EntitySpec:
|
||||
schema: Type[BaseModel]
|
||||
model: type
|
||||
repository: Repository
|
||||
conflict_fields: Sequence[str] | None
|
||||
|
||||
|
||||
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,
|
||||
),
|
||||
"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,
|
||||
),
|
||||
"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
|
||||
# `document` source (read from the report text) populate this field,
|
||||
# so merge_duplicates/on_conflict=upsert can land them on one row.
|
||||
conflict_fields=("eeg_id_registro_laboratorio",),
|
||||
),
|
||||
"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,
|
||||
),
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
"""Row-level validation. Each row is validated on its own, collecting all of
|
||||
its errors, and sorted into accepted or rejected; a bad row does not abort
|
||||
the batch."""
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Iterable, Type
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic import ValidationError as PydanticValidationError
|
||||
|
||||
from webapi.imports.schemas.classify import ValidationError, classify_error
|
||||
|
||||
|
||||
@dataclass
|
||||
class RowErrors:
|
||||
row_index: int
|
||||
errors: list[ValidationError] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AcceptedRow:
|
||||
row_index: int
|
||||
data: dict[str, Any]
|
||||
|
||||
|
||||
@dataclass
|
||||
class BatchValidationResult:
|
||||
total_rows: int = 0
|
||||
accepted_rows: list[AcceptedRow] = field(default_factory=list)
|
||||
rejected: list[RowErrors] = field(default_factory=list)
|
||||
|
||||
@property
|
||||
def accepted(self) -> list[dict[str, Any]]:
|
||||
return [row.data for row in self.accepted_rows]
|
||||
|
||||
@property
|
||||
def valid_count(self) -> int:
|
||||
return len(self.accepted)
|
||||
|
||||
@property
|
||||
def error_count(self) -> int:
|
||||
return len(self.rejected)
|
||||
|
||||
|
||||
def validate_rows(schema_cls: Type[BaseModel], rows: Iterable[dict[str, Any] | None]) -> BatchValidationResult:
|
||||
"""`None` rows count towards the total but are not validated: they were
|
||||
merged into a row of another source."""
|
||||
result = BatchValidationResult()
|
||||
for index, row in enumerate(rows):
|
||||
result.total_rows += 1
|
||||
if row is None:
|
||||
continue
|
||||
try:
|
||||
validated = schema_cls(**row)
|
||||
except PydanticValidationError as exc:
|
||||
result.rejected.append(
|
||||
RowErrors(row_index=index, errors=[classify_error(e) for e in exc.errors()])
|
||||
)
|
||||
else:
|
||||
# exclude_unset keeps only the fields this source supplied, so an
|
||||
# upsert does not overwrite columns the source never mapped.
|
||||
result.accepted_rows.append(AcceptedRow(row_index=index, data=validated.model_dump(exclude_unset=True)))
|
||||
return result
|
||||
@@ -1,66 +0,0 @@
|
||||
"""Import schema for `core.tea.models.AntecedentesMaternosGestacion`. All fields
|
||||
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,
|
||||
TipoEmbarazo,
|
||||
TrastornoHipertensivoGestacion,
|
||||
VolumenLiquidoAmniotico,
|
||||
)
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, optional_str
|
||||
|
||||
_FUENTE_ANTECEDENTE_MATERNO_CATALOG = Catalog(FuenteAntecedenteMaterno)
|
||||
_CATEGORIA_PESO_MATERNO_CATALOG = Catalog(CategoriaPesoMaterno)
|
||||
_TIPO_EMBARAZO_CATALOG = Catalog(TipoEmbarazo)
|
||||
_TRASTORNO_HIPERTENSIVO_GESTACION_CATALOG = Catalog(TrastornoHipertensivoGestacion)
|
||||
_VOLUMEN_LIQUIDO_AMNIOTICO_CATALOG = Catalog(VolumenLiquidoAmniotico)
|
||||
|
||||
|
||||
class AntecedentesMaternosGestacionImportSchema(ImportSchema):
|
||||
amg_pac_id: Optional[int] = None
|
||||
amg_id_madre_seudonimo: Optional[str] = None
|
||||
amg_fuente_antecedente: CatalogValue(_FUENTE_ANTECEDENTE_MATERNO_CATALOG) = None
|
||||
amg_flag_vinculo_verificado: Optional[int] = None
|
||||
amg_imc_pregestacional: Optional[float] = None
|
||||
amg_categoria_peso_materno: CatalogValue(_CATEGORIA_PESO_MATERNO_CATALOG) = None
|
||||
amg_tabaquismo_gestacion: Optional[int] = None
|
||||
amg_acido_folico_preconcepcional: Optional[int] = None
|
||||
amg_intervalo_intergenesico_meses: Optional[int] = None
|
||||
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_hospitalizacion: Optional[int] = None
|
||||
amg_diabetes_gestacional: Optional[int] = None
|
||||
amg_hipertension_preeclampsia: CatalogValue(_TRASTORNO_HIPERTENSIVO_GESTACION_CATALOG) = None
|
||||
amg_hipotiroidismo: Optional[int] = None
|
||||
amg_hipertiroidismo: Optional[int] = None
|
||||
amg_incompatibilidad_rh: Optional[int] = None
|
||||
amg_crisis_convulsivas: Optional[int] = None
|
||||
amg_proceso_proinflamatorio: Optional[int] = None
|
||||
amg_enfermedad_autoinmune: Optional[int] = None
|
||||
amg_migrana: Optional[int] = None
|
||||
amg_asma: Optional[int] = None
|
||||
amg_hipoxia_materna: Optional[int] = None
|
||||
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_farmaco_riesgo_neurodesarrollo: Optional[int] = None
|
||||
amg_observaciones: Optional[str] = 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)
|
||||
@@ -1,95 +0,0 @@
|
||||
"""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,
|
||||
DistribucionAnormalidad,
|
||||
EstadoRegistroEeg,
|
||||
FuenteInterpretacionEeg,
|
||||
Lentificacion,
|
||||
RespuestaFotoestimulacion,
|
||||
Simetria,
|
||||
TipoGrafoelemento,
|
||||
)
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import edf_file, Catalog, CatalogValue, coerce_date, optional_str, rounded_int
|
||||
|
||||
_FUENTE_INTERPRETACION_EEG_CATALOG = Catalog(FuenteInterpretacionEeg)
|
||||
_ESTADO_REGISTRO_EEG_CATALOG = Catalog(EstadoRegistroEeg)
|
||||
_CALIDAD_TECNICA_EEG_CATALOG = Catalog(CalidadTecnicaEeg)
|
||||
_SIMETRIA_CATALOG = Catalog(Simetria)
|
||||
_TIPO_GRAFOELEMENTO_CATALOG = Catalog(TipoGrafoelemento)
|
||||
_DISTRIBUCION_ANORMALIDAD_CATALOG = Catalog(DistribucionAnormalidad)
|
||||
_LENTIFICACION_CATALOG = Catalog(Lentificacion)
|
||||
_RESPUESTA_FOTOESTIMULACION_CATALOG = Catalog(RespuestaFotoestimulacion)
|
||||
_CONCLUSION_EEG_CATALOG = Catalog(ConclusionEeg)
|
||||
|
||||
|
||||
class EegEstudioImportSchema(ImportSchema):
|
||||
eeg_ord_id: Optional[str] = None
|
||||
eeg_pac_id: Optional[str] = None
|
||||
eeg_reporte_disponible: Optional[int] = None
|
||||
eeg_fuente_interpretacion: CatalogValue(_FUENTE_INTERPRETACION_EEG_CATALOG) = None
|
||||
eeg_fecha_nacimiento_archivo: Optional[date] = None
|
||||
eeg_edad_meses: Optional[float] = None
|
||||
eeg_fecha_estudio: Optional[date] = None
|
||||
eeg_fecha_reporte: Optional[date] = None
|
||||
eeg_dias_respuesta: Optional[int] = None
|
||||
eeg_medico_interpreta: Optional[str] = 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_duracion_min: Optional[int] = None
|
||||
eeg_calidad_tecnica: CatalogValue(_CALIDAD_TECNICA_EEG_CATALOG) = None
|
||||
eeg_descripcion_senal: Optional[str] = None
|
||||
eeg_ritmo_base_frecuencia: Optional[float] = None
|
||||
eeg_ritmo_base_amplitud: Optional[int] = None
|
||||
eeg_simetria: CatalogValue(_SIMETRIA_CATALOG) = None
|
||||
eeg_anormalidad_presente: Optional[int] = None
|
||||
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_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_categoria: CatalogValue(_CONCLUSION_EEG_CATALOG) = None
|
||||
eeg_id_registro_laboratorio: Optional[str] = None
|
||||
eeg_pdf_ruta: Optional[str] = None
|
||||
eeg_ocr_confianza: Optional[float] = None
|
||||
eeg_nlp_version: Optional[str] = None
|
||||
eeg_utilizable: Optional[int] = None
|
||||
eeg_estudio: Optional[bytes] = None
|
||||
|
||||
@field_validator(
|
||||
"eeg_ord_id", "eeg_pac_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_duracion_min", mode="before")
|
||||
@classmethod
|
||||
def _coerce_duracion_min(cls, v):
|
||||
return rounded_int(v)
|
||||
|
||||
@field_validator("eeg_estudio", mode="before")
|
||||
@classmethod
|
||||
def _valid_edf(cls, v):
|
||||
return edf_file(v)
|
||||
@@ -1,28 +0,0 @@
|
||||
"""Import schema for `core.tea.models.EegSegmento`. 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
|
||||
|
||||
|
||||
class EegSegmentoImportSchema(ImportSchema):
|
||||
seg_eeg_id: Optional[str] = None
|
||||
seg_estado: Optional[str] = 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_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,101 +0,0 @@
|
||||
"""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,
|
||||
ModuloAdos2,
|
||||
NivelRiesgoTamizaje,
|
||||
VentanaMadurativa,
|
||||
)
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, coerce_date, optional_str
|
||||
|
||||
_VENTANA_MADURATIVA_CATALOG = Catalog(VentanaMadurativa)
|
||||
_INSTRUMENTO_TAMIZAJE_CATALOG = Catalog(InstrumentoTamizaje)
|
||||
_NIVEL_RIESGO_TAMIZAJE_CATALOG = Catalog(NivelRiesgoTamizaje)
|
||||
_MODULO_ADOS2_CATALOG = Catalog(ModuloAdos2)
|
||||
_CLASIFICACION_ADOS2_CATALOG = Catalog(ClasificacionAdos2)
|
||||
|
||||
|
||||
class EvaluacionPsicologicaImportSchema(ImportSchema):
|
||||
psi_ord_id: Optional[str] = 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_edad_meses: Optional[float] = None
|
||||
psi_ventana_madurativa: CatalogValue(_VENTANA_MADURATIVA_CATALOG) = None
|
||||
psi_instrumento_tamizaje: CatalogValue(_INSTRUMENTO_TAMIZAJE_CATALOG) = None
|
||||
psi_tamizaje_puntaje: Optional[int] = None
|
||||
psi_tamizaje_riesgo: CatalogValue(_NIVEL_RIESGO_TAMIZAJE_CATALOG) = None
|
||||
psi_ados2_modulo: CatalogValue(_MODULO_ADOS2_CATALOG) = None
|
||||
|
||||
# Items ADOS-2, dominio SA (Interaccion Social Reciproca)
|
||||
psi_ados2_sa_a2: Optional[int] = None
|
||||
psi_ados2_sa_a6: Optional[int] = None
|
||||
psi_ados2_sa_a7: Optional[int] = None
|
||||
psi_ados2_sa_a8: Optional[int] = None
|
||||
psi_ados2_sa_b1: Optional[int] = None
|
||||
psi_ados2_sa_b2: Optional[int] = None
|
||||
psi_ados2_sa_b3: Optional[int] = None
|
||||
psi_ados2_sa_b4: Optional[int] = None
|
||||
psi_ados2_sa_b5: Optional[int] = None
|
||||
psi_ados2_sa_b6: Optional[int] = None
|
||||
psi_ados2_sa_b7: Optional[int] = None
|
||||
psi_ados2_sa_b8: Optional[int] = None
|
||||
psi_ados2_sa_b9: Optional[int] = None
|
||||
psi_ados2_sa_b10: Optional[int] = None
|
||||
psi_ados2_sa_b11: Optional[int] = None
|
||||
psi_ados2_sa_b12: Optional[int] = None
|
||||
psi_ados2_sa_b13: Optional[int] = None
|
||||
psi_ados2_sa_b14: Optional[int] = None
|
||||
psi_ados2_sa_b15: Optional[int] = None
|
||||
psi_ados2_sa_b16b: Optional[int] = None
|
||||
psi_ados2_sa_b18: Optional[int] = None
|
||||
|
||||
# Items ADOS-2, dominio RRB (Conductas Restringidas y Repetitivas)
|
||||
psi_ados2_rrb_a3: Optional[int] = None
|
||||
psi_ados2_rrb_a4: Optional[int] = None
|
||||
psi_ados2_rrb_a5: Optional[int] = None
|
||||
psi_ados2_rrb_d1: Optional[int] = None
|
||||
psi_ados2_rrb_d2: Optional[int] = None
|
||||
psi_ados2_rrb_d4: Optional[int] = None
|
||||
psi_ados2_rrb_d5: Optional[int] = None
|
||||
|
||||
psi_ados2_sa: Optional[int] = None
|
||||
psi_ados2_rrb: Optional[int] = None
|
||||
psi_ados2_total: Optional[int] = None
|
||||
psi_ados2_css: Optional[int] = None
|
||||
psi_ados2_css_sa: Optional[int] = None
|
||||
psi_ados2_css_rrb: Optional[int] = None
|
||||
psi_ados2_clasificacion: CatalogValue(_CLASIFICACION_ADOS2_CATALOG) = None
|
||||
psi_rgd: Optional[int] = None
|
||||
psi_cociente_desarrollo: Optional[float] = None
|
||||
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_regresion_desarrollo: Optional[int] = None
|
||||
psi_diagnostico_texto: Optional[str] = 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)
|
||||
@@ -1,24 +0,0 @@
|
||||
"""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
|
||||
|
||||
|
||||
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)
|
||||
@@ -1,65 +0,0 @@
|
||||
"""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
|
||||
|
||||
_TIPO_NOTA_CATALOG = Catalog(TipoNota)
|
||||
_ESPECIALIDAD_CATALOG = Catalog(Especialidad)
|
||||
_VENTANA_MADURATIVA_CATALOG = Catalog(VentanaMadurativa)
|
||||
_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_tipo_nota: CatalogValue(_TIPO_NOTA_CATALOG) = None
|
||||
nm_especialidad: CatalogValue(_ESPECIALIDAD_CATALOG) = None
|
||||
nm_fecha: Optional[date] = 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_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_pronostico: CatalogValue(_PRONOSTICO_CATALOG) = None
|
||||
nm_observaciones: Optional[str] = None
|
||||
nm_masa_corporal: Optional[float] = None
|
||||
nm_talla: Optional[float] = None
|
||||
nm_imc_visita: Optional[float] = None
|
||||
nm_frecuencia_cardiaca: Optional[int] = None
|
||||
nm_frecuencia_respiratoria: Optional[int] = None
|
||||
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)
|
||||
@@ -1,53 +0,0 @@
|
||||
"""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 Especialidad, EstatusEstudio, TipoEstudio, VentanaMadurativa
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, coerce_date, optional_str
|
||||
|
||||
_ESPECIALIDAD_CATALOG = Catalog(Especialidad)
|
||||
_TIPO_ESTUDIO_CATALOG = Catalog(TipoEstudio)
|
||||
_ESTATUS_ESTUDIO_CATALOG = Catalog(EstatusEstudio)
|
||||
_VENTANA_MADURATIVA_CATALOG = Catalog(VentanaMadurativa)
|
||||
|
||||
|
||||
class OrdenesEstudioImportSchema(ImportSchema):
|
||||
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_especialidad: CatalogValue(_ESPECIALIDAD_CATALOG) = None
|
||||
ord_diagnostico_asignado: Optional[str] = None
|
||||
ord_cie_asignado: Optional[str] = None
|
||||
ord_dias_vigencia: Optional[int] = None
|
||||
ord_fecha_vencimiento: Optional[date] = 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_dias_espera: Optional[int] = None
|
||||
ord_proveedor: Optional[str] = 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)
|
||||
@@ -1,37 +0,0 @@
|
||||
"""Import schema for `core.tea.models.Pacientes`. All fields optional, like TEA's
|
||||
Core; system-managed `pac_created_at`/`pac_updated_at`/`pac_fuente_sistema` are excluded.
|
||||
|
||||
`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
|
||||
|
||||
_SEXO_CATALOG = Catalog(SexoBiologico)
|
||||
_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_parentesco: CatalogValue(_PARENTESCO_CATALOG) = None
|
||||
pac_fecha_nacimiento: Optional[date] = 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)
|
||||
@@ -1,60 +0,0 @@
|
||||
"""Import schema for `core.tea.models.PartoNeonatal`. All fields optional, like
|
||||
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,
|
||||
FuenteAntecedenteNeonatal,
|
||||
TamanoParaEdadGestacional,
|
||||
TipoParto,
|
||||
)
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, optional_str
|
||||
|
||||
_FUENTE_ANTECEDENTE_NEONATAL_CATALOG = Catalog(FuenteAntecedenteNeonatal)
|
||||
_TIPO_PARTO_CATALOG = Catalog(TipoParto)
|
||||
_COMPLICACION_INTRAPARTO_CATALOG = Catalog(ComplicacionIntraparto)
|
||||
_CLASIFICACION_EDAD_GESTACIONAL_CATALOG = Catalog(ClasificacionEdadGestacional)
|
||||
_TAMANO_PARA_EDAD_GESTACIONAL_CATALOG = Catalog(TamanoParaEdadGestacional)
|
||||
|
||||
|
||||
class PartoNeonatalImportSchema(ImportSchema):
|
||||
pnn_pac_id: Optional[int] = None
|
||||
pnn_fuente_antecedente: CatalogValue(_FUENTE_ANTECEDENTE_NEONATAL_CATALOG) = None
|
||||
pnn_tipo_parto: CatalogValue(_TIPO_PARTO_CATALOG) = None
|
||||
pnn_complicaciones_intraparto: Optional[int] = None
|
||||
pnn_complicacion_tipo: CatalogValue(_COMPLICACION_INTRAPARTO_CATALOG) = None
|
||||
pnn_peso_nacer_g: Optional[int] = None
|
||||
pnn_talla_nacer_cm: Optional[float] = None
|
||||
pnn_perimetro_cefalico_nacer_cm: Optional[float] = None
|
||||
pnn_edad_gestacional_sem: Optional[float] = None
|
||||
pnn_clasificacion_eg: CatalogValue(_CLASIFICACION_EDAD_GESTACIONAL_CATALOG) = None
|
||||
pnn_tamano_para_eg: CatalogValue(_TAMANO_PARA_EDAD_GESTACIONAL_CATALOG) = None
|
||||
pnn_peso_nacer_zscore: Optional[float] = None
|
||||
pnn_apgar_1min: Optional[int] = None
|
||||
pnn_apgar_5min: Optional[int] = None
|
||||
pnn_ingreso_ucin: Optional[int] = None
|
||||
pnn_dias_ucin: Optional[int] = None
|
||||
pnn_encefalopatia_hipoxico_isquemica: Optional[int] = None
|
||||
pnn_hipotermia_nacer: Optional[int] = None
|
||||
pnn_hiperbilirrubinemia: Optional[int] = None
|
||||
pnn_fototerapia: Optional[int] = None
|
||||
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_flag_riesgo_neonatal: Optional[int] = None
|
||||
pnn_observaciones: Optional[str] = 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)
|
||||
@@ -1,42 +0,0 @@
|
||||
"""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
|
||||
|
||||
_GRADO_HIPOACUSIA_CATALOG = Catalog(GradoHipoacusia)
|
||||
|
||||
|
||||
class PotencialesEvocadosAuditivosImportSchema(ImportSchema):
|
||||
pea_ord_id: Optional[str] = None
|
||||
pea_pac_id: Optional[int] = None
|
||||
pea_fecha_estudio: Optional[date] = None
|
||||
pea_medico_interpreta: Optional[str] = None
|
||||
pea_umbral_od: Optional[int] = None
|
||||
pea_umbral_oi: Optional[int] = None
|
||||
pea_latencia_v_od: Optional[float] = None
|
||||
pea_latencia_v_oi: Optional[float] = None
|
||||
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_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)
|
||||
@@ -1,288 +0,0 @@
|
||||
"""Runs one configured source, or a batch of them, end to end: resolve the
|
||||
target entity, build the connector, read and validate the rows and, for
|
||||
`commit_sources`, write the accepted ones through `Repository`.
|
||||
|
||||
A batch composes the database from several sources (files, SQL tables or
|
||||
queries, PDFs, documents, EEG files), each feeding one target entity. All
|
||||
sources of a batch target the same domain and the batch is written in one
|
||||
transaction: it lands completely or not at all.
|
||||
"""
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Iterator
|
||||
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
|
||||
from persistance.repository import ConflictPolicy
|
||||
from webapi.imports.connectors import Connector, ConnectorError, build_connector
|
||||
from webapi.imports.schemas.registry import ENTITY_REGISTRY, EntitySpec
|
||||
from webapi.imports.schemas.service import BatchValidationResult, validate_rows
|
||||
from webapi.imports.services.link_resolver import LinkResolver, dependency_rank
|
||||
|
||||
|
||||
class ImportRequestError(Exception):
|
||||
"""A structurally invalid import request, such as an unknown target, a
|
||||
bad connection string or an invalid on_conflict. Mapped to HTTP 400."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ImportSource:
|
||||
"""One parsed and structurally validated entry of a request's `sources`."""
|
||||
|
||||
source_type: str
|
||||
target: str
|
||||
spec: EntitySpec
|
||||
column_mapping: dict[str, str]
|
||||
defaults: dict[str, Any]
|
||||
payload: dict[str, Any]
|
||||
label: str | None = None
|
||||
|
||||
@classmethod
|
||||
def parse(cls, raw: Any) -> "ImportSource":
|
||||
if not isinstance(raw, dict):
|
||||
raise ImportRequestError("each source must be an object")
|
||||
target = raw.get("target")
|
||||
if not target:
|
||||
raise ImportRequestError("source is missing 'target'")
|
||||
spec = ENTITY_REGISTRY.get(target)
|
||||
if spec is None:
|
||||
raise ImportRequestError(f"unknown target: {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")
|
||||
unknown = sorted((set(mapping.values()) | set(defaults)) - fields)
|
||||
if unknown:
|
||||
raise ImportRequestError(f"{target} has no field(s) {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}")
|
||||
if not mapping and not defaults:
|
||||
raise ImportRequestError(f"source for {target} maps no columns")
|
||||
|
||||
payload = raw.get("payload")
|
||||
if not isinstance(payload, dict):
|
||||
raise ImportRequestError("source is missing 'payload'")
|
||||
return cls(
|
||||
source_type=raw.get("source_type", ""),
|
||||
target=target,
|
||||
spec=spec,
|
||||
column_mapping=mapping,
|
||||
defaults=defaults,
|
||||
payload=payload,
|
||||
label=raw.get("label"),
|
||||
)
|
||||
|
||||
@property
|
||||
def domain(self) -> str:
|
||||
return self.target.split(".", 1)[0]
|
||||
|
||||
def connector(self) -> Connector:
|
||||
payload = self.payload
|
||||
if self.source_type == "document":
|
||||
# A document source extracts the fields of the entity it feeds.
|
||||
payload = {**payload, "target": payload.get("target") or self.target}
|
||||
try:
|
||||
return build_connector(self.source_type, payload)
|
||||
except ConnectorError as exc:
|
||||
raise ImportRequestError(str(exc)) from exc
|
||||
|
||||
def rows(self) -> Iterator[dict[str, Any]]:
|
||||
"""Mapped rows, with `defaults` filling any field the source left
|
||||
empty or didn't map at all (a constant "dependencia" for a file that
|
||||
has none, a fallback for blank cells)."""
|
||||
try:
|
||||
for row in self.connector().read_rows(self.column_mapping):
|
||||
for field_name, value in self.defaults.items():
|
||||
if _is_blank(row.get(field_name)):
|
||||
row[field_name] = value
|
||||
yield row
|
||||
except ConnectorError as exc:
|
||||
raise ImportRequestError(str(exc)) from exc
|
||||
|
||||
def validate(self) -> BatchValidationResult:
|
||||
return validate_rows(self.spec.schema, self.rows())
|
||||
|
||||
|
||||
def _is_blank(value: Any) -> bool:
|
||||
return value is None or (isinstance(value, str) and not value.strip())
|
||||
|
||||
|
||||
def serialize_errors(validation: BatchValidationResult) -> list[dict[str, Any]]:
|
||||
return [
|
||||
{
|
||||
"row_index": row_errors.row_index,
|
||||
"field": e.field,
|
||||
"category": e.category.value,
|
||||
"message": e.message,
|
||||
"raw_value": _jsonable(e.raw_value),
|
||||
}
|
||||
for row_errors in validation.rejected
|
||||
for e in row_errors.errors
|
||||
]
|
||||
|
||||
|
||||
def _jsonable(value: Any) -> Any:
|
||||
if value is None or isinstance(value, (str, int, float, bool)):
|
||||
return value
|
||||
return str(value)
|
||||
|
||||
|
||||
def validate_source(raw_source: dict[str, Any]) -> BatchValidationResult:
|
||||
return ImportSource.parse(raw_source).validate()
|
||||
|
||||
|
||||
@dataclass
|
||||
class SourceCommitResult:
|
||||
target: str
|
||||
label: str | None
|
||||
total: int
|
||||
created: int
|
||||
updated: int
|
||||
rejected: int
|
||||
errors: list[dict[str, Any]]
|
||||
linked: dict[str, int]
|
||||
merged: int = 0
|
||||
warnings: list[dict[str, Any]] = field(default_factory=list)
|
||||
|
||||
|
||||
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")
|
||||
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"
|
||||
)
|
||||
return sources
|
||||
|
||||
|
||||
def merge_duplicates(sources: list[ImportSource], rows: list[list[dict[str, Any] | None]]) -> tuple[dict[int, int], dict[int, list]]:
|
||||
"""Combines rows that describe the same record (same target entity and
|
||||
natural key) across the sources of a batch, before validation: a
|
||||
patient's demographics from a CSV completed with the birth date read
|
||||
from a scanned form. The first row seen is kept and completed with the
|
||||
fields it lacks; merged rows become `None`. A field two sources disagree
|
||||
on keeps the first value and is reported as a warning on the later one.
|
||||
Returns per-source merge counts and warnings."""
|
||||
first_seen: dict[tuple[str, tuple], tuple[int, dict[str, Any]]] = {}
|
||||
merged: dict[int, int] = {}
|
||||
warnings: dict[int, list] = {}
|
||||
for position, source in enumerate(sources):
|
||||
keys = source.spec.conflict_fields
|
||||
if not keys:
|
||||
continue
|
||||
for index, row in enumerate(rows[position]):
|
||||
key_values = tuple(_key_part(row.get(k)) for k in keys)
|
||||
if any(v is None for v in key_values):
|
||||
continue
|
||||
first = first_seen.setdefault((source.target, key_values), (position, row))
|
||||
if first[1] is row:
|
||||
continue
|
||||
first_position, first_row = first
|
||||
for name, value in row.items():
|
||||
if _is_blank(value):
|
||||
continue
|
||||
current = first_row.get(name)
|
||||
if _is_blank(current):
|
||||
first_row[name] = value
|
||||
elif _key_part(current) != _key_part(value):
|
||||
warnings.setdefault(position, []).append(
|
||||
{
|
||||
"row_index": index,
|
||||
"field": name,
|
||||
"category": "merge_conflict",
|
||||
"message": f"se conservó {current!r} de {sources[first_position].label or 'otra fuente'}",
|
||||
"raw_value": _jsonable(value),
|
||||
}
|
||||
)
|
||||
rows[position][index] = None
|
||||
merged[position] = merged.get(position, 0) + 1
|
||||
return merged, warnings
|
||||
|
||||
|
||||
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."""
|
||||
if _is_blank(value):
|
||||
return None
|
||||
return str(value).strip().upper()
|
||||
|
||||
|
||||
def commit_sources(raw_sources: Any, *, on_conflict: str, merge: bool = False) -> list[SourceCommitResult]:
|
||||
"""Writes a batch in one transaction. With `merge`, rows of different
|
||||
sources sharing a natural key are combined first (see `merge_duplicates`)."""
|
||||
try:
|
||||
policy = ConflictPolicy(on_conflict)
|
||||
except ValueError as exc:
|
||||
raise ImportRequestError(f"invalid on_conflict: {on_conflict!r}") from exc
|
||||
|
||||
sources = _parse_batch(raw_sources)
|
||||
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")
|
||||
|
||||
# Read + validate everything before opening the write transaction, so a
|
||||
# slow source (OCR, a remote SQL table) never holds database locks.
|
||||
rows: list[list[dict[str, Any] | None]] = [list(source.rows()) for source in sources]
|
||||
merged, merge_warnings = merge_duplicates(sources, rows) if merge else ({}, {})
|
||||
validated = [(source, validate_rows(source.spec.schema, source_rows)) for source, source_rows in zip(sources, rows)]
|
||||
|
||||
session = sources[0].spec.repository.open_session()
|
||||
links = LinkResolver(session)
|
||||
results: dict[int, SourceCommitResult] = {}
|
||||
# Parents first (Paciente, then OrdenesEstudio, then the rest), so a
|
||||
# child's FK lookup finds a parent loaded by another source of the same
|
||||
# batch. Results are still reported in the caller's order.
|
||||
write_order = sorted(range(len(validated)), key=lambda i: dependency_rank(validated[i][0].target))
|
||||
try:
|
||||
for position in write_order:
|
||||
source, validation = validated[position]
|
||||
linked: dict[str, int] = {}
|
||||
for row in validation.accepted_rows:
|
||||
for fk_field in links.resolve(source.target, row.data):
|
||||
linked[fk_field] = linked.get(fk_field, 0) + 1
|
||||
objs = [source.spec.model(**row.data) for row in validation.accepted_rows]
|
||||
write = source.spec.repository.bulk_upsert(
|
||||
objs, conflict_fields=source.spec.conflict_fields, on_conflict=policy, session=session
|
||||
)
|
||||
conflict_errors = [
|
||||
{
|
||||
"row_index": validation.accepted_rows[outcome.index].row_index,
|
||||
"field": ",".join(source.spec.conflict_fields or ()),
|
||||
"category": "conflict",
|
||||
"message": outcome.error or "conflict",
|
||||
"raw_value": _jsonable(
|
||||
validation.accepted_rows[outcome.index].data.get((source.spec.conflict_fields or ("",))[0])
|
||||
),
|
||||
}
|
||||
for outcome in write.outcomes
|
||||
if outcome.status == "rejected"
|
||||
]
|
||||
errors = sorted(serialize_errors(validation) + conflict_errors, key=lambda e: e["row_index"])
|
||||
results[position] = SourceCommitResult(
|
||||
target=source.target,
|
||||
label=source.label,
|
||||
total=validation.total_rows,
|
||||
created=write.created_count,
|
||||
updated=write.updated_count,
|
||||
rejected=write.rejected_count + validation.error_count,
|
||||
errors=errors,
|
||||
linked=linked,
|
||||
merged=merged.get(position, 0),
|
||||
warnings=merge_warnings.get(position, []),
|
||||
)
|
||||
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
|
||||
finally:
|
||||
session.close()
|
||||
return [results[i] for i in range(len(validated))]
|
||||
@@ -1,81 +0,0 @@
|
||||
"""Response shapes for the `/imports/sources/*` routes: previews with
|
||||
auto-match suggestions, PDF table detection and region extraction, and
|
||||
document extraction reports."""
|
||||
from typing import Any
|
||||
|
||||
import pandas as pd
|
||||
|
||||
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.schemas.registry import ENTITY_REGISTRY
|
||||
|
||||
|
||||
def suggest_mapping(source_columns: list[str], target_key: str | None) -> list[dict[str, Any]]:
|
||||
if not target_key:
|
||||
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()))
|
||||
return [
|
||||
{"source_column": m.source_column, "target_field": m.target_field, "confidence": m.confidence, "reason": m.reason}
|
||||
for m in matches
|
||||
]
|
||||
|
||||
|
||||
def preview_with_suggestions(connector: Connector, target_key: str | None, *, limit: int = 50) -> dict[str, Any]:
|
||||
preview = connector.preview(limit=limit)
|
||||
return {
|
||||
"columns": [{"name": c.name, "inferred_type": c.inferred_type} for c in preview.columns],
|
||||
"sample_rows": preview.sample_rows,
|
||||
"total_rows": preview.total_rows,
|
||||
"suggested_mapping": suggest_mapping([c.name for c in preview.columns], target_key),
|
||||
"tables": [{"name": t.name, "options": t.options, "kind": t.kind} for t in connector.tables()],
|
||||
"source_metadata": connector.metadata(),
|
||||
}
|
||||
|
||||
|
||||
def detect_pdf(raw: bytes) -> dict[str, Any]:
|
||||
"""Page count, whether there is a text layer, and every ruled table
|
||||
pdfplumber found, best candidates first."""
|
||||
connector = PdfConnector(raw)
|
||||
return {
|
||||
"page_count": connector.page_count,
|
||||
"has_text_layer": connector.has_text_layer(),
|
||||
"table_candidates": [
|
||||
{
|
||||
"page_number": candidate.page_number,
|
||||
"bbox": list(candidate.bbox),
|
||||
"column_count": len(candidate.grid[0]) if candidate.grid else 0,
|
||||
"row_count": len(candidate.grid) - 1 if candidate.grid else 0,
|
||||
"preview_grid": candidate.grid,
|
||||
}
|
||||
for candidate in connector.detect_tables()
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def extract_pdf_regions(raw: bytes, regions: list[dict[str, Any]], *, dpi: int = 150, target_key: str | None = None) -> dict[str, Any]:
|
||||
connector = PdfConnector(raw)
|
||||
resolved = connector.extract_regions([RegionSpec.parse(r) for r in regions], dpi=dpi)
|
||||
df = pd.DataFrame(resolved, dtype=object)
|
||||
columns = columns_from_dataframe(df)
|
||||
return {
|
||||
"columns": [{"name": c.name, "inferred_type": c.inferred_type} for c in columns],
|
||||
"rows": rows_from_dataframe(df),
|
||||
"warnings": [{"page_number": w.page_number, "message": w.message} for w in connector.warnings],
|
||||
"suggested_mapping": suggest_mapping([c.name for c in columns], target_key),
|
||||
}
|
||||
|
||||
|
||||
def document_report(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
connector = DocumentConnector.from_payload(payload)
|
||||
preview = preview_with_suggestions(connector, connector.target, limit=500)
|
||||
fields = [
|
||||
{"name": spec.name, "kind": spec.kind.value, "required": spec.required, "labels": list(spec.labels)}
|
||||
for spec in connector.specs
|
||||
]
|
||||
return {**preview, "key_field": connector.key_field, "fields": fields, "records": connector.report()}
|
||||
@@ -1,82 +0,0 @@
|
||||
"""Fills a child row's foreign keys from the natural keys it carries, as
|
||||
Core's column descriptions specify (e.g. `NotaMedica.pac_id` is looked up by
|
||||
`pac_id_hospital`). This links rows that came from unrelated sources in the
|
||||
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.
|
||||
"""
|
||||
from dataclasses import dataclass
|
||||
from functools import cache
|
||||
from typing import Any
|
||||
|
||||
from sqlmodel import Session, select
|
||||
|
||||
from webapi.imports.schemas.registry import ENTITY_REGISTRY
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ForeignKeyLink:
|
||||
fk_field: str # on the child, e.g. "pac_id"
|
||||
via_field: str # natural key on the child, e.g. "pac_id_hospital"
|
||||
parent: str # registry key, e.g. "cacu.Paciente"
|
||||
parent_key: str # natural key on the parent
|
||||
parent_pk: str # primary key on the parent
|
||||
|
||||
|
||||
# (fk column, natural-key column, parent entity name, parent primary key)
|
||||
_CONVENTIONS = (
|
||||
("pac_id", "pac_id_hospital", "Paciente", "pac_id"),
|
||||
("ord_id", "ord_numero_hospital", "OrdenesEstudio", "ord_id"),
|
||||
)
|
||||
|
||||
|
||||
@cache
|
||||
def links_for(target_key: str) -> tuple[ForeignKeyLink, ...]:
|
||||
domain, _, name = target_key.partition(".")
|
||||
columns = set(ENTITY_REGISTRY[target_key].model.__table__.columns.keys())
|
||||
links = []
|
||||
for fk_field, via_field, parent_name, parent_pk in _CONVENTIONS:
|
||||
parent = f"{domain}.{parent_name}"
|
||||
if name != parent_name and parent in ENTITY_REGISTRY and {fk_field, via_field} <= columns:
|
||||
links.append(ForeignKeyLink(fk_field, via_field, parent, via_field, parent_pk))
|
||||
return tuple(links)
|
||||
|
||||
|
||||
@cache
|
||||
def dependency_rank(target_key: str) -> int:
|
||||
"""Write order within a batch: parents rank lower than their children, so
|
||||
a child's lookup finds a parent written earlier in the same batch."""
|
||||
return max((dependency_rank(link.parent) + 1 for link in links_for(target_key)), default=0)
|
||||
|
||||
|
||||
class LinkResolver:
|
||||
"""Looks up parent primary keys by natural key within the batch's session,
|
||||
so parents written earlier in the same uncommitted transaction are found.
|
||||
A missing parent leaves the FK null, which Core allows."""
|
||||
|
||||
def __init__(self, session: Session):
|
||||
self._session = session
|
||||
self._cache: dict[tuple[str, Any], Any] = {}
|
||||
|
||||
def resolve(self, target_key: str, row: dict[str, Any]) -> list[str]:
|
||||
linked = []
|
||||
for link in links_for(target_key):
|
||||
value = row.get(link.via_field)
|
||||
if row.get(link.fk_field) is not None or value is None:
|
||||
continue
|
||||
pk = self._lookup(link, value)
|
||||
if pk is not None:
|
||||
row[link.fk_field] = pk
|
||||
linked.append(link.fk_field)
|
||||
return linked
|
||||
|
||||
def _lookup(self, link: ForeignKeyLink, value: Any) -> Any:
|
||||
cache_key = (link.parent, value)
|
||||
if cache_key not in self._cache:
|
||||
parent = ENTITY_REGISTRY[link.parent].model
|
||||
statement = select(getattr(parent, link.parent_pk)).where(getattr(parent, link.parent_key) == value)
|
||||
self._cache[cache_key] = self._session.exec(statement).first()
|
||||
return self._cache[cache_key]
|
||||
@@ -1,199 +0,0 @@
|
||||
"""Las rutas de indicadores, iguales para cada proyecto (CaCu, CaMa, TEA).
|
||||
|
||||
`registrar_indicadores` agrega a un blueprint:
|
||||
|
||||
GET /indicadores catálogo de indicadores
|
||||
GET /indicadores/<id>/periodos periodos con reporte
|
||||
GET /indicadores/<id>/datos?periodos=&estrato= los números, sin figura
|
||||
GET /indicadores/<id>/metadatos ficha metodológica
|
||||
GET /indicadores/<id>/figuras/<figura>?periodos=&tema=
|
||||
|
||||
Las definiciones salen del kit (`measures_de`), los datos de
|
||||
`indicadores_kit.serving.datos` y las figuras de
|
||||
`indicadores_kit.serving.figuras`; aquí solo se valida, se abre la sesión y
|
||||
se traducen los errores a códigos HTTP. La forma de cada respuesta es un
|
||||
contrato con el frontend: no se quita ni se renombra un campo.
|
||||
"""
|
||||
|
||||
import json
|
||||
import re
|
||||
from collections.abc import Callable
|
||||
|
||||
from flask import Blueprint, Response, jsonify, request
|
||||
from indicadores_kit.registry.measures import Measure, measures_de
|
||||
from indicadores_kit.serving.datos import datos_de, metadatos_de, periodos_de, resumen_de
|
||||
from indicadores_kit.serving.figuras import (
|
||||
TEMAS,
|
||||
figura_json,
|
||||
figuras_de,
|
||||
periodos_con_reporte,
|
||||
periodos_por_defecto,
|
||||
)
|
||||
from indicadores_kit.tablas import tablas_de
|
||||
from sqlmodel import Session
|
||||
|
||||
# Cómo se escribe un periodo de cada tipo (`registry/periodos.py`) y un ejemplo para el mensaje.
|
||||
FORMATOS = {
|
||||
"dia": (re.compile(r"\d{4}-\d{2}-\d{2}"), "AAAA-MM-DD"),
|
||||
"semana_epidemiologica": (re.compile(r"\d{4}-SE\d{2}"), "AAAA-SEnn"),
|
||||
"semana_habil": (re.compile(r"\d{4}-SH\d{2}"), "AAAA-SHnn"),
|
||||
"semana_iso": (re.compile(r"\d{4}-W\d{2}"), "AAAA-Wnn"),
|
||||
"mes": (re.compile(r"\d{4}-\d{2}"), "AAAA-MM"),
|
||||
"bimestre": (re.compile(r"\d{4}-B[1-6]"), "AAAA-B1 a AAAA-B6"),
|
||||
"trimestre": (re.compile(r"\d{4}-T[1-4]"), "AAAA-T1 a AAAA-T4"),
|
||||
"semestre": (re.compile(r"\d{4}-S[12]"), "AAAA-S1 o AAAA-S2"),
|
||||
}
|
||||
|
||||
|
||||
def _error(mensaje: str, codigo: int):
|
||||
return jsonify({"error": mensaje}), codigo
|
||||
|
||||
|
||||
def _json(contenido) -> Response:
|
||||
"""Sin `jsonify`, que ordena las llaves: grupos y categorías van en su orden de presentación."""
|
||||
return Response(json.dumps(contenido, ensure_ascii=False), mimetype="application/json")
|
||||
|
||||
|
||||
def _tipo_de(periodo: str, tipos: list[str]) -> str | None:
|
||||
"""El tipo, entre los que publica el indicador, al que pertenece el periodo (o `None`)."""
|
||||
return next((tipo for tipo in tipos if FORMATOS[tipo][0].fullmatch(periodo)), None)
|
||||
|
||||
|
||||
def periodos_pedidos(texto: str | None, medida: Measure) -> tuple[list[str], str | None]:
|
||||
"""Los periodos de `?periodos=` y su tipo. Sin parámetro (o vacío): `([], None)`.
|
||||
|
||||
Raises:
|
||||
ValueError: un periodo mal formado, de un tipo que el indicador no
|
||||
publica (`extension.publicacion.tipos_periodo`), o de tipos mezclados.
|
||||
"""
|
||||
if not texto:
|
||||
return [], None
|
||||
tipos = medida.extension.publicacion.tipos_periodo
|
||||
periodos = list(dict.fromkeys(texto.split(",")))
|
||||
encontrados = {_tipo_de(periodo, tipos) for periodo in periodos}
|
||||
if None in encontrados:
|
||||
formatos = "; ".join(FORMATOS[tipo][1] for tipo in tipos)
|
||||
raise ValueError(f"Periodos mal formados: {texto!r}; este indicador publica {formatos}.")
|
||||
if len(encontrados) > 1:
|
||||
raise ValueError(f"Periodos de tipos distintos: {texto!r}; pida un solo tipo a la vez.")
|
||||
return periodos, encontrados.pop()
|
||||
|
||||
|
||||
def registrar_indicadores(
|
||||
blueprint: Blueprint, proyecto: str, get_session: Callable[[], Session]
|
||||
) -> None:
|
||||
"""Agrega las rutas de indicadores de `proyecto` al blueprint.
|
||||
|
||||
`get_session` es la fábrica de `Persistance` (`get_<proyecto>_session`):
|
||||
se llama en cada petición, no al registrar.
|
||||
"""
|
||||
definiciones = measures_de(proyecto) # fijas: se leen una vez
|
||||
tablas = tablas_de(proyecto)
|
||||
|
||||
def listar_indicadores():
|
||||
# Los marcados `oculto` en su TOML no salen en el catálogo; su id sigue respondiendo.
|
||||
return _json([
|
||||
resumen_de(id_, medida)
|
||||
for id_, medida in definiciones.items()
|
||||
if not medida.extension.publicacion.oculto
|
||||
])
|
||||
|
||||
def _periodos_o_los_que_haya(sesion: Session, medida: Measure, periodos: list[str]) -> list[str]:
|
||||
"""Los pedidos; sin pedir ninguno, los que tienen reporte del primer tipo que publica."""
|
||||
if periodos:
|
||||
return periodos
|
||||
tipo = medida.extension.publicacion.tipos_periodo[0]
|
||||
return periodos_con_reporte(sesion, medida, tablas=tablas, tipo=tipo)
|
||||
|
||||
def get_periodos(indicador: str):
|
||||
medida = definiciones.get(indicador)
|
||||
if medida is None:
|
||||
return _error("indicador desconocido", 404)
|
||||
sesion = get_session()
|
||||
try:
|
||||
periodos = periodos_de(sesion, medida, tablas=tablas)
|
||||
finally:
|
||||
sesion.close()
|
||||
return _json({"id": indicador, "version": medida.version, "periodos": periodos})
|
||||
|
||||
def get_metadatos(indicador: str):
|
||||
medida = definiciones.get(indicador)
|
||||
if medida is None:
|
||||
return _error("indicador desconocido", 404)
|
||||
sesion = get_session()
|
||||
try:
|
||||
metadatos = metadatos_de(sesion, medida, tablas=tablas)
|
||||
finally:
|
||||
sesion.close()
|
||||
return _json({"id": indicador, **metadatos})
|
||||
|
||||
def get_datos(indicador: str):
|
||||
medida = definiciones.get(indicador)
|
||||
if medida is None:
|
||||
return _error("indicador desconocido", 404)
|
||||
estrato = request.args.get("estrato") or None
|
||||
if estrato is not None and estrato not in medida.extension.estratos:
|
||||
return _error(
|
||||
f"estrato desconocido {estrato!r}; este indicador tiene {medida.extension.estratos}",
|
||||
400,
|
||||
)
|
||||
try:
|
||||
periodos, _ = periodos_pedidos(request.args.get("periodos"), medida)
|
||||
except ValueError as error:
|
||||
return _error(str(error), 400)
|
||||
|
||||
sesion = get_session()
|
||||
try:
|
||||
periodos = _periodos_o_los_que_haya(sesion, medida, periodos)
|
||||
if not periodos:
|
||||
return _error("el indicador no tiene reportes calculados", 404)
|
||||
datos = datos_de(sesion, medida, periodos, tablas=tablas, estrato=estrato)
|
||||
except KeyError:
|
||||
# KeyError también es LookupError: aquí es un error interno (500), no un periodo sin reporte.
|
||||
raise
|
||||
except LookupError as error:
|
||||
return _error(str(error), 404)
|
||||
finally:
|
||||
sesion.close()
|
||||
return _json({"id": indicador, **datos})
|
||||
|
||||
def get_figura(indicador: str, figura: str):
|
||||
medida = definiciones.get(indicador)
|
||||
if medida is None:
|
||||
return _error("indicador desconocido", 404)
|
||||
if figura not in figuras_de(medida):
|
||||
return _error(
|
||||
f"figura {figura!r} no es del contrato {medida.extension.contrato}", 404
|
||||
)
|
||||
|
||||
tema = request.args.get("tema", "claro")
|
||||
if tema not in TEMAS:
|
||||
return _error(f"tema desconocido {tema!r}; use claro u oscuro", 400)
|
||||
try:
|
||||
periodos, tipo = periodos_pedidos(request.args.get("periodos"), medida)
|
||||
except ValueError as error:
|
||||
return _error(str(error), 400)
|
||||
|
||||
sesion = get_session()
|
||||
try:
|
||||
# Sin pedir ninguno: todos, o solo el más reciente si la figura se lee en un periodo.
|
||||
periodos = periodos or periodos_por_defecto(sesion, medida, figura, tablas=tablas)
|
||||
if not periodos:
|
||||
return _error("el indicador no tiene reportes calculados", 404)
|
||||
texto = figura_json(sesion, medida, periodos, figura, tablas=tablas, tema=tema)
|
||||
except KeyError:
|
||||
# KeyError también es LookupError: aquí es un error interno (500), no un periodo sin reporte.
|
||||
raise
|
||||
except LookupError as error:
|
||||
return _error(str(error), 404)
|
||||
finally:
|
||||
sesion.close()
|
||||
return Response(texto, mimetype="application/json")
|
||||
|
||||
blueprint.add_url_rule("/indicadores", "listar_indicadores", listar_indicadores)
|
||||
blueprint.add_url_rule("/indicadores/<indicador>/periodos", "get_periodos", get_periodos)
|
||||
blueprint.add_url_rule("/indicadores/<indicador>/datos", "get_datos", get_datos)
|
||||
blueprint.add_url_rule("/indicadores/<indicador>/metadatos", "get_metadatos", get_metadatos)
|
||||
blueprint.add_url_rule(
|
||||
"/indicadores/<indicador>/figuras/<figura>", "get_figura", get_figura
|
||||
)
|
||||
@@ -0,0 +1,158 @@
|
||||
from typing import Annotated, Any
|
||||
|
||||
from dagster_graphql import DagsterGraphQLClient, DagsterGraphQLClientError
|
||||
from fastapi import APIRouter, Depends, HTTPException, Path, Query
|
||||
from fhir.resources.R4B.conceptmap import ConceptMap
|
||||
from pydantic import BaseModel
|
||||
|
||||
from core import concept_map
|
||||
from core.pipeline import ID_PATTERN, Pipeline, Source, redacted, restored
|
||||
from core.schema import ENTITIES
|
||||
from persistance import config_log, nodes
|
||||
from webapi.runs import dagster
|
||||
|
||||
router = APIRouter(prefix="/ingest", tags=["ingest"])
|
||||
PipelineId = Annotated[str, Path(pattern=ID_PATTERN, max_length=40)]
|
||||
NodeId = Annotated[str, Path(pattern=ID_PATTERN, max_length=40)]
|
||||
Rows = list[dict[str, Any]]
|
||||
|
||||
|
||||
def _from_source(call, *args):
|
||||
try:
|
||||
return call(*args)
|
||||
except Exception as e: # noqa: BLE001
|
||||
raise HTTPException(422, detail=f"{type(e).__name__}: {e}") from e
|
||||
|
||||
|
||||
@router.get(
|
||||
"/schema",
|
||||
description="What the canvas draws with: every node kind's form, and the platform entities.",
|
||||
)
|
||||
def schema() -> dict[str, Any]:
|
||||
return {
|
||||
"pipeline": Pipeline.model_json_schema(),
|
||||
"entities": {name: model.model_json_schema() for name, model in ENTITIES.items()},
|
||||
}
|
||||
|
||||
|
||||
@router.post(
|
||||
"/sources/preview",
|
||||
description="The first rows a source node would load.",
|
||||
)
|
||||
def source_preview(node: Source, limit: Annotated[int, Query(ge=1, le=200)] = 20) -> Rows:
|
||||
return [nodes.shown(r) for r in _from_source(nodes.preview, node, limit)]
|
||||
|
||||
|
||||
@router.get("/pipelines")
|
||||
def pipelines() -> Rows:
|
||||
return config_log.pipelines()
|
||||
|
||||
|
||||
class SavedPipeline(BaseModel):
|
||||
version: int
|
||||
pipeline: Pipeline
|
||||
|
||||
|
||||
@router.get(
|
||||
"/pipelines/{pipeline_id}",
|
||||
description="A saved pipeline (latest by default), with its secrets masked.",
|
||||
)
|
||||
def pipeline(pipeline_id: PipelineId, version: int | None = None) -> SavedPipeline:
|
||||
if not config_log.latest_version(pipeline_id):
|
||||
raise HTTPException(404, detail=f"no pipeline {pipeline_id}")
|
||||
found, saved = config_log.get(pipeline_id, version)
|
||||
return SavedPipeline(version=found, pipeline=redacted(saved))
|
||||
|
||||
|
||||
@router.put(
|
||||
"/pipelines/{pipeline_id}",
|
||||
description=(
|
||||
"Saves a new version. Masked secrets sent back are kept as they "
|
||||
"were saved; every\n"
|
||||
"ConceptMap a node names must exist."
|
||||
),
|
||||
)
|
||||
def save_pipeline(pipeline_id: PipelineId, drawn: Pipeline) -> dict[str, int]:
|
||||
named = {n.concept_map for n in drawn.nodes if getattr(n, "concept_map", None)}
|
||||
if missing := sorted(m for m in named if not config_log.latest_version(m, "concept_maps")):
|
||||
raise HTTPException(422, detail=f"no concept maps {missing}")
|
||||
previous = config_log.get(pipeline_id)[1] if config_log.latest_version(pipeline_id) else None
|
||||
try:
|
||||
complete = restored(drawn, previous)
|
||||
except ValueError as e:
|
||||
raise HTTPException(422, detail=str(e)) from e
|
||||
return {"version": config_log.save(pipeline_id, complete)}
|
||||
|
||||
|
||||
@router.get(
|
||||
"/concept-maps/{map_id}",
|
||||
description="A site's codes in platform terms (FHIR R4B ConceptMap), latest version.",
|
||||
)
|
||||
def get_concept_map(map_id: PipelineId) -> dict[str, Any]:
|
||||
if not config_log.latest_version(map_id, "concept_maps"):
|
||||
raise HTTPException(404, detail=f"no concept map {map_id}")
|
||||
return config_log.concept_map(map_id).model_dump(mode="json", exclude_none=True)
|
||||
|
||||
|
||||
@router.put(
|
||||
"/concept-maps/{map_id}",
|
||||
description=(
|
||||
"Saves a new version of a ConceptMap. Its groups target the "
|
||||
"systems platform fields\n"
|
||||
"take codes from, and only codes those fields allow "
|
||||
"(core.concept_map)."
|
||||
),
|
||||
)
|
||||
def save_concept_map(map_id: PipelineId, doc: dict[str, Any]) -> dict[str, int]:
|
||||
try:
|
||||
found = ConceptMap.model_validate({**doc, "resourceType": "ConceptMap"})
|
||||
except ValueError as e:
|
||||
raise HTTPException(422, detail=str(e)) from e
|
||||
if problems := concept_map.problems(found):
|
||||
raise HTTPException(422, detail=problems)
|
||||
return {"version": config_log.save(map_id, found, "concept_maps")}
|
||||
|
||||
|
||||
class RunRequest(BaseModel):
|
||||
version: int | None = None
|
||||
|
||||
|
||||
@router.post(
|
||||
"/pipelines/{pipeline_id}/runs",
|
||||
description="Starts the `ingest` job for this pipeline; follow it at /runs/{run_id}.",
|
||||
)
|
||||
def start_run(
|
||||
pipeline_id: PipelineId,
|
||||
request: RunRequest,
|
||||
client: DagsterGraphQLClient = Depends(dagster),
|
||||
) -> dict[str, str]:
|
||||
if not config_log.latest_version(pipeline_id):
|
||||
raise HTTPException(404, detail=f"no pipeline {pipeline_id}")
|
||||
return {"run_id": submit(client, pipeline_id, request.version)}
|
||||
|
||||
|
||||
def submit(client: DagsterGraphQLClient, pipeline_id: str, version: int | None = None) -> str:
|
||||
config = {"pipeline": pipeline_id, "version": version}
|
||||
try:
|
||||
return client.submit_job_execution(
|
||||
"ingest", run_config={"ops": {"run_pipeline": {"config": config}}}
|
||||
)
|
||||
except DagsterGraphQLClientError as e:
|
||||
raise HTTPException(502, detail=str(e)) from e
|
||||
|
||||
|
||||
@router.get(
|
||||
"/pipelines/{pipeline_id}/nodes/{node_id}/rows",
|
||||
description="What a node produced in the last run (empty if it produced nothing yet).",
|
||||
)
|
||||
def node_rows(
|
||||
pipeline_id: PipelineId,
|
||||
node_id: NodeId,
|
||||
limit: Annotated[int, Query(ge=1, le=500)] = 50,
|
||||
) -> Rows:
|
||||
out = []
|
||||
for row in nodes.rows(pipeline_id, node_id):
|
||||
out.append(nodes.shown(row))
|
||||
if len(out) == limit:
|
||||
break
|
||||
return out
|
||||
@@ -0,0 +1,42 @@
|
||||
from fastapi import Depends, FastAPI, Request
|
||||
from fastapi.exception_handlers import http_exception_handler
|
||||
from starlette.exceptions import HTTPException
|
||||
|
||||
from core.domains import Domain
|
||||
from webapi import eeg, execution, fhir, ingest, models, preview, review, runs, sources, users
|
||||
from webapi.auth import caller
|
||||
|
||||
app = FastAPI(
|
||||
title="ISSSTELEON",
|
||||
version="0.0.0",
|
||||
dependencies=[Depends(caller)],
|
||||
generate_unique_id_function=lambda route: route.name,
|
||||
lifespan=users.lifespan,
|
||||
)
|
||||
app.include_router(ingest.router)
|
||||
app.include_router(sources.router)
|
||||
app.include_router(review.router)
|
||||
app.include_router(runs.router)
|
||||
app.include_router(execution.router)
|
||||
app.include_router(models.router)
|
||||
app.include_router(eeg.router)
|
||||
app.include_router(preview.router)
|
||||
app.include_router(fhir.router)
|
||||
app.include_router(users.router)
|
||||
|
||||
|
||||
@app.exception_handler(HTTPException)
|
||||
async def errors(request: Request, error: HTTPException):
|
||||
if "/fhir/" in request.url.path or request.url.path.endswith("/fhir"):
|
||||
return fhir.outcome(error.status_code, str(error.detail))
|
||||
return await http_exception_handler(request, error)
|
||||
|
||||
|
||||
@app.get("/health")
|
||||
def health() -> dict[str, str]:
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@app.get("/domains")
|
||||
def domains() -> list[Domain]:
|
||||
return list(Domain)
|
||||
@@ -0,0 +1,289 @@
|
||||
import mimetypes
|
||||
import zipfile
|
||||
from datetime import date
|
||||
from typing import Annotated, Any, Literal
|
||||
|
||||
from dagster_graphql import DagsterGraphQLClient
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, UploadFile
|
||||
from fastapi.responses import Response
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from core.domains import Domain
|
||||
from core.models import title
|
||||
from persistance import bundle, cluster, registry
|
||||
from persistance.cluster import Execution, TrainingSource
|
||||
from webapi.runs import dagster, execution_config, submit
|
||||
|
||||
router = APIRouter(prefix="/models", tags=["models"])
|
||||
|
||||
|
||||
class Version(BaseModel):
|
||||
version: int
|
||||
created: int
|
||||
aliases: list[str]
|
||||
metrics: dict[str, float]
|
||||
params: dict[str, str]
|
||||
reports: list[str]
|
||||
status: Literal["champion", "retired", "candidate"]
|
||||
|
||||
|
||||
class Model(BaseModel):
|
||||
name: str
|
||||
title: str
|
||||
|
||||
|
||||
@router.get("/{domain}")
|
||||
def models(domain: Domain) -> list[Model]:
|
||||
prefix = f"{domain.value}."
|
||||
return [Model(name=n.removeprefix(prefix), title=title(n)) for n in registry.names(prefix)]
|
||||
|
||||
|
||||
@router.get(
|
||||
"/{domain}/export",
|
||||
responses={200: {"content": {"application/zip": {}}}},
|
||||
response_class=Response,
|
||||
)
|
||||
def export_models(
|
||||
domain: Domain,
|
||||
names: Annotated[list[str] | None, Query()] = None,
|
||||
versions: bundle.Selection = "champion",
|
||||
) -> Response:
|
||||
try:
|
||||
exported = bundle.export(domain, names, versions)
|
||||
except bundle.Empty as e:
|
||||
raise HTTPException(409, detail=str(e)) from e
|
||||
except bundle.BundleError as e:
|
||||
raise HTTPException(422, detail=str(e)) from e
|
||||
return Response(
|
||||
exported.data,
|
||||
media_type="application/zip",
|
||||
headers={
|
||||
"X-Bundle-Sha256": exported.sha256,
|
||||
"X-Bundle-Versions": ",".join(f"{name}/{v}" for name, v in exported.versions),
|
||||
"Content-Disposition": (
|
||||
f'attachment; filename="{domain}-models-{exported.sha256[:12]}.zip"'
|
||||
),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@router.post("/{domain}/import")
|
||||
def import_models(
|
||||
domain: Domain,
|
||||
sha256: Annotated[str, Query(pattern=r"^[0-9a-fA-F]{64}$")],
|
||||
file: UploadFile,
|
||||
client: DagsterGraphQLClient = Depends(dagster),
|
||||
) -> dict[str, str]:
|
||||
computed, path = bundle.stage(file.file)
|
||||
if computed != sha256.lower():
|
||||
path.unlink(missing_ok=True)
|
||||
raise HTTPException(422, detail=f"the file's SHA-256 is {computed}, not the one given")
|
||||
if not zipfile.is_zipfile(path):
|
||||
path.unlink(missing_ok=True)
|
||||
raise HTTPException(422, detail="not a bundle")
|
||||
if not bundle.trusted(computed):
|
||||
path.unlink(missing_ok=True)
|
||||
raise HTTPException(
|
||||
403,
|
||||
detail=f"bundle {computed} is not trusted on this server: "
|
||||
f"the operator adds its SHA-256 to {bundle.trusted_file()}",
|
||||
)
|
||||
return submit(
|
||||
client,
|
||||
"import_bundle",
|
||||
"import_bundle_files",
|
||||
{"domain": domain.value, "sha256": computed},
|
||||
domain.value,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{domain}/{name}/versions")
|
||||
def versions(domain: Domain, name: str) -> list[Version]:
|
||||
if not (found := registry.versions(f"{domain.value}.{name}")):
|
||||
raise HTTPException(404, detail=f"no {domain.value} model {name}")
|
||||
return [Version(**v) for v in found]
|
||||
|
||||
|
||||
@router.get("/{domain}/{name}/versions/{version}/reports/{report}",
|
||||
responses={200: {"content": {"application/json": {}, "application/octet-stream": {}},
|
||||
"description": "the report as stored"}},
|
||||
response_class=Response,
|
||||
description=(
|
||||
"A version's report: the generated ones as JSON (what the "
|
||||
'governance page draws), the\n'
|
||||
'clinical validation as the file the clinical team uploaded.'
|
||||
),
|
||||
) # fmt: skip
|
||||
def read_report(domain: Domain, name: str, version: int, report: str) -> Response:
|
||||
found = registry.report(f"{domain.value}.{name}", version, report)
|
||||
if found is None:
|
||||
raise HTTPException(404, detail=f"{domain.value}.{name} v{version} has no {report}")
|
||||
filename, content = found
|
||||
kind = mimetypes.guess_type(filename)[0] or "application/octet-stream"
|
||||
return Response(content, media_type=kind,
|
||||
headers={"Content-Disposition": f'inline; filename="{filename}"'}) # fmt: skip
|
||||
|
||||
|
||||
@router.post(
|
||||
"/{domain}/{name}/versions/{version}/reports/clinical_validation",
|
||||
description=(
|
||||
"The clinical team's validation of a version: the third report, "
|
||||
"which promotion needs\n"
|
||||
"unless the site left it out of PROMOTION_REPORTS."
|
||||
),
|
||||
)
|
||||
def add_clinical_validation(domain: Domain, name: str, version: int, file: UploadFile) -> dict:
|
||||
registry.add_report(f"{domain.value}.{name}", version, "clinical_validation",
|
||||
file.filename or "report", file.file.read()) # fmt: skip
|
||||
return {"reports": sorted(registry.reports(f"{domain.value}.{name}", version))}
|
||||
|
||||
|
||||
@router.post(
|
||||
"/{domain}/{name}/versions/{version}/promote",
|
||||
description=(
|
||||
"The version risk batches come from from now on; refused (409) "
|
||||
"without the reports\n"
|
||||
"the site requires (PROMOTION_REPORTS; default: technical "
|
||||
"validation, interpretability\n"
|
||||
"and clinical validation)."
|
||||
),
|
||||
)
|
||||
def promote(domain: Domain, name: str, version: int) -> dict:
|
||||
try:
|
||||
registry.promote(f"{domain.value}.{name}", version)
|
||||
except registry.UnknownVersion as e:
|
||||
raise HTTPException(404, detail=str(e)) from e
|
||||
except ValueError as e:
|
||||
raise HTTPException(409, detail=str(e)) from e
|
||||
return {"champion": version}
|
||||
|
||||
|
||||
@router.get("/{domain}/{name}/versions/{version}/checks")
|
||||
def version_checks(domain: Domain, name: str, version: int) -> dict:
|
||||
registered = f"{domain.value}.{name}"
|
||||
try:
|
||||
status = registry.status(registered, version)
|
||||
except registry.UnknownVersion as e:
|
||||
raise HTTPException(404, detail=str(e)) from e
|
||||
checks = registry.checks(registered, version)
|
||||
return {
|
||||
"version": version,
|
||||
"status": status,
|
||||
"checks": checks,
|
||||
"promotable": status != "retired" and all(check["present"] for check in checks),
|
||||
}
|
||||
|
||||
|
||||
@router.post("/{domain}/{name}/versions/{version}/retire")
|
||||
def retire(domain: Domain, name: str, version: int) -> dict[str, str]:
|
||||
try:
|
||||
registry.retire(f"{domain.value}.{name}", version)
|
||||
except registry.UnknownVersion as e:
|
||||
raise HTTPException(404, detail=str(e)) from e
|
||||
except ValueError as e:
|
||||
raise HTTPException(409, detail=str(e)) from e
|
||||
return {"status": "retired"}
|
||||
|
||||
|
||||
@router.get("/{domain}/{name}/versions/{version}/lineage")
|
||||
def lineage(domain: Domain, name: str, version: int) -> dict:
|
||||
try:
|
||||
return registry.lineage(f"{domain.value}.{name}", version)
|
||||
except registry.UnknownVersion as e:
|
||||
raise HTTPException(404, detail=str(e)) from e
|
||||
|
||||
|
||||
@router.get("/{domain}/{name}/versions/{version}/curve")
|
||||
def curve(domain: Domain, name: str, version: int, feature: str = "value") -> list[dict]:
|
||||
if domain != Domain.TEA:
|
||||
raise HTTPException(404, detail="no age curve for this model")
|
||||
try:
|
||||
model = registry.load(f"{domain.value}.{name}", version).unwrap_python_model()
|
||||
if not hasattr(model, "curve"):
|
||||
raise HTTPException(404, detail="no age curve for this model")
|
||||
return model.curve(feature, range(16, 37))
|
||||
except KeyError as e:
|
||||
raise HTTPException(404, detail=f"no curve feature {feature!r}") from e
|
||||
except LookupError as e:
|
||||
raise HTTPException(404, detail=str(e)) from e
|
||||
|
||||
|
||||
class TrainingForm(BaseModel):
|
||||
as_of: date | None = Field(
|
||||
None, title="Datos hasta", description="Fecha de corte de los datos (por omisión, hoy)"
|
||||
)
|
||||
execution: Execution | None = None
|
||||
source: TrainingSource | None = Field(None, title="Datos de entrenamiento")
|
||||
|
||||
|
||||
class Training(TrainingForm):
|
||||
models: list[str] = []
|
||||
|
||||
|
||||
class TrainingConfig(BaseModel):
|
||||
domain: str
|
||||
name: str
|
||||
json_schema: dict[str, Any]
|
||||
defaults: dict[str, Any]
|
||||
|
||||
|
||||
@router.get("/{domain}/{name}/training-config")
|
||||
def training_config(domain: Domain, name: str) -> TrainingConfig:
|
||||
json_schema = TrainingForm.model_json_schema()
|
||||
defaults = {"execution": {"mode": cluster.default_mode(), "scheduler": None}}
|
||||
if domain == Domain.TEA:
|
||||
defaults["source"] = {"kind": "site"}
|
||||
else:
|
||||
del json_schema["properties"]["source"]
|
||||
for definition in ("TrainingSource", "SiteTrainingSource", "FolderTrainingSource"):
|
||||
del json_schema["$defs"][definition]
|
||||
return TrainingConfig(
|
||||
domain=domain.value, name=name, json_schema=json_schema, defaults=defaults
|
||||
)
|
||||
|
||||
|
||||
class Analyze(BaseModel):
|
||||
execution: Execution | None = None
|
||||
|
||||
|
||||
@router.post(
|
||||
"/{domain}/train",
|
||||
description="Starts training a new version of every model of the domain; follow it at /runs.",
|
||||
)
|
||||
def train(domain: Domain, request: Training,
|
||||
client: DagsterGraphQLClient = Depends(dagster)) -> dict[str, str]: # fmt: skip
|
||||
if request.source is not None and domain != Domain.TEA:
|
||||
raise HTTPException(422, f"{domain.value} models take no training source")
|
||||
config: dict = {"domain": domain.value, "execution": execution_config(request.execution)}
|
||||
if request.as_of:
|
||||
config["as_of"] = request.as_of.isoformat()
|
||||
if request.models:
|
||||
config["models"] = request.models
|
||||
if request.source is not None:
|
||||
config["source"] = request.source.model_dump()
|
||||
return submit(client, "train", "train_models", config, domain=domain.value)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/{domain}/analyze",
|
||||
description=(
|
||||
"Starts analysing the studies the domain's models read whole "
|
||||
"(TEA: its EEGs); follow\n"
|
||||
"it at /runs."
|
||||
),
|
||||
)
|
||||
def analyze(
|
||||
domain: Domain,
|
||||
request: Analyze = Analyze(), # noqa: B008
|
||||
client: DagsterGraphQLClient = Depends(dagster),
|
||||
) -> dict[str, str]:
|
||||
config = {"domain": domain.value, "execution": execution_config(request.execution)}
|
||||
return submit(client, "analyze", "analyze_studies", config, domain=domain.value)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/{domain}/score",
|
||||
description="Starts a risk batch from each model's champion; follow it at /runs.",
|
||||
)
|
||||
def score(domain: Domain, client: DagsterGraphQLClient = Depends(dagster)) -> dict[str, str]:
|
||||
return submit(client, "score", "score_models", {"domain": domain.value}, domain=domain.value)
|
||||
@@ -0,0 +1,6 @@
|
||||
import json
|
||||
|
||||
from webapi.main import app
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(json.dumps(app.openapi(), indent=1, sort_keys=True))
|
||||
@@ -0,0 +1,50 @@
|
||||
from datetime import date
|
||||
from typing import Annotated
|
||||
|
||||
from dagster_graphql import DagsterGraphQLClient
|
||||
from fastapi import APIRouter, Depends, Form, HTTPException, UploadFile
|
||||
from pydantic import BaseModel, WithJsonSchema
|
||||
|
||||
from persistance import previews
|
||||
from webapi import runs
|
||||
|
||||
router = APIRouter(prefix="/tea/preview", tags=["preview"])
|
||||
_MAX_FILE_BYTES = 200 * 1024 * 1024
|
||||
_BinaryUpload = Annotated[UploadFile, WithJsonSchema({"type": "string", "format": "binary"})]
|
||||
|
||||
|
||||
class PreviewStatus(BaseModel):
|
||||
state: runs.State
|
||||
result: previews.PreviewResult | None
|
||||
|
||||
|
||||
@router.post("")
|
||||
def start_preview(
|
||||
edf: _BinaryUpload,
|
||||
ados2: _BinaryUpload | None = None,
|
||||
birth_date: Annotated[date | None, Form()] = None,
|
||||
pipeline: Annotated[str, Form()] = "tea",
|
||||
client: DagsterGraphQLClient = Depends(runs.dagster),
|
||||
) -> dict[str, str]:
|
||||
for file in (edf, ados2):
|
||||
if file is not None and file.size is not None and file.size > _MAX_FILE_BYTES:
|
||||
raise HTTPException(413, detail="preview files may be at most 200 MiB each")
|
||||
config = {
|
||||
"edf": previews.put(edf.file.read()),
|
||||
"ados2": previews.put(ados2.file.read()) if ados2 is not None else None,
|
||||
"birth_date": birth_date.isoformat() if birth_date else None,
|
||||
"pipeline": pipeline,
|
||||
}
|
||||
return runs.submit(client, "tea_preview", "preview_study", config, domain="tea")
|
||||
|
||||
|
||||
@router.get("/{run_id}")
|
||||
def preview_status(run_id: str) -> PreviewStatus:
|
||||
run = runs.run_status(run_id, outputs=True)
|
||||
if run.job != "tea_preview":
|
||||
raise HTTPException(404, detail=f"no TEA preview run {run_id}")
|
||||
raw = (run.outputs or {}).get("preview_study.result") if run.state == "succeeded" else None
|
||||
return PreviewStatus(
|
||||
state=run.state,
|
||||
result=previews.PreviewResult.model_validate(raw) if raw is not None else None,
|
||||
)
|
||||
@@ -0,0 +1,128 @@
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from pydantic import BaseModel, ConfigDict, model_validator
|
||||
|
||||
from core.pipeline import EntityName, Id, validate
|
||||
from core.schema import ENTITIES
|
||||
from persistance import nodes, review
|
||||
from webapi.auth import Caller, caller
|
||||
|
||||
router = APIRouter(prefix="/review", tags=["review"])
|
||||
Rows = list[dict[str, Any]]
|
||||
|
||||
|
||||
@router.get(
|
||||
"/held",
|
||||
description="Rows a rule held, with the reasons and the values as they came.",
|
||||
)
|
||||
def held(entity: EntityName) -> Rows:
|
||||
return review.held(entity)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/conflicts",
|
||||
description="Rows of one person and date that disagree; reject the wrong ones.",
|
||||
)
|
||||
def conflicts(entity: EntityName) -> Rows:
|
||||
return review.conflicts(entity)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/unrecognised",
|
||||
description=(
|
||||
"Documents a pipeline's routes don't recognise (what its "
|
||||
"`otherwise` routes took):\n"
|
||||
"a new layout, a study the platform doesn't know, a scan nothing "
|
||||
"could read."
|
||||
),
|
||||
)
|
||||
def unrecognised(pipeline: Id) -> Rows:
|
||||
return review.unrecognised(pipeline)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/persons",
|
||||
description=(
|
||||
"Persons to settle (with their possible owners), torn persons "
|
||||
"and persons nothing\n"
|
||||
"names (with their records) left by a pipeline's link node."
|
||||
),
|
||||
)
|
||||
def persons(pipeline: Id, node: Id) -> dict[str, Rows]:
|
||||
return review.persons(pipeline, node)
|
||||
|
||||
|
||||
class PersonDecision(BaseModel):
|
||||
person: str
|
||||
candidate: str
|
||||
same: bool
|
||||
|
||||
|
||||
@router.post(
|
||||
"/persons",
|
||||
status_code=201,
|
||||
description="Whether a person and a possible owner are one patient; applied on the next run.",
|
||||
)
|
||||
def decide_persons(decision: PersonDecision, who: Caller = Depends(caller)) -> dict[str, str]:
|
||||
nodes.decide_persons(decision.person, decision.candidate, decision.same, who.id)
|
||||
return {"person": decision.person}
|
||||
|
||||
|
||||
class Correction(BaseModel):
|
||||
model_config = ConfigDict(
|
||||
json_schema_extra={
|
||||
"description": (
|
||||
"One field of one record as a reviewer read it in the source "
|
||||
"document: an identity\n"
|
||||
"field (a mistyped record number) or a study's (a stage the scan "
|
||||
"made unreadable)."
|
||||
)
|
||||
}
|
||||
)
|
||||
|
||||
entity: EntityName = "identity"
|
||||
record: str
|
||||
field: str
|
||||
value: str
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _a_valid_value(self):
|
||||
if self.field not in ENTITIES[self.entity].model_fields:
|
||||
raise ValueError(f"{self.entity} has no field {self.field}")
|
||||
reasons = [r for r in validate(self.entity, {self.field: self.value})
|
||||
if r.split(":")[0] == self.field] # fmt: skip
|
||||
if reasons:
|
||||
raise ValueError("; ".join(reasons))
|
||||
return self
|
||||
|
||||
|
||||
@router.post(
|
||||
"/corrections",
|
||||
status_code=201,
|
||||
description=(
|
||||
"A corrected field of one record; the next run uses it (linking "
|
||||
"for identity fields,\n"
|
||||
"the study's target for the others). Fixing the source too is "
|
||||
"still worth it."
|
||||
),
|
||||
)
|
||||
def correct(fix: Correction, who: Caller = Depends(caller)) -> dict[str, str]:
|
||||
nodes.correct(fix.record, fix.field, fix.value, who.id, fix.entity)
|
||||
return {"record": fix.record}
|
||||
|
||||
|
||||
class Rejection(BaseModel):
|
||||
entity: EntityName
|
||||
record: str
|
||||
reason: str
|
||||
|
||||
|
||||
@router.post(
|
||||
"/rejections",
|
||||
status_code=201,
|
||||
description="This record's row must not reach silver; applied on the next run.",
|
||||
)
|
||||
def reject(decision: Rejection, who: Caller = Depends(caller)) -> dict[str, str]:
|
||||
nodes.reject(decision.entity, decision.record, decision.reason, who.id)
|
||||
return {"record": decision.record}
|
||||
+297
@@ -0,0 +1,297 @@
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from typing import Any, Literal
|
||||
|
||||
import requests
|
||||
from dagster_graphql import DagsterGraphQLClient, DagsterGraphQLClientError
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from pydantic import BaseModel, ValidationError
|
||||
|
||||
from core.domains import Domain
|
||||
from persistance import cluster
|
||||
from persistance.cluster import Execution, Progress
|
||||
|
||||
router = APIRouter(prefix="/runs", tags=["runs"])
|
||||
|
||||
State = Literal["queued", "running", "succeeded", "failed", "cancelling", "cancelled"]
|
||||
STATE: dict[str, State] = {
|
||||
"QUEUED": "queued",
|
||||
"NOT_STARTED": "queued",
|
||||
"MANAGED": "queued",
|
||||
"STARTING": "running",
|
||||
"STARTED": "running",
|
||||
"CANCELING": "cancelling",
|
||||
"CANCELED": "cancelled",
|
||||
"SUCCESS": "succeeded",
|
||||
"FAILURE": "failed",
|
||||
}
|
||||
|
||||
RUN_QUERY = """
|
||||
query Run($id: ID!, $outputs: Boolean! = false) {
|
||||
runOrError(runId: $id) {
|
||||
__typename
|
||||
... on Run { runId jobName status startTime endTime tags { key value }
|
||||
stepStats { stepKey status startTime endTime } }
|
||||
... on RunNotFoundError { message }
|
||||
... on PythonError { message }
|
||||
}
|
||||
logsForRun(runId: $id, limit: 5000) {
|
||||
__typename
|
||||
... on EventConnection { events { __typename
|
||||
... on MessageEvent { message level stepKey }
|
||||
... on ExecutionStepOutputEvent @include(if: $outputs) {
|
||||
stepKey outputName metadataEntries { label ... on JsonMetadataEntry { jsonString } }
|
||||
}
|
||||
... on ExecutionStepFailureEvent { error { message causes { message } } }
|
||||
... on RunFailureEvent { error { message causes { message } } } } }
|
||||
... on RunNotFoundError { message }
|
||||
... on PythonError { message }
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
RUNS_QUERY = """
|
||||
query Runs($filter: RunsFilter, $cursor: String, $limit: Int) {
|
||||
runsOrError(filter: $filter, cursor: $cursor, limit: $limit) {
|
||||
__typename
|
||||
... on Runs { results { runId jobName status startTime endTime tags { key value } } }
|
||||
... on InvalidPipelineRunsFilterError { message }
|
||||
... on PythonError { message }
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
class RunSummary(BaseModel):
|
||||
id: str
|
||||
job: str
|
||||
domain: str | None
|
||||
status: str
|
||||
state: State
|
||||
started: float | None
|
||||
ended: float | None
|
||||
|
||||
|
||||
class Step(BaseModel):
|
||||
key: str
|
||||
status: str
|
||||
started: float | None
|
||||
ended: float | None
|
||||
|
||||
|
||||
class Run(RunSummary):
|
||||
progress: Progress | None
|
||||
steps: list[Step]
|
||||
info: list[str]
|
||||
warnings: list[str]
|
||||
error: str | None
|
||||
outputs: dict[str, Any] | None = None
|
||||
|
||||
|
||||
class Cancel(BaseModel):
|
||||
id: str
|
||||
status: str
|
||||
state: State
|
||||
|
||||
|
||||
def _dagster_address() -> tuple[str, int]:
|
||||
return os.environ.get("DAGSTER_HOST", "localhost"), int(os.environ.get("DAGSTER_PORT", "3000"))
|
||||
|
||||
|
||||
def dagster() -> DagsterGraphQLClient:
|
||||
host, port = _dagster_address()
|
||||
return DagsterGraphQLClient(host, port_number=port)
|
||||
|
||||
|
||||
LOCKED = "database is locked"
|
||||
LOCK_RETRIES = 5
|
||||
STARTING_WAIT_S = 30
|
||||
|
||||
|
||||
def _locked(payload: dict) -> bool:
|
||||
results = (payload.get("data") or {}).values()
|
||||
return LOCKED in str(payload.get("errors", "")) or any(
|
||||
isinstance(r, dict)
|
||||
and r.get("__typename") == "PythonError"
|
||||
and LOCKED in r.get("message", "")
|
||||
for r in results
|
||||
)
|
||||
|
||||
|
||||
def _graphql_response(url: str, query: str, variables: dict) -> dict:
|
||||
try:
|
||||
response = requests.post(url, json={"query": query, "variables": variables}, timeout=15)
|
||||
if response.status_code != 200:
|
||||
raise HTTPException(502, detail=response.text)
|
||||
return response.json()
|
||||
except requests.RequestException as e:
|
||||
raise HTTPException(502, detail=str(e)) from e
|
||||
|
||||
|
||||
def graphql(query: str, variables: dict) -> dict:
|
||||
host, port = _dagster_address()
|
||||
url = f"http://{host}:{port}/graphql"
|
||||
payload = _graphql_response(url, query, variables)
|
||||
for attempt in range(LOCK_RETRIES):
|
||||
if not _locked(payload):
|
||||
break
|
||||
time.sleep(0.2 * 2**attempt)
|
||||
payload = _graphql_response(url, query, variables)
|
||||
if _locked(payload):
|
||||
raise HTTPException(
|
||||
503, detail="Dagster's run storage is busy; try again", headers={"Retry-After": "5"}
|
||||
)
|
||||
if "errors" in payload:
|
||||
raise HTTPException(502, detail=str(payload["errors"]))
|
||||
return payload["data"]
|
||||
|
||||
|
||||
def _tags(run: dict) -> dict[str, str]:
|
||||
return {tag["key"]: tag["value"] for tag in run.get("tags", [])}
|
||||
|
||||
|
||||
def _summary(run: dict) -> RunSummary:
|
||||
status = run["status"]
|
||||
return RunSummary(
|
||||
id=run["runId"],
|
||||
job=run["jobName"],
|
||||
domain=_tags(run).get("domain"),
|
||||
status=status,
|
||||
state=STATE.get(status, "running"),
|
||||
started=run.get("startTime"),
|
||||
ended=run.get("endTime"),
|
||||
)
|
||||
|
||||
|
||||
def shape(run: dict, logs: list[dict], outputs: bool = False) -> Run:
|
||||
summary = _summary(run)
|
||||
progress = None
|
||||
if (tag := _tags(run).get("isssteleon/progress")) is not None:
|
||||
try:
|
||||
progress = Progress.model_validate_json(tag)
|
||||
except ValidationError:
|
||||
pass
|
||||
|
||||
steps = [
|
||||
Step(
|
||||
key=step["stepKey"],
|
||||
status=step["status"],
|
||||
started=step.get("startTime"),
|
||||
ended=step.get("endTime"),
|
||||
)
|
||||
for step in run.get("stepStats", [])
|
||||
]
|
||||
steps.sort(key=lambda step: (step.started is None, step.started or 0.0))
|
||||
|
||||
info, warnings = [], []
|
||||
error = None
|
||||
result = {} if outputs else None
|
||||
for event in logs:
|
||||
kind = event["__typename"]
|
||||
if kind == "LogMessageEvent" and event["level"] in ("INFO", "WARNING"):
|
||||
line = event["message"]
|
||||
if step_key := event.get("stepKey"):
|
||||
line = f"{step_key}: {line}"
|
||||
(info if event["level"] == "INFO" else warnings).append(line)
|
||||
if result is not None and kind == "ExecutionStepOutputEvent":
|
||||
for entry in event.get("metadataEntries", ()):
|
||||
if "jsonString" in entry:
|
||||
result[f"{event['stepKey']}.{entry['label']}"] = json.loads(entry["jsonString"])
|
||||
if summary.state == "failed" and kind in ("ExecutionStepFailureEvent", "RunFailureEvent"):
|
||||
failure = event.get("error")
|
||||
error = None
|
||||
if failure:
|
||||
causes = failure.get("causes")
|
||||
message = (causes[-1] if causes else failure)["message"]
|
||||
lines = message.strip().splitlines()
|
||||
error = lines[0][:500] if lines else None
|
||||
|
||||
return Run(
|
||||
**summary.model_dump(),
|
||||
progress=progress,
|
||||
outputs=result,
|
||||
steps=steps,
|
||||
info=info[-200:],
|
||||
warnings=warnings[:200],
|
||||
error=(error or "the run failed") if summary.state == "failed" else None,
|
||||
)
|
||||
|
||||
|
||||
def _result(result: dict, typename: str) -> dict:
|
||||
if result["__typename"] != typename:
|
||||
status = 404 if result["__typename"] == "RunNotFoundError" else 502
|
||||
raise HTTPException(status, detail=result.get("message", result["__typename"]))
|
||||
return result
|
||||
|
||||
|
||||
@router.get("/{run_id}")
|
||||
def run_status(run_id: str, outputs: bool = False) -> Run:
|
||||
data = graphql(RUN_QUERY, {"id": run_id, "outputs": outputs})
|
||||
run = _result(data["runOrError"], "Run")
|
||||
logs = _result(data["logsForRun"], "EventConnection")
|
||||
return shape(run, logs["events"], outputs)
|
||||
|
||||
|
||||
def _status(client: DagsterGraphQLClient, run_id: str) -> str:
|
||||
try:
|
||||
return client.get_run_status(run_id).value
|
||||
except DagsterGraphQLClientError as e:
|
||||
raise HTTPException(404 if e.args[0] == "RunNotFoundError" else 502, detail=str(e)) from e
|
||||
|
||||
|
||||
@router.post("/{run_id}/cancel")
|
||||
def cancel_run(run_id: str, client: DagsterGraphQLClient = Depends(dagster)) -> Cancel:
|
||||
status = _status(client, run_id)
|
||||
deadline = time.monotonic() + STARTING_WAIT_S
|
||||
while status == "STARTING" and time.monotonic() < deadline:
|
||||
time.sleep(0.5)
|
||||
status = _status(client, run_id)
|
||||
if status in ("SUCCESS", "FAILURE", "CANCELED"):
|
||||
raise HTTPException(409, detail=f"the run already ended: {STATE[status]}")
|
||||
if status == "STARTING":
|
||||
raise HTTPException(
|
||||
409, detail="the run is still starting; try again", headers={"Retry-After": "5"}
|
||||
)
|
||||
try:
|
||||
client.terminate_run(run_id)
|
||||
except DagsterGraphQLClientError as e:
|
||||
raise HTTPException(502, detail=str(e)) from e
|
||||
status = _status(client, run_id)
|
||||
return Cancel(id=run_id, status=status, state=STATE.get(status, "running"))
|
||||
|
||||
|
||||
@router.get("")
|
||||
def run_history(
|
||||
job: str | None = None,
|
||||
domain: Domain | None = None,
|
||||
limit: int = Query(50, ge=1, le=200),
|
||||
before: str | None = None,
|
||||
) -> list[RunSummary]:
|
||||
filters = {}
|
||||
if job is not None:
|
||||
filters["pipelineName"] = job
|
||||
if domain is not None:
|
||||
filters["tags"] = [{"key": "domain", "value": domain.value}]
|
||||
data = graphql(RUNS_QUERY, {"filter": filters, "cursor": before, "limit": limit})
|
||||
return [_summary(run) for run in _result(data["runsOrError"], "Runs")["results"]]
|
||||
|
||||
|
||||
def submit(
|
||||
client: DagsterGraphQLClient, job: str, op: str, config: dict, domain: str
|
||||
) -> dict[str, str]:
|
||||
try:
|
||||
run_id = client.submit_job_execution(
|
||||
job, run_config={"ops": {op: {"config": config}}}, tags={"domain": domain}
|
||||
)
|
||||
except DagsterGraphQLClientError as e:
|
||||
raise HTTPException(502, detail=str(e)) from e
|
||||
return {"run_id": run_id}
|
||||
|
||||
|
||||
def execution_config(choice: Execution | None) -> dict:
|
||||
try:
|
||||
resolved = cluster.resolve(choice)
|
||||
except cluster.ExecutionError as e:
|
||||
raise HTTPException(422, detail=str(e)) from e
|
||||
return {"mode": resolved.mode, "scheduler": resolved.scheduler}
|
||||
@@ -0,0 +1,369 @@
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import uuid
|
||||
from pathlib import Path, PurePosixPath
|
||||
from typing import Annotated, Any, Literal
|
||||
|
||||
from fastapi import APIRouter, Form, HTTPException, Query, UploadFile
|
||||
from pydantic import BaseModel, ValidationError
|
||||
|
||||
from core import sources
|
||||
from core.pipeline import MASK, Pipeline, Source, restored
|
||||
from persistance import config_log, nodes
|
||||
from persistance.config import DATA_DIR
|
||||
|
||||
router = APIRouter(prefix="/ingest", tags=["ingest"])
|
||||
UPLOADS = "uploads"
|
||||
|
||||
|
||||
@router.get(
|
||||
"/sources/types",
|
||||
description="Every kind of source the dialog offers, grouped, with the fields each one asks.",
|
||||
)
|
||||
def source_types() -> sources.Catalog:
|
||||
return sources.catalog()
|
||||
|
||||
|
||||
class Answers(BaseModel):
|
||||
type: str
|
||||
answers: dict[str, Any] = {}
|
||||
pipeline: str | None = None
|
||||
node: str | None = None
|
||||
|
||||
|
||||
class Tested(BaseModel):
|
||||
ok: bool
|
||||
message: str
|
||||
detail: str | None = None
|
||||
tables: list[str] = []
|
||||
rows: list[dict[str, Any]] = []
|
||||
|
||||
|
||||
PLAIN = [
|
||||
(
|
||||
r"login failed|password authentication failed|access denied|authentication|"
|
||||
r"401|403|permission denied|invalid credentials",
|
||||
"El usuario o la contraseña no son correctos, o no tiene permiso.",
|
||||
), # fmt: skip
|
||||
(
|
||||
r"name or service not known|could not translate host|nodename nor servname|"
|
||||
r"getaddrinfo|unknown host|no such host|resolve",
|
||||
"No se encontró el servidor. Revise el nombre o la dirección.",
|
||||
), # fmt: skip
|
||||
(
|
||||
r"timed out|timeout|connection refused|unable to connect|adaptive server is unavailable|"
|
||||
r"could not connect|connection reset",
|
||||
"El servidor no respondió. Revise la dirección, el puerto o si está encendido.",
|
||||
), # fmt: skip
|
||||
(
|
||||
r"database .* does not exist|cannot open database|unknown database",
|
||||
"No existe esa base de datos en el servidor.",
|
||||
), # fmt: skip
|
||||
(
|
||||
r"no such table|invalid object name|does not exist|not found|no such file|404",
|
||||
"No se encontró lo que pidió (la tabla, la carpeta o el archivo).",
|
||||
), # fmt: skip
|
||||
]
|
||||
|
||||
|
||||
def plain(error: BaseException) -> str:
|
||||
said = f"{type(error).__name__}: {error}"
|
||||
for pattern, message in PLAIN:
|
||||
if re.search(pattern, said, re.IGNORECASE):
|
||||
return message
|
||||
return "No se pudo conectar. Abajo está lo que respondió el sistema."
|
||||
|
||||
|
||||
def _with_saved_secrets(asked: Answers) -> dict[str, Any]:
|
||||
if MASK not in repr(asked.answers):
|
||||
return asked.answers
|
||||
if not (asked.pipeline and asked.node and config_log.latest_version(asked.pipeline)):
|
||||
raise HTTPException(422, detail="una contraseña oculta necesita la fuente guardada")
|
||||
saved = config_log.get(asked.pipeline)[1]
|
||||
node = {"id": asked.node, "kind": "source", "source": "core.sources:catalog",
|
||||
"guided": {"type": asked.type, "answers": asked.answers}} # fmt: skip
|
||||
try:
|
||||
found = restored(Pipeline(nodes=[node]), saved).nodes[0]
|
||||
except ValueError as e:
|
||||
raise HTTPException(422, detail=str(e)) from e
|
||||
return found.guided.answers
|
||||
|
||||
|
||||
@router.post(
|
||||
"/sources/test",
|
||||
description=(
|
||||
'"Probar conexión": reaches the source with the answers given. A '
|
||||
"database lists its\n"
|
||||
"tables (until one is picked; then its first rows); files and "
|
||||
"records show their first\n"
|
||||
"rows. Never a server error: what went wrong comes back in plain "
|
||||
"words."
|
||||
),
|
||||
)
|
||||
def test_source(asked: Answers, limit: Annotated[int, Query(ge=1, le=100)] = 20) -> Tested:
|
||||
if asked.type not in sources.catalog().types:
|
||||
raise HTTPException(404, detail=f"no source type {asked.type}")
|
||||
answers = _with_saved_secrets(asked)
|
||||
spec = sources.catalog().types[asked.type]
|
||||
picked = all(answers.get(k) for k, f in spec.fields.items() if f.type == "table")
|
||||
try:
|
||||
if not picked and (listed := sources.listing(asked.type, answers)):
|
||||
tables = nodes.resources(*listed)
|
||||
count = "1 tabla" if len(tables) == 1 else f"{len(tables)} tablas"
|
||||
return Tested(ok=True, message=f"Conexión correcta: {count}.",
|
||||
tables=tables) # fmt: skip
|
||||
node = Source(id="probe", guided={"type": asked.type, "answers": answers})
|
||||
rows = [nodes.shown(r) for r in nodes.preview(node, limit)]
|
||||
except (sources.MissingAnswer, ValidationError) as e:
|
||||
return Tested(ok=False, message=_missing(e))
|
||||
except Exception as e: # noqa: BLE001
|
||||
return Tested(ok=False, message=plain(e), detail=f"{type(e).__name__}: {e}"[:2000])
|
||||
found = (
|
||||
"Conexión correcta."
|
||||
if rows
|
||||
else (
|
||||
"Se conectó, pero no encontró archivos ni filas. Revise la ruta y qué archivos tomar."
|
||||
)
|
||||
)
|
||||
return Tested(ok=True, message=found, rows=rows)
|
||||
|
||||
|
||||
def _missing(e: Exception) -> str:
|
||||
if isinstance(e, ValidationError):
|
||||
return next((str(err["ctx"]["error"]) for err in e.errors()
|
||||
if isinstance(err.get("ctx", {}).get("error"), sources.MissingAnswer)),
|
||||
str(e)) # fmt: skip
|
||||
return str(e)
|
||||
|
||||
|
||||
def roots() -> dict[str, Path]:
|
||||
found = {"Subidos": (DATA_DIR / UPLOADS).resolve()}
|
||||
for raw in filter(None, os.environ.get("SOURCE_ROOTS", "").split(os.pathsep)):
|
||||
path = Path(raw).resolve()
|
||||
found[path.name or str(path)] = path
|
||||
return found
|
||||
|
||||
|
||||
class Entry(BaseModel):
|
||||
name: str
|
||||
path: str
|
||||
kind: Literal["folder", "file"]
|
||||
size: int | None = None
|
||||
|
||||
|
||||
class Browsed(BaseModel):
|
||||
path: str | None
|
||||
parent: str | None
|
||||
entries: list[Entry]
|
||||
|
||||
|
||||
@router.get(
|
||||
"/sources/browse",
|
||||
description=(
|
||||
"The server folders a source may read: the roots, or what one "
|
||||
"folder under them\n"
|
||||
"holds. Nothing outside the roots is shown."
|
||||
),
|
||||
)
|
||||
def browse(path: str | None = None) -> Browsed:
|
||||
allowed = roots()
|
||||
if path is None:
|
||||
return Browsed(path=None, parent=None, entries=[
|
||||
Entry(name=name, path=str(root), kind="folder")
|
||||
for name, root in allowed.items() if root.is_dir()]) # fmt: skip
|
||||
folder = Path(path).resolve()
|
||||
root = next((r for r in allowed.values() if folder == r or r in folder.parents), None)
|
||||
if root is None or not folder.is_dir():
|
||||
raise HTTPException(404, detail="esa carpeta no está entre las habilitadas")
|
||||
entries = sorted(
|
||||
(Entry(name=p.name, path=str(p), kind="folder" if p.is_dir() else "file",
|
||||
size=None if p.is_dir() else p.stat().st_size)
|
||||
for p in folder.iterdir() if not p.name.startswith(".")),
|
||||
key=lambda e: (e.kind != "folder", e.name.lower())) # fmt: skip
|
||||
return Browsed(path=str(folder), parent=None if folder == root else str(folder.parent),
|
||||
entries=entries) # fmt: skip
|
||||
|
||||
|
||||
class Uploaded(BaseModel):
|
||||
bucket_url: str
|
||||
files: list[str]
|
||||
|
||||
|
||||
def _relative(name: str) -> PurePosixPath:
|
||||
parts = [p for p in PurePosixPath(name.replace("\\", "/")).parts if p not in ("", ".", "..")]
|
||||
if not parts:
|
||||
raise HTTPException(422, detail="the file needs a name")
|
||||
return PurePosixPath(*parts)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/uploads",
|
||||
description=(
|
||||
"Files from the operator's computer (one, many, or a whole "
|
||||
"folder), kept on the\n"
|
||||
"server for a `filesystem` source; streamed to disk, so large "
|
||||
"recordings fit. Send\n"
|
||||
"`folder` from a previous answer to add to the same set."
|
||||
),
|
||||
)
|
||||
def upload(files: list[UploadFile], folder: Annotated[str | None, Form()] = None) -> Uploaded:
|
||||
base = (DATA_DIR / UPLOADS).resolve()
|
||||
target = Path(folder).resolve() if folder else base / uuid.uuid4().hex[:12]
|
||||
if target.parent != base:
|
||||
raise HTTPException(422, detail="folder is not an upload set")
|
||||
kept = []
|
||||
for file in files:
|
||||
relative = _relative(file.filename or "")
|
||||
destination = target / relative
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
with destination.open("wb") as out:
|
||||
shutil.copyfileobj(file.file, out, length=1 << 20)
|
||||
kept.append(str(relative))
|
||||
return Uploaded(bucket_url=str(target), files=kept)
|
||||
|
||||
|
||||
PENDING = DATA_DIR / "oauth_pending"
|
||||
PENDING_SECONDS = 600
|
||||
STATE = re.compile(r"[A-Za-z0-9_-]{8,128}")
|
||||
|
||||
|
||||
def _pend(state: str, pending: dict[str, Any]) -> None:
|
||||
import json
|
||||
import time
|
||||
|
||||
PENDING.mkdir(parents=True, exist_ok=True)
|
||||
for old in PENDING.glob("*.json"):
|
||||
if time.time() - old.stat().st_mtime > PENDING_SECONDS:
|
||||
old.unlink(missing_ok=True)
|
||||
path = PENDING / f"{state}.json"
|
||||
path.write_text(json.dumps(pending))
|
||||
path.chmod(0o600)
|
||||
|
||||
|
||||
def _claimed(state: str) -> dict[str, Any] | None:
|
||||
import json
|
||||
import time
|
||||
|
||||
if not STATE.fullmatch(state):
|
||||
return None
|
||||
taken = PENDING / f"{state}.{uuid.uuid4().hex}.taken"
|
||||
try:
|
||||
(PENDING / f"{state}.json").rename(taken)
|
||||
except FileNotFoundError:
|
||||
return None
|
||||
try:
|
||||
fresh = time.time() - taken.stat().st_mtime <= PENDING_SECONDS
|
||||
return json.loads(taken.read_text()) if fresh else None
|
||||
finally:
|
||||
taken.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def _registration(provider: str) -> tuple[sources.Provider, dict[str, str]]:
|
||||
found = sources.catalog().providers.get(provider)
|
||||
if found is None:
|
||||
raise HTTPException(404, detail=f"no provider {provider}")
|
||||
env = {k: os.environ.get(f"{found.env}_{k.upper()}", "")
|
||||
for k in ("client_id", "client_secret", "tenant_id", "project_id")} # fmt: skip
|
||||
if not (env["client_id"] and env["client_secret"]):
|
||||
needed = f"{found.env}_CLIENT_ID y {found.env}_CLIENT_SECRET"
|
||||
raise HTTPException(503, detail=(
|
||||
f"Para iniciar sesión con {found.title}, el área de sistemas debe registrar la "
|
||||
f"aplicación y darle al servidor {needed}.")) # fmt: skip
|
||||
return found, env
|
||||
|
||||
|
||||
def _endpoint(url: str, env: dict[str, str]) -> str:
|
||||
return url.format(tenant=env["tenant_id"] or "organizations")
|
||||
|
||||
|
||||
def _client(provider: sources.Provider, env: dict[str, str], redirect_uri: str):
|
||||
from authlib.integrations.httpx_client import OAuth2Client
|
||||
|
||||
return OAuth2Client(env["client_id"], env["client_secret"], scope=provider.scope,
|
||||
redirect_uri=redirect_uri, code_challenge_method="S256") # fmt: skip
|
||||
|
||||
|
||||
class SignIn(BaseModel):
|
||||
url: str
|
||||
state: str
|
||||
|
||||
|
||||
@router.get(
|
||||
"/sources/oauth/{provider}/start",
|
||||
description=(
|
||||
"The provider's sign-in address. `origin` is the web app's "
|
||||
"(where the user returns:\n"
|
||||
"`{origin}/api/…/callback`, the address IT registered)."
|
||||
),
|
||||
)
|
||||
def oauth_start(provider: str, origin: str) -> SignIn:
|
||||
import secrets
|
||||
|
||||
found, env = _registration(provider)
|
||||
redirect_uri = f"{origin.rstrip('/')}/api/ingest/sources/oauth/{provider}/callback"
|
||||
verifier = secrets.token_urlsafe(48)
|
||||
url, state = _client(found, env, redirect_uri).create_authorization_url(
|
||||
_endpoint(found.authorize_url, env), code_verifier=verifier, **found.authorize_params
|
||||
)
|
||||
_pend(state, {"provider": provider, "verifier": verifier, "redirect_uri": redirect_uri,
|
||||
"origin": origin.rstrip("/")}) # fmt: skip
|
||||
return SignIn(url=url, state=state)
|
||||
|
||||
|
||||
def account(provider: str, token: dict[str, Any], env: dict[str, str]) -> dict[str, Any]:
|
||||
import httpx
|
||||
|
||||
found = sources.catalog().providers[provider]
|
||||
bearer = {"Authorization": f"Bearer {token['access_token']}"}
|
||||
if provider == "microsoft":
|
||||
me = httpx.get("https://graph.microsoft.com/v1.0/me", headers=bearer).json()
|
||||
drive = httpx.get("https://graph.microsoft.com/v1.0/me/drive", headers=bearer).json()
|
||||
return {
|
||||
"user": me.get("mail") or me.get("userPrincipalName") or me.get("displayName"),
|
||||
"drive_id": drive.get("id"),
|
||||
"oauth2_client_params": {
|
||||
"client_id": env["client_id"], "client_secret": env["client_secret"],
|
||||
"token_endpoint": _endpoint(found.token_url, env), "scope": found.scope,
|
||||
"token": token,
|
||||
},
|
||||
} # fmt: skip
|
||||
about = httpx.get("https://www.googleapis.com/drive/v3/about", params={"fields": "user"},
|
||||
headers=bearer).json() # fmt: skip
|
||||
credentials = {"client_id": env["client_id"], "client_secret": env["client_secret"],
|
||||
"refresh_token": token.get("refresh_token"),
|
||||
"project_id": env["project_id"] or None} # fmt: skip
|
||||
return {"user": about.get("user", {}).get("emailAddress"),
|
||||
"credentials": {k: v for k, v in credentials.items() if v}} # fmt: skip
|
||||
|
||||
|
||||
@router.get("/sources/oauth/{provider}/callback", include_in_schema=False)
|
||||
def oauth_callback(provider: str, state: str, code: str | None = None, error: str | None = None):
|
||||
import json
|
||||
|
||||
from fastapi.responses import HTMLResponse
|
||||
|
||||
pending = _claimed(state)
|
||||
if pending is None or pending["provider"] != provider:
|
||||
return HTMLResponse("<p>La solicitud de inicio de sesión venció. Cierre esta ventana "
|
||||
"e inténtelo de nuevo.</p>", status_code=400) # fmt: skip
|
||||
message: dict[str, Any] = {"type": "isssteleon-oauth", "state": state}
|
||||
if error or not code:
|
||||
message["error"] = "No se completó el inicio de sesión."
|
||||
else:
|
||||
found, env = _registration(provider)
|
||||
try:
|
||||
token = _client(found, env, pending["redirect_uri"]).fetch_token(
|
||||
_endpoint(found.token_url, env), code=code, code_verifier=pending["verifier"]
|
||||
)
|
||||
message["account"] = account(provider, dict(token), env)
|
||||
except Exception as e: # noqa: BLE001
|
||||
message["error"] = f"No se pudo iniciar sesión: {e}"
|
||||
payload = json.dumps(message).replace("</", "<\\/")
|
||||
target = json.dumps(pending["origin"])
|
||||
return HTMLResponse(
|
||||
"<!doctype html><meta charset=utf-8><title>ISSSTELEON</title>"
|
||||
"<p>Listo. Puede cerrar esta ventana.</p>"
|
||||
f"<script>window.opener&&window.opener.postMessage({payload},{target});"
|
||||
"window.close()</script>"
|
||||
)
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user