improve ingestion system to match isssteleon setup
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
"""`DocumentConnector` reading its documents from a SQL source instead of
|
||||
uploaded files: one document per row, read from a column that may hold a
|
||||
PDF (`varbinary(max)`) or already be plain text, both without a filesystem
|
||||
PDF (a binary column) or already be plain text, both without a filesystem
|
||||
path in between. Fails if the bridge to `SqlConnector` breaks, or if a
|
||||
plain-text column stops reaching the same field extraction a PDF does.
|
||||
"""
|
||||
@@ -31,7 +31,7 @@ REPORT = text_pdf(
|
||||
|
||||
@pytest.fixture
|
||||
def sqlite_studies_table(tmp_path):
|
||||
"""A source table shaped like ISSSTELEON's: one row per study, its
|
||||
"""A source table with one row per study, its
|
||||
report in a binary column, plus a plain-text variant of the same
|
||||
report in another row, both alongside the row's own key column."""
|
||||
db_path = tmp_path / "estudios.db"
|
||||
@@ -57,118 +57,6 @@ def _sql_payload(url: str, **overrides) -> dict:
|
||||
return {"connection_string": url, "table": "estudios", "column": "reporte", "key_column": "estudio_id", **overrides}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sqlite_archivos_uni_table(tmp_path):
|
||||
"""Shaped exactly like the hospital's own `ArchivosUni` table (`Id`,
|
||||
`PacienteId`, `OrdenServicioId`, `Archivo`): no column prints a
|
||||
recognizable "Expediente" label anywhere, and two rows (the same
|
||||
order's cover page and its result) share one `PacienteId`, the way the
|
||||
source's own export does. Proves a table with no text-parseable key at
|
||||
all can still be read correctly through `sql.fields`."""
|
||||
db_path = tmp_path / "archivos_uni.db"
|
||||
url = f"sqlite:///{db_path}"
|
||||
engine = create_engine(url)
|
||||
with engine.begin() as conn:
|
||||
conn.execute(text("CREATE TABLE ArchivosUni (Id INTEGER, PacienteId INTEGER, OrdenServicioId INTEGER, Archivo BLOB)"))
|
||||
rows = [
|
||||
(1, 115220, 297914, "VPH alto riesgo: POSITIVO"),
|
||||
(2, 115220, 297914, "Genotipo 18: DETECTADO"),
|
||||
(3, 209622, 298182, "VPH alto riesgo: NEGATIVO"),
|
||||
]
|
||||
for id_, paciente_id, orden_id, archivo in rows:
|
||||
conn.execute(
|
||||
text("INSERT INTO ArchivosUni (Id, PacienteId, OrdenServicioId, Archivo) VALUES (:id, :pid, :oid, :archivo)"),
|
||||
{"id": id_, "pid": paciente_id, "oid": orden_id, "archivo": archivo},
|
||||
)
|
||||
return url
|
||||
|
||||
|
||||
def _archivos_uni_payload(url: str, **overrides) -> dict:
|
||||
return {
|
||||
"connection_string": url,
|
||||
"table": "ArchivosUni",
|
||||
"column": "Archivo",
|
||||
"key_column": "Id",
|
||||
"fields": {"pac_id_hospital": "PacienteId"},
|
||||
**overrides,
|
||||
}
|
||||
|
||||
|
||||
def test_rows_with_no_text_label_are_keyed_from_a_structured_column(client, sqlite_archivos_uni_table):
|
||||
"""Neither row prints "Expediente" anywhere; `sql.fields` is the only
|
||||
way these rows can be keyed at all. Fails if `fields` stops reaching
|
||||
the key computation through `DocumentConnector.source_fields`."""
|
||||
body = client.post(
|
||||
"/imports/sources/document/extract",
|
||||
json={"sql": _archivos_uni_payload(sqlite_archivos_uni_table), "target": "cacu.CitologiaCervical"},
|
||||
).get_json()
|
||||
by_key = {r["key"]: r for r in body["records"]}
|
||||
assert set(by_key) == {"115220", "209622"}
|
||||
assert by_key["115220"]["fields"]["cit_vph_resultado"]["value"] == "POSITIVO"
|
||||
|
||||
|
||||
def test_rows_sharing_a_patient_id_merge_into_one_record(client, sqlite_archivos_uni_table):
|
||||
"""Rows 1 and 2 are two blob parts of the same order (same
|
||||
`PacienteId` and `OrdenServicioId`, the way the hospital stores a
|
||||
split report) and must land on a single record, not two. Fails if
|
||||
`fields` stops being enough to merge documents that share no text in
|
||||
common at all."""
|
||||
body = client.post(
|
||||
"/imports/sources/document/extract",
|
||||
json={"sql": _archivos_uni_payload(sqlite_archivos_uni_table), "target": "cacu.CitologiaCervical"},
|
||||
).get_json()
|
||||
[record] = [r for r in body["records"] if r["key"] == "115220"]
|
||||
assert record["fields"]["pac_id_hospital"]["value"] == "115220"
|
||||
assert record["fields"]["cit_vph_resultado"]["value"] == "POSITIVO"
|
||||
assert record["fields"]["cit_vph_genotipo_18"]["value"] == 1
|
||||
assert {s["document"] for s in record["sources"]} == {"1", "2"}
|
||||
|
||||
|
||||
def test_sql_fields_value_wins_over_a_conflicting_text_label(client, sqlite_archivos_uni_table):
|
||||
"""If a row's own text happens to print a different "Expediente" than
|
||||
its `PacienteId`, the structured column must still be trusted — it is
|
||||
the hospital's real join key. Fails if a text-derived reading is ever
|
||||
allowed to outrank `sql.fields`."""
|
||||
engine = create_engine(sqlite_archivos_uni_table)
|
||||
with engine.begin() as conn:
|
||||
conn.execute(
|
||||
text("INSERT INTO ArchivosUni (Id, PacienteId, OrdenServicioId, Archivo) VALUES (4, 300000, 400000, :archivo)"),
|
||||
{"archivo": "Expediente: WRONG-LABEL\nVPH alto riesgo: NEGATIVO"},
|
||||
)
|
||||
body = client.post(
|
||||
"/imports/sources/document/extract",
|
||||
json={"sql": _archivos_uni_payload(sqlite_archivos_uni_table), "target": "cacu.CitologiaCervical"},
|
||||
).get_json()
|
||||
[record] = [r for r in body["records"] if r["key"] == "300000"]
|
||||
assert record["fields"]["pac_id_hospital"]["value"] == "300000"
|
||||
|
||||
|
||||
def test_an_unknown_sql_field_is_a_bad_request(client, sqlite_archivos_uni_table):
|
||||
payload = _archivos_uni_payload(sqlite_archivos_uni_table, fields={"campo_inexistente": "PacienteId"})
|
||||
response = client.post(
|
||||
"/imports/sources/document/extract", json={"sql": payload, "target": "cacu.CitologiaCervical"}
|
||||
)
|
||||
assert response.status_code == 400 and "campo_inexistente" in response.get_json()["error"]
|
||||
|
||||
|
||||
def test_sql_fields_source_commits_like_a_text_derived_key(client, sqlite_archivos_uni_table):
|
||||
source = {
|
||||
"source_type": "document",
|
||||
"target": "cacu.CitologiaCervical",
|
||||
"column_mapping": {"pac_id_hospital": "pac_id_hospital", "cit_vph_resultado": "cit_vph_resultado"},
|
||||
"payload": {"sql": _archivos_uni_payload(sqlite_archivos_uni_table)},
|
||||
"label": "archivos_uni",
|
||||
}
|
||||
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 in ("115220", "209622")}
|
||||
assert rows["115220"].cit_vph_resultado == "POSITIVO"
|
||||
assert rows["209622"].cit_vph_resultado == "NEGATIVO"
|
||||
|
||||
|
||||
def test_a_pdf_column_is_read_like_an_uploaded_pdf(client, sqlite_studies_table):
|
||||
body = client.post(
|
||||
"/imports/sources/document/extract",
|
||||
@@ -182,7 +70,7 @@ def test_a_pdf_column_is_read_like_an_uploaded_pdf(client, sqlite_studies_table)
|
||||
|
||||
def test_a_plain_text_column_reaches_the_same_field_extraction(client, sqlite_studies_table):
|
||||
"""Fails if a source whose bundle is a plain string (not binary at
|
||||
all) stops producing fields, since ISSSTELEON's column may not always
|
||||
all) stops producing fields, since a source's column may not always
|
||||
be a PDF (`extraction.readers.TextReader`)."""
|
||||
body = client.post(
|
||||
"/imports/sources/document/extract",
|
||||
@@ -231,9 +119,11 @@ def test_a_missing_column_is_a_bad_request(client, sqlite_studies_table):
|
||||
|
||||
def test_a_caption_outside_the_target_schema_is_committed_through_the_catalog(client, tmp_path, monkeypatch):
|
||||
"""Mixing sources: a field the import schema doesn't name (`Tipo de
|
||||
fijador`) still reaches the silver layer through the open-catalog
|
||||
path, alongside the recognized fields `commit_sources` writes as
|
||||
before. Fails if `/imports/commit` stops wiring that second path in.
|
||||
fijador`) but the project's catalog does still reaches the silver
|
||||
layer through the open-catalog path, alongside the recognized fields
|
||||
`commit_sources` writes as before, when the source asks for it with
|
||||
`catalog_fallback`. Fails if `/imports/commit` stops wiring that second
|
||||
path in, or runs it for a source that didn't ask.
|
||||
Its own table and patient (`SQL-EXTRA-1`), so it doesn't collide with
|
||||
the module's other tests sharing this `client`'s database."""
|
||||
from datetime import date
|
||||
@@ -246,7 +136,11 @@ def test_a_caption_outside_the_target_schema_is_committed_through_the_catalog(cl
|
||||
from persistance.cacu import carga_repository, paciente_repository
|
||||
|
||||
monkeypatch.setattr(catalogos, "RAIZ_CATALOGOS", tmp_path)
|
||||
(tmp_path / "cacu.toml").write_text('[citologia]\netiqueta = "Citología cervical"\n', encoding="utf-8")
|
||||
catalog = (
|
||||
'[citologia]\netiqueta = "Citología cervical"\n\n'
|
||||
'[citologia.resultados.tipo_de_fijador]\netiqueta = "Tipo de fijador"\ntipo_valor = "texto"\n'
|
||||
)
|
||||
(tmp_path / "cacu.toml").write_text(catalog, encoding="utf-8")
|
||||
paciente_repository.create(Paciente(pac_id_hospital="SQL-EXTRA-1", pac_fecha_nacimiento=date(1981, 3, 12)))
|
||||
|
||||
db_url = f"sqlite:///{tmp_path / 'estudios_extra.db'}"
|
||||
@@ -264,14 +158,17 @@ def test_a_caption_outside_the_target_schema_is_committed_through_the_catalog(cl
|
||||
}
|
||||
body = client.post("/imports/commit", json={"sources": [source]}).get_json()
|
||||
assert body["results"][0]["created"] == 1, body
|
||||
assert not [r for r in body.get("catalog_fallback", []) if r["label"] == "estudios_extra"]
|
||||
|
||||
[report] = [r for r in body["catalog_fallback"] if r["label"] == "estudios_extra"]
|
||||
assert report["records_written"] == 1 and report["fields_minted"] == 1
|
||||
body = client.post("/imports/commit", json={"sources": [{**source, "catalog_fallback": True}], "on_conflict": "upsert"}).get_json()
|
||||
[fallback] = [r for r in body["catalog_fallback"] if r["label"] == "estudios_extra"]
|
||||
assert (fallback["records_written"], fallback["fields_matched"], fallback["fields_minted"]) == (1, 1, 0)
|
||||
assert (tmp_path / "cacu.toml").read_text(encoding="utf-8") == catalog
|
||||
|
||||
with carga_repository.open_session() as sesion:
|
||||
[minted] = list(
|
||||
[written] = list(
|
||||
sesion.exec(select(carga_repository.observacion).where(carga_repository.observacion.pac_id.in_(
|
||||
select(Paciente.pac_id).where(Paciente.pac_id_hospital == "SQL-EXTRA-1")
|
||||
)))
|
||||
)
|
||||
assert minted.resultado_id == "citologia.tipo_de_fijador" and minted.valor_texto == "Formol"
|
||||
assert written.resultado_id == "citologia.tipo_de_fijador" and written.valor_texto == "Formol"
|
||||
Reference in New Issue
Block a user