The import's catalog matching and commit read the WebApi's catalog, silver batch and table maps; add_resultado moves here
How: `catalog_matching`, `catalog_commit_service` and the imports blueprint import `Catalogo`, `catalogo_desde_toml`, `ruta_de_catalogo`, `CatalogoInvalido`, `LotePlata`, `valor_de_observacion` and `tablas_de` from `webapi.orchestration`; the commit writes through `carga_repository.save_load` and `catalog_repository.sync`. `add_resultado` and its tests come over unchanged from the indicator kit. Implications: the import path no longer needs the indicator kit, which isn't a dependency.
This commit is contained in:
@@ -9,8 +9,8 @@ from datetime import date
|
||||
import pytest
|
||||
from sqlmodel import select
|
||||
|
||||
from indicadores_kit.registry import catalogos
|
||||
from indicadores_kit.tablas import tablas_de
|
||||
from webapi.orchestration.reference import catalogs as catalogos
|
||||
from webapi.orchestration.tables import tablas_de
|
||||
|
||||
from extraction import ExtractedRecord
|
||||
from extraction.nlp import DiscoveredField, Evidence
|
||||
@@ -27,7 +27,7 @@ def _record(key: str, pairs: list[tuple[str, str]]) -> ExtractedRecord:
|
||||
|
||||
@pytest.fixture
|
||||
def cacu_catalog(tmp_path, monkeypatch):
|
||||
"""`add_resultado`/`sincronizar` write real rows and a real file:
|
||||
"""`add_resultado`/`sync` 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(
|
||||
|
||||
@@ -6,9 +6,9 @@ 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 webapi.orchestration.reference import catalogs as catalogos
|
||||
from webapi.orchestration.reference.catalogs import Catalogo
|
||||
from webapi.orchestration.tables import tablas_de
|
||||
|
||||
from extraction.nlp import DiscoveredField, Evidence
|
||||
from webapi.imports.schemas.catalog_matching import match_or_mint
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
"""`add_resultado`: adds a new field to a project's catalog TOML file on
|
||||
disk, for a caller (`webapi.imports.schemas.catalog_matching`) that found a
|
||||
field no catalog entry matches closely enough. Each test pins down one
|
||||
rule of that append; fails if any of them regresses into losing data or
|
||||
duplicating an entry that's already there.
|
||||
"""
|
||||
import pytest
|
||||
|
||||
from webapi.orchestration.reference import catalogs as catalogos
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def catalogo_file(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(catalogos, "RAIZ_CATALOGOS", tmp_path)
|
||||
|
||||
def escribir(contenido: str) -> None:
|
||||
(tmp_path / "prueba.toml").write_text(contenido, encoding="utf-8")
|
||||
|
||||
return escribir
|
||||
|
||||
|
||||
def test_a_new_resultado_is_appended_under_its_existing_estudio(catalogo_file):
|
||||
catalogo_file('[citologia]\netiqueta = "Citología"\n')
|
||||
|
||||
resultado_id = catalogos.add_resultado(
|
||||
"prueba", estudio_id="citologia", nombre="nuevo_campo", etiqueta="Nuevo campo", tipo_valor="texto"
|
||||
)
|
||||
|
||||
assert resultado_id == "citologia.nuevo_campo"
|
||||
leido = catalogos._leer(catalogos.ruta_de_catalogo("prueba"))
|
||||
assert leido["citologia"]["etiqueta"] == "Citología" # what was already there survives
|
||||
assert leido["citologia"]["resultados"]["nuevo_campo"] == {"etiqueta": "Nuevo campo", "tipo_valor": "texto"}
|
||||
|
||||
|
||||
def test_a_resultado_of_an_unknown_estudio_also_creates_the_estudio(catalogo_file):
|
||||
catalogo_file("")
|
||||
|
||||
catalogos.add_resultado(
|
||||
"prueba",
|
||||
estudio_id="documento_externo",
|
||||
nombre="campo",
|
||||
etiqueta="Campo",
|
||||
tipo_valor="fecha",
|
||||
estudio_etiqueta="Documento externo",
|
||||
)
|
||||
|
||||
leido = catalogos._leer(catalogos.ruta_de_catalogo("prueba"))
|
||||
assert leido["documento_externo"]["etiqueta"] == "Documento externo"
|
||||
assert leido["documento_externo"]["resultados"]["campo"]["tipo_valor"] == "fecha"
|
||||
|
||||
|
||||
def test_adding_the_same_resultado_twice_does_not_touch_the_file(catalogo_file):
|
||||
"""Fails if re-discovering the same field on a later row duplicates it
|
||||
or rewrites what a human already edited in the file."""
|
||||
original = '[citologia]\netiqueta = "Citología"\n\n[citologia.resultados.campo]\netiqueta = "Campo"\ntipo_valor = "texto"\n'
|
||||
catalogo_file(original)
|
||||
|
||||
catalogos.add_resultado("prueba", estudio_id="citologia", nombre="campo", etiqueta="Otra cosa", tipo_valor="numero")
|
||||
|
||||
assert catalogos.ruta_de_catalogo("prueba").read_text(encoding="utf-8") == original
|
||||
|
||||
|
||||
def test_an_unknown_tipo_valor_is_rejected(catalogo_file):
|
||||
catalogo_file("")
|
||||
with pytest.raises(catalogos.CatalogoInvalido):
|
||||
catalogos.add_resultado("prueba", estudio_id="x", nombre="y", etiqueta="Y", tipo_valor="no_existe")
|
||||
|
||||
|
||||
def test_a_quote_in_a_label_does_not_break_the_file(catalogo_file):
|
||||
"""Fails if a caption or label read off a document (arbitrary text)
|
||||
produces TOML the next `catalogo_desde_toml` can't parse."""
|
||||
catalogo_file("")
|
||||
catalogos.add_resultado(
|
||||
"prueba", estudio_id="nota", nombre="campo", etiqueta='Dx: "sospechoso"', tipo_valor="texto"
|
||||
)
|
||||
leido = catalogos._leer(catalogos.ruta_de_catalogo("prueba"))
|
||||
assert leido["nota"]["resultados"]["campo"]["etiqueta"] == 'Dx: "sospechoso"'
|
||||
@@ -131,7 +131,7 @@ def test_a_caption_outside_the_target_schema_is_committed_through_the_catalog(cl
|
||||
from sqlalchemy import create_engine, text as sa_text
|
||||
from sqlmodel import select
|
||||
|
||||
from indicadores_kit.registry import catalogos
|
||||
from webapi.orchestration.reference import catalogs as catalogos
|
||||
from core.cacu.paciente.model import Paciente
|
||||
from persistance.cacu import carga_repository, paciente_repository
|
||||
|
||||
|
||||
@@ -8,11 +8,11 @@ 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
|
||||
from webapi.imports.connectors.pdf import PdfConnector
|
||||
from webapi.orchestration.reference.catalogs import CatalogoInvalido
|
||||
from webapi.imports.connectors.sql import SqlConnector
|
||||
from webapi.imports.connectors.tabular import FileConnector
|
||||
from webapi.imports.schemas.registry import ENTITY_REGISTRY
|
||||
|
||||
@@ -16,8 +16,8 @@ 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
|
||||
from webapi.orchestration.reference.catalogs import Catalogo, add_resultado
|
||||
from webapi.orchestration.silver.procedures import valor_de_observacion
|
||||
|
||||
# `token_sort_ratio`, not `WRatio`: `WRatio`'s partial-alignment bonus scores
|
||||
# two short, unrelated captions that merely share common words ("de", "del")
|
||||
|
||||
@@ -11,7 +11,7 @@ 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
|
||||
straight through the domain's existing `carga_repository`, the same one
|
||||
`webapi.orquestacion`'s `cargar` step uses for staging-derived batches.
|
||||
`webapi.orchestration`'s `load` 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
|
||||
@@ -27,11 +27,11 @@ 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
|
||||
from webapi.orchestration.reference.catalogs import Catalogo, catalogo_desde_toml, ruta_de_catalogo
|
||||
from webapi.orchestration.silver.procedures import LotePlata
|
||||
from webapi.orchestration.tables import tablas_de
|
||||
|
||||
FUENTE_CATALOGO_ABIERTO = "catalogo_abierto"
|
||||
|
||||
@@ -93,7 +93,7 @@ def commit_discovered_fields(
|
||||
|
||||
if procedures:
|
||||
_sync_catalog(dominio, proyecto, tablas)
|
||||
dominio.carga_repository.guardar_carga(
|
||||
dominio.carga_repository.save_load(
|
||||
fuente=FUENTE_CATALOGO_ABIERTO, personas=(), plata=LotePlata(procedures, observations, {})
|
||||
)
|
||||
return result
|
||||
@@ -120,4 +120,4 @@ def _sync_catalog(dominio, proyecto: str, tablas) -> None:
|
||||
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)
|
||||
dominio.catalog_repository.sync(catalogo.estudios, catalogo.resultados, catalogo.valores)
|
||||
|
||||
@@ -79,6 +79,40 @@ def catalogo_desde_toml(ruta: Path, *, tablas: TablasKit) -> Catalogo:
|
||||
return Catalogo(estudios, resultados, valores)
|
||||
|
||||
|
||||
def add_resultado(
|
||||
proyecto: str, *, estudio_id: str, nombre: str, etiqueta: str, tipo_valor: str, estudio_etiqueta: str | None = None
|
||||
) -> str:
|
||||
"""Appends a new `resultado_id` to the project's TOML (not to the
|
||||
database): a `[estudio.resultados.nombre]` table, and the `[estudio]`
|
||||
table too if it didn't exist yet. The file stays the source: the next
|
||||
`catalogo_desde_toml` already brings it, and whoever syncs the table
|
||||
writes it.
|
||||
|
||||
Idempotent: if the resultado is already in the file, nothing is
|
||||
written and its `resultado_id` is returned as is. `nombre` must be a
|
||||
valid TOML key (whoever discovers the field builds it, e.g. from a
|
||||
slug of the text found).
|
||||
"""
|
||||
if tipo_valor not in TIPOS_DE_VALOR:
|
||||
raise CatalogoInvalido(f"{estudio_id}.{nombre}: tipo_valor {tipo_valor!r} no es uno de {', '.join(TIPOS_DE_VALOR)}.")
|
||||
ruta = ruta_de_catalogo(proyecto)
|
||||
existentes = _leer(ruta)
|
||||
resultado_id = f"{estudio_id}.{nombre}"
|
||||
if estudio_id in existentes and nombre in existentes[estudio_id].get("resultados", {}):
|
||||
return resultado_id
|
||||
blocks = []
|
||||
if estudio_id not in existentes:
|
||||
blocks.append(f'\n[{estudio_id}]\netiqueta = "{_escape(estudio_etiqueta or estudio_id)}"\n')
|
||||
blocks.append(f'\n[{estudio_id}.resultados.{nombre}]\netiqueta = "{_escape(etiqueta)}"\ntipo_valor = "{tipo_valor}"\n')
|
||||
with Path(ruta).open("a", encoding="utf-8") as archivo:
|
||||
archivo.write("".join(blocks))
|
||||
return resultado_id
|
||||
|
||||
|
||||
def _escape(text: str) -> str:
|
||||
return text.replace("\\", "\\\\").replace('"', '\\"')
|
||||
|
||||
|
||||
def codigos_hospital(proyecto: str) -> dict[str, str]:
|
||||
"""Código del hospital -> `estudio_id`, del catálogo del proyecto.
|
||||
|
||||
|
||||
Reference in New Issue
Block a user