Compare commits

..

3 Commits

7 changed files with 729 additions and 9 deletions
+120
View File
@@ -0,0 +1,120 @@
"""`commit_discovered_fields`: writes captions no known field claims
straight into `procedimiento`/`observacion`, tagged apart from every
staging-derived row with `FUENTE_CATALOGO_ABIERTO`. Fails if a known
patient's discovered fields stop landing there, or if an unmatched one
stops growing the catalog instead of being silently dropped.
"""
from datetime import date
import pytest
from sqlmodel import select
from indicadores_kit.registry import catalogos
from indicadores_kit.tablas import tablas_de
from extraction import ExtractedRecord
from extraction.nlp import DiscoveredField, Evidence
from webapi.imports.services.catalog_commit_service import FUENTE_CATALOGO_ABIERTO, commit_discovered_fields
EVIDENCE = Evidence("fila.pdf", 1, "")
def _record(key: str, pairs: list[tuple[str, str]]) -> ExtractedRecord:
return ExtractedRecord(
values={}, sources=[], key=key, discovered=[DiscoveredField(c, v, EVIDENCE) for c, v in pairs]
)
@pytest.fixture
def cacu_catalog(tmp_path, monkeypatch):
"""`add_resultado`/`sincronizar` write real rows and a real file:
kept off the checked-in `cacu.toml` and off any other domain's data."""
monkeypatch.setattr(catalogos, "RAIZ_CATALOGOS", tmp_path)
(tmp_path / "cacu.toml").write_text(
'[citologia]\netiqueta = "Citología cervical"\n\n'
'[citologia.resultados.calidad_muestra]\netiqueta = "Calidad de la muestra"\ntipo_valor = "texto"\n',
encoding="utf-8",
)
return tmp_path / "cacu.toml"
@pytest.fixture
def known_patient(wire_domain):
wire_domain("cacu")
from core.cacu.paciente.model import Paciente
from persistance.cacu import paciente_repository
paciente_repository.create(Paciente(pac_id_hospital="DOC-FB-1", pac_fecha_nacimiento=date(1990, 1, 1)))
return "DOC-FB-1"
def test_a_matched_field_is_written_on_the_existing_resultado(cacu_catalog, known_patient):
result = commit_discovered_fields(
[_record(known_patient, [("Calidad de muestra", "Insatisfactoria")])], proyecto="cacu", estudio_id="citologia"
)
assert (result.records_written, result.fields_matched, result.fields_minted) == (1, 1, 0)
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 == "citologia.calidad_muestra"
assert observacion.valor_texto == "Insatisfactoria"
[procedimiento] = sesion.exec(select(carga_repository.procedimiento)).all()
assert procedimiento.fuente_tabla == FUENTE_CATALOGO_ABIERTO
assert procedimiento.fuente_id == known_patient
def test_an_unmatched_field_mints_a_resultado_and_is_written_too(cacu_catalog, known_patient):
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}
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"
def test_a_patient_outside_persona_is_skipped_not_dropped_silently(cacu_catalog, known_patient):
result = commit_discovered_fields(
[_record("NOT-A-PATIENT", [("Calidad de muestra", "x")])], proyecto="cacu", estudio_id="citologia"
)
assert (result.records_written, result.records_without_patient) == (0, 1)
def test_a_record_without_discovered_fields_is_ignored(cacu_catalog, known_patient):
result = commit_discovered_fields([_record(known_patient, [])], proyecto="cacu", estudio_id="citologia")
assert result.records_written == 0
def test_a_repeated_caption_is_folded_not_written_twice(cacu_catalog, known_patient):
"""A static label printed on several pages of the same document (a date,
a signature line) discovers as one `DiscoveredField` per occurrence,
on purpose (`discover_captions`'s docstring). Fails if this stops
folding repeats before writing: `observacion` has one row per
`(procedimiento, resultado_id)`, so a second occurrence of the same
resultado_id raises `IntegrityError` and the whole record's fields —
including the ones that weren't duplicated — are lost."""
result = commit_discovered_fields(
[_record(known_patient, [("Calidad de muestra", "Insatisfactoria"), ("Calidad de muestra", "Satisfactoria")])],
proyecto="cacu",
estudio_id="citologia",
)
assert (result.records_written, result.fields_matched, result.fields_minted) == (1, 1, 0)
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 == "citologia.calidad_muestra"
assert observacion.valor_texto == "Insatisfactoria"
+90
View File
@@ -0,0 +1,90 @@
"""`catalog_matching.match_or_mint`: fails if it stops reusing an existing
catalog field for an OCR caption that's clearly the same thing worded
differently, or if an unmatched caption stops being added to the catalog
and silently drops its value instead.
"""
from datetime import date
import pytest
from indicadores_kit.registry import catalogos
from indicadores_kit.registry.catalogos import Catalogo
from indicadores_kit.tablas import tablas_de
from extraction.nlp import DiscoveredField, Evidence
from webapi.imports.schemas.catalog_matching import match_or_mint
EVIDENCE = Evidence("fila.pdf", 1, "")
def _field(caption: str, value: str) -> DiscoveredField:
return DiscoveredField(caption, value, EVIDENCE)
@pytest.fixture
def catalogo() -> Catalogo:
tablas = tablas_de("cacu")
return Catalogo(
estudios=[tablas.CatEstudio(estudio_id="citologia", etiqueta="Citología cervical")],
resultados=[
tablas.CatResultado(
resultado_id="citologia.calidad_muestra", estudio_id="citologia",
etiqueta="Calidad de la muestra", tipo_valor="codigo",
),
tablas.CatResultado(
resultado_id="citologia.celulas_glandulares", estudio_id="citologia",
etiqueta="Células glandulares", tipo_valor="texto",
),
],
valores=[
tablas.CatValor(
resultado_id="citologia.calidad_muestra", valor_id="SATISFACTORIO",
etiqueta="Satisfactoria", orden=1, estado="vigente",
),
],
)
@pytest.fixture
def catalogo_toml(tmp_path, monkeypatch):
"""`add_resultado` writes to disk; keep it off the real `cacu.toml`."""
monkeypatch.setattr(catalogos, "RAIZ_CATALOGOS", tmp_path)
(tmp_path / "cacu.toml").write_text("", encoding="utf-8")
return tmp_path / "cacu.toml"
def test_a_worded_differently_caption_reuses_the_existing_resultado(catalogo, catalogo_toml):
[matched] = match_or_mint(
[_field("Calidad de muestra", "SATISFACTORIO")], proyecto="cacu", catalogo=catalogo, estudio_id="citologia"
)
assert matched.resultado_id == "citologia.calidad_muestra" and not matched.is_new
assert matched.observacion["valor_id"] == "SATISFACTORIO"
assert catalogo_toml.read_text(encoding="utf-8") == "" # nothing minted
def test_an_unmatched_caption_in_a_known_estudio_is_minted_there(catalogo, catalogo_toml):
[matched] = match_or_mint(
[_field("Tipo de fijador", "Formol")], proyecto="cacu", catalogo=catalogo, estudio_id="citologia"
)
assert matched.is_new and matched.resultado_id.startswith("citologia.")
assert matched.observacion["valor_texto"] == "Formol"
sincronizado = catalogos.catalogo_desde_toml(catalogo_toml, tablas=tablas_de("cacu"))
assert matched.resultado_id in {r.resultado_id for r in sincronizado.resultados}
def test_an_unmatched_caption_with_no_estudio_falls_back_to_documento_externo(catalogo, catalogo_toml):
[matched] = match_or_mint([_field("Observación suelta", "algo")], proyecto="cacu", catalogo=catalogo)
assert matched.resultado_id == "documento_externo." + matched.resultado_id.split(".", 1)[1]
sincronizado = catalogos.catalogo_desde_toml(catalogo_toml, tablas=tablas_de("cacu"))
assert "documento_externo" in {e.estudio_id for e in sincronizado.estudios}
def test_the_inferred_tipo_valor_follows_the_value_shape(catalogo, catalogo_toml):
fecha, numero, texto = match_or_mint(
[_field("Fecha de algo", "15/01/2024"), _field("Cuenta de algo", "12.5"), _field("Nota libre", "ninguna")],
proyecto="cacu", catalogo=catalogo, estudio_id="citologia",
)
assert fecha.observacion["valor_fecha"] == date(2024, 1, 15)
assert numero.observacion["valor_numerico"] == 12.5
assert texto.observacion["valor_texto"] == "ninguna"
+165
View File
@@ -0,0 +1,165 @@
"""`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
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.
"""
import base64
import pytest
from sqlalchemy import create_engine, text
from extraction.testing import text_pdf
@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
REPORT = text_pdf(
[["Expediente: SQL-0001", "Fecha de nacimiento: 12/03/1981", "VPH alto riesgo: POSITIVO"]]
)
@pytest.fixture
def sqlite_studies_table(tmp_path):
"""A source table shaped like ISSSTELEON's: 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"
url = f"sqlite:///{db_path}"
engine = create_engine(url)
with engine.begin() as conn:
conn.execute(text("CREATE TABLE estudios (estudio_id TEXT, reporte BLOB)"))
conn.execute(
text("INSERT INTO estudios (estudio_id, reporte) VALUES (:id, :reporte)"),
{"id": "ROW-1", "reporte": REPORT},
)
conn.execute(
text("INSERT INTO estudios (estudio_id, reporte) VALUES (:id, :reporte)"),
{
"id": "ROW-2",
"reporte": "Expediente: SQL-0002\nFecha de nacimiento: 01/01/1990\nVPH alto riesgo: NEGATIVO",
},
)
return url
def _sql_payload(url: str, **overrides) -> dict:
return {"connection_string": url, "table": "estudios", "column": "reporte", "key_column": "estudio_id", **overrides}
def test_a_pdf_column_is_read_like_an_uploaded_pdf(client, sqlite_studies_table):
body = client.post(
"/imports/sources/document/extract",
json={"sql": _sql_payload(sqlite_studies_table), "target": "cacu.CitologiaCervical"},
).get_json()
[first, second] = body["records"]
assert first["key"] == "SQL-0001"
assert first["fields"]["cit_vph_resultado"]["value"] == "POSITIVO"
assert first["sources"] == [{"document": "ROW-1", "page_numbers": [1]}]
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
be a PDF (`extraction.readers.TextReader`)."""
body = client.post(
"/imports/sources/document/extract",
json={"sql": _sql_payload(sqlite_studies_table), "target": "cacu.CitologiaCervical"},
).get_json()
[_, second] = body["records"]
assert second["key"] == "SQL-0002"
assert second["fields"]["cit_vph_resultado"]["value"] == "NEGATIVO"
assert second["sources"] == [{"document": "ROW-2", "page_numbers": [1]}]
def test_sql_sourced_documents_commit_like_uploaded_ones(client, sqlite_studies_table):
source = {
"source_type": "document",
"target": "cacu.CitologiaCervical",
"column_mapping": {"pac_id_hospital": "pac_id_hospital", "cit_vph_resultado": "cit_vph_resultado"},
"payload": {"sql": _sql_payload(sqlite_studies_table)},
"label": "estudios",
}
result = client.post("/imports/commit", json={"sources": [source]}).get_json()["results"][0]
assert result["created"] == 2, result
from persistance.cacu import citologia_cervical_repository
rows = {r.pac_id_hospital: r for r in citologia_cervical_repository.list(limit=100) if r.pac_id_hospital.startswith("SQL-")}
assert rows["SQL-0001"].cit_vph_resultado == "POSITIVO"
assert rows["SQL-0002"].cit_vph_resultado == "NEGATIVO"
def test_column_and_key_column_must_differ(client, sqlite_studies_table):
response = client.post(
"/imports/sources/document/extract",
json={"sql": _sql_payload(sqlite_studies_table, key_column="reporte"), "target": "cacu.CitologiaCervical"},
)
assert response.status_code == 400 and "key_column" in response.get_json()["error"]
def test_a_missing_column_is_a_bad_request(client, sqlite_studies_table):
payload = _sql_payload(sqlite_studies_table)
del payload["column"]
response = client.post(
"/imports/sources/document/extract", json={"sql": payload, "target": "cacu.CitologiaCervical"}
)
assert response.status_code == 400 and "column" in response.get_json()["error"]
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.
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
from sqlalchemy import create_engine, text as sa_text
from sqlmodel import select
from indicadores_kit.registry import catalogos
from core.cacu.paciente.model import Paciente
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")
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'}"
report = text_pdf([["Expediente: SQL-EXTRA-1", "VPH alto riesgo: POSITIVO", "Tipo de fijador: Formol"]])
with create_engine(db_url).begin() as conn:
conn.execute(sa_text("CREATE TABLE estudios (estudio_id TEXT, reporte BLOB)"))
conn.execute(sa_text("INSERT INTO estudios (estudio_id, reporte) VALUES ('ROW-1', :r)"), {"r": report})
source = {
"source_type": "document",
"target": "cacu.CitologiaCervical",
"column_mapping": {"pac_id_hospital": "pac_id_hospital", "cit_vph_resultado": "cit_vph_resultado"},
"payload": {"sql": _sql_payload(db_url), "estudio_id": "citologia"},
"label": "estudios_extra",
}
body = client.post("/imports/commit", json={"sources": [source]}).get_json()
assert body["results"][0]["created"] == 1, body
[report] = [r for r in body["catalog_fallback"] if r["label"] == "estudios_extra"]
assert report["records_written"] == 1 and report["fields_minted"] == 1
with carga_repository.open_session() as sesion:
[minted] = 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"
+42 -1
View File
@@ -4,9 +4,11 @@ import json
import logging
from flask import Blueprint, Response, jsonify, request
from sqlalchemy.exc import SQLAlchemyError
from extraction import BBox, ExtractionError
from extraction.readers import reader_for
from indicadores_kit.registry.catalogos import CatalogoInvalido
from webapi.imports import audit as import_audit
from webapi.imports.connectors import ConnectorError, build_connector, catalog, connector_class, kind_for_filename
from webapi.imports.connectors.base import decode_file
@@ -14,6 +16,7 @@ from webapi.imports.connectors.pdf import PdfConnector
from webapi.imports.connectors.sql import SqlConnector
from webapi.imports.connectors.tabular import FileConnector
from webapi.imports.schemas.registry import ENTITY_REGISTRY
from webapi.imports.services.catalog_commit_service import commit_discovered_fields
from webapi.imports.services.import_service import (
DatabaseRefused,
ImportRequestError,
@@ -251,11 +254,13 @@ 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).
Each record comes back with per-field confidence and evidence, conflicts
between sources, and the images found on its pages."""
body = _json_body()
_require(body, "target")
if not body.get("files"):
if not body.get("files") and not body.get("sql"):
raise BadRequest("faltan los archivos")
return jsonify(document_report(body))
@@ -302,6 +307,41 @@ 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."""
reports = []
for raw in raw_sources:
if not isinstance(raw, dict) or raw.get("source_type") != "document":
continue
target = raw.get("target") or ""
domain = target.split(".", 1)[0]
if not domain:
continue
payload = {**(raw.get("payload") or {}), "target": target}
try:
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:
log.warning("catalog_fallback: %s no se pudo procesar: %s", raw.get("label") or target, exc)
continue
reports.append(
{
"label": raw.get("label"),
"domain": result.proyecto,
"records_written": result.records_written,
"records_without_patient": result.records_without_patient,
"fields_matched": result.fields_matched,
"fields_minted": result.fields_minted,
}
)
return reports
@imports_bp.post("/commit")
def commit():
"""`{sources: [...], on_conflict: "reject"|"upsert", merge_duplicates: bool}`.
@@ -333,6 +373,7 @@ def commit():
"ok": all(r.rejected == 0 for r in results),
"audit_id": audit.id,
"indicadores_en_recalculo": recalculating,
"catalog_fallback": _commit_catalog_fallback(body.get("sources") or []),
"results": [
{
"target": r.target,
+47 -8
View File
@@ -12,6 +12,7 @@ from extraction.segmentation import SEGMENTERS
from webapi.imports.connectors.base import decode_file
from webapi.imports.connectors.errors import ConnectorError
from webapi.imports.connectors.registry import register_connector
from webapi.imports.connectors.sql import SqlConnector
from webapi.imports.connectors.tabular import DataFrameConnector
from webapi.imports.schemas.field_specs import field_specs_for, key_field_for
from webapi.imports.schemas.registry import ENTITY_REGISTRY
@@ -48,16 +49,49 @@ class _ResultCache:
_CACHE = _ResultCache()
def _files_from_sql(sql: dict[str, Any]) -> list[tuple[str, bytes]]:
"""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), and
`key_column` names the row (a patient or study id) for tracing. Any
column type `SqlConnector` can read works; it's not limited to PDFs."""
column = sql.get("column")
if not column:
raise ConnectorError("falta column")
if not sql.get("query") and not sql.get("table"):
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")
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 = []
for row in connector.read_rows({column: "contenido", key_column: "clave"}):
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")))
return files
@register_connector
class DocumentConnector(DataFrameConnector):
"""Clinical documents that are not tables: one report per patient,
several pages per patient, many patients per file, scans, free text.
several pages per patient, many patients per file, scans, free text —
uploaded directly, or read one row at a time from a SQL source whose
`payload` carries `sql` (a connection plus `table`/`query`, `column`
and `key_column`) instead of `files`; either way, every row's content
reaches the same extraction, PDF, image or plain text alike.
Every file is read page by page (text layer or OCR), split into
per-patient records, and the target entity's fields are extracted from
labels and narrative text. Records of the same patient found in other
pages or files are merged. Each row also carries the record's pages as
a PDF (`documento`), mappable to the entity's file column.
Every file is read page by page (text layer or OCR; plain text as its
own lines), split into per-patient records, and the target entity's
fields are extracted from labels and narrative text. Records of the
same patient found in other pages or files — or rows — are merged.
Each row also carries the record's pages as a PDF (`documento`),
mappable to the entity's file column, when the source produced one.
Corrections made while reviewing travel in `overrides`
(`{"<row>": {"field": value}}`) and win over the extracted value.
@@ -65,7 +99,7 @@ class DocumentConnector(DataFrameConnector):
kind = "document"
label = "Documentos clínicos"
description = "Reportes, formatos y notas en PDF o imagen; los campos se extraen del texto libre"
description = "Reportes, formatos y notas en PDF, imagen o texto; los campos se extraen del contenido"
category = "document"
icon = "document_scanner"
extensions: ClassVar[tuple[str, ...]] = tuple(supported_extensions())
@@ -103,7 +137,12 @@ class DocumentConnector(DataFrameConnector):
@classmethod
def from_payload(cls, payload: dict[str, Any]) -> "DocumentConnector":
files = [(f.get("name") or f"documento_{i}", decode_file(f)) for i, f in enumerate(payload.get("files") or [], 1)]
if payload.get("sql"):
files = _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)
]
return cls(
files,
target=payload["target"],
+151
View File
@@ -0,0 +1,151 @@
"""Matching OCR-discovered captions against a project's catalog, and
minting new catalog entries when nothing matches well enough.
`discover_captions` (Extraction) finds `caption: value` lines no known
`FieldSpec` already explains. For each one, this module decides whether an
existing `resultado_id` means the same thing closely enough to reuse
(`rapidfuzz`, tolerant of how a hospital's own report wording differs from
the catalog's own), or whether it's a field the catalog doesn't have yet —
in which case it's added (`add_resultado`), never silently dropped.
"""
import re
import unicodedata
from dataclasses import dataclass
from rapidfuzz import fuzz, process
from extraction.nlp import DiscoveredField
from extraction.nlp.text import find_date, fold
from indicadores_kit.plata.procedimiento import valor_de_observacion
from indicadores_kit.registry.catalogos import Catalogo, add_resultado
# `token_sort_ratio`, not `WRatio`: `WRatio`'s partial-alignment bonus scores
# two short, unrelated captions that merely share common words ("de", "del")
# too high for this use (two genuinely different captions can clear 80).
# Lower than `extraction.nlp.extractors.FUZZY_LABEL_THRESHOLD` (0-100 scale
# here, that one 0-1): a caption is free text, not a single known label
# tolerating only OCR noise, so it varies more from the catalog's wording.
CAPTION_MATCH_THRESHOLD = 80.0
CAPTION_SCORER = fuzz.token_sort_ratio
FALLBACK_ESTUDIO_ID = "documento_externo"
FALLBACK_ESTUDIO_ETIQUETA = "Documento externo"
@dataclass(frozen=True)
class MatchedField:
"""One discovered caption, resolved to a `resultado_id` (existing or
just minted) with its value already shaped for `observacion`."""
resultado_id: str
is_new: bool
observacion: dict
@dataclass(frozen=True)
class _NewResultado:
resultado_id: str
tipo_valor: str
def match_or_mint(
discovered: list[DiscoveredField], *, proyecto: str, catalogo: Catalogo, estudio_id: str | None = None
) -> list[MatchedField]:
"""One `MatchedField` per discovered caption, in order.
`estudio_id`, when the caller already knows it (the row's own
study-type column, resolved through `codigos_hospital`), scopes which
resultados are tried first and which estudio a minted field joins;
without it, every resultado in the catalog is a candidate and a new
field's estudio is guessed the same way, or falls back to
`documento_externo`.
"""
labels = _resultado_labels(catalogo, estudio_id)
valid_codes = {(v.resultado_id, v.valor_id) for v in catalogo.valores if v.estado == "vigente"}
by_resultado_id = {r.resultado_id: r for r in catalogo.resultados}
resolved = []
for field in discovered:
found = _best_match(field.caption, labels)
if found is not None:
resultado, is_new = by_resultado_id[found], False
else:
resultado = _mint(field, proyecto=proyecto, estudio_id=estudio_id, catalogo=catalogo)
is_new = True
value = _coerce_value(field.value, resultado.tipo_valor)
observacion = valor_de_observacion(
value,
field.value,
tipo_valor=resultado.tipo_valor,
en_catalogo=lambda v, r=resultado.resultado_id: (r, v) in valid_codes,
)
resolved.append(MatchedField(resultado.resultado_id, is_new, observacion))
return resolved
def _resultado_labels(catalogo: Catalogo, estudio_id: str | None) -> dict[str, str]:
resultados = catalogo.resultados
if estudio_id is not None:
of_estudio = [r for r in resultados if r.estudio_id == estudio_id]
if of_estudio:
resultados = of_estudio
return {r.resultado_id: fold(r.etiqueta) for r in resultados}
def _best_match(caption: str, labels: dict[str, str]) -> str | None:
if not labels:
return None
found = process.extractOne(fold(caption), labels, scorer=CAPTION_SCORER, score_cutoff=CAPTION_MATCH_THRESHOLD)
return found[2] if found is not None else None
def _mint(field: DiscoveredField, *, proyecto: str, estudio_id: str | None, catalogo: Catalogo) -> _NewResultado:
estudio = estudio_id
estudio_etiqueta = None
if estudio is None:
estudio_labels = {e.estudio_id: fold(e.etiqueta) for e in catalogo.estudios}
found = process.extractOne(fold(field.caption), estudio_labels, scorer=CAPTION_SCORER, score_cutoff=CAPTION_MATCH_THRESHOLD)
estudio = found[2] if found is not None else None
if estudio is None:
estudio, estudio_etiqueta = FALLBACK_ESTUDIO_ID, FALLBACK_ESTUDIO_ETIQUETA
tipo_valor = _infer_tipo_valor(field.value)
resultado_id = add_resultado(
proyecto,
estudio_id=estudio,
nombre=_slug(field.caption),
etiqueta=field.caption.strip(),
tipo_valor=tipo_valor,
estudio_etiqueta=estudio_etiqueta,
)
return _NewResultado(resultado_id, tipo_valor)
def _slug(text: str) -> str:
without_accents = unicodedata.normalize("NFKD", text).encode("ascii", "ignore").decode("ascii")
return re.sub(r"[^a-z0-9]+", "_", without_accents.lower()).strip("_") or "campo"
def _infer_tipo_valor(value: str) -> str:
if find_date(value) is not None:
return "fecha"
if _is_number(value):
return "numero"
return "texto"
def _is_number(value: str) -> bool:
try:
float(value.strip().replace(",", "."))
return True
except ValueError:
return False
def _coerce_value(value: str, tipo_valor: str):
if tipo_valor == "fecha":
found = find_date(value)
return found[0] if found else None
if tipo_valor in ("numero", "booleano"):
try:
return float(value.strip().replace(",", "."))
except ValueError:
return None
return value
@@ -0,0 +1,114 @@
"""Writes the catalog-fallback fields a document source's records carry
(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`).
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
straight through the domain's existing `carga_repository`, the same one
`webapi.orquestacion`'s `cargar` step uses for staging-derived batches.
Marked clearly apart from every staging-derived procedimiento:
`fuente_tabla` is the sentinel `FUENTE_CATALOGO_ABIERTO`, never a real
staging table name. `fuente_id` is the record's own natural key (not a SQL
row's surrogate id), so reprocessing the same record later — read again
from the SQL source, re-uploaded as a file, or corrected by hand — updates
the same rows in place instead of duplicating them; the structured fields
a source also carries keep going through the unmodified staging/import
path (`commit_sources`), independently of this.
"""
from collections import defaultdict
from dataclasses import dataclass
from importlib import import_module
from extraction import ExtractedRecord
from indicadores_kit.plata.procedimiento import LotePlata
from indicadores_kit.registry.catalogos import Catalogo, catalogo_desde_toml, ruta_de_catalogo
from indicadores_kit.tablas import tablas_de
from webapi.imports.schemas.catalog_matching import MatchedField, match_or_mint
FUENTE_CATALOGO_ABIERTO = "catalogo_abierto"
@dataclass
class CatalogCommitResult:
proyecto: str
records_written: int = 0
records_without_patient: int = 0
fields_matched: int = 0
fields_minted: int = 0
def commit_discovered_fields(
records: list[ExtractedRecord], *, proyecto: str, estudio_id: str | None = None
) -> 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."""
dominio = import_module(f"persistance.{proyecto}")
tablas = tablas_de(proyecto)
ruta = ruta_de_catalogo(proyecto)
catalogo = catalogo_desde_toml(ruta, tablas=tablas)
result = CatalogCommitResult(proyecto=proyecto)
procedures, observations = [], []
for record in records:
if not record.discovered or record.key is None:
continue
patients = dominio.paciente_repository.list(pac_id_hospital=record.key, limit=1)
if not patients:
result.records_without_patient += 1
continue
pac_id = patients[0].pac_id
matched = match_or_mint(record.discovered, proyecto=proyecto, catalogo=catalogo, estudio_id=estudio_id)
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)
by_estudio: dict[str, list] = defaultdict(list)
for field in matched:
by_estudio[field.resultado_id.split(".", 1)[0]].append(field)
result.fields_minted += int(field.is_new)
result.fields_matched += int(not field.is_new)
for estudio, fields in by_estudio.items():
key = (FUENTE_CATALOGO_ABIERTO, record.key, estudio, "reporte")
procedures.append({"llave": key, "padres": [], "pac_id": pac_id, "fecha": None, "fecha_del_padre": False})
observations += [
{"procedimiento": key, "pac_id": pac_id, "resultado_id": field.resultado_id, **field.observacion}
for field in fields
]
result.records_written += 1
if procedures:
_sync_catalog(dominio, proyecto, tablas)
dominio.carga_repository.guardar_carga(
fuente=FUENTE_CATALOGO_ABIERTO, personas=(), plata=LotePlata(procedures, observations, {})
)
return result
def _fold_duplicates(matched: list[MatchedField]) -> list[MatchedField]:
"""A record's discovered captions can repeat the same resultado_id (a
static label such as "FECHA" printed on several pages): `observacion`
has one row per `(procedimiento, resultado_id)`, so only the first
occurrence survives. `discover_captions` keeps every repeat on purpose
and leaves folding to the caller (see its docstring)."""
seen: set[str] = set()
folded = []
for field in matched:
if field.resultado_id in seen:
continue
seen.add(field.resultado_id)
folded.append(field)
return folded
def _sync_catalog(dominio, proyecto: str, tablas) -> None:
"""A field minted by `match_or_mint` only exists in the TOML until this
runs: `procedimiento.estudio_id` and `observacion`'s catalog both need
the matching `cat_estudio`/`cat_resultado` row to already be there."""
catalogo: Catalogo = catalogo_desde_toml(ruta_de_catalogo(proyecto), tablas=tablas)
dominio.catalogo_repository.sincronizar(catalogo.estudios, catalogo.resultados, catalogo.valores)