113b792a7b
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.
124 lines
5.6 KiB
Python
124 lines
5.6 KiB
Python
"""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
|
|
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
|
|
straight through the domain's existing `carga_repository`, the same one
|
|
`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
|
|
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 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"
|
|
|
|
|
|
@dataclass
|
|
class CatalogCommitResult:
|
|
proyecto: str
|
|
records_written: int = 0
|
|
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, 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. `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)
|
|
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, 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)
|
|
|
|
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.save_load(
|
|
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.catalog_repository.sync(catalogo.estudios, catalogo.resultados, catalogo.valores)
|