"""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 collections import Counter from itertools import islice from typing import Any, Iterator 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 from webapi.imports.services.review_learning import learn_from_reviews 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.""" class DatabaseRefused(ImportRequestError): """The database rejected the batch at write time; nothing was written.""" @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 derived: dict[str, Derivation] = field(default_factory=dict) documents: dict[str, Any] | None = None @classmethod def parse(cls, raw: Any) -> "ImportSource": if not isinstance(raw, dict): raise ImportRequestError("cada fuente debe ser un objeto") target = raw.get("target") if not target: raise ImportRequestError("a la fuente le falta 'target'") spec = ENTITY_REGISTRY.get(target) if spec is None: raise ImportRequestError(f"destino desconocido: {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' y 'defaults' deben ser objetos") unknown = sorted((set(mapping.values()) | set(defaults)) - fields) if unknown: raise ImportRequestError(f"{target} no tiene los campos {unknown}") 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}") 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") if not isinstance(payload, dict): raise ImportRequestError("a la fuente le falta 'payload'") return cls( source_type=raw.get("source_type", ""), target=target, spec=spec, column_mapping=mapping, defaults=defaults, payload=payload, label=raw.get("label"), derived=derived, documents=documents, ) @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 @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: 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: 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 yield row except ConnectorError as exc: raise ImportRequestError(str(exc)) from exc def validate(self) -> BatchValidationResult: 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()) 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 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: return source.validate() 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 @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' debe ser una lista no vacía") sources = [ImportSource.parse(raw) for raw in raw_sources] domains = sorted({source.domain for source in sources}) if len(domains) > 1: raise ImportRequestError( f"un lote no puede mezclar dominios ({', '.join(domains)}): todas las fuentes deben ir al mismo" ) 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 key is the string "5001" where a typed source gives the int 5001.""" if _is_blank(value): return None return str(value).strip().upper() def commit_sources( raw_sources: Any, *, on_conflict: str, merge: bool = False, audit: ImportAudit | None = None ) -> 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"on_conflict inválido: {on_conflict!r}") from exc sources = _parse_batch(raw_sources) tracked = [audit.source(source) for source in sources] if audit else [] 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)} no tiene llave natural: on_conflict=upsert no aplica") # 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)] for position, source_audit in enumerate(tracked): 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) 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 "conflicto", "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, []), ) if tracked: tracked[position].observe_write( created=write.created_count, updated=write.updated_count, conflicts=write.rejected_count, linked=linked, ) session.commit() except SQLAlchemyError as exc: session.rollback() detail = exc.orig if hasattr(exc, "orig") else exc raise DatabaseRefused( f"la base de datos rechazó el lote y no se escribió nada: {exc.__class__.__name__}: {detail}" ) from exc finally: session.close() learn_from_reviews(sources) return [results[i] for i in range(len(validated))]