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
+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)