Files
ISSSTELEON/Core/core/pipeline.py
T
edgar ba81ab811f Preparar la evidencia fuente y la elegibilidad CaCu por visita
01a: fechas clínicas, disponibilidad en origen y referencia por campo; evidencia FHIR independiente.
01b (parcial): proyección de elegibilidad por instancia y lector con comprobación del esquema gold.

Pendiente: las exclusiones propias de cada escenario conservan solo el motivo prioritario; fechas FHIR parciales o sin zona, estados de resultado y actualización desde instalaciones anteriores. Ver PLAN_CONTEXTO_CACU.md.
2026-12-02 15:38:10 -06:00

566 lines
23 KiB
Python

"""The ingestion DSL: a graph an operator draws, and the pure steps it needs. No IO here.
A pipeline is one versioned JSON document of nodes; each node names its inputs (the edges).
Every node kind wraps one library operation and outputs one table, so any node's output can
be previewed and a run can restart from the node that changed. Each kind's JSON Schema is
the form the canvas shows for it. Nothing in a graph is specific to one hospital in code.
"""
import re
from datetime import datetime
from graphlib import CycleError, TopologicalSorter
from typing import Annotated, Any, ClassVar, Literal
from urllib.parse import urlsplit, urlunsplit
import dateparser
from pydantic import (
BaseModel,
ConfigDict,
Field,
ValidationError,
create_model,
field_validator,
model_validator,
)
from core import catalog, sources
from core.schema import ENTITIES
ID_PATTERN = r"^[a-z][a-z0-9_]*$" # pipeline and node ids: also table-name safe
Id = Annotated[str, Field(pattern=ID_PATTERN, max_length=40)]
ImportPath = Annotated[str, Field(pattern=r"^[A-Za-z_][\w.]*:[A-Za-z_]\w*$")]
EntityName = Literal[tuple(ENTITIES)] # type: ignore[valid-type]
# How the forms name each entity: identity, and each study by its catalog title.
ENTITY_TITLES = {"identity": "Identidad de la persona",
**{name: spec.title for name, spec in catalog.studies().items()}} # fmt: skip
def _says(title: str, description: str = "", options: dict[str, str] | None = None,
advanced: bool = False, keys: Literal["field"] | None = None) -> Any: # fmt: skip
"""A field as the canvas form shows it: its title and help in the operator's words,
for a fixed set of values how each one reads, and whether only the "Avanzado" tab
shows it (what a guided dialog fills instead); a map keyed by platform fields says so
(`keys="field"`), so its keys are picked by their titles."""
extra: dict[str, Any] = {}
if options:
listed = [{"value": k, "label": v} for k, v in options.items()]
extra["widget"] = {"formlyConfig": {"props": {"options": listed}}}
if advanced:
extra["advanced"] = True
if keys:
extra["keys"] = keys
return Field(title=title, description=description or None, json_schema_extra=extra or None)
class Position(BaseModel):
x: float
y: float
class Node(BaseModel):
model_config = ConfigDict(extra="forbid")
inputs_allowed: ClassVar[tuple[int, int | None]] = (1, 1) # (min, max); None: no max
id: Id
inputs: list[Id] = []
label: Annotated[str, _says("Nombre", "Cómo se ve en el diagrama.")] = ""
position: Position | None = None # where the canvas drew it
class Guided(BaseModel):
"""How the Conectar dialog drew a source: its type (core.sources) and the answers given.
The node's dlt fields are made from them; drawn by hand ("Avanzado"), a node has none."""
model_config = ConfigDict(extra="forbid")
type: str
answers: dict[str, Any] = {}
class Source(Node):
"""One table, file set or API resource, copied as it is (dlt). Merged on the source's
own primary key or `primary_key`; replaced whole when it has none."""
inputs_allowed = (0, 0)
kind: Literal["source"] = "source"
# any dlt source or resource, e.g. dlt.sources.sql_database:sql_table
source: Annotated[
ImportPath, _says("Fuente dlt", "Módulo:función de la fuente dlt.", advanced=True)
]
args: Annotated[
dict[str, Any], _says("Argumentos", "Los de la fuente dlt.", advanced=True)
] = {}
resource: Annotated[ # which resource, when the source has several
str | None,
_says("Recurso", "Cuál, si la fuente ofrece varios (una tabla).", advanced=True),
] = None
then: Annotated[ # a dlt transformer piped after (file contents, Excel)
ImportPath | None, _says("Lector", "Transformador dlt para los archivos.", advanced=True)
] = None
primary_key: Annotated[
list[str], _says("Llave", "Columnas que identifican una fila.", advanced=True)
] = []
guided: Annotated[Guided | None, _says("Asistente", advanced=True)] = None
@model_validator(mode="before")
@classmethod
def _made_from_answers(cls, data: Any) -> Any:
"""A guided source's dlt fields always follow its answers. A source drawn by hand
that a catalog type makes exactly is read as that type, so the dialog edits it."""
if isinstance(data, dict) and not data.get("guided") and data.get("source"):
if found := sources.recognise(data):
data = {**data, "guided": {"type": found[0], "answers": found[1]}}
if isinstance(data, dict) and data.get("guided"):
guided = data["guided"]
guided = guided.model_dump() if isinstance(guided, BaseModel) else guided
if MASK not in repr(guided.get("answers", {})): # masked: shown, not run
data = {**data, **sources.render(guided["type"], guided.get("answers", {}))}
return data
class Read(Node):
"""Files in a column (PDF, Word, Excel, scans...) to text (MarkItDown, OCRmyPDF)."""
kind: Literal["read"] = "read"
column: Annotated[
str, _says("Columna con los archivos", "Donde la entrada trae cada documento.")
]
class Condition(BaseModel):
column: Annotated[str, _says("Columna", "Por ejemplo «text», el texto leído del documento.")]
op: Annotated[
Literal["equals", "contains", "matches", "present"],
_says(
"Condición",
options={
"equals": "es igual a",
"contains": "contiene",
"matches": "coincide con la expresión",
"present": "tiene algún valor",
},
), # fmt: skip
]
value: Annotated[str, _says("Valor", "Lo que se busca; por ejemplo «citología».")] = ""
class Route(Node):
"""Only the rows where every condition holds (e.g. reports titled "Citología"). An
`otherwise` route takes the rows of its input that none of the other routes on that
input take (documents nobody recognises, for a reviewer), then its own conditions."""
kind: Literal["route"] = "route"
when: Annotated[list[Condition], _says("Pasan las filas donde")] = []
otherwise: Annotated[
bool, _says("Lo que ningún otro tome", "Recoge lo que nadie reconoce, para revisarlo.")
] = False
class Map(Node):
"""Columns to platform fields, the site's codes translated by its ConceptMap
(core.concept_map), and its date formats."""
kind: Literal["map"] = "map"
fields: Annotated[ # platform field -> column
dict[str, str], _says("Campos", "Dato de la plataforma → columna del sitio.", keys="field")
]
concept_map: Annotated[ # the site's codes in platform terms
Id | None, _says("Equivalencias de códigos", "La tabla de códigos del sitio.")
] = None
formats: Annotated[ # platform field -> strptime format
dict[str, str], _says("Formatos de fecha", "Por ejemplo %d/%m/%Y.", keys="field")
] = {}
# platform field -> a value in platform terms that every row has, though no column says
# it (a table of neurology notes: their specialty)
values: Annotated[
dict[str, str], _says("Valores fijos", "Un dato igual para todas las filas.", keys="field")
] = {}
class Extract(Node):
"""Platform fields read from text, each kept with the text it was read from.
`auto` asks the LLM when one is configured and answering, else applies `patterns`;
with neither, the row is held. Patterns are regexes with one group, per field (the
LLM can propose them from sample documents); their values go through the ConceptMap
and `formats` as in `map`."""
kind: Literal["extract"] = "extract"
# the text to read; several columns are read as one document, in their order (an
# outsourced result joined to the order it answers)
column: Annotated[str | list[str], _says("Columna con el texto")]
entity: Annotated[
EntityName, _says("Estudio", "Qué estudio se saca del documento.", ENTITY_TITLES)
]
method: Annotated[
Literal["auto", "llm", "patterns"],
_says(
"Cómo leer",
options={
"auto": "Automático",
"llm": "Con el modelo de lenguaje",
"patterns": "Con patrones",
},
), # fmt: skip
] = "auto"
hints: Annotated[str, _says("Indicaciones", "Para el modelo de lenguaje.")] = ""
patterns: Annotated[ # platform field -> regex with one group
dict[str, str], _says("Patrones", "Dato → expresión con un grupo ( ).", keys="field")
] = {}
# platform field -> a column of the row taken as it is, not read from the text (an EEG
# report joined to its recording: the date from the report, the file from the column)
columns: Annotated[
dict[str, str],
_says("Datos tomados de columnas", "Dato → columna, sin leer el texto.", keys="field"),
] = {}
concept_map: Annotated[Id | None, _says("Equivalencias de códigos")] = None
formats: Annotated[dict[str, str], _says("Formatos de fecha", keys="field")] = {}
@field_validator("patterns")
@classmethod
def _one_group_each(cls, v: dict[str, str]) -> dict[str, str]:
for field, pattern in v.items():
if re.compile(pattern, re.IGNORECASE).groups != 1:
raise ValueError(f"{field}: a pattern needs exactly one (group)")
return v
def text(self, row: dict[str, Any]) -> str:
"""The row's text this node reads."""
columns = [self.column] if isinstance(self.column, str) else self.column
return "\n".join(str(row[c]) for c in columns if row.get(c))
class Fhir(Node):
"""FHIR R4 Bundles a standard hospital sent (a column of their JSON) as rows of one
entity: identity, death or a study (core.fhir_in). The sender's own codes go through
its ConceptMap."""
kind: Literal["fhir"] = "fhir"
column: Annotated[str, _says("Columna con el FHIR")] = "doc"
entity: Annotated[EntityName, _says("Estudio", options=ENTITY_TITLES)]
concept_map: Annotated[Id | None, _says("Equivalencias de códigos")] = None
class Join(Node):
"""Two inputs side by side where their columns match."""
inputs_allowed = (2, 2)
kind: Literal["join"] = "join"
on: Annotated[ # (left column, right column)
list[tuple[str, str]],
_says("Columnas iguales", "Columna de la primera entrada = columna de la segunda."),
]
how: Annotated[
Literal["inner", "left"],
_says(
"Cuáles quedan",
options={"inner": "Solo las que tienen pareja", "left": "Todas las de la izquierda"},
), # fmt: skip
] = "inner"
IDENTIFIERS = ("record_number", "curp", "nss")
class Link(Node):
"""Identity rows from every input, grouped into persons (Splink).
Two records are the same person when any rule holds (Splink's SQL rule syntax, `l.`
and `r.` for the two records); persons are the connected groups. A person whose
records disagree on birth date or sex is held for review as a whole. Pairs Splink
scores above `review` that ended up apart are queued as possible matches."""
inputs_allowed = (1, None)
kind: Literal["link"] = "link"
fields: Annotated[list[str], _says("Datos que comparar")] = [
"record_number", "full_name", "curp", "nss", "birth_date", "sex"] # fmt: skip
rules: Annotated[ # empty: the defaults for `fields` (see default_rules)
list[str],
_says(
"Reglas",
"Vacío: las de siempre (mismo identificador, o misma fecha de nacimiento y nombre).",
), # fmt: skip
] = []
review: Annotated[
float,
Field(gt=0, le=1),
_says("Umbral para revisar", "Parecidos por encima de esto los ve un revisor."),
] = 0.5
def default_rules(self) -> list[str]:
"""The same identifier, unless the birth dates differ; or the same birth date and
the same name (as compared: upper case, no accents, single spaces)."""
dob = "birth_date" in self.fields
same_dob = (
" and (l.birth_date is null or r.birth_date is null"
" or l.birth_date = r.birth_date)" if dob else ""
) # fmt: skip
rules = [f"l.{f} = r.{f}{same_dob}" for f in IDENTIFIERS if f in self.fields]
if dob and "full_name" in self.fields:
rules.append("l.birth_date = r.birth_date and l.full_name = r.full_name")
return rules
class Target(Node):
"""Rows of platform fields into one platform entity, each row given its person by the
one `link` node among the inputs. Rule breaks are held for review."""
inputs_allowed = (2, None)
kind: Literal["target"] = "target"
entity: Annotated[
EntityName,
_says("Estudio", "En qué estudio de la plataforma se guarda.", ENTITY_TITLES),
]
@field_validator("entity")
@classmethod
def _not_identity(cls, v: str) -> str:
if v == "identity":
raise ValueError("identity rows go into a link node, not a target")
return v
AnyNode = Annotated[
Source | Read | Route | Map | Extract | Fhir | Join | Link | Target, Field(discriminator="kind")
]
class Pipeline(BaseModel):
nodes: list[AnyNode]
@model_validator(mode="after")
def _a_valid_graph(self):
ids = [n.id for n in self.nodes]
if len(ids) != len(set(ids)):
raise ValueError("node ids must be unique")
for n in self.nodes:
lo, hi = n.inputs_allowed
if not lo <= len(n.inputs) <= (hi if hi is not None else len(n.inputs)):
raise ValueError(f"{n.id}: {n.kind} takes {lo}..{hi} inputs")
if missing := set(n.inputs) - set(ids):
raise ValueError(f"{n.id}: no node {sorted(missing)}")
kinds = {n.id: n.kind for n in self.nodes}
for n in self.nodes:
if n.kind == "target" and [kinds[i] for i in n.inputs].count("link") != 1:
raise ValueError(f"{n.id}: a target takes exactly one link node among its inputs")
try:
self.order()
except CycleError as e:
raise ValueError(f"cycle: {e.args[1]}") from None
return self
def order(self) -> list[AnyNode]:
"""Nodes in an order where every input runs before the nodes that read it."""
by_id = {n.id: n for n in self.nodes}
graph = TopologicalSorter({n.id: n.inputs for n in self.nodes})
return [by_id[i] for i in graph.static_order()]
RECORD = "_record" # the source row every row comes from (hash of that row)
HELD = "_held" # why a row may not reach silver (list of reasons) or None
QUOTES = "_quotes" # what text each LLM value was read from
FIELD_EVIDENCE = "_field_evidence" # source dates and reference for individual values
def matches(node: Route, row: dict[str, Any]) -> bool:
for c in node.when:
value = row.get(c.column)
text = "" if value is None else str(value)
ok = {
"equals": text == c.value,
"contains": c.value.casefold() in text.casefold(),
"matches": re.search(c.value, text) is not None,
"present": value not in (None, ""),
}[c.op]
if not ok:
return False
return True
def join(node: Join, left: list[dict], right: list[dict], right_id: str) -> list[dict]:
"""Left rows with the matching right rows' columns (a clashing name gets `__<right>`)."""
index: dict[tuple, list[dict]] = {}
for r in right:
index.setdefault(tuple(r.get(b) for _, b in node.on), []).append(r)
out = []
for row in left:
found = index.get(tuple(row.get(a) for a, _ in node.on), [])
for r in found or ([{}] if node.how == "left" else []):
extra = {(k if k not in row else f"{k}__{right_id}"): v for k, v in r.items()}
out.append({**row, **extra, RECORD: row[RECORD]})
return out
Codes = dict[str, dict[str, str]] # field -> site code (casefolded) -> platform code
def convert(node: Map | Extract, field: str, raw: Any, codes: Codes) -> Any:
"""A raw value as the platform field expects it: the site's code translated (its
ConceptMap, case ignored), then its date format: a strptime format (spaces inside the
value ignored when the format has none), or `dateparser:<language>` for dates written
out ("9 de diciembre de 2025"). A value that doesn't parse is kept as written, so the
target holds it with the reason."""
if not isinstance(raw, str):
return raw
raw = _SPACE.sub(" ", raw.strip()) # a value read across a line break is one value
raw = codes.get(field, {}).get(raw.casefold(), raw)
fmt = node.formats.get(field)
if fmt and fmt.startswith("dateparser:"):
found = dateparser.parse(raw, languages=[fmt.split(":")[1]])
return found.date() if found else raw
if fmt:
if " " not in fmt: # OCR may split a number ("25/01/1 967")
raw = "".join(raw.split())
try:
return datetime.strptime(raw, fmt).date()
except ValueError:
return raw
return raw
def map_row(node: Map, row: dict[str, Any], codes: Codes) -> dict[str, Any]:
mapped = {
field: convert(node, field, row.get(col), codes) for field, col in node.fields.items()
}
return {**mapped, **node.values, RECORD: row[RECORD]}
def validate(entity: str, values: dict[str, Any]) -> list[str]:
"""Why these values break the platform schema; empty if they don't."""
try:
ENTITIES[entity].model_validate(values)
except ValidationError as e:
return [f"{'.'.join(map(str, err['loc']))}: {err['msg']}" for err in e.errors()]
return []
_SPACE = re.compile(r"\s+")
def grounded(quote: str | None, text: str) -> bool:
"""An LLM value counts only if the text it says it read is really in the document."""
if not quote:
return False
norm = lambda s: _SPACE.sub(" ", s).strip().casefold() # noqa: E731
return norm(quote) in norm(text)
def ground(answer: dict, text: str) -> list[tuple[dict, dict, list[str]]]:
"""Each record of an LLM answer as (values, quotes, reasons to hold it). A value whose
quote is not in the text is dropped, and the record is held saying so."""
out = []
for record in answer.get("records", []):
values, quotes, held = {}, {}, []
for field, got in record.items():
if not got or got.get("value") is None:
continue
if grounded(got.get("quote"), text):
values[field], quotes[field] = got["value"], got["quote"]
else:
held.append(f"{field}: not found in the document as quoted")
out.append((values, quotes, held))
return out
def apply_patterns(node: Extract, text: str, codes: Codes) -> list[tuple[dict, dict, list[str]]]:
"""One record from the node's patterns: (values, quotes, reasons to hold it). A value
found this way is grounded by construction: the quote is the matched text."""
values, quotes = {}, {}
for field, pattern in node.patterns.items():
if found := re.search(pattern, text, re.IGNORECASE):
values[field] = convert(node, field, found.group(1), codes)
quotes[field] = found.group(0)
if not values:
return []
return [(values, quotes, [])]
def answer_schema(entity: str) -> dict:
"""JSON Schema for an LLM answer: every record of `entity` found, each field with the
quote it was read from."""
fields = {
f: (create_model(f"{entity}_{f}", value=(info.annotation, None), quote=(str, "")), None)
for f, info in ENTITIES[entity].model_fields.items()
}
record = create_model(entity, **fields)
return create_model("Answer", records=(list[record], [])).model_json_schema()
MASK = "********"
_SECRET_KEY = re.compile(r"pass|secret|token|key", re.IGNORECASE)
def _mask(key: str, value: Any) -> Any:
if isinstance(value, dict):
return {k: _mask(k, v) for k, v in value.items()}
if not isinstance(value, str):
return value
if _SECRET_KEY.search(key):
return MASK
url = urlsplit(value)
if url.password:
netloc = url.netloc.replace(f":{url.password}@", f":{MASK}@", 1)
return urlunsplit(url._replace(netloc=netloc))
return value
def _secret_answers(guided: "Guided") -> set[str]:
"""Answers masked whole (a password); a sign-in's account keeps who it is and masks
its tokens and client secret, like any argument."""
fields = sources.catalog().types[guided.type].fields
return {k for k, f in fields.items() if f.type == "password"}
def _masked_source(n: "Source") -> "Source":
update: dict[str, Any] = {"args": _mask("", n.args)}
if n.guided:
secret = _secret_answers(n.guided)
answers = {k: MASK if k in secret and v not in (None, "") else _mask(k, v)
for k, v in n.guided.answers.items()} # fmt: skip
update["guided"] = n.guided.model_copy(update={"answers": answers})
return n.model_copy(update=update)
def redacted(pipeline: Pipeline) -> Pipeline:
"""The pipeline with every secret in its sources masked (arguments and the dialog's
answers), as the API shows it."""
nodes = [_masked_source(n) if n.kind == "source" else n for n in pipeline.nodes]
return pipeline.model_copy(update={"nodes": nodes})
def _restore(new: Any, old: Any, where: str) -> Any:
if isinstance(new, dict):
old = old if isinstance(old, dict) else {}
return {k: _restore(v, old.get(k), f"{where}.{k}") for k, v in new.items()}
if isinstance(new, str) and MASK in new:
if not isinstance(old, str) or _mask(where.rsplit(".", 1)[-1], old) != new:
raise ValueError(f"{where}: masked, but no saved secret to keep there")
return old
return new
def restored(new: Pipeline, old: Pipeline | None) -> Pipeline:
"""A pipeline sent back by the UI with masks where secrets were: the saved secrets are
kept. A mask with nothing saved behind it is refused."""
saved = {n.id: n for n in old.nodes if n.kind == "source"} if old else {}
nodes = [_restored_source(n, saved.get(n.id)) if n.kind == "source" else n
for n in new.nodes] # fmt: skip
return new.model_copy(update={"nodes": nodes})
def _restored_source(new: "Source", old: "Source | None") -> "Source":
if not new.guided:
return new.model_copy(update={"args": _restore(new.args, old and old.args, new.id)})
kept = old.guided.answers if old and old.guided and old.guided.type == new.guided.type else {}
secret = _secret_answers(new.guided)
answers = {}
for k, v in new.guided.answers.items():
if k in secret and v == MASK:
if kept.get(k) in (None, ""):
raise ValueError(f"{new.id}.{k}: masked, but no saved secret to keep there")
answers[k] = kept[k]
else:
answers[k] = _restore(v, kept.get(k), f"{new.id}.{k}")
guided = new.guided.model_copy(update={"answers": answers})
drawn = new.model_dump(exclude={"guided"})
return Source.model_validate({**drawn, "guided": guided.model_dump()})