improve ingestion system to match isssteleon setup

This commit is contained in:
Roberto Treviño Cervantes
2026-11-13 11:52:36 -06:00
parent 59fe94ad97
commit e41a2b7127
16 changed files with 1450 additions and 319 deletions
@@ -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)
+161 -6
View File
@@ -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)
@@ -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,
}