integration layer; merge work on indicators from forks with existing ingestion pipeline

This commit is contained in:
Roberto Treviño Cervantes
2026-10-23 00:00:13 -06:00
parent c1444e2b8d
commit 043f7635f4
80 changed files with 7766 additions and 38 deletions
View File
+288
View File
@@ -0,0 +1,288 @@
"""Runs one configured source, or a batch of them, end to end: resolve the
target entity, build the connector, read and validate the rows and, for
`commit_sources`, write the accepted ones through `Repository`.
A batch composes the database from several sources (files, SQL tables or
queries, PDFs, documents, EEG files), each feeding one target entity. All
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 typing import Any, Iterator
from sqlalchemy.exc import SQLAlchemyError
from persistance.repository import ConflictPolicy
from webapi.imports.connectors import Connector, ConnectorError, build_connector
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
class ImportRequestError(Exception):
"""A structurally invalid import request, such as an unknown target, a
bad connection string or an invalid on_conflict. Mapped to HTTP 400."""
@dataclass(frozen=True)
class ImportSource:
"""One parsed and structurally validated entry of a request's `sources`."""
source_type: str
target: str
spec: EntitySpec
column_mapping: dict[str, str]
defaults: dict[str, Any]
payload: dict[str, Any]
label: str | None = None
@classmethod
def parse(cls, raw: Any) -> "ImportSource":
if not isinstance(raw, dict):
raise ImportRequestError("each source must be an object")
target = raw.get("target")
if not target:
raise ImportRequestError("source is missing 'target'")
spec = ENTITY_REGISTRY.get(target)
if spec is None:
raise ImportRequestError(f"unknown target: {target!r}")
fields = set(spec.schema.model_fields)
mapping = raw.get("column_mapping") or {}
defaults = raw.get("defaults") or {}
if not isinstance(mapping, dict) or not isinstance(defaults, dict):
raise ImportRequestError("'column_mapping' and 'defaults' must be objects")
unknown = sorted((set(mapping.values()) | set(defaults)) - fields)
if unknown:
raise ImportRequestError(f"{target} has no field(s) {unknown}")
targets = list(mapping.values())
duplicated = sorted({t for t in targets if targets.count(t) > 1})
if duplicated:
raise ImportRequestError(f"more than one source column mapped to {duplicated}")
if not mapping and not defaults:
raise ImportRequestError(f"source for {target} maps no columns")
payload = raw.get("payload")
if not isinstance(payload, dict):
raise ImportRequestError("source is missing 'payload'")
return cls(
source_type=raw.get("source_type", ""),
target=target,
spec=spec,
column_mapping=mapping,
defaults=defaults,
payload=payload,
label=raw.get("label"),
)
@property
def domain(self) -> str:
return self.target.split(".", 1)[0]
def connector(self) -> Connector:
payload = self.payload
if self.source_type == "document":
# A document source extracts the fields of the entity it feeds.
payload = {**payload, "target": payload.get("target") or self.target}
try:
return build_connector(self.source_type, payload)
except ConnectorError as exc:
raise ImportRequestError(str(exc)) from exc
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)."""
try:
for row in self.connector().read_rows(self.column_mapping):
for field_name, value in self.defaults.items():
if _is_blank(row.get(field_name)):
row[field_name] = value
yield row
except ConnectorError as exc:
raise ImportRequestError(str(exc)) from exc
def validate(self) -> BatchValidationResult:
return validate_rows(self.spec.schema, self.rows())
def _is_blank(value: Any) -> bool:
return value is None or (isinstance(value, str) and not value.strip())
def serialize_errors(validation: BatchValidationResult) -> list[dict[str, Any]]:
return [
{
"row_index": row_errors.row_index,
"field": e.field,
"category": e.category.value,
"message": e.message,
"raw_value": _jsonable(e.raw_value),
}
for row_errors in validation.rejected
for e in row_errors.errors
]
def _jsonable(value: Any) -> Any:
if value is None or isinstance(value, (str, int, float, bool)):
return value
return str(value)
def validate_source(raw_source: dict[str, Any]) -> BatchValidationResult:
return ImportSource.parse(raw_source).validate()
@dataclass
class SourceCommitResult:
target: str
label: str | None
total: int
created: int
updated: int
rejected: int
errors: list[dict[str, Any]]
linked: dict[str, int]
merged: int = 0
warnings: list[dict[str, Any]] = field(default_factory=list)
def _parse_batch(raw_sources: Any) -> list[ImportSource]:
if not isinstance(raw_sources, list) or not raw_sources:
raise ImportRequestError("'sources' must be a non-empty list")
sources = [ImportSource.parse(raw) for raw in raw_sources]
domains = sorted({source.domain for source in sources})
if len(domains) > 1:
raise ImportRequestError(
f"a batch cannot mix domains — got {domains}, every source must target the same one"
)
return sources
def merge_duplicates(sources: list[ImportSource], rows: list[list[dict[str, Any] | None]]) -> tuple[dict[int, int], dict[int, list]]:
"""Combines rows that describe the same record (same target entity and
natural key) across the sources of a batch, before validation: a
patient's demographics from a CSV completed with the birth date read
from a scanned form. The first row seen is kept and completed with the
fields it lacks; merged rows become `None`. A field two sources disagree
on keeps the first value and is reported as a warning on the later one.
Returns per-source merge counts and warnings."""
first_seen: dict[tuple[str, tuple], tuple[int, dict[str, Any]]] = {}
merged: dict[int, int] = {}
warnings: dict[int, list] = {}
for position, source in enumerate(sources):
keys = source.spec.conflict_fields
if not keys:
continue
for index, row in enumerate(rows[position]):
key_values = tuple(_key_part(row.get(k)) for k in keys)
if any(v is None for v in key_values):
continue
first = first_seen.setdefault((source.target, key_values), (position, row))
if first[1] is row:
continue
first_position, first_row = first
for name, value in row.items():
if _is_blank(value):
continue
current = first_row.get(name)
if _is_blank(current):
first_row[name] = value
elif _key_part(current) != _key_part(value):
warnings.setdefault(position, []).append(
{
"row_index": index,
"field": name,
"category": "merge_conflict",
"message": f"se conservó {current!r} de {sources[first_position].label or 'otra fuente'}",
"raw_value": _jsonable(value),
}
)
rows[position][index] = None
merged[position] = merged.get(position, 0) + 1
return merged, warnings
def _key_part(value: Any) -> Any:
"""Normalized for comparison across sources: a CSV's natural key is
always a string ("5001"), while a typed source (the document extractor,
a SQL column) can hand back an int or a date for the very same value.
Stringifying both sides is what lets rows that describe the same record
actually match, instead of silently landing as two separate ones."""
if _is_blank(value):
return None
return str(value).strip().upper()
def commit_sources(raw_sources: Any, *, on_conflict: str, merge: bool = False) -> list[SourceCommitResult]:
"""Writes a batch in one transaction. With `merge`, rows of different
sources sharing a natural key are combined first (see `merge_duplicates`)."""
try:
policy = ConflictPolicy(on_conflict)
except ValueError as exc:
raise ImportRequestError(f"invalid on_conflict: {on_conflict!r}") from exc
sources = _parse_batch(raw_sources)
if policy is ConflictPolicy.UPSERT:
keyless = sorted({s.target for s in sources if not s.spec.conflict_fields})
if keyless:
raise ImportRequestError(f"{', '.join(keyless)} has no natural key — on_conflict=upsert is not valid for it")
# Read + validate everything before opening the write transaction, so a
# slow source (OCR, a remote SQL table) never holds database locks.
rows: list[list[dict[str, Any] | None]] = [list(source.rows()) for source in sources]
merged, merge_warnings = merge_duplicates(sources, rows) if merge else ({}, {})
validated = [(source, validate_rows(source.spec.schema, source_rows)) for source, source_rows in zip(sources, rows)]
session = sources[0].spec.repository.open_session()
links = LinkResolver(session)
results: dict[int, SourceCommitResult] = {}
# Parents first (Paciente, then OrdenesEstudio, then the rest), so a
# child's FK lookup finds a parent loaded by another source of the same
# batch. Results are still reported in the caller's order.
write_order = sorted(range(len(validated)), key=lambda i: dependency_rank(validated[i][0].target))
try:
for position in write_order:
source, validation = validated[position]
linked: dict[str, int] = {}
for row in validation.accepted_rows:
for fk_field in links.resolve(source.target, row.data):
linked[fk_field] = linked.get(fk_field, 0) + 1
objs = [source.spec.model(**row.data) for row in validation.accepted_rows]
write = source.spec.repository.bulk_upsert(
objs, conflict_fields=source.spec.conflict_fields, on_conflict=policy, session=session
)
conflict_errors = [
{
"row_index": validation.accepted_rows[outcome.index].row_index,
"field": ",".join(source.spec.conflict_fields or ()),
"category": "conflict",
"message": outcome.error or "conflict",
"raw_value": _jsonable(
validation.accepted_rows[outcome.index].data.get((source.spec.conflict_fields or ("",))[0])
),
}
for outcome in write.outcomes
if outcome.status == "rejected"
]
errors = sorted(serialize_errors(validation) + conflict_errors, key=lambda e: e["row_index"])
results[position] = SourceCommitResult(
target=source.target,
label=source.label,
total=validation.total_rows,
created=write.created_count,
updated=write.updated_count,
rejected=write.rejected_count + validation.error_count,
errors=errors,
linked=linked,
merged=merged.get(position, 0),
warnings=merge_warnings.get(position, []),
)
session.commit()
except SQLAlchemyError as exc:
session.rollback()
raise ImportRequestError(f"the database refused the batch, nothing was written: {exc.__class__.__name__}: {exc.orig if hasattr(exc, 'orig') else exc}") from exc
finally:
session.close()
return [results[i] for i in range(len(validated))]
@@ -0,0 +1,81 @@
"""Response shapes for the `/imports/sources/*` routes: previews with
auto-match suggestions, PDF table detection and region extraction, and
document extraction reports."""
from typing import Any
import pandas as pd
from webapi.imports.connectors import Connector, ConnectorError
from webapi.imports.connectors.document import DocumentConnector
from webapi.imports.connectors.pdf import PdfConnector, RegionSpec
from webapi.imports.connectors.tabular import columns_from_dataframe, rows_from_dataframe
from webapi.imports.mapping.column_matcher import ColumnMatcher
from webapi.imports.schemas.registry import ENTITY_REGISTRY
def suggest_mapping(source_columns: list[str], target_key: str | None) -> list[dict[str, Any]]:
if not target_key:
return []
spec = ENTITY_REGISTRY.get(target_key)
if spec is None:
raise ConnectorError(f"unknown target: {target_key!r}")
matches = ColumnMatcher().suggest(source_columns, list(spec.schema.model_fields.keys()))
return [
{"source_column": m.source_column, "target_field": m.target_field, "confidence": m.confidence, "reason": m.reason}
for m in matches
]
def preview_with_suggestions(connector: Connector, target_key: str | None, *, limit: int = 50) -> dict[str, Any]:
preview = connector.preview(limit=limit)
return {
"columns": [{"name": c.name, "inferred_type": c.inferred_type} for c in preview.columns],
"sample_rows": preview.sample_rows,
"total_rows": preview.total_rows,
"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(),
}
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."""
connector = PdfConnector(raw)
return {
"page_count": connector.page_count,
"has_text_layer": connector.has_text_layer(),
"table_candidates": [
{
"page_number": candidate.page_number,
"bbox": list(candidate.bbox),
"column_count": len(candidate.grid[0]) if candidate.grid else 0,
"row_count": len(candidate.grid) - 1 if candidate.grid else 0,
"preview_grid": candidate.grid,
}
for candidate in connector.detect_tables()
],
}
def extract_pdf_regions(raw: bytes, regions: list[dict[str, Any]], *, dpi: int = 150, target_key: str | None = None) -> dict[str, Any]:
connector = PdfConnector(raw)
resolved = connector.extract_regions([RegionSpec.parse(r) for r in regions], dpi=dpi)
df = pd.DataFrame(resolved, dtype=object)
columns = columns_from_dataframe(df)
return {
"columns": [{"name": c.name, "inferred_type": c.inferred_type} for c in columns],
"rows": rows_from_dataframe(df),
"warnings": [{"page_number": w.page_number, "message": w.message} for w in connector.warnings],
"suggested_mapping": suggest_mapping([c.name for c in columns], target_key),
}
def document_report(payload: dict[str, Any]) -> dict[str, Any]:
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()}
+82
View File
@@ -0,0 +1,82 @@
"""Fills a child row's foreign keys from the natural keys it carries, as
Core's column descriptions specify (e.g. `NotaMedica.pac_id` is looked up by
`pac_id_hospital`). This links rows that came from unrelated sources in the
same batch.
Links are derived from Core's columns: an entity with both `pac_id` and
`pac_id_hospital` links to its domain's `Paciente`, and one with both
`ord_id` and `ord_numero_hospital` links to its `OrdenesEstudio`. TEA uses
UUID keys without such pairs, so it gets no links.
"""
from dataclasses import dataclass
from functools import cache
from typing import Any
from sqlmodel import Session, select
from webapi.imports.schemas.registry import ENTITY_REGISTRY
@dataclass(frozen=True)
class ForeignKeyLink:
fk_field: str # on the child, e.g. "pac_id"
via_field: str # natural key on the child, e.g. "pac_id_hospital"
parent: str # registry key, e.g. "cacu.Paciente"
parent_key: str # natural key on the parent
parent_pk: str # primary key on the parent
# (fk column, natural-key column, parent entity name, parent primary key)
_CONVENTIONS = (
("pac_id", "pac_id_hospital", "Paciente", "pac_id"),
("ord_id", "ord_numero_hospital", "OrdenesEstudio", "ord_id"),
)
@cache
def links_for(target_key: str) -> tuple[ForeignKeyLink, ...]:
domain, _, name = target_key.partition(".")
columns = set(ENTITY_REGISTRY[target_key].model.__table__.columns.keys())
links = []
for fk_field, via_field, parent_name, parent_pk in _CONVENTIONS:
parent = f"{domain}.{parent_name}"
if name != parent_name and parent in ENTITY_REGISTRY and {fk_field, via_field} <= columns:
links.append(ForeignKeyLink(fk_field, via_field, parent, via_field, parent_pk))
return tuple(links)
@cache
def dependency_rank(target_key: str) -> int:
"""Write order within a batch: parents rank lower than their children, so
a child's lookup finds a parent written earlier in the same batch."""
return max((dependency_rank(link.parent) + 1 for link in links_for(target_key)), default=0)
class LinkResolver:
"""Looks up parent primary keys by natural key within the batch's session,
so parents written earlier in the same uncommitted transaction are found.
A missing parent leaves the FK null, which Core allows."""
def __init__(self, session: Session):
self._session = session
self._cache: dict[tuple[str, Any], Any] = {}
def resolve(self, target_key: str, row: dict[str, Any]) -> list[str]:
linked = []
for link in links_for(target_key):
value = row.get(link.via_field)
if row.get(link.fk_field) is not None or value is None:
continue
pk = self._lookup(link, value)
if pk is not None:
row[link.fk_field] = pk
linked.append(link.fk_field)
return linked
def _lookup(self, link: ForeignKeyLink, value: Any) -> Any:
cache_key = (link.parent, value)
if cache_key not in self._cache:
parent = ENTITY_REGISTRY[link.parent].model
statement = select(getattr(parent, link.parent_pk)).where(getattr(parent, link.parent_key) == value)
self._cache[cache_key] = self._session.exec(statement).first()
return self._cache[cache_key]