diff --git a/tests/test_catalog_commit_service.py b/tests/test_catalog_commit_service.py index 06913a0..1604242 100644 --- a/tests/test_catalog_commit_service.py +++ b/tests/test_catalog_commit_service.py @@ -65,24 +65,21 @@ def test_a_matched_field_is_written_on_the_existing_resultado(cacu_catalog, know assert procedimiento.fuente_id == known_patient -def test_an_unmatched_field_mints_a_resultado_and_is_written_too(cacu_catalog, known_patient): +def test_an_unmatched_field_is_counted_and_the_catalog_left_untouched(cacu_catalog, known_patient): + """A caption the catalog doesn't know is counted, not written, and the + catalog file isn't edited: it's versioned with the code. Fails if the + import path mints catalog entries again.""" + before = cacu_catalog.read_text(encoding="utf-8") result = commit_discovered_fields( [_record(known_patient, [("Tipo de fijador", "Formol")])], proyecto="cacu", estudio_id="citologia" ) - assert result.fields_minted == 1 - nombres = set(catalogos._leer(cacu_catalog)["citologia"]["resultados"]) - assert nombres == {"calidad_muestra", "tipo_de_fijador"} # the fixture's field, plus the minted one - minted_id = "citologia.tipo_de_fijador" - - catalogo = catalogos.catalogo_desde_toml(cacu_catalog, tablas=tablas_de("cacu")) - assert minted_id in {r.resultado_id for r in catalogo.resultados} + assert (result.records_written, result.fields_minted, result.fields_unmatched) == (0, 0, 1) + assert cacu_catalog.read_text(encoding="utf-8") == before from persistance.cacu import carga_repository with carga_repository.open_session() as sesion: - [observacion] = sesion.exec(select(carga_repository.observacion)).all() - assert observacion.resultado_id == minted_id - assert observacion.valor_texto == "Formol" + assert sesion.exec(select(carga_repository.observacion)).all() == [] def test_a_patient_outside_persona_is_skipped_not_dropped_silently(cacu_catalog, known_patient): diff --git a/tests/test_document_source_options.py b/tests/test_document_source_options.py new file mode 100644 index 0000000..c815f3e --- /dev/null +++ b/tests/test_document_source_options.py @@ -0,0 +1,180 @@ +"""Options that let one document source cope with however its rows are +stored: columns carried through as field values, a column grouping rows +into records, filters that pick which documents feed a target, documents +kept as hex or base64 text, unreadable rows, and queries that a derived +table can't hold as written. + +Fixtures: `client` (the app wired to a fresh CaCu database) and +`documents_table`, a SQLite table built per test whose rows carry two +reports of one order, a third report of the same patient under another +order, and an unrelated kind of report. +""" +import base64 + +import pytest +from sqlalchemy import create_engine, text + +from extraction.testing import text_pdf +from webapi.imports.connectors.document import document_bytes +from webapi.imports.connectors.sql import SqlConnector, _without_trailing_order_by + + +@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 +def documents_table(tmp_path): + """Rows 1 and 2 are two reports of order 10 of patient P-1, row 3 is + a report of order 11 of the same patient, and row 4 is a report of a + kind the CaCu cytology target doesn't take. No body prints the + patient id the structured columns hold.""" + url = f"sqlite:///{tmp_path / 'docs.db'}" + rows = [ + (1, "P-1", 10, "Prueba de VPH\nVPH alto riesgo: POSITIVO"), + (2, "P-1", 10, "Prueba de VPH\nGenotipo 18: DETECTADO"), + (3, "P-1", 11, "Prueba de VPH\nVPH alto riesgo: NEGATIVO"), + (4, "P-1", 12, "Informe de otra especialidad\nSin datos de VPH"), + ] + with create_engine(url).begin() as conn: + conn.execute(text("CREATE TABLE docs (row_id INTEGER, patient INTEGER, order_ref INTEGER, body TEXT)")) + for row in rows: + conn.execute(text("INSERT INTO docs VALUES (:a, :b, :c, :d)"), dict(zip("abcd", row))) + return url + + +def _payload(url: str, **sql) -> dict: + base = {"connection_string": url, "table": "docs", "column": "body", "key_column": "row_id"} + return {"sql": {**base, **sql}, "target": "cacu.CitologiaCervical"} + + +def _extract(client, payload: dict) -> dict: + response = client.post("/imports/sources/document/extract", json=payload) + assert response.status_code == 200, response.get_json() + return response.get_json() + + +def test_group_column_keeps_orders_apart_and_merges_within_one(client, documents_table): + """Rows sharing `group_column` become one record; the same patient's + other order stays its own record. Fails if `group_column` stops + reaching `record_keys`.""" + body = _extract( + client, + _payload( + documents_table, + fields={"pac_id_hospital": "patient", "ord_numero_hospital": "order_ref"}, + group_column="order_ref", + ) + | {"exclude_pattern": "otra especialidad"}, + ) + by_key = {record["key"]: record for record in body["records"]} + assert set(by_key) == {"10", "11"} + assert by_key["10"]["fields"]["cit_vph_genotipo_18"]["value"] == 1 + assert by_key["11"]["fields"]["cit_vph_resultado"]["value"] == "NEGATIVO" + assert by_key["10"]["fields"]["pac_id_hospital"]["value"] == "P-1" + + +def test_filters_leave_out_other_kinds_of_report_and_say_so(client, documents_table): + """`include_pattern` keeps only matching documents, matched without + regard to case or accents, and the rest are listed as skipped. Fails + if the filters stop applying or `skipped` stops reporting them.""" + body = _extract( + client, + _payload(documents_table, fields={"pac_id_hospital": "patient"}) | {"include_pattern": "prueba de vph"}, + ) + assert [skipped["document"] for skipped in body["skipped"]] == ["4"] + + +def test_a_filter_that_matches_nothing_is_an_error(client, documents_table): + """Filtering out every document is reported instead of returning an + empty import. Fails if `_extract` stops refusing an empty selection.""" + response = client.post( + "/imports/sources/document/extract", json=_payload(documents_table) | {"include_pattern": "no aparece"} + ) + assert response.status_code == 400 + + +def test_an_invalid_filter_is_a_bad_request(client, documents_table): + """A filter that isn't a valid regular expression is rejected with a + message naming it. Fails if `_compile_filter` lets `re.error` through.""" + response = client.post("/imports/sources/document/extract", json=_payload(documents_table) | {"exclude_pattern": "("}) + assert response.status_code == 400 and "exclude_pattern" in response.get_json()["error"] + + +def test_documents_stored_as_hex_or_base64_text_are_decoded(): + """A PDF kept in a text column as hex (with or without `0x`) or base64 + reaches the readers as the PDF itself, and ordinary text stays text. + Fails if `document_bytes` stops recognizing either encoding.""" + pdf = text_pdf([["Expediente: X-1"]]) + assert document_bytes("0x" + pdf.hex()) == pdf + assert document_bytes(pdf.hex().upper()) == pdf + assert document_bytes(base64.b64encode(pdf).decode()) == pdf + assert document_bytes("Expediente: X-1") == b"Expediente: X-1" + + +def test_an_unreadable_row_is_skipped_not_fatal(client, tmp_path): + """One corrupt document among readable ones is listed as skipped while + the rest are extracted. Fails if a single unreadable row aborts the + whole source again.""" + url = f"sqlite:///{tmp_path / 'mixed.db'}" + with create_engine(url).begin() as conn: + conn.execute(text("CREATE TABLE docs (row_id INTEGER, body BLOB)")) + conn.execute(text("INSERT INTO docs VALUES (1, :b)"), {"b": b"%PDF-1.4 truncated"}) + conn.execute(text("INSERT INTO docs VALUES (2, :b)"), {"b": text_pdf([["Expediente: X-2", "VPH alto riesgo: POSITIVO"]])}) + body = _extract(client, _payload(url)) + assert [record["key"] for record in body["records"]] == ["X-2"] + assert [skipped["document"] for skipped in body["skipped"]] == ["1"] + + +def test_repeated_key_column_values_still_name_rows_apart(tmp_path): + """Two rows with the same `key_column` value get distinct names, so + neither one's fields or pages overwrite the other's. Fails if + `_files_from_sql` stops suffixing repeated names.""" + from webapi.imports.connectors.document import _files_from_sql + + url = f"sqlite:///{tmp_path / 'r.db'}" + with create_engine(url).begin() as conn: + conn.execute(text("CREATE TABLE docs (row_id INTEGER, body TEXT)")) + conn.execute(text("INSERT INTO docs VALUES (7, 'uno'), (7, 'dos')")) + documents = _files_from_sql({"connection_string": url, "table": "docs", "column": "body", "key_column": "row_id"}) + assert [name for name, _ in documents.files] == ["7", "7#2"] + + +@pytest.mark.parametrize( + "query,kept", + [ + ("SELECT a FROM t ORDER BY a", "SELECT a FROM t"), + ("SELECT TOP 5 a FROM t ORDER BY a", None), + ("SELECT a FROM t ORDER BY a OFFSET 0 ROWS FETCH NEXT 5 ROWS ONLY", None), + ("SELECT a, (SELECT TOP 1 b FROM u ORDER BY b) AS x FROM t", None), + ("SELECT 'ORDER BY' AS s FROM t ORDER BY s", "SELECT 'ORDER BY' AS s FROM t"), + ], +) +def test_an_unlimited_trailing_order_by_is_dropped_before_wrapping(query, kept): + """SQL Server refuses `ORDER BY` inside a derived table unless TOP or + OFFSET goes with it, so one that only sorts is dropped; one that picks + rows, or sits inside a subquery or a string, stays. Fails if + `_without_trailing_order_by` drops an `ORDER BY` that chooses rows or + keeps one that would make the wrapped query invalid.""" + assert _without_trailing_order_by(query, "mssql") == (kept or query) + + +def test_a_named_instance_or_embedded_port_reaches_the_driver(): + """`host\\instance` leaves the port unset for the server to resolve, + and `host,port` or `host:port` fill it in. Fails if `server_url` stops + parsing addresses or goes back to forcing the default port on a named + instance.""" + named = SqlConnector.server_url({"engine": "mssql", "host": "db.example\\INST", "database": "d"}) + assert (named.host, named.port) == ("db.example\\INST", None) + comma = SqlConnector.server_url({"engine": "mssql", "host": "db.example,1500", "database": "d"}) + assert (comma.host, comma.port) == ("db.example", 1500) + colon = SqlConnector.server_url({"engine": "postgresql", "host": "db.example:6543", "database": "d"}) + assert (colon.host, colon.port) == ("db.example", 6543) diff --git a/tests/test_document_sql_source.py b/tests/test_document_sql_source.py index 41c380c..56b8132 100644 --- a/tests/test_document_sql_source.py +++ b/tests/test_document_sql_source.py @@ -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" \ No newline at end of file diff --git a/tests/test_mapping_rules.py b/tests/test_mapping_rules.py new file mode 100644 index 0000000..bb93d42 --- /dev/null +++ b/tests/test_mapping_rules.py @@ -0,0 +1,284 @@ +"""Derived fields and document columns inside an ordinary mapping: target +fields computed from several source columns (joined, split, picked, read +out of a longer text or translated), files kept in a column of a CSV or +SQL source read for the fields the plain mapping left empty, and the +captions nothing used, as the import report lists them. + +Fixtures: `client` (the app wired to a fresh CaCu database). Sources are +built inline: CSV text through `_csv`, SQLite tables under `tmp_path`. +""" +import base64 + +import pytest +from sqlalchemy import create_engine, text + +from extraction.testing import text_pdf +from webapi.imports.connectors.errors import ConnectorError +from webapi.imports.mapping.derived import build_derivation, parse_derived + + +@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(content: str, **source) -> dict: + return {"source_type": "csv", "target": "cacu.Paciente", "payload": {"file_base64": _b64(content.encode())}, **source} + + +ROW = {"nombre": " ana maría ", "paterno": "Pérez", "materno": "", "completo": "Ana María Pérez López", "dir": "Calle 5, CP 64000"} + + +@pytest.mark.parametrize( + "rule,expected", + [ + ({"op": "concat", "columns": ["nombre", "paterno", "materno"]}, "ana maría Pérez"), + ({"op": "concat", "columns": ["paterno", "nombre"], "separator": ", ", "case": "upper"}, "PÉREZ, ANA MARÍA"), + ({"op": "template", "template": "{paterno} {materno} / {nombre}"}, "Pérez / ana maría"), + ({"op": "split", "column": "completo", "start": 0, "stop": -2}, "Ana María"), + ({"op": "split", "column": "completo", "start": -2, "stop": -1}, "Pérez"), + ({"op": "coalesce", "columns": ["materno", "paterno"]}, "Pérez"), + ({"op": "extract", "column": "dir", "pattern": r"CP\s*(\d{5})", "group": 1}, "64000"), + ({"op": "map", "column": "paterno", "values": {"pérez": "P"}}, "P"), + ({"op": "map", "column": "nombre", "values": {"x": "y"}, "keep_unmatched": False}, None), + ({"op": "column", "column": "paterno"}, "Pérez"), + ], +) +def test_each_operation_computes_its_value(rule, expected): + """Pins what every registered operation returns for one row, blanks + skipped and spaces collapsed. Fails if an operation's semantics change + (`start`/`stop` counting, separators, `case`, unmatched values).""" + assert build_derivation(rule).apply(ROW) == expected + + +def test_rules_are_checked_before_any_row_is_read(): + """Unknown operations, missing parameters, bad patterns and fields the + target lacks are refused up front. Fails if `parse_derived` lets a + malformed rule through to fail row by row.""" + for bad in ({"op": "nope"}, {"op": "concat"}, {"op": "extract", "column": "a", "pattern": "("}, {"op": "split", "column": "a", "case": "x"}): + with pytest.raises(ConnectorError): + build_derivation(bad) + with pytest.raises(ConnectorError): + parse_derived({"no_such_field": "a"}, {"pac_sexo"}) + + +def test_short_forms_name_a_column_or_join_several(): + """A rule given as a column name reads it; a list of columns joins them. + Fails if `rule_from` stops accepting the short forms.""" + rules = parse_derived({"a": "paterno", "b": ["nombre", "paterno"]}, {"a", "b"}) + assert rules["a"].apply(ROW) == "Pérez" and rules["b"].apply(ROW) == "ana maría Pérez" + + +def test_derived_fields_reach_validation_and_the_mapped_preview(client): + """A source whose id is split over two columns and whose sex comes + coded validates cleanly once `derived` joins and translates them, and + `/imports/mapped-preview` shows the rows as they would be written. + Fails if `ImportSource.rows` stops applying `derived`.""" + source = _csv( + "serie,numero,sx,cp,nac\nA,001,1,64000,1980-01-02\nB,002,2,64100,1975-03-04\n", + column_mapping={"cp": "pac_codigo_postal", "nac": "pac_fecha_nacimiento"}, + derived={ + "pac_id_hospital": {"op": "concat", "columns": ["serie", "numero"], "separator": "-"}, + "pac_sexo": {"op": "map", "column": "sx", "values": {"1": "F", "2": "M"}}, + }, + ) + rows = client.post("/imports/mapped-preview", json={"source": source}).get_json()["rows"] + assert [(r["pac_id_hospital"], r["pac_sexo"]) for r in rows] == [("A-001", "F"), ("B-002", "M")] + result = client.post("/imports/validate", json={"source": source}).get_json() + assert result["error_count"] == 0, result["errors"] + + +def test_a_field_cannot_be_both_mapped_and_derived(client): + """Fails if a field fed twice (mapping and `derived`) stops being refused.""" + source = _csv("a\n1\n", column_mapping={"a": "pac_id_hospital"}, derived={"pac_id_hospital": "a"}) + assert client.post("/imports/validate", json={"source": source}).status_code == 400 + + +def test_the_operations_are_listed_for_clients(client): + """`/imports/derivations` lists every operation with its parameters, so + the import screen builds its forms from the server. Fails if an + operation is registered without being described.""" + body = client.get("/imports/derivations").get_json() + ops = {d["op"]: d for d in body["derivations"]} + assert {"column", "concat", "template", "split", "coalesce", "extract", "map"} <= set(ops) + assert [p["name"] for p in ops["split"]["params"]] == ["column", "separator", "start", "stop"] + assert body["cases"] == ["upper", "lower", "title"] + + +def _documents_table(tmp_path) -> str: + """Two rows of one order of patient P-7, one with its report as a PDF + and one as base64 text, and a third row with no document.""" + url = f"sqlite:///{tmp_path / 'docs.db'}" + report = text_pdf([["VPH alto riesgo: POSITIVO"]]) + with create_engine(url).begin() as conn: + conn.execute(text("CREATE TABLE t (pid TEXT, orden INTEGER, archivo BLOB, texto TEXT)")) + conn.execute(text("INSERT INTO t VALUES ('P-7', 5, :f, NULL)"), {"f": report}) + conn.execute( + text("INSERT INTO t VALUES ('P-7', 5, NULL, :t)"), {"t": _b64(text_pdf([["Genotipo 16: DETECTADO"]]))} + ) + conn.execute(text("INSERT INTO t VALUES ('P-8', 6, NULL, NULL)")) + return url + + +def _sql_source(url: str, **extra) -> dict: + return { + "source_type": "sql", + "target": "cacu.CitologiaCervical", + "payload": {"connection_string": url, "table": "t"}, + "column_mapping": {"pid": "pac_id_hospital", "orden": "ord_numero_hospital"}, + **extra, + } + + +def test_a_sql_preview_flags_the_columns_that_hold_documents(client, tmp_path): + """Binary files and files written as base64 text are both flagged; + plain values aren't. Fails if `document_columns` stops reaching the + preview.""" + url = _documents_table(tmp_path) + body = client.post("/imports/sources/sql/preview", json={"connection_string": url, "table": "t"}).get_json() + assert set(body["document_columns"]) == {"archivo", "texto"} + + +def test_document_columns_fill_what_the_mapping_leaves_empty(client, tmp_path): + """The mapped id and order are kept; the documents of both rows of the + order add the fields they print; a row without documents passes + through mapped. Fails if `documents` stops reading cells of an + ordinary mapping, or loses the rows that have none.""" + source = _sql_source(_documents_table(tmp_path), documents={"columns": ["archivo", "texto"], "group_by": "orden"}) + rows = client.post("/imports/mapped-preview", json={"source": source}).get_json()["rows"] + by_patient = {row["pac_id_hospital"]: row for row in rows} + assert by_patient["P-7"]["ord_numero_hospital"] == 5 + assert by_patient["P-7"]["cit_vph_resultado"] == "POSITIVO" + assert by_patient["P-7"]["cit_vph_genotipo_16"] == 1 + assert by_patient["P-8"]["ord_numero_hospital"] == 6 + + +def test_documents_of_a_mapping_can_be_reviewed_and_committed(client, tmp_path): + """`/imports/sources/document/extract` with `{source}` reviews the same + records the commit writes, with the record's pages in `file_field`. + Fails if the review and the commit read document columns differently.""" + source = _sql_source( + _documents_table(tmp_path), + documents={"columns": "archivo", "group_by": "orden", "file_field": "cit_pdf_blob"}, + label="t", + ) + report = client.post("/imports/sources/document/extract", json={"source": source}).get_json() + [record] = report["records"] + assert record["fields"]["pac_id_hospital"]["method"] == "columna_fuente" + result = client.post("/imports/commit", json={"sources": [source]}).get_json()["results"][0] + assert result["created"] == 2, result + + from persistance.cacu import citologia_cervical_repository + + stored = {r.pac_id_hospital: r for r in citologia_cervical_repository.list(limit=100)} + assert stored["P-7"].cit_vph_resultado == "POSITIVO" + assert stored["P-7"].cit_pdf_blob.startswith(b"%PDF") + + +def test_a_csv_column_of_base64_documents_is_read_like_a_sql_one(client): + """Document columns are not tied to SQL: a CSV whose column carries + base64 PDFs feeds the same extraction. Fails if `documents` only works + for one kind of source.""" + report = _b64(text_pdf([["VPH alto riesgo: NEGATIVO"]])) + source = _csv( + f"exp,doc\nC-1,{report}\n", + target="cacu.CitologiaCervical", + column_mapping={"exp": "pac_id_hospital"}, + documents={"columns": "doc"}, + ) + [row] = client.post("/imports/mapped-preview", json={"source": source}).get_json()["rows"] + assert row["pac_id_hospital"] == "C-1" and row["cit_vph_resultado"] == "NEGATIVO" + + +def _id_and_file_table(tmp_path) -> str: + """Each row has only an id and a file; every other value is printed + in the file under captions no target field knows.""" + url = f"sqlite:///{tmp_path / 'files.db'}" + report = text_pdf([["Tipo de persona: Mujer", "Domicilio actual: Calle 5, C.P. 64000", "Nacida el: 02/01/1980"]]) + with create_engine(url).begin() as conn: + conn.execute(text("CREATE TABLE t (pid TEXT, archivo BLOB)")) + conn.execute(text("INSERT INTO t VALUES ('Q-1', :f)"), {"f": report}) + return url + + +def _paciente_from_file(url: str, **extra) -> dict: + return { + "source_type": "sql", + "target": "cacu.Paciente", + "payload": {"connection_string": url, "table": "t"}, + "documents": {"columns": "archivo"}, + **extra, + } + + +def test_captions_printed_in_documents_are_offered_as_columns(client, tmp_path): + """`/imports/sources/document/columns` lists the source's own columns + and every caption its documents print, with their values. Fails if + discovered captions stop becoming columns of the source.""" + body = client.post( + "/imports/sources/document/columns", json={"source": _paciente_from_file(_id_and_file_table(tmp_path))} + ).get_json() + names = [column["name"] for column in body["columns"]] + assert {"pid", "Tipo de persona", "Domicilio actual", "Nacida el"} <= set(names) + [row] = body["sample_rows"] + assert row["Tipo de persona"] == "Mujer" + + +def test_mapping_and_rules_reach_what_the_documents_print(client, tmp_path): + """A caption maps onto a field like a column does, and derived rules + translate or cut values read from the page. Fails if the mapping and + `derived` stop running over the record's document values.""" + source = _paciente_from_file( + _id_and_file_table(tmp_path), + column_mapping={"pid": "pac_id_hospital", "Nacida el": "pac_fecha_nacimiento"}, + derived={ + "pac_sexo": {"op": "map", "column": "Tipo de persona", "values": {"mujer": "F", "hombre": "M"}}, + "pac_codigo_postal": {"op": "extract", "column": "Domicilio actual", "pattern": r"\d{5}"}, + }, + ) + [row] = client.post("/imports/mapped-preview", json={"source": source}).get_json()["rows"] + assert (row["pac_id_hospital"], row["pac_sexo"], row["pac_codigo_postal"]) == ("Q-1", "F", "64000") + assert row["pac_fecha_nacimiento"] == "02/01/1980" + result = client.post("/imports/validate", json={"source": source}).get_json() + assert result["error_count"] == 0, result["errors"] + + +def _last_report() -> dict: + from webapi.imports.audit import default_sink + + return default_sink().read()[-1] + + +def test_the_import_report_lists_unused_captions_never_their_values(client, tmp_path, monkeypatch): + """Captions the documents print that nothing in the import used are + listed with how many records print them, and none of their values + reaches the report. Below the minimum count they are only counted. + Fails if `unused_captions` stops reaching the audit, lists a caption + the mapping uses, or lets a value through.""" + import json + + source = _paciente_from_file( + _id_and_file_table(tmp_path), column_mapping={"pid": "pac_id_hospital", "Nacida el": "pac_fecha_nacimiento"} + ) + monkeypatch.setenv("WEBAPI_REPORT_MIN_COUNT", "1") + client.post("/imports/validate", json={"source": source}) + report = _last_report()["fuentes"][0] + assert report["etiquetas_sin_usar"] == {"Tipo de persona": 1, "Domicilio actual": 1} + text = json.dumps(_last_report(), ensure_ascii=False) + assert "Mujer" not in text and "64000" not in text and "02/01/1980" not in text + + monkeypatch.setenv("WEBAPI_REPORT_MIN_COUNT", "2") + client.post("/imports/validate", json={"source": source}) + report = _last_report()["fuentes"][0] + assert report["etiquetas_sin_usar"] == {} and report["etiquetas_sin_usar_poco_frecuentes"] == 2 diff --git a/tests/test_new_sources.py b/tests/test_new_sources.py index 3e52081..3fd3d62 100644 --- a/tests/test_new_sources.py +++ b/tests/test_new_sources.py @@ -9,7 +9,6 @@ import sqlalchemy as sa from sqlalchemy.dialects import mssql from extraction.testing import edf_file, scanned_pdf, text_pdf -from webapi.imports.connectors.errors import ConnectorError @pytest.fixture(scope="module") @@ -62,91 +61,6 @@ def test_sql_server_url_is_built_from_form_fields(): assert url.password == "p@ss:/w" -@pytest.mark.parametrize( - "raw,expected", - [ - # bare host, nothing to pull apart - ("10.56.0.45", ("10.56.0.45", None, None)), - (" 10.56.0.45 ", ("10.56.0.45", None, None)), - # SQL Server named instance, as the hospital's IT contact pasted it - ("10.56.0.45\\SQLMAIN", ("10.56.0.45", "SQLMAIN", None)), - # the SSMS "Connect to Database Engine" convention: comma before the port - ("10.56.0.45,1433", ("10.56.0.45", None, 1433)), - ("10.56.0.45\\SQLMAIN,1433", ("10.56.0.45", "SQLMAIN", 1433)), - # a colon is also tolerated, as long as it isn't an IPv6 literal - ("10.56.0.45:1433", ("10.56.0.45", None, 1433)), - # a copied connection string: scheme prefix and a trailing database/property list - ("jdbc:sqlserver://10.56.0.45\\SQLMAIN;databaseName=Pruebas", ("10.56.0.45", "SQLMAIN", None)), - ("tcp:10.56.0.45,1433", ("10.56.0.45", None, 1433)), - ("postgresql://10.56.0.45:5432/Pruebas", ("10.56.0.45", None, 5432)), - # an IPv6 literal has more than one colon: left alone rather than mis-split - ("fe80::1", ("fe80::1", None, None)), - ], -) -def test_parse_server_address_tolerates_pasted_formats(raw, expected): - """Pins the address parser against every way Erick (the hospital's IT - contact) is known to paste a server address — plain host, a SQL Server - named instance, the SSMS `host,port` convention and a copied JDBC/URI - string — plus an IPv6 literal that must NOT be mistaken for a - `host:port` pair. Fails if a future change stops stripping one of these - shapes, or starts mangling an IPv6 address.""" - from webapi.imports.connectors.sql import _parse_server_address - - assert _parse_server_address(raw) == expected - - -def test_sql_server_named_instance_leaves_port_unset_for_browser_resolution(): - """A named instance with no port given anywhere must reach pymssql as - `host\\instance` with no port appended, so FreeTDS can resolve the - instance's real port through SQL Server Browser (UDP 1434) instead of - being forced onto the wrong default port. Fails if `server_url` goes - back to always filling in `engine.default_port`.""" - from webapi.imports.connectors.sql import SqlConnector - - url = SqlConnector.server_url({"engine": "mssql", "host": "10.56.0.45\\SQLMAIN", "database": "Pruebas", "user": "enlace", "password": "Enlace"}) - assert url.host == "10.56.0.45\\SQLMAIN" - assert url.port is None - - -def test_sql_server_named_instance_with_explicit_port_is_appended_after_the_backslash(): - """When the instance's real static port IS known (typed in Puerto, or - pasted as `host\\instance,port`), it must still reach the driver - attached to the instance name, not silently dropped. Fails if the - explicit-port path stops composing `host\\instance` before handing off - to SQLAlchemy.""" - from webapi.imports.connectors.sql import SqlConnector - - url = SqlConnector.server_url( - {"engine": "mssql", "host": "10.56.0.45\\SQLMAIN", "port": "52001", "database": "Pruebas", "user": "enlace", "password": "Enlace"} - ) - assert url.host == "10.56.0.45\\SQLMAIN" - assert url.port == 52001 - - -def test_mysql_tolerates_an_embedded_port_with_no_explicit_port_field(): - """Any engine, not just SQL Server, benefits from the same parser: a - host pasted as `host:port` must still work when the Puerto field is - left blank. Fails if the fix regresses to engine-specific handling that - only covers mssql.""" - from webapi.imports.connectors.sql import SqlConnector - - url = SqlConnector.server_url({"engine": "mysql", "host": "10.56.0.45:3307", "database": "hospital_legacy"}) - assert url.host == "10.56.0.45" - assert url.port == 3307 - - -def test_mysql_rejects_a_named_instance_it_cannot_speak(): - """MySQL/MariaDB/PostgreSQL have no concept of a named instance; a - backslash in the host for one of them is a mistake (e.g. the address - was meant for a different engine), and must be reported rather than - sent on as a garbled hostname. Fails if `server_url` stops validating - `supports_instance_name` per engine.""" - from webapi.imports.connectors.sql import SqlConnector - - with pytest.raises(ConnectorError, match="instancia"): - SqlConnector.server_url({"engine": "mysql", "host": "10.56.0.45\\SQLMAIN", "database": "hospital_legacy"}) - - def test_sql_server_preview_compiles_to_top(monkeypatch): from webapi.imports.connectors.sql import _text_subquery diff --git a/webapi/blueprints/imports.py b/webapi/blueprints/imports.py index ce8c634..6976e27 100644 --- a/webapi/blueprints/imports.py +++ b/webapi/blueprints/imports.py @@ -17,10 +17,14 @@ 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.catalog_commit_service import commit_discovered_fields +from webapi.imports.mapping.derived import CASES, DERIVATIONS from webapi.imports.services.import_service import ( DatabaseRefused, ImportRequestError, + ImportSource, commit_sources, + document_columns_preview, + mapped_sample, serialize_errors, validate_source, ) @@ -30,6 +34,7 @@ from webapi.imports.services.introspection_service import ( document_report, extract_pdf_regions, preview_with_suggestions, + suggest_mapping, ) imports_bp = Blueprint("imports", __name__) @@ -253,12 +258,15 @@ def pdf_regions_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?}`. - `files` may be `sql` instead: `{connection details, table|query, column, - key_column}`, one document per row (a PDF or plain-text column). + segmentation?, pages_per_record?, ocr_mode?, key_pattern?, overrides?, + include_pattern?, exclude_pattern?}`. `files` may be `sql` instead (a + connection plus `table`/`query` and `DocumentColumns`' options), or the + whole body may be `{source}`, an import source with `documents`. Each record comes back with per-field confidence and evidence, conflicts between sources, and the images found on its pages.""" body = _json_body() + if body.get("source"): + return jsonify(document_report(body)) _require(body, "target") if not body.get("files") and not body.get("sql"): raise BadRequest("faltan los archivos") @@ -284,6 +292,32 @@ def document_page_image(): # -- validate and load ------------------------------------------------------------------------- +@imports_bp.get("/derivations") +def derivations(): + """The operations a source's `derived` fields may use, with their + parameters, so a client can build the form for each.""" + return jsonify({"derivations": [cls.describe() for cls in DERIVATIONS.values()], "cases": list(CASES)}) + + +@imports_bp.post("/mapped-preview") +def mapped_preview(): + """`{source, limit?}`: the source's first rows as they would be + written, with its mapping, derived fields and defaults applied.""" + body = _json_body() + return jsonify({"rows": mapped_sample(_require(body, "source"), limit=min(int(body.get("limit", 20)), 200))}) + + +@imports_bp.post("/sources/document/columns") +def document_columns_of_source(): + """`{source, target?}` for a source with `documents`: its own columns + plus every field and caption its documents print, as a preview the + mapping screen offers like any table's, with suggestions.""" + body = _json_body() + preview = document_columns_preview(_require(body, "source"), limit=min(int(body.get("limit", 20)), 200)) + target = body.get("target") or body["source"].get("target") + return jsonify({**preview, "suggested_mapping": suggest_mapping([c["name"] for c in preview["columns"]], target)}) + + @imports_bp.post("/validate") def validate(): source = _require(_json_body(), "source") @@ -308,15 +342,17 @@ def validate(): def _commit_catalog_fallback(raw_sources: list) -> list[dict]: - """For every `document` source in the request (uploaded, or reading a - SQL column — same connector either way), writes the captions no known - field claimed straight into the silver layer (`catalog_commit_service`), - matched or minted against the project's catalog. Best-effort: the - structured fields already landed through `commit_sources`, so a failure - here is reported, not raised.""" + """For every source that asks for it (`catalog_fallback: true`) and + reads documents, writes the captions no known field claimed but the + project's catalog does know straight into the silver layer + (`catalog_commit_service`). Best-effort: the structured fields already + landed through `commit_sources`, so a failure here is reported, not + raised.""" reports = [] for raw in raw_sources: - if not isinstance(raw, dict) or raw.get("source_type") != "document": + if not isinstance(raw, dict) or raw.get("catalog_fallback") is not True: + continue + if raw.get("source_type") != "document" and not raw.get("documents"): continue target = raw.get("target") or "" domain = target.split(".", 1)[0] @@ -324,9 +360,14 @@ def _commit_catalog_fallback(raw_sources: list) -> list[dict]: continue payload = {**(raw.get("payload") or {}), "target": target} try: - connector = build_connector("document", payload) + if raw.get("documents"): + connector, _, _ = ImportSource.parse(raw).document_connector() + if connector is None: + continue + else: + connector = build_connector("document", payload) result = commit_discovered_fields(connector.records, proyecto=domain, estudio_id=payload.get("estudio_id")) - except (ConnectorError, ExtractionError, CatalogoInvalido, SQLAlchemyError) as exc: + except (ConnectorError, ExtractionError, CatalogoInvalido, SQLAlchemyError, ImportRequestError) as exc: log.warning("catalog_fallback: %s no se pudo procesar: %s", raw.get("label") or target, exc) continue reports.append( @@ -337,6 +378,7 @@ def _commit_catalog_fallback(raw_sources: list) -> list[dict]: "records_without_patient": result.records_without_patient, "fields_matched": result.fields_matched, "fields_minted": result.fields_minted, + "fields_unmatched": result.fields_unmatched, } ) return reports diff --git a/webapi/imports/audit.py b/webapi/imports/audit.py index db45c5c..7525f2d 100644 --- a/webapi/imports/audit.py +++ b/webapi/imports/audit.py @@ -15,6 +15,7 @@ from __future__ import annotations import fcntl import json +import logging import os import re import time @@ -23,7 +24,7 @@ from collections import Counter, defaultdict from dataclasses import dataclass, field from datetime import datetime, timezone from pathlib import Path -from typing import TYPE_CHECKING, Any, Iterable +from typing import TYPE_CHECKING, Any, Callable, Iterable from webapi.imports.schemas.classify import ErrorCategory @@ -31,7 +32,11 @@ if TYPE_CHECKING: from webapi.imports.schemas.service import BatchValidationResult from webapi.imports.services.import_service import ImportSource +log = logging.getLogger(__name__) + SCHEMA_VERSION = 1 +# Longest caption, in words, that document discovery reports. +CAPTION_MAX_WORDS = 6 _SHAPE_MAX = 40 _MESSAGE_MAX = 300 _QUOTED = re.compile(r"'[^']*'|\"[^\"]*\"") @@ -57,11 +62,12 @@ def value_shape(value: Any) -> str: return shape + ("…" if len(text) > _SHAPE_MAX else "") -def column_label(name: Any) -> str: +def column_label(name: Any, *, max_words: int = 4) -> str: """A source column name as it can be logged: verbatim when it looks like a - header, its shape when it looks like data.""" + header, its shape when it looks like data. A document caption, already + cut at a colon, may run to more words (`max_words`) than a header.""" text = str(name).strip() - if len(text) > _SHAPE_MAX or text.count(" ") > 3 or _VALUE_LIKE.search(text): + if len(text) > _SHAPE_MAX or text.count(" ") >= max_words or _VALUE_LIKE.search(text): return value_shape(text) return text @@ -128,9 +134,10 @@ class _SourceAudit: self.rows: dict[str, Any] = {"leidas": 0} self.links: dict[str, int] = {} self.warnings: Counter = Counter() + self.captions: Counter = Counter() def observe_rows(self, rows: Iterable[dict[str, Any] | None]) -> None: - mapped = set(self.source.column_mapping.values()) | set(self.source.defaults) + mapped = set(self.source.column_mapping.values()) | set(self.source.derived) | set(self.source.defaults) merged = 0 for row in rows: self.rows["leidas"] += 1 @@ -164,6 +171,15 @@ class _SourceAudit: self.rows.update(insertadas=created, actualizadas=updated, rechazadas_por_conflicto=conflicts) self.links = dict(linked) + def observe_captions(self, count: Callable[[], Counter]) -> None: + """Captions the source's documents print that the import didn't + use (`ImportSource.unused_captions`). Best-effort: the report must + never be what makes an import fail.""" + try: + self.captions = Counter(count()) + except Exception: + log.warning("no se pudieron contar las etiquetas sin usar de %s", self.source.target, exc_info=True) + def observe_warnings(self, warnings: Iterable[dict[str, Any]]) -> None: for warning in warnings: self.warnings[f"{warning.get('category')}:{warning.get('field')}"] += 1 @@ -171,13 +187,14 @@ class _SourceAudit: def as_dict(self, threshold: int) -> dict[str, Any]: spec_fields = self.source.spec.schema.model_fields required = {name for name, info in spec_fields.items() if info.is_required()} - mapped = set(self.source.column_mapping.values()) + mapped = set(self.source.column_mapping.values()) | set(self.source.derived) fixed = set(self.source.defaults) out: dict[str, Any] = { "destino": self.source.target, "origen": _source_origin(self.source), "mapeo": { - "columnas_origen": sorted(column_label(c) for c in self.source.column_mapping), + "columnas_origen": sorted(column_label(c) for c in self.source.source_columns), + "campos_derivados": {name: rule.op for name, rule in sorted(self.source.derived.items())}, "campos_mapeados": sorted(mapped), "campos_con_valor_fijo": sorted(fixed), "campos_sin_mapear": sorted(set(spec_fields) - mapped - fixed), @@ -190,6 +207,15 @@ class _SourceAudit: out["vinculos_resueltos"] = self.links if self.warnings: out["advertencias"] = dict(self.warnings) + if self.captions: + # Captions only, and only those enough records print: a caption + # seen once or twice can be a misread line holding a value. + out["etiquetas_sin_usar"] = { + column_label(c, max_words=CAPTION_MAX_WORDS): n for c, n in self.captions.most_common() if n >= threshold + } + rare = sum(1 for n in self.captions.values() if n < threshold) + if rare: + out["etiquetas_sin_usar_poco_frecuentes"] = rare return out diff --git a/webapi/imports/connectors/document.py b/webapi/imports/connectors/document.py index d2c0a41..f2cd9ec 100644 --- a/webapi/imports/connectors/document.py +++ b/webapi/imports/connectors/document.py @@ -1,8 +1,10 @@ import hashlib import json +import re import threading +import unicodedata from collections import OrderedDict -from typing import Any, ClassVar +from typing import Any, ClassVar, Iterator import pandas as pd @@ -10,6 +12,7 @@ from extraction import DocumentExtractor, ExtractedRecord, ExtractionError, make 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.document_columns import DocumentBatch, DocumentColumns, document_bytes # noqa: F401 from webapi.imports.connectors.errors import ConnectorError from webapi.imports.connectors.registry import register_connector from webapi.imports.connectors.sql import SqlConnector @@ -29,11 +32,11 @@ class _ResultCache: per worker for the last few distinct requests.""" def __init__(self, size: int = 8): - self._items: OrderedDict[str, list[ExtractedRecord]] = OrderedDict() + self._items: OrderedDict[str, Any] = OrderedDict() self._size = size self._lock = threading.Lock() - def get_or_compute(self, key: str, compute) -> list[ExtractedRecord]: + def get_or_compute(self, key: str, compute) -> Any: with self._lock: if key in self._items: self._items.move_to_end(key) @@ -49,49 +52,19 @@ class _ResultCache: _CACHE = _ResultCache() -def _files_from_sql(sql: dict[str, Any]) -> tuple[list[tuple[str, bytes]], dict[str, dict[str, Any]]]: - """One `(name, bytes)` per row of a SQL source (connected the same way - `SqlConnector` is): `column` is the field bundle (a `varbinary(max)` - PDF, or already a plain string — `read_document` reads either), - `key_column` names the row (a patient or study id) for tracing, and the - optional `fields` (`{target_field: sql_column}`) carries other columns - through as that row's authoritative values — a source's own patient or - study id, trusted over whatever the document's text happens to say. - Any column type `SqlConnector` can read works; it's not limited to PDFs. - - Returns the files alongside, per row name, the `fields` values read for - it (`DocumentExtractor.extract`'s `source_fields`).""" - column = sql.get("column") - if not column: - raise ConnectorError("falta column") - if not sql.get("query") and not sql.get("table"): +def _files_from_sql(sql: dict[str, Any]) -> DocumentBatch: + """The documents of a SQL table or query (connected the same way + `SqlConnector` is), read as `DocumentColumns` describes: `column` or + `columns` hold them, and `key_column`/`name_by`, `group_column`/ + `group_by` and `fields` name, group and carry values for them.""" + if not sql.get("table") and not sql.get("query"): raise ConnectorError("falta table o query") - key_column = sql.get("key_column") or column - if key_column == column: - raise ConnectorError("key_column debe ser distinta de column") - - fields: dict[str, str] = sql.get("fields") or {} - mapping = {column: "contenido", key_column: "clave"} - for field_name, sql_column in fields.items(): - if sql_column in mapping: - raise ConnectorError(f"la columna {sql_column!r} ya está asignada a otro papel en fields/column/key_column") - mapping[sql_column] = field_name - + spec = DocumentColumns.parse(sql) connector = SqlConnector.connect(sql) connector = ( connector.select_query(sql["query"]) if sql.get("query") else connector.select_table(sql["table"], schema=sql.get("schema")) ) - files = [] - source_fields: dict[str, dict[str, Any]] = {} - for row in connector.read_rows(mapping): - raw = row.get("contenido") - if raw is None: - continue - name = str(row.get("clave", len(files) + 1)) - files.append((name, raw if isinstance(raw, bytes) else str(raw).encode("utf-8"))) - if fields: - source_fields[name] = {field_name: row.get(field_name) for field_name in fields if row.get(field_name) is not None} - return files, source_fields + return spec.assemble(connector.read_rows({column: column for column in spec.source_columns()})) @register_connector @@ -138,6 +111,9 @@ class DocumentConnector(DataFrameConnector): key_pattern: str | None = None, overrides: dict[str, dict[str, Any]] | None = None, source_fields: dict[str, dict[str, Any]] | None = None, + record_keys: dict[str, str] | None = None, + include_pattern: str | None = None, + exclude_pattern: str | None = None, ): if not files: raise ConnectorError("no se recibieron documentos") @@ -158,6 +134,10 @@ class DocumentConnector(DataFrameConnector): self.key_pattern = key_pattern self.overrides = {str(k): v for k, v in (overrides or {}).items()} self.source_fields = {str(k): v for k, v in (source_fields or {}).items()} + self.record_keys = {str(k): str(v) for k, v in (record_keys or {}).items()} + self.include_pattern = _compile_filter(include_pattern, "include_pattern") + self.exclude_pattern = _compile_filter(exclude_pattern, "exclude_pattern") + self.skipped: list[dict[str, str]] = [] known = {spec.name for spec in self.specs} unknown = sorted({name for values in self.source_fields.values() for name in values} - known) if unknown: @@ -167,21 +147,23 @@ class DocumentConnector(DataFrameConnector): @classmethod def from_payload(cls, payload: dict[str, Any]) -> "DocumentConnector": if payload.get("sql"): - files, source_fields = _files_from_sql(payload["sql"]) + documents = _files_from_sql(payload["sql"]) else: - files = [ - (f.get("name") or f"documento_{i}", decode_file(f)) for i, f in enumerate(payload.get("files") or [], 1) - ] - source_fields = {} + documents = DocumentBatch( + files=[(f.get("name") or f"documento_{i}", decode_file(f)) for i, f in enumerate(payload.get("files") or [], 1)] + ) return cls( - files, + documents.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"), - source_fields=source_fields, + source_fields=documents.source_fields, + record_keys=documents.record_keys, + include_pattern=payload.get("include_pattern") or None, + exclude_pattern=payload.get("exclude_pattern") or None, ) @classmethod @@ -193,28 +175,65 @@ class DocumentConnector(DataFrameConnector): @property def records(self) -> list[ExtractedRecord]: - return _CACHE.get_or_compute(self._cache_key(), self._extract) + records, self.skipped = _CACHE.get_or_compute(self._cache_key(), self._extract) + return records - 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 + def _extract(self) -> tuple[list[ExtractedRecord], list[dict[str, str]]]: + documents, skipped = [], [] + for name, raw in self.files: + try: + document = read_document(name, raw, ocr_mode=self.ocr_mode) + except ExtractionError as exc: + skipped.append({"document": name, "reason": f"ilegible: {exc}"}) + continue + reason = self._filtered_out(document) + if reason: + skipped.append({"document": name, "reason": reason}) + continue + documents.append(document) + if not documents: + detail = "; ".join(f"{s['document']}: {s['reason']}" for s in skipped[:5]) + raise ConnectorError(f"ningún documento se pudo usar ({detail})") 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, source_fields=self.source_fields + records = DocumentExtractor(self.specs, key_field=self.key_field, segmenter=segmenter).extract( + documents, source_fields=self.source_fields, record_keys=self.record_keys ) + return records, skipped + + + def _filtered_out(self, document) -> str | None: + """Why a document is left out by `include_pattern`/`exclude_pattern`, + matched case- and accent-insensitively against all of its text, + so a source mixing several kinds of report feeds each target only + its own.""" + text = "\n".join(page.text for page in document.pages) + plain = _unaccented(text) + if self.include_pattern and not (self.include_pattern.search(text) or self.include_pattern.search(plain)): + return "no coincide con include_pattern" + if self.exclude_pattern and (self.exclude_pattern.search(text) or self.exclude_pattern.search(plain)): + return "coincide con exclude_pattern" + return None 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, self.source_fields] + config = [ + self.target, + self.segmentation, + self.pages_per_record, + self.ocr_mode, + self.key_pattern, + self.source_fields, + self.record_keys, + self.include_pattern.pattern if self.include_pattern else None, + self.exclude_pattern.pattern if self.exclude_pattern else None, + ] digest.update(json.dumps(config, sort_keys=True, default=str).encode()) return digest.hexdigest() @@ -222,13 +241,40 @@ class DocumentConnector(DataFrameConnector): 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] + columns = ( + [spec.name for spec in self.specs] + + self.caption_columns() + + [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 caption_columns(self) -> list[str]: + """Every caption the documents print that no field of the target + claims, in the order first seen: columns of their own, mappable + and usable in derived fields like any column of a table.""" + reserved = {spec.name for spec in self.specs} | {DOCUMENT_COLUMN, IMAGE_COLUMN, CONFIDENCE_COLUMN, SOURCES_COLUMN} + columns: list[str] = [] + for record in self.records: + for found in record.discovered: + name = _caption_column(found.caption, reserved) + if name not in columns: + columns.append(name) + return columns + + def record_rows(self) -> Iterator[tuple[dict[str, Any], list[str]]]: + """Each record's row (overrides applied, its captions as columns, + its pages as `documento`) with the names of the documents it was + read from.""" + for index, record in enumerate(self.records): + yield self._row(index, record), [source.document for source in record.sources] + def _row(self, index: int, record: ExtractedRecord) -> dict[str, Any]: row: dict[str, Any] = record.row() + reserved = {spec.name for spec in self.specs} | {DOCUMENT_COLUMN, IMAGE_COLUMN, CONFIDENCE_COLUMN, SOURCES_COLUMN} + for found in record.discovered: + row.setdefault(_caption_column(found.caption, reserved), found.value) row.update(self.overrides.get(str(index), {})) row[DOCUMENT_COLUMN] = self._record_pdf(record) row[IMAGE_COLUMN] = self._record_image(record) @@ -295,4 +341,50 @@ class DocumentConnector(DataFrameConnector): 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]} + return { + "records": len(self.records), + "key_field": self.key_field, + "documents": [name for name, _ in self.files], + "skipped": self.skipped, + } + + +def _caption_column(caption: str, reserved: set[str]) -> str: + """A discovered caption as a column name, kept apart from the target's + own fields and the connector's bookkeeping columns.""" + name = " ".join(caption.split()) + return f"texto: {name}" if name in reserved else name + + +def _compile_filter(pattern: str | None, name: str) -> re.Pattern | None: + if not pattern: + return None + try: + return re.compile(pattern, re.I) + except re.error as exc: + raise ConnectorError(f"{name} no es una expresión regular válida: {exc}") from exc + + +def _unaccented(text: str) -> str: + return "".join(ch for ch in unicodedata.normalize("NFKD", text) if not unicodedata.combining(ch)) + + +DOCUMENT_OPTIONS = ("segmentation", "pages_per_record", "ocr_mode", "key_pattern", "overrides", "include_pattern", "exclude_pattern") + + +def document_options(raw: dict[str, Any]) -> dict[str, Any]: + """The extraction settings `DocumentConnector` takes, out of a request.""" + return {name: raw[name] for name in DOCUMENT_OPTIONS if raw.get(name) not in (None, "")} + + +def connector_for_batch(batch: DocumentBatch, target: str, options: dict[str, Any]) -> "DocumentConnector": + """A `DocumentConnector` over documents read from a source's columns, + their row values restricted to the fields extraction knows.""" + entity = ENTITY_REGISTRY.get(target) + if entity is None: + raise ConnectorError(f"destino desconocido: {target!r}") + known = {spec.name for spec in field_specs_for(entity)} + source_fields = {name: {k: v for k, v in values.items() if k in known} for name, values in batch.source_fields.items()} + return DocumentConnector( + batch.files, target=target, source_fields=source_fields, record_keys=batch.record_keys, **document_options(options) + ) diff --git a/webapi/imports/connectors/document_columns.py b/webapi/imports/connectors/document_columns.py new file mode 100644 index 0000000..baf41e5 --- /dev/null +++ b/webapi/imports/connectors/document_columns.py @@ -0,0 +1,167 @@ +"""Documents stored in the columns of any tabular source: a SQL table or +query, a CSV or Excel sheet, a JSON list. Each non-empty cell of a document +column becomes one document; the rest of its row travels with it as values +the extraction must trust over the page, and an optional grouping decides +which documents form one record. + +A cell may hold the file itself (binary), the same file written as hex or +base64 text, or plain text; `document_bytes` tells them apart. +""" +import base64 +import binascii +import re +from dataclasses import dataclass, field +from typing import Any, Iterable + +from webapi.imports.connectors.errors import ConnectorError +from webapi.imports.mapping.derived import Derivation, rule_from + +_HEX = re.compile(r"^(?:0x)?(?:[0-9a-fA-F]{2})+$") +_BASE64 = re.compile(r"^[A-Za-z0-9+/\r\n]+={0,2}$") +DOCUMENT_MAGIC = (b"%PDF", b"\x89PNG", b"\xff\xd8\xff", b"II*\x00", b"MM\x00*", b"BM", b"RIFF", b"GIF8") + + +def document_bytes(raw: Any) -> bytes: + """A stored document as bytes. Binary values pass through; text is + checked for a binary file written out as hex or base64 before being + taken as plain UTF-8 text.""" + if isinstance(raw, memoryview): + raw = raw.tobytes() + if isinstance(raw, (bytes, bytearray)): + return bytes(raw) + text = str(raw).strip() + if len(text) >= 16 and _HEX.match(text): + decoded = bytes.fromhex(text[2:] if text[:2].lower() == "0x" else text) + if decoded.startswith(DOCUMENT_MAGIC): + return decoded + if len(text) >= 16 and _BASE64.match(text): + try: + decoded = base64.b64decode(text, validate=False) + except (binascii.Error, ValueError): + decoded = b"" + if decoded.startswith(DOCUMENT_MAGIC): + return decoded + return text.encode("utf-8") + + +def is_document(raw: Any) -> bool: + """Whether a cell holds a file a document reader opens (as opposed to + a plain value), whatever way it was stored.""" + if raw is None or isinstance(raw, (int, float, bool)): + return False + return document_bytes(raw).startswith(DOCUMENT_MAGIC) + + +@dataclass +class DocumentBatch: + """What the extractor receives: one `(name, bytes)` per document and, + per document name, its authoritative values and the record it joins. + `rows` and `row_numbers` keep, per document name, the values of the row + it came from and that row's position (from 1).""" + + files: list[tuple[str, bytes]] = field(default_factory=list) + source_fields: dict[str, dict[str, Any]] = field(default_factory=dict) + record_keys: dict[str, str] = field(default_factory=dict) + rows: dict[str, dict[str, Any]] = field(default_factory=dict) + row_numbers: dict[str, int] = field(default_factory=dict) + without_documents: list[dict[str, Any]] = field(default_factory=list) + + +@dataclass +class DocumentColumns: + """How to read documents out of a source's rows. + + `columns`: the columns holding documents (one or several per row). + `name_by`: names each row in reports (default: its row number). + `group_by`: rows giving the same value form one record, apart from + the same patient's other rows; without it, documents merge by the + target's key field, as uploaded files do. + `fields`: target fields filled from the row, trusted over the page. + The last three take a column name, a list of columns or a `derived` + rule (`webapi.imports.mapping.derived`).""" + + columns: list[str] + name_by: Derivation | None = None + group_by: Derivation | None = None + fields: dict[str, Derivation] = field(default_factory=dict) + + @classmethod + def parse(cls, raw: Any) -> "DocumentColumns": + if not isinstance(raw, dict): + raise ConnectorError("'documents' debe ser un objeto") + columns = raw.get("columns", raw.get("column")) + columns = [columns] if isinstance(columns, str) else list(columns or []) + if not columns or not all(isinstance(column, str) and column for column in columns): + raise ConnectorError("indique la columna (o columnas) con los documentos") + fields = raw.get("fields") or {} + if not isinstance(fields, dict): + raise ConnectorError("'fields' debe ser un objeto {campo: columna o regla}") + name_by = raw.get("name_by", raw.get("key_column")) + group_by = raw.get("group_by", raw.get("group_column")) + parsed = cls( + columns=columns, + name_by=rule_from(name_by) if name_by else None, + group_by=rule_from(group_by) if group_by else None, + fields={name: rule_from(rule, separator=" ") for name, rule in fields.items()}, + ) + roles = {"name_by (key_column)": [parsed.name_by], "group_by (group_column)": [parsed.group_by], "fields": list(parsed.fields.values())} + for role, rules in roles.items(): + reused = set().union(*(rule.columns() for rule in rules if rule is not None)) & set(columns) + if reused: + raise ConnectorError(f"{sorted(reused)} contiene los documentos; no puede usarse también en {role}") + return parsed + + def columns_read_by_rules(self) -> set[str]: + read: set[str] = set() + for rule in [self.name_by, self.group_by, *self.fields.values()]: + if rule is not None: + read |= rule.columns() + return read + + def source_columns(self) -> set[str]: + return set(self.columns) | self.columns_read_by_rules() + + def assemble( + self, raw_rows: Iterable[dict[str, Any]], mapped_rows: Iterable[dict[str, Any]] | None = None + ) -> DocumentBatch: + """`raw_rows` keyed by source column; `mapped_rows`, when the source + also has a mapping, the same rows already mapped to target fields, + whose values join `fields` as values to trust.""" + batch = DocumentBatch() + seen: dict[str, int] = {} + mapped = iter(mapped_rows) if mapped_rows is not None else None + for number, raw in enumerate(raw_rows, start=1): + values = dict(next(mapped)) if mapped is not None else {} + values.update({name: rule.apply(raw) for name, rule in self.fields.items()}) + values = {name: value for name, value in values.items() if not _blank(value)} + contents = [(column, raw.get(column)) for column in self.columns if not _blank(raw.get(column))] + if not contents: + batch.without_documents.append(values) + continue + base = _text(self.name_by.apply(raw)) if self.name_by else "" + base = base or str(number) + group = _text(self.group_by.apply(raw)) if self.group_by else "" + for column, content in contents: + name = base if len(self.columns) == 1 else f"{base}:{column}" + seen[name] = seen.get(name, 0) + 1 + if seen[name] > 1: + name = f"{name}#{seen[name]}" + batch.files.append((name, document_bytes(content))) + batch.source_fields[name] = values + batch.rows[name] = values + batch.row_numbers[name] = number + if group: + batch.record_keys[name] = group + return batch + + +def _blank(value: Any) -> bool: + return value is None or (isinstance(value, str) and not value.strip()) + + +def _text(value: Any) -> str: + if value is None: + return "" + if isinstance(value, float) and value.is_integer(): + value = int(value) + return str(value).strip() diff --git a/webapi/imports/connectors/sql.py b/webapi/imports/connectors/sql.py index 5e5762f..ce63148 100644 --- a/webapi/imports/connectors/sql.py +++ b/webapi/imports/connectors/sql.py @@ -7,12 +7,13 @@ from typing import Any, ClassVar, Iterator import pandas as pd import sqlalchemy as sa +import sqlglot 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.sql_policy import SQLGLOT_DIALECTS, SqlSourcePolicy from webapi.imports.connectors.tabular import infer_type @@ -222,7 +223,7 @@ class SqlConnector(Connector): if self._table is not None: return sa.select(self._table).subquery("source") if self._query: - return _text_subquery(self._query) + return _text_subquery(self._query, self.get_dialect()) raise ConnectorError("no hay tabla ni consulta seleccionada") def _columns(self, names: list[str], rows: list[dict[str, Any]]) -> list[SourceColumn]: @@ -258,11 +259,11 @@ _ADDRESS_PORT_SEPARATORS = (",", ":") def _parse_server_address(raw: str) -> tuple[str, str | None, int | None]: """Tolerates the ways a server address arrives typed or pasted from - SSMS, a JDBC string or a connection URI instead of a bare host: a + a SQL client, a JDBC string or a connection URI instead of a bare host: a leading scheme (`jdbc:sqlserver://`, `postgresql://`, `tcp:`), a trailing path/query/property list, surrounding whitespace, a SQL Server named instance (`host\\instance`), and a port given as - `host:port` or the SSMS convention `host,port` / `host\\instance,port`. + `host:port` or SQL Server's `host,port` / `host\\instance,port`. Returns `(host, instance, port)`, with `instance` and `port` `None` when absent, so the caller can leave the port unset for a named @@ -298,12 +299,41 @@ def _parse_server_address(raw: str) -> tuple[str, str | None, int | None]: return host, (instance or None), port -def _text_subquery(query: str) -> sa.Subquery: +def _text_subquery(query: str, dialect: str | None = None) -> sa.Subquery: """Wraps policy-checked SELECT text as a derived table, so SQLAlchemy composes LIMIT/TOP and COUNT(*) for whichever dialect the source speaks.""" + query = _without_trailing_order_by(query, dialect) return sa.select(sa.literal_column("*")).select_from(sa.text(f"({query}) AS source_query")).subquery("source") +_ORDER_BY = re.compile(r"\bORDER\s+BY\b", re.I) + + +def _without_trailing_order_by(query: str, dialect: str | None) -> str: + """Drops a top-level `ORDER BY` that nothing limits: SQL Server refuses + one inside a derived table, and row order means nothing to an import. + Kept when TOP, LIMIT or OFFSET makes it choose the rows.""" + try: + [root] = sqlglot.parse(query, read=SQLGLOT_DIALECTS.get(dialect, dialect)) + except Exception: + return query + if root is None or not root.args.get("order") or root.args.get("limit") or root.args.get("offset"): + return query + depth, quote, cut = 0, None, None + for position, char in enumerate(query): + if quote: + quote = None if char == quote else quote + elif char in "'\"[`": + quote = "]" if char == "[" else char + elif char == "(": + depth += 1 + elif char == ")": + depth -= 1 + elif depth == 0 and _ORDER_BY.match(query, position): + cut = position + return query[:cut].rstrip() if cut is not None else query + + def _sa_type_to_kind(sa_type: sa.types.TypeEngine) -> str: try: python_type = sa_type.python_type diff --git a/webapi/imports/connectors/sql_policy.py b/webapi/imports/connectors/sql_policy.py index 3dd81a6..78c9d8f 100644 --- a/webapi/imports/connectors/sql_policy.py +++ b/webapi/imports/connectors/sql_policy.py @@ -22,7 +22,7 @@ from webapi.imports.connectors.errors import ConnectorError _DEFAULT_DIALECTS = "mysql,mariadb,postgresql,mssql" _DEFAULT_PORTS = {"mysql": 3306, "mariadb": 3306, "postgresql": 5432, "mssql": 1433} # SQLAlchemy dialect name -> sqlglot's name for it, where they differ. -_SQLGLOT_DIALECTS = {"postgresql": "postgres", "mssql": "tsql", "mariadb": "mysql"} +SQLGLOT_DIALECTS = {"postgresql": "postgres", "mssql": "tsql", "mariadb": "mysql"} # Anything that writes, wherever it sits in the tree: a top-level # `SELECT ... INTO table`/`INTO OUTFILE`, or a writable CTE # (`WITH t AS (DELETE FROM x RETURNING *) SELECT * FROM t` still parses as a @@ -73,7 +73,7 @@ class SqlSourcePolicy: if not statement: raise ConnectorError("la consulta no puede estar vacía") try: - parsed = [node for node in sqlglot.parse(statement, read=_SQLGLOT_DIALECTS.get(dialect, dialect)) if node is not None] + parsed = [node for node in sqlglot.parse(statement, read=SQLGLOT_DIALECTS.get(dialect, dialect)) if node is not None] except sqlglot.errors.ParseError as exc: raise ConnectorError(f"la consulta no es SQL válido: {exc}") from exc if len(parsed) != 1: diff --git a/webapi/imports/mapping/derived.py b/webapi/imports/mapping/derived.py new file mode 100644 index 0000000..b6ce300 --- /dev/null +++ b/webapi/imports/mapping/derived.py @@ -0,0 +1,305 @@ +"""Target fields computed from one or more source columns, for sources whose +columns don't line up one-to-one with the target: a name and surnames kept +apart where the target wants one full name, or the reverse; an id spread +over two columns; a code that must be read out of a longer text. + +A source's `derived` maps each target field to one rule, +`{"op": , ...params}`, plus the optional `case` (`upper`, `lower`, +`title`) applied to the result. To add an operation, subclass `Derivation`, +declare its `params` and register it with `@register_derivation`. +""" +import re +import string +from abc import ABC, abstractmethod +from dataclasses import dataclass +from typing import Any, ClassVar + +from webapi.imports.connectors.errors import ConnectorError + + +@dataclass(frozen=True) +class Param: + """One parameter of an operation, described so a client can build its form.""" + + name: str + kind: str # column | columns | text | integer | mapping | boolean + label: str + required: bool = True + default: Any = None + + def to_dict(self) -> dict[str, Any]: + return {"name": self.name, "kind": self.kind, "label": self.label, "required": self.required, "default": self.default} + + +CASES = {"upper": str.upper, "lower": str.lower, "title": str.title} + + +class Derivation(ABC): + op: ClassVar[str] + label: ClassVar[str] + description: ClassVar[str] + params: ClassVar[tuple[Param, ...]] + + def __init__(self, rule: dict[str, Any]): + self.args: dict[str, Any] = {} + for param in self.params: + value = rule.get(param.name, param.default) + if param.required and _blank(value): + raise ConnectorError(f"la regla {self.op!r} requiere {param.name!r}") + if param.kind == "columns" and value is not None and not isinstance(value, list): + raise ConnectorError(f"{param.name!r} debe ser una lista de columnas") + self.args[param.name] = value + self.case = rule.get("case") or None + if self.case is not None and self.case not in CASES: + raise ConnectorError(f"case desconocido {self.case!r} (disponibles: {', '.join(CASES)})") + + @abstractmethod + def columns(self) -> set[str]: + """The source columns this rule reads.""" + + @abstractmethod + def compute(self, row: dict[str, Any]) -> Any: ... + + def apply(self, row: dict[str, Any]) -> Any: + value = self.compute(row) + if isinstance(value, str): + value = " ".join(value.split()) + if self.case: + value = CASES[self.case](value) + return value or None + return value + + @classmethod + def describe(cls) -> dict[str, Any]: + return { + "op": cls.op, + "label": cls.label, + "description": cls.description, + "params": [param.to_dict() for param in cls.params], + } + + +DERIVATIONS: dict[str, type[Derivation]] = {} + + +def register_derivation(cls: type[Derivation]) -> type[Derivation]: + DERIVATIONS[cls.op] = cls + return cls + + +def build_derivation(rule: Any) -> Derivation: + if not isinstance(rule, dict): + raise ConnectorError("cada regla de 'derived' debe ser un objeto") + cls = DERIVATIONS.get(rule.get("op", "")) + if cls is None: + raise ConnectorError(f"operación desconocida {rule.get('op')!r} (disponibles: {', '.join(DERIVATIONS)})") + return cls(rule) + + +def _blank(value: Any) -> bool: + return value is None or (isinstance(value, str) and not value.strip()) or value == [] or value == {} + + +def _index(value: Any) -> int | None: + if value in (None, ""): + return None + try: + return int(value) + except (TypeError, ValueError) as exc: + raise ConnectorError(f"se esperaba un número entero, no {value!r}") from exc + + +def _text(value: Any) -> str: + if value is None: + return "" + if isinstance(value, float) and value.is_integer(): + value = int(value) + return str(value).strip() + + +@register_derivation +class Column(Derivation): + op = "column" + label = "Columna" + description = "El valor de una columna, tal cual." + params = (Param("column", "column", "Columna"),) + + def columns(self) -> set[str]: + return {self.args["column"]} + + def compute(self, row: dict[str, Any]) -> Any: + return row.get(self.args["column"]) + + +@register_derivation +class Concat(Derivation): + op = "concat" + label = "Unir columnas" + description = "Une los valores no vacíos de varias columnas, en orden, con un separador." + params = ( + Param("columns", "columns", "Columnas"), + Param("separator", "text", "Separador", required=False, default=" "), + ) + + def columns(self) -> set[str]: + return set(self.args["columns"]) + + def compute(self, row: dict[str, Any]) -> Any: + parts = [_text(row.get(column)) for column in self.args["columns"]] + separator = self.args["separator"] if self.args["separator"] is not None else " " + return separator.join(part for part in parts if part) + + +@register_derivation +class Template(Derivation): + op = "template" + label = "Plantilla" + description = "Arma un texto con columnas entre llaves: `{Nombre} {Apellido}`. Las columnas vacías se omiten." + params = (Param("template", "text", "Plantilla"),) + + def __init__(self, rule: dict[str, Any]): + super().__init__(rule) + try: + self._names = [name for _, name, _, _ in string.Formatter().parse(self.args["template"]) if name] + except ValueError as exc: + raise ConnectorError(f"plantilla inválida: {exc}") from exc + + def columns(self) -> set[str]: + return set(self._names) + + def compute(self, row: dict[str, Any]) -> Any: + values = {name: _text(row.get(name)) for name in self._names} + return string.Formatter().vformat(self.args["template"], (), _Fill(values)) + + +class _Fill(dict): + def __missing__(self, key: str) -> str: + return "" + + +@register_derivation +class Split(Derivation): + op = "split" + label = "Tomar partes" + description = ( + "Separa el valor de una columna y toma las partes de `start` a `stop` " + "(se cuentan desde 0; negativas desde el final): de un nombre completo, " + "el primer apellido es `start=-2, stop=-1`." + ) + params = ( + Param("column", "column", "Columna"), + Param("separator", "text", "Separador (vacío: espacios)", required=False, default=""), + Param("start", "integer", "Desde", required=False, default=0), + Param("stop", "integer", "Hasta (sin incluir)", required=False, default=None), + ) + + def columns(self) -> set[str]: + return {self.args["column"]} + + def compute(self, row: dict[str, Any]) -> Any: + text = _text(row.get(self.args["column"])) + if not text: + return None + separator = self.args["separator"] or None + parts = text.split(separator) if separator else text.split() + start, stop = (_index(self.args[name]) for name in ("start", "stop")) + return (separator or " ").join(part.strip() for part in parts[start:stop] if part.strip()) + + +@register_derivation +class Coalesce(Derivation): + op = "coalesce" + label = "Primera con valor" + description = "El valor de la primera columna, en orden, que no esté vacía." + params = (Param("columns", "columns", "Columnas"),) + + def columns(self) -> set[str]: + return set(self.args["columns"]) + + def compute(self, row: dict[str, Any]) -> Any: + for column in self.args["columns"]: + value = row.get(column) + if not _blank(value): + return value + return None + + +@register_derivation +class Extract(Derivation): + op = "extract" + label = "Extraer con patrón" + description = "La parte del valor que coincide con una expresión regular (o su grupo `group`)." + params = ( + Param("column", "column", "Columna"), + Param("pattern", "text", "Expresión regular"), + Param("group", "integer", "Grupo", required=False, default=0), + ) + + def __init__(self, rule: dict[str, Any]): + super().__init__(rule) + try: + self._regex = re.compile(self.args["pattern"], re.I) + except re.error as exc: + raise ConnectorError(f"expresión regular inválida: {exc}") from exc + + def columns(self) -> set[str]: + return {self.args["column"]} + + def compute(self, row: dict[str, Any]) -> Any: + match = self._regex.search(_text(row.get(self.args["column"]))) + if not match: + return None + try: + return match.group(_index(self.args["group"]) or 0) + except IndexError as exc: + raise ConnectorError(f"la expresión no tiene el grupo {self.args['group']}") from exc + + +@register_derivation +class Translate(Derivation): + op = "map" + label = "Traducir valores" + description = "Cambia cada valor por otro según una tabla (`M` → `Masculino`), sin distinguir mayúsculas ni espacios." + params = ( + Param("column", "column", "Columna"), + Param("values", "mapping", "Tabla de valores"), + Param("keep_unmatched", "boolean", "Conservar los que no estén en la tabla", required=False, default=True), + ) + + def __init__(self, rule: dict[str, Any]): + super().__init__(rule) + if not isinstance(self.args["values"], dict): + raise ConnectorError("'values' debe ser un objeto") + self._table = {_text(key).casefold(): value for key, value in self.args["values"].items()} + + def columns(self) -> set[str]: + return {self.args["column"]} + + def compute(self, row: dict[str, Any]) -> Any: + value = row.get(self.args["column"]) + key = _text(value).casefold() + if key in self._table: + return self._table[key] + return value if self.args["keep_unmatched"] is not False else None + + +def rule_from(value: Any, *, separator: str = " | ") -> Derivation: + """A rule given in short form: a column name, a list of columns (joined + with `separator`) or a full rule object.""" + if isinstance(value, str): + return Column({"column": value}) + if isinstance(value, list): + return Concat({"columns": value, "separator": separator}) + return build_derivation(value) + + +def parse_derived(raw: Any, fields: set[str]) -> dict[str, Derivation]: + """`{target_field: rule}` validated against the target's fields.""" + if raw in (None, {}): + return {} + if not isinstance(raw, dict): + raise ConnectorError("'derived' debe ser un objeto {campo: regla}") + unknown = sorted(set(raw) - fields) + if unknown: + raise ConnectorError(f"campos desconocidos en 'derived': {unknown}") + return {field: rule_from(rule, separator=" ") for field, rule in raw.items()} diff --git a/webapi/imports/schemas/catalog_matching.py b/webapi/imports/schemas/catalog_matching.py index 243fe2c..76f8047 100644 --- a/webapi/imports/schemas/catalog_matching.py +++ b/webapi/imports/schemas/catalog_matching.py @@ -48,9 +48,16 @@ class _NewResultado: def match_or_mint( - discovered: list[DiscoveredField], *, proyecto: str, catalogo: Catalogo, estudio_id: str | None = None + discovered: list[DiscoveredField], + *, + proyecto: str, + catalogo: Catalogo, + estudio_id: str | None = None, + mint: bool = True, ) -> list[MatchedField]: - """One `MatchedField` per discovered caption, in order. + """One `MatchedField` per discovered caption, in order. With + `mint=False`, a caption nothing in the catalog matches is left out + instead of being added to the catalog file. `estudio_id`, when the caller already knows it (the row's own study-type column, resolved through `codigos_hospital`), scopes which @@ -67,6 +74,8 @@ def match_or_mint( found = _best_match(field.caption, labels) if found is not None: resultado, is_new = by_resultado_id[found], False + elif not mint: + continue else: resultado = _mint(field, proyecto=proyecto, estudio_id=estudio_id, catalogo=catalogo) is_new = True diff --git a/webapi/imports/services/catalog_commit_service.py b/webapi/imports/services/catalog_commit_service.py index acff5ac..0fca715 100644 --- a/webapi/imports/services/catalog_commit_service.py +++ b/webapi/imports/services/catalog_commit_service.py @@ -2,7 +2,11 @@ (captions no known `FieldSpec` claimed, see `extraction.nlp.discovery`) into the silver layer directly: one synthetic `procedimiento` per record per estudio its resolved fields touch, with their `observacion`s matched -or minted against the project's catalog (`catalog_matching`). +against the project's catalog (`catalog_matching`). Only a source that +asks for it (`catalog_fallback`) gets here, and only captions the catalog +already knows are written: the catalog is versioned with the code, so a +running import never adds to it. Captions nothing matches are counted; +the import report lists them (`webapi.imports.audit`). There is no staging row for these — the whole point is a field outside today's structured schemas — so this bypasses `DESDE_STAGING` and writes @@ -39,14 +43,16 @@ class CatalogCommitResult: records_without_patient: int = 0 fields_matched: int = 0 fields_minted: int = 0 + fields_unmatched: int = 0 def commit_discovered_fields( - records: list[ExtractedRecord], *, proyecto: str, estudio_id: str | None = None + records: list[ExtractedRecord], *, proyecto: str, estudio_id: str | None = None, mint: bool = False ) -> CatalogCommitResult: """A patient without a row in `persona` is counted and skipped: this path only fills in fields for a patient already known, it doesn't - create one.""" + create one. `mint` lets unmatched captions become new catalog entries, + written to the catalog file; the import path never sets it.""" dominio = import_module(f"persistance.{proyecto}") tablas = tablas_de(proyecto) ruta = ruta_de_catalogo(proyecto) @@ -63,7 +69,10 @@ def commit_discovered_fields( continue pac_id = patients[0].pac_id - matched = match_or_mint(record.discovered, proyecto=proyecto, catalogo=catalogo, estudio_id=estudio_id) + matched = match_or_mint(record.discovered, proyecto=proyecto, catalogo=catalogo, estudio_id=estudio_id, mint=mint) + result.fields_unmatched += len(record.discovered) - len(matched) + if not matched: + continue if any(field.is_new for field in matched): catalogo = catalogo_desde_toml(ruta, tablas=tablas) # so a later record in this batch can match it too matched = _fold_duplicates(matched) diff --git a/webapi/imports/services/import_service.py b/webapi/imports/services/import_service.py index ea7c417..8d9eb29 100644 --- a/webapi/imports/services/import_service.py +++ b/webapi/imports/services/import_service.py @@ -8,6 +8,8 @@ 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 collections import Counter +from itertools import islice from typing import Any, Iterator from sqlalchemy.exc import SQLAlchemyError @@ -15,6 +17,16 @@ from sqlalchemy.exc import SQLAlchemyError from persistance.repository import ConflictPolicy from webapi.imports.audit import ImportAudit from webapi.imports.connectors import Connector, ConnectorError, build_connector +from webapi.imports.connectors.document import ( + CONFIDENCE_COLUMN, + DOCUMENT_COLUMN, + IMAGE_COLUMN, + SOURCES_COLUMN, + DocumentConnector, + connector_for_batch, +) +from webapi.imports.connectors.document_columns import DocumentColumns +from webapi.imports.mapping.derived import Derivation, parse_derived 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 @@ -40,6 +52,8 @@ class ImportSource: defaults: dict[str, Any] payload: dict[str, Any] label: str | None = None + derived: dict[str, Derivation] = field(default_factory=dict) + documents: dict[str, Any] | None = None @classmethod def parse(cls, raw: Any) -> "ImportSource": @@ -60,11 +74,24 @@ class ImportSource: unknown = sorted((set(mapping.values()) | set(defaults)) - fields) if unknown: raise ImportRequestError(f"{target} no tiene los campos {unknown}") - targets = list(mapping.values()) + try: + derived = parse_derived(raw.get("derived"), fields) + except ConnectorError as exc: + raise ImportRequestError(str(exc)) from exc + targets = list(mapping.values()) + list(derived) duplicated = sorted({t for t in targets if targets.count(t) > 1}) if duplicated: raise ImportRequestError(f"más de una columna de origen asignada a {duplicated}") - if not mapping and not defaults: + documents = raw.get("documents") or None + if documents is not None: + try: + DocumentColumns.parse(documents) + except ConnectorError as exc: + raise ImportRequestError(str(exc)) from exc + file_field = documents.get("file_field") + if file_field and file_field not in fields: + raise ImportRequestError(f"{target} no tiene el campo {file_field!r}") + if not mapping and not defaults and not derived and not documents: raise ImportRequestError(f"la fuente de {target} no asigna ninguna columna") payload = raw.get("payload") @@ -78,6 +105,8 @@ class ImportSource: defaults=defaults, payload=payload, label=raw.get("label"), + derived=derived, + documents=documents, ) @property @@ -94,12 +123,106 @@ class ImportSource: except ConnectorError as exc: raise ImportRequestError(str(exc)) from exc + @property + def source_columns(self) -> set[str]: + """Every source column the mapping, the derived fields and the + document columns read.""" + columns = set(self.column_mapping) + for rule in self.derived.values(): + columns |= rule.columns() + if self.documents: + columns |= DocumentColumns.parse(self.documents).source_columns() + return columns + + def _mapped(self, raw: dict[str, Any]) -> dict[str, Any]: + row = {target: raw.get(column) for column, target in self.column_mapping.items()} + for field_name, rule in self.derived.items(): + row[field_name] = rule.apply(raw) + return row + + def document_connector( + self, raw_rows: list[dict[str, Any]] | None = None + ) -> tuple[DocumentConnector | None, list[dict[str, Any]], dict[str, dict[str, Any]]]: + """For a source with `documents`: the extraction over its document + cells, the rows that had none (as read) and, per document, the row + it came from. Values the mapping and `derived` take from the row's + own columns go to the extraction as values to trust.""" + if raw_rows is None: + raw_rows = list(self.connector().read_rows({column: column for column in self.source_columns})) + spec = DocumentColumns.parse(self.documents) + batch = spec.assemble(raw_rows, [self._mapped(raw) for raw in raw_rows]) + raw_by_document = {name: raw_rows[number - 1] for name, number in batch.row_numbers.items()} + with_documents = set(batch.row_numbers.values()) + plain = [raw for number, raw in enumerate(raw_rows, start=1) if number not in with_documents] + if not batch.files: + return None, plain, raw_by_document + return connector_for_batch(batch, self.target, self.documents), plain, raw_by_document + + def record_namespaces(self, raw_rows: list[dict[str, Any]] | None = None) -> Iterator[tuple[dict[str, Any], dict[str, Any]]]: + """Per record of a source with `documents`: everything known about + it by column name (its rows' own columns first, then every field + and caption its documents gave) and what extraction produced.""" + connector, plain, raw_by_document = self.document_connector(raw_rows) + if connector is not None: + for extracted, documents in connector.record_rows(): + namespace: dict[str, Any] = {} + for name in documents: + for key, value in raw_by_document.get(name, {}).items(): + if _is_blank(namespace.get(key)): + namespace[key] = value + for key, value in extracted.items(): + if _is_blank(namespace.get(key)): + namespace[key] = value + yield namespace, extracted + for raw in plain: + yield raw, {} + + def unused_captions(self) -> Counter: + """For a source that reads documents: per caption its documents + print that neither a field claims nor the mapping or a derived + field uses, how many records print it. Captions only, never their + values, for the import report.""" + if self.source_type == "document": + connector = self.connector() + elif self.documents: + connector, _, _ = self.document_connector() + else: + return Counter() + if not isinstance(connector, DocumentConnector): + return Counter() + used = {column.casefold() for column in self.source_columns} + counts: Counter = Counter() + for record in connector.records: + captions = {" ".join(found.caption.split()) for found in record.discovered} + counts.update(caption for caption in captions if caption.casefold() not in used) + return counts + + def _document_rows(self, raw_rows: list[dict[str, Any]]) -> Iterator[dict[str, Any]]: + """Rows of a source with document columns: the mapping and `derived` + applied to each record's namespace, so they reach what the + documents print as well as the row's own columns; then every field + extraction filled that they left empty, and the record's pages in + `file_field`.""" + fields = set(self.spec.schema.model_fields) + file_field = self.documents.get("file_field") + for namespace, extracted in self.record_namespaces(raw_rows): + row = self._mapped(namespace) + for key, value in extracted.items(): + if key in fields and _is_blank(row.get(key)) and not _is_blank(value): + row[key] = value + if file_field and extracted: + row[file_field] = extracted.get(DOCUMENT_COLUMN) + yield row + 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).""" + """Mapped rows: each mapped column under its field, each `derived` + field computed from the source columns it names, and `defaults` + filling any field still empty or not mapped 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): + raw_rows = self.connector().read_rows({column: column for column in self.source_columns}) + mapped = self._document_rows(list(raw_rows)) if self.documents else (self._mapped(raw) for raw in raw_rows) + for row in mapped: for field_name, value in self.defaults.items(): if _is_blank(row.get(field_name)): row[field_name] = value @@ -111,6 +234,9 @@ class ImportSource: return validate_rows(self.spec.schema, self.rows()) +DOCUMENT_BOOKKEEPING = {DOCUMENT_COLUMN, IMAGE_COLUMN, CONFIDENCE_COLUMN, SOURCES_COLUMN} + + def _is_blank(value: Any) -> bool: return value is None or (isinstance(value, str) and not value.strip()) @@ -135,6 +261,33 @@ def _jsonable(value: Any) -> Any: return str(value) +def document_columns_preview(raw_source: dict[str, Any], limit: int = 20) -> dict[str, Any]: + """The columns a source with `documents` offers to its mapping (its own + columns and every field and caption its documents print), with sample + values per record, shaped like a source preview.""" + source = ImportSource.parse({**raw_source, "column_mapping": raw_source.get("column_mapping") or {}}) + connector = source.connector() + own = [column.name for column in connector.preview(limit=1).columns] + raw_rows = list(connector.read_rows({column: column for column in set(own) | source.source_columns})) + names: list[str] = list(own) + rows = [] + for namespace, _ in source.record_namespaces(raw_rows): + for key in namespace: + if key not in names and key not in DOCUMENT_BOOKKEEPING: + names.append(key) + if len(rows) < limit: + rows.append({key: _jsonable(value) for key, value in namespace.items() if key not in DOCUMENT_BOOKKEEPING}) + columns = [{"name": name, "inferred_type": "string"} for name in names] + return {"columns": columns, "sample_rows": rows, "total_rows": None} + + +def mapped_sample(raw_source: dict[str, Any], limit: int = 20) -> list[dict[str, Any]]: + """The first rows of a source as they would be written: mapping, + derived fields and defaults applied, before validation.""" + source = ImportSource.parse(raw_source) + return [{name: _jsonable(value) for name, value in row.items()} for row in islice(source.rows(), max(1, limit))] + + def validate_source(raw_source: dict[str, Any], audit: ImportAudit | None = None) -> BatchValidationResult: source = ImportSource.parse(raw_source) if audit is None: @@ -142,6 +295,7 @@ def validate_source(raw_source: dict[str, Any], audit: ImportAudit | None = None tracked = audit.source(source) rows = list(source.rows()) tracked.observe_rows(rows) + tracked.observe_captions(source.unused_captions) validation = validate_rows(source.spec.schema, rows) tracked.observe_validation(validation) return validation @@ -251,6 +405,7 @@ def commit_sources( source_audit.observe_rows(rows[position]) source_audit.observe_validation(validated[position][1]) source_audit.observe_warnings(merge_warnings.get(position, [])) + source_audit.observe_captions(sources[position].unused_captions) session = sources[0].spec.repository.open_session() links = LinkResolver(session) diff --git a/webapi/imports/services/introspection_service.py b/webapi/imports/services/introspection_service.py index 14211b4..dd382fa 100644 --- a/webapi/imports/services/introspection_service.py +++ b/webapi/imports/services/introspection_service.py @@ -7,6 +7,7 @@ import pandas as pd from webapi.imports.connectors import Connector, ConnectorError from webapi.imports.connectors.document import DocumentConnector +from webapi.imports.connectors.document_columns import is_document from webapi.imports.connectors.pdf import PdfConnector, RegionSpec from webapi.imports.connectors.tabular import columns_from_dataframe, rows_from_dataframe from webapi.imports.mapping import column_matcher @@ -35,9 +36,16 @@ def preview_with_suggestions(connector: Connector, target_key: str | None, *, li "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(), + "document_columns": document_columns(preview.columns, preview.sample_rows), } +def document_columns(columns, rows: list[dict[str, Any]]) -> list[str]: + """The columns whose sampled cells hold files a document reader opens, + so a client can offer to read them as documents.""" + return [column.name for column in columns if any(is_document(row.get(column.name)) for row in rows)] + + 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.""" @@ -72,10 +80,26 @@ def extract_pdf_regions(raw: bytes, regions: list[dict[str, Any]], *, dpi: int = def document_report(payload: dict[str, Any]) -> dict[str, Any]: - connector = DocumentConnector.from_payload(payload) + """The extraction report of uploaded documents, of a document source's + SQL table, or (with `source`) of the document columns of any import + source, read through that source's own mapping.""" + if payload.get("source"): + from webapi.imports.services.import_service import ImportSource + + connector, _, _ = ImportSource.parse(payload["source"]).document_connector() + if connector is None: + raise ConnectorError("ninguna fila de la fuente tiene documentos") + else: + 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()} + return { + **preview, + "key_field": connector.key_field, + "fields": fields, + "records": connector.report(), + "skipped": connector.skipped, + }