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
+54 -12
View File
@@ -17,10 +17,14 @@ from webapi.imports.connectors.sql import SqlConnector
from webapi.imports.connectors.tabular import FileConnector
from webapi.imports.schemas.registry import ENTITY_REGISTRY
from webapi.imports.services.catalog_commit_service import commit_discovered_fields
from webapi.imports.mapping.derived import CASES, DERIVATIONS
from webapi.imports.services.import_service import (
DatabaseRefused,
ImportRequestError,
ImportSource,
commit_sources,
document_columns_preview,
mapped_sample,
serialize_errors,
validate_source,
)
@@ -30,6 +34,7 @@ from webapi.imports.services.introspection_service import (
document_report,
extract_pdf_regions,
preview_with_suggestions,
suggest_mapping,
)
imports_bp = Blueprint("imports", __name__)
@@ -253,12 +258,15 @@ def pdf_regions_extract():
def document_extract():
"""Reads the documents, splits them into patient records and extracts
the target's fields: `{files: [{name, file_base64}], target,
segmentation?, pages_per_record?, ocr_mode?, key_pattern?, overrides?}`.
`files` may be `sql` instead: `{connection details, table|query, column,
key_column}`, one document per row (a PDF or plain-text column).
segmentation?, pages_per_record?, ocr_mode?, key_pattern?, overrides?,
include_pattern?, exclude_pattern?}`. `files` may be `sql` instead (a
connection plus `table`/`query` and `DocumentColumns`' options), or the
whole body may be `{source}`, an import source with `documents`.
Each record comes back with per-field confidence and evidence, conflicts
between sources, and the images found on its pages."""
body = _json_body()
if body.get("source"):
return jsonify(document_report(body))
_require(body, "target")
if not body.get("files") and not body.get("sql"):
raise BadRequest("faltan los archivos")
@@ -284,6 +292,32 @@ def document_page_image():
# -- validate and load -------------------------------------------------------------------------
@imports_bp.get("/derivations")
def derivations():
"""The operations a source's `derived` fields may use, with their
parameters, so a client can build the form for each."""
return jsonify({"derivations": [cls.describe() for cls in DERIVATIONS.values()], "cases": list(CASES)})
@imports_bp.post("/mapped-preview")
def mapped_preview():
"""`{source, limit?}`: the source's first rows as they would be
written, with its mapping, derived fields and defaults applied."""
body = _json_body()
return jsonify({"rows": mapped_sample(_require(body, "source"), limit=min(int(body.get("limit", 20)), 200))})
@imports_bp.post("/sources/document/columns")
def document_columns_of_source():
"""`{source, target?}` for a source with `documents`: its own columns
plus every field and caption its documents print, as a preview the
mapping screen offers like any table's, with suggestions."""
body = _json_body()
preview = document_columns_preview(_require(body, "source"), limit=min(int(body.get("limit", 20)), 200))
target = body.get("target") or body["source"].get("target")
return jsonify({**preview, "suggested_mapping": suggest_mapping([c["name"] for c in preview["columns"]], target)})
@imports_bp.post("/validate")
def validate():
source = _require(_json_body(), "source")
@@ -308,15 +342,17 @@ def validate():
def _commit_catalog_fallback(raw_sources: list) -> list[dict]:
"""For every `document` source in the request (uploaded, or reading a
SQL column — same connector either way), writes the captions no known
field claimed straight into the silver layer (`catalog_commit_service`),
matched or minted against the project's catalog. Best-effort: the
structured fields already landed through `commit_sources`, so a failure
here is reported, not raised."""
"""For every source that asks for it (`catalog_fallback: true`) and
reads documents, writes the captions no known field claimed but the
project's catalog does know straight into the silver layer
(`catalog_commit_service`). Best-effort: the structured fields already
landed through `commit_sources`, so a failure here is reported, not
raised."""
reports = []
for raw in raw_sources:
if not isinstance(raw, dict) or raw.get("source_type") != "document":
if not isinstance(raw, dict) or raw.get("catalog_fallback") is not True:
continue
if raw.get("source_type") != "document" and not raw.get("documents"):
continue
target = raw.get("target") or ""
domain = target.split(".", 1)[0]
@@ -324,9 +360,14 @@ def _commit_catalog_fallback(raw_sources: list) -> list[dict]:
continue
payload = {**(raw.get("payload") or {}), "target": target}
try:
connector = build_connector("document", payload)
if raw.get("documents"):
connector, _, _ = ImportSource.parse(raw).document_connector()
if connector is None:
continue
else:
connector = build_connector("document", payload)
result = commit_discovered_fields(connector.records, proyecto=domain, estudio_id=payload.get("estudio_id"))
except (ConnectorError, ExtractionError, CatalogoInvalido, SQLAlchemyError) as exc:
except (ConnectorError, ExtractionError, CatalogoInvalido, SQLAlchemyError, ImportRequestError) as exc:
log.warning("catalog_fallback: %s no se pudo procesar: %s", raw.get("label") or target, exc)
continue
reports.append(
@@ -337,6 +378,7 @@ def _commit_catalog_fallback(raw_sources: list) -> list[dict]:
"records_without_patient": result.records_without_patient,
"fields_matched": result.fields_matched,
"fields_minted": result.fields_minted,
"fields_unmatched": result.fields_unmatched,
}
)
return reports
+33 -7
View File
@@ -15,6 +15,7 @@ from __future__ import annotations
import fcntl
import json
import logging
import os
import re
import time
@@ -23,7 +24,7 @@ from collections import Counter, defaultdict
from dataclasses import dataclass, field
from datetime import datetime, timezone
from pathlib import Path
from typing import TYPE_CHECKING, Any, Iterable
from typing import TYPE_CHECKING, Any, Callable, Iterable
from webapi.imports.schemas.classify import ErrorCategory
@@ -31,7 +32,11 @@ if TYPE_CHECKING:
from webapi.imports.schemas.service import BatchValidationResult
from webapi.imports.services.import_service import ImportSource
log = logging.getLogger(__name__)
SCHEMA_VERSION = 1
# Longest caption, in words, that document discovery reports.
CAPTION_MAX_WORDS = 6
_SHAPE_MAX = 40
_MESSAGE_MAX = 300
_QUOTED = re.compile(r"'[^']*'|\"[^\"]*\"")
@@ -57,11 +62,12 @@ def value_shape(value: Any) -> str:
return shape + ("…" if len(text) > _SHAPE_MAX else "")
def column_label(name: Any) -> str:
def column_label(name: Any, *, max_words: int = 4) -> str:
"""A source column name as it can be logged: verbatim when it looks like a
header, its shape when it looks like data."""
header, its shape when it looks like data. A document caption, already
cut at a colon, may run to more words (`max_words`) than a header."""
text = str(name).strip()
if len(text) > _SHAPE_MAX or text.count(" ") > 3 or _VALUE_LIKE.search(text):
if len(text) > _SHAPE_MAX or text.count(" ") >= max_words or _VALUE_LIKE.search(text):
return value_shape(text)
return text
@@ -128,9 +134,10 @@ class _SourceAudit:
self.rows: dict[str, Any] = {"leidas": 0}
self.links: dict[str, int] = {}
self.warnings: Counter = Counter()
self.captions: Counter = Counter()
def observe_rows(self, rows: Iterable[dict[str, Any] | None]) -> None:
mapped = set(self.source.column_mapping.values()) | set(self.source.defaults)
mapped = set(self.source.column_mapping.values()) | set(self.source.derived) | set(self.source.defaults)
merged = 0
for row in rows:
self.rows["leidas"] += 1
@@ -164,6 +171,15 @@ class _SourceAudit:
self.rows.update(insertadas=created, actualizadas=updated, rechazadas_por_conflicto=conflicts)
self.links = dict(linked)
def observe_captions(self, count: Callable[[], Counter]) -> None:
"""Captions the source's documents print that the import didn't
use (`ImportSource.unused_captions`). Best-effort: the report must
never be what makes an import fail."""
try:
self.captions = Counter(count())
except Exception:
log.warning("no se pudieron contar las etiquetas sin usar de %s", self.source.target, exc_info=True)
def observe_warnings(self, warnings: Iterable[dict[str, Any]]) -> None:
for warning in warnings:
self.warnings[f"{warning.get('category')}:{warning.get('field')}"] += 1
@@ -171,13 +187,14 @@ class _SourceAudit:
def as_dict(self, threshold: int) -> dict[str, Any]:
spec_fields = self.source.spec.schema.model_fields
required = {name for name, info in spec_fields.items() if info.is_required()}
mapped = set(self.source.column_mapping.values())
mapped = set(self.source.column_mapping.values()) | set(self.source.derived)
fixed = set(self.source.defaults)
out: dict[str, Any] = {
"destino": self.source.target,
"origen": _source_origin(self.source),
"mapeo": {
"columnas_origen": sorted(column_label(c) for c in self.source.column_mapping),
"columnas_origen": sorted(column_label(c) for c in self.source.source_columns),
"campos_derivados": {name: rule.op for name, rule in sorted(self.source.derived.items())},
"campos_mapeados": sorted(mapped),
"campos_con_valor_fijo": sorted(fixed),
"campos_sin_mapear": sorted(set(spec_fields) - mapped - fixed),
@@ -190,6 +207,15 @@ class _SourceAudit:
out["vinculos_resueltos"] = self.links
if self.warnings:
out["advertencias"] = dict(self.warnings)
if self.captions:
# Captions only, and only those enough records print: a caption
# seen once or twice can be a misread line holding a value.
out["etiquetas_sin_usar"] = {
column_label(c, max_words=CAPTION_MAX_WORDS): n for c, n in self.captions.most_common() if n >= threshold
}
rare = sum(1 for n in self.captions.values() if n < threshold)
if rare:
out["etiquetas_sin_usar_poco_frecuentes"] = rare
return out
+151 -59
View File
@@ -1,8 +1,10 @@
import hashlib
import json
import re
import threading
import unicodedata
from collections import OrderedDict
from typing import Any, ClassVar
from typing import Any, ClassVar, Iterator
import pandas as pd
@@ -10,6 +12,7 @@ from extraction import DocumentExtractor, ExtractedRecord, ExtractionError, make
from extraction.readers import PdfReader, combine_pages, supported_extensions
from extraction.segmentation import SEGMENTERS
from webapi.imports.connectors.base import decode_file
from webapi.imports.connectors.document_columns import DocumentBatch, DocumentColumns, document_bytes # noqa: F401
from webapi.imports.connectors.errors import ConnectorError
from webapi.imports.connectors.registry import register_connector
from webapi.imports.connectors.sql import SqlConnector
@@ -29,11 +32,11 @@ class _ResultCache:
per worker for the last few distinct requests."""
def __init__(self, size: int = 8):
self._items: OrderedDict[str, list[ExtractedRecord]] = OrderedDict()
self._items: OrderedDict[str, Any] = OrderedDict()
self._size = size
self._lock = threading.Lock()
def get_or_compute(self, key: str, compute) -> list[ExtractedRecord]:
def get_or_compute(self, key: str, compute) -> Any:
with self._lock:
if key in self._items:
self._items.move_to_end(key)
@@ -49,49 +52,19 @@ class _ResultCache:
_CACHE = _ResultCache()
def _files_from_sql(sql: dict[str, Any]) -> tuple[list[tuple[str, bytes]], dict[str, dict[str, Any]]]:
"""One `(name, bytes)` per row of a SQL source (connected the same way
`SqlConnector` is): `column` is the field bundle (a `varbinary(max)`
PDF, or already a plain string — `read_document` reads either),
`key_column` names the row (a patient or study id) for tracing, and the
optional `fields` (`{target_field: sql_column}`) carries other columns
through as that row's authoritative values — a source's own patient or
study id, trusted over whatever the document's text happens to say.
Any column type `SqlConnector` can read works; it's not limited to PDFs.
Returns the files alongside, per row name, the `fields` values read for
it (`DocumentExtractor.extract`'s `source_fields`)."""
column = sql.get("column")
if not column:
raise ConnectorError("falta column")
if not sql.get("query") and not sql.get("table"):
def _files_from_sql(sql: dict[str, Any]) -> DocumentBatch:
"""The documents of a SQL table or query (connected the same way
`SqlConnector` is), read as `DocumentColumns` describes: `column` or
`columns` hold them, and `key_column`/`name_by`, `group_column`/
`group_by` and `fields` name, group and carry values for them."""
if not sql.get("table") and not sql.get("query"):
raise ConnectorError("falta table o query")
key_column = sql.get("key_column") or column
if key_column == column:
raise ConnectorError("key_column debe ser distinta de column")
fields: dict[str, str] = sql.get("fields") or {}
mapping = {column: "contenido", key_column: "clave"}
for field_name, sql_column in fields.items():
if sql_column in mapping:
raise ConnectorError(f"la columna {sql_column!r} ya está asignada a otro papel en fields/column/key_column")
mapping[sql_column] = field_name
spec = DocumentColumns.parse(sql)
connector = SqlConnector.connect(sql)
connector = (
connector.select_query(sql["query"]) if sql.get("query") else connector.select_table(sql["table"], schema=sql.get("schema"))
)
files = []
source_fields: dict[str, dict[str, Any]] = {}
for row in connector.read_rows(mapping):
raw = row.get("contenido")
if raw is None:
continue
name = str(row.get("clave", len(files) + 1))
files.append((name, raw if isinstance(raw, bytes) else str(raw).encode("utf-8")))
if fields:
source_fields[name] = {field_name: row.get(field_name) for field_name in fields if row.get(field_name) is not None}
return files, source_fields
return spec.assemble(connector.read_rows({column: column for column in spec.source_columns()}))
@register_connector
@@ -138,6 +111,9 @@ class DocumentConnector(DataFrameConnector):
key_pattern: str | None = None,
overrides: dict[str, dict[str, Any]] | None = None,
source_fields: dict[str, dict[str, Any]] | None = None,
record_keys: dict[str, str] | None = None,
include_pattern: str | None = None,
exclude_pattern: str | None = None,
):
if not files:
raise ConnectorError("no se recibieron documentos")
@@ -158,6 +134,10 @@ class DocumentConnector(DataFrameConnector):
self.key_pattern = key_pattern
self.overrides = {str(k): v for k, v in (overrides or {}).items()}
self.source_fields = {str(k): v for k, v in (source_fields or {}).items()}
self.record_keys = {str(k): str(v) for k, v in (record_keys or {}).items()}
self.include_pattern = _compile_filter(include_pattern, "include_pattern")
self.exclude_pattern = _compile_filter(exclude_pattern, "exclude_pattern")
self.skipped: list[dict[str, str]] = []
known = {spec.name for spec in self.specs}
unknown = sorted({name for values in self.source_fields.values() for name in values} - known)
if unknown:
@@ -167,21 +147,23 @@ class DocumentConnector(DataFrameConnector):
@classmethod
def from_payload(cls, payload: dict[str, Any]) -> "DocumentConnector":
if payload.get("sql"):
files, source_fields = _files_from_sql(payload["sql"])
documents = _files_from_sql(payload["sql"])
else:
files = [
(f.get("name") or f"documento_{i}", decode_file(f)) for i, f in enumerate(payload.get("files") or [], 1)
]
source_fields = {}
documents = DocumentBatch(
files=[(f.get("name") or f"documento_{i}", decode_file(f)) for i, f in enumerate(payload.get("files") or [], 1)]
)
return cls(
files,
documents.files,
target=payload["target"],
segmentation=payload.get("segmentation", "auto"),
pages_per_record=payload.get("pages_per_record", 1),
ocr_mode=payload.get("ocr_mode", "auto"),
key_pattern=payload.get("key_pattern") or None,
overrides=payload.get("overrides"),
source_fields=source_fields,
source_fields=documents.source_fields,
record_keys=documents.record_keys,
include_pattern=payload.get("include_pattern") or None,
exclude_pattern=payload.get("exclude_pattern") or None,
)
@classmethod
@@ -193,28 +175,65 @@ class DocumentConnector(DataFrameConnector):
@property
def records(self) -> list[ExtractedRecord]:
return _CACHE.get_or_compute(self._cache_key(), self._extract)
records, self.skipped = _CACHE.get_or_compute(self._cache_key(), self._extract)
return records
def _extract(self) -> list[ExtractedRecord]:
try:
documents = [read_document(name, raw, ocr_mode=self.ocr_mode) for name, raw in self.files]
except ExtractionError as exc:
raise ConnectorError(str(exc)) from exc
def _extract(self) -> tuple[list[ExtractedRecord], list[dict[str, str]]]:
documents, skipped = [], []
for name, raw in self.files:
try:
document = read_document(name, raw, ocr_mode=self.ocr_mode)
except ExtractionError as exc:
skipped.append({"document": name, "reason": f"ilegible: {exc}"})
continue
reason = self._filtered_out(document)
if reason:
skipped.append({"document": name, "reason": reason})
continue
documents.append(document)
if not documents:
detail = "; ".join(f"{s['document']}: {s['reason']}" for s in skipped[:5])
raise ConnectorError(f"ningún documento se pudo usar ({detail})")
segmenter = make_segmenter(
self.segmentation,
key=next((s for s in self.specs if s.name == self.key_field), None),
pages_per_record=self.pages_per_record,
)
return DocumentExtractor(self.specs, key_field=self.key_field, segmenter=segmenter).extract(
documents, source_fields=self.source_fields
records = DocumentExtractor(self.specs, key_field=self.key_field, segmenter=segmenter).extract(
documents, source_fields=self.source_fields, record_keys=self.record_keys
)
return records, skipped
def _filtered_out(self, document) -> str | None:
"""Why a document is left out by `include_pattern`/`exclude_pattern`,
matched case- and accent-insensitively against all of its text,
so a source mixing several kinds of report feeds each target only
its own."""
text = "\n".join(page.text for page in document.pages)
plain = _unaccented(text)
if self.include_pattern and not (self.include_pattern.search(text) or self.include_pattern.search(plain)):
return "no coincide con include_pattern"
if self.exclude_pattern and (self.exclude_pattern.search(text) or self.exclude_pattern.search(plain)):
return "coincide con exclude_pattern"
return None
def _cache_key(self) -> str:
digest = hashlib.sha256()
for name, raw in self.files:
digest.update(name.encode())
digest.update(hashlib.sha256(raw).digest())
config = [self.target, self.segmentation, self.pages_per_record, self.ocr_mode, self.key_pattern, self.source_fields]
config = [
self.target,
self.segmentation,
self.pages_per_record,
self.ocr_mode,
self.key_pattern,
self.source_fields,
self.record_keys,
self.include_pattern.pattern if self.include_pattern else None,
self.exclude_pattern.pattern if self.exclude_pattern else None,
]
digest.update(json.dumps(config, sort_keys=True, default=str).encode())
return digest.hexdigest()
@@ -222,13 +241,40 @@ class DocumentConnector(DataFrameConnector):
def _dataframe(self) -> pd.DataFrame:
if self._df is None:
columns = [spec.name for spec in self.specs] + [DOCUMENT_COLUMN, IMAGE_COLUMN, CONFIDENCE_COLUMN, SOURCES_COLUMN]
columns = (
[spec.name for spec in self.specs]
+ self.caption_columns()
+ [DOCUMENT_COLUMN, IMAGE_COLUMN, CONFIDENCE_COLUMN, SOURCES_COLUMN]
)
rows = [self._row(index, record) for index, record in enumerate(self.records)]
self._df = pd.DataFrame(rows, columns=columns, dtype=object)
return self._df
def caption_columns(self) -> list[str]:
"""Every caption the documents print that no field of the target
claims, in the order first seen: columns of their own, mappable
and usable in derived fields like any column of a table."""
reserved = {spec.name for spec in self.specs} | {DOCUMENT_COLUMN, IMAGE_COLUMN, CONFIDENCE_COLUMN, SOURCES_COLUMN}
columns: list[str] = []
for record in self.records:
for found in record.discovered:
name = _caption_column(found.caption, reserved)
if name not in columns:
columns.append(name)
return columns
def record_rows(self) -> Iterator[tuple[dict[str, Any], list[str]]]:
"""Each record's row (overrides applied, its captions as columns,
its pages as `documento`) with the names of the documents it was
read from."""
for index, record in enumerate(self.records):
yield self._row(index, record), [source.document for source in record.sources]
def _row(self, index: int, record: ExtractedRecord) -> dict[str, Any]:
row: dict[str, Any] = record.row()
reserved = {spec.name for spec in self.specs} | {DOCUMENT_COLUMN, IMAGE_COLUMN, CONFIDENCE_COLUMN, SOURCES_COLUMN}
for found in record.discovered:
row.setdefault(_caption_column(found.caption, reserved), found.value)
row.update(self.overrides.get(str(index), {}))
row[DOCUMENT_COLUMN] = self._record_pdf(record)
row[IMAGE_COLUMN] = self._record_image(record)
@@ -295,4 +341,50 @@ class DocumentConnector(DataFrameConnector):
return report
def metadata(self) -> dict[str, Any]:
return {"records": len(self.records), "key_field": self.key_field, "documents": [name for name, _ in self.files]}
return {
"records": len(self.records),
"key_field": self.key_field,
"documents": [name for name, _ in self.files],
"skipped": self.skipped,
}
def _caption_column(caption: str, reserved: set[str]) -> str:
"""A discovered caption as a column name, kept apart from the target's
own fields and the connector's bookkeeping columns."""
name = " ".join(caption.split())
return f"texto: {name}" if name in reserved else name
def _compile_filter(pattern: str | None, name: str) -> re.Pattern | None:
if not pattern:
return None
try:
return re.compile(pattern, re.I)
except re.error as exc:
raise ConnectorError(f"{name} no es una expresión regular válida: {exc}") from exc
def _unaccented(text: str) -> str:
return "".join(ch for ch in unicodedata.normalize("NFKD", text) if not unicodedata.combining(ch))
DOCUMENT_OPTIONS = ("segmentation", "pages_per_record", "ocr_mode", "key_pattern", "overrides", "include_pattern", "exclude_pattern")
def document_options(raw: dict[str, Any]) -> dict[str, Any]:
"""The extraction settings `DocumentConnector` takes, out of a request."""
return {name: raw[name] for name in DOCUMENT_OPTIONS if raw.get(name) not in (None, "")}
def connector_for_batch(batch: DocumentBatch, target: str, options: dict[str, Any]) -> "DocumentConnector":
"""A `DocumentConnector` over documents read from a source's columns,
their row values restricted to the fields extraction knows."""
entity = ENTITY_REGISTRY.get(target)
if entity is None:
raise ConnectorError(f"destino desconocido: {target!r}")
known = {spec.name for spec in field_specs_for(entity)}
source_fields = {name: {k: v for k, v in values.items() if k in known} for name, values in batch.source_fields.items()}
return DocumentConnector(
batch.files, target=target, source_fields=source_fields, record_keys=batch.record_keys, **document_options(options)
)
@@ -0,0 +1,167 @@
"""Documents stored in the columns of any tabular source: a SQL table or
query, a CSV or Excel sheet, a JSON list. Each non-empty cell of a document
column becomes one document; the rest of its row travels with it as values
the extraction must trust over the page, and an optional grouping decides
which documents form one record.
A cell may hold the file itself (binary), the same file written as hex or
base64 text, or plain text; `document_bytes` tells them apart.
"""
import base64
import binascii
import re
from dataclasses import dataclass, field
from typing import Any, Iterable
from webapi.imports.connectors.errors import ConnectorError
from webapi.imports.mapping.derived import Derivation, rule_from
_HEX = re.compile(r"^(?:0x)?(?:[0-9a-fA-F]{2})+$")
_BASE64 = re.compile(r"^[A-Za-z0-9+/\r\n]+={0,2}$")
DOCUMENT_MAGIC = (b"%PDF", b"\x89PNG", b"\xff\xd8\xff", b"II*\x00", b"MM\x00*", b"BM", b"RIFF", b"GIF8")
def document_bytes(raw: Any) -> bytes:
"""A stored document as bytes. Binary values pass through; text is
checked for a binary file written out as hex or base64 before being
taken as plain UTF-8 text."""
if isinstance(raw, memoryview):
raw = raw.tobytes()
if isinstance(raw, (bytes, bytearray)):
return bytes(raw)
text = str(raw).strip()
if len(text) >= 16 and _HEX.match(text):
decoded = bytes.fromhex(text[2:] if text[:2].lower() == "0x" else text)
if decoded.startswith(DOCUMENT_MAGIC):
return decoded
if len(text) >= 16 and _BASE64.match(text):
try:
decoded = base64.b64decode(text, validate=False)
except (binascii.Error, ValueError):
decoded = b""
if decoded.startswith(DOCUMENT_MAGIC):
return decoded
return text.encode("utf-8")
def is_document(raw: Any) -> bool:
"""Whether a cell holds a file a document reader opens (as opposed to
a plain value), whatever way it was stored."""
if raw is None or isinstance(raw, (int, float, bool)):
return False
return document_bytes(raw).startswith(DOCUMENT_MAGIC)
@dataclass
class DocumentBatch:
"""What the extractor receives: one `(name, bytes)` per document and,
per document name, its authoritative values and the record it joins.
`rows` and `row_numbers` keep, per document name, the values of the row
it came from and that row's position (from 1)."""
files: list[tuple[str, bytes]] = field(default_factory=list)
source_fields: dict[str, dict[str, Any]] = field(default_factory=dict)
record_keys: dict[str, str] = field(default_factory=dict)
rows: dict[str, dict[str, Any]] = field(default_factory=dict)
row_numbers: dict[str, int] = field(default_factory=dict)
without_documents: list[dict[str, Any]] = field(default_factory=list)
@dataclass
class DocumentColumns:
"""How to read documents out of a source's rows.
`columns`: the columns holding documents (one or several per row).
`name_by`: names each row in reports (default: its row number).
`group_by`: rows giving the same value form one record, apart from
the same patient's other rows; without it, documents merge by the
target's key field, as uploaded files do.
`fields`: target fields filled from the row, trusted over the page.
The last three take a column name, a list of columns or a `derived`
rule (`webapi.imports.mapping.derived`)."""
columns: list[str]
name_by: Derivation | None = None
group_by: Derivation | None = None
fields: dict[str, Derivation] = field(default_factory=dict)
@classmethod
def parse(cls, raw: Any) -> "DocumentColumns":
if not isinstance(raw, dict):
raise ConnectorError("'documents' debe ser un objeto")
columns = raw.get("columns", raw.get("column"))
columns = [columns] if isinstance(columns, str) else list(columns or [])
if not columns or not all(isinstance(column, str) and column for column in columns):
raise ConnectorError("indique la columna (o columnas) con los documentos")
fields = raw.get("fields") or {}
if not isinstance(fields, dict):
raise ConnectorError("'fields' debe ser un objeto {campo: columna o regla}")
name_by = raw.get("name_by", raw.get("key_column"))
group_by = raw.get("group_by", raw.get("group_column"))
parsed = cls(
columns=columns,
name_by=rule_from(name_by) if name_by else None,
group_by=rule_from(group_by) if group_by else None,
fields={name: rule_from(rule, separator=" ") for name, rule in fields.items()},
)
roles = {"name_by (key_column)": [parsed.name_by], "group_by (group_column)": [parsed.group_by], "fields": list(parsed.fields.values())}
for role, rules in roles.items():
reused = set().union(*(rule.columns() for rule in rules if rule is not None)) & set(columns)
if reused:
raise ConnectorError(f"{sorted(reused)} contiene los documentos; no puede usarse también en {role}")
return parsed
def columns_read_by_rules(self) -> set[str]:
read: set[str] = set()
for rule in [self.name_by, self.group_by, *self.fields.values()]:
if rule is not None:
read |= rule.columns()
return read
def source_columns(self) -> set[str]:
return set(self.columns) | self.columns_read_by_rules()
def assemble(
self, raw_rows: Iterable[dict[str, Any]], mapped_rows: Iterable[dict[str, Any]] | None = None
) -> DocumentBatch:
"""`raw_rows` keyed by source column; `mapped_rows`, when the source
also has a mapping, the same rows already mapped to target fields,
whose values join `fields` as values to trust."""
batch = DocumentBatch()
seen: dict[str, int] = {}
mapped = iter(mapped_rows) if mapped_rows is not None else None
for number, raw in enumerate(raw_rows, start=1):
values = dict(next(mapped)) if mapped is not None else {}
values.update({name: rule.apply(raw) for name, rule in self.fields.items()})
values = {name: value for name, value in values.items() if not _blank(value)}
contents = [(column, raw.get(column)) for column in self.columns if not _blank(raw.get(column))]
if not contents:
batch.without_documents.append(values)
continue
base = _text(self.name_by.apply(raw)) if self.name_by else ""
base = base or str(number)
group = _text(self.group_by.apply(raw)) if self.group_by else ""
for column, content in contents:
name = base if len(self.columns) == 1 else f"{base}:{column}"
seen[name] = seen.get(name, 0) + 1
if seen[name] > 1:
name = f"{name}#{seen[name]}"
batch.files.append((name, document_bytes(content)))
batch.source_fields[name] = values
batch.rows[name] = values
batch.row_numbers[name] = number
if group:
batch.record_keys[name] = group
return batch
def _blank(value: Any) -> bool:
return value is None or (isinstance(value, str) and not value.strip())
def _text(value: Any) -> str:
if value is None:
return ""
if isinstance(value, float) and value.is_integer():
value = int(value)
return str(value).strip()
+35 -5
View File
@@ -7,12 +7,13 @@ from typing import Any, ClassVar, Iterator
import pandas as pd
import sqlalchemy as sa
import sqlglot
from sqlalchemy.pool import NullPool
from webapi.imports.connectors.base import Connector, PreviewResult, SourceColumn
from webapi.imports.connectors.errors import ConnectorError
from webapi.imports.connectors.registry import register_connector
from webapi.imports.connectors.sql_policy import SqlSourcePolicy
from webapi.imports.connectors.sql_policy import SQLGLOT_DIALECTS, SqlSourcePolicy
from webapi.imports.connectors.tabular import infer_type
@@ -222,7 +223,7 @@ class SqlConnector(Connector):
if self._table is not None:
return sa.select(self._table).subquery("source")
if self._query:
return _text_subquery(self._query)
return _text_subquery(self._query, self.get_dialect())
raise ConnectorError("no hay tabla ni consulta seleccionada")
def _columns(self, names: list[str], rows: list[dict[str, Any]]) -> list[SourceColumn]:
@@ -258,11 +259,11 @@ _ADDRESS_PORT_SEPARATORS = (",", ":")
def _parse_server_address(raw: str) -> tuple[str, str | None, int | None]:
"""Tolerates the ways a server address arrives typed or pasted from
SSMS, a JDBC string or a connection URI instead of a bare host: a
a SQL client, a JDBC string or a connection URI instead of a bare host: a
leading scheme (`jdbc:sqlserver://`, `postgresql://`, `tcp:`), a
trailing path/query/property list, surrounding whitespace, a SQL
Server named instance (`host\\instance`), and a port given as
`host:port` or the SSMS convention `host,port` / `host\\instance,port`.
`host:port` or SQL Server's `host,port` / `host\\instance,port`.
Returns `(host, instance, port)`, with `instance` and `port` `None`
when absent, so the caller can leave the port unset for a named
@@ -298,12 +299,41 @@ def _parse_server_address(raw: str) -> tuple[str, str | None, int | None]:
return host, (instance or None), port
def _text_subquery(query: str) -> sa.Subquery:
def _text_subquery(query: str, dialect: str | None = None) -> sa.Subquery:
"""Wraps policy-checked SELECT text as a derived table, so SQLAlchemy
composes LIMIT/TOP and COUNT(*) for whichever dialect the source speaks."""
query = _without_trailing_order_by(query, dialect)
return sa.select(sa.literal_column("*")).select_from(sa.text(f"({query}) AS source_query")).subquery("source")
_ORDER_BY = re.compile(r"\bORDER\s+BY\b", re.I)
def _without_trailing_order_by(query: str, dialect: str | None) -> str:
"""Drops a top-level `ORDER BY` that nothing limits: SQL Server refuses
one inside a derived table, and row order means nothing to an import.
Kept when TOP, LIMIT or OFFSET makes it choose the rows."""
try:
[root] = sqlglot.parse(query, read=SQLGLOT_DIALECTS.get(dialect, dialect))
except Exception:
return query
if root is None or not root.args.get("order") or root.args.get("limit") or root.args.get("offset"):
return query
depth, quote, cut = 0, None, None
for position, char in enumerate(query):
if quote:
quote = None if char == quote else quote
elif char in "'\"[`":
quote = "]" if char == "[" else char
elif char == "(":
depth += 1
elif char == ")":
depth -= 1
elif depth == 0 and _ORDER_BY.match(query, position):
cut = position
return query[:cut].rstrip() if cut is not None else query
def _sa_type_to_kind(sa_type: sa.types.TypeEngine) -> str:
try:
python_type = sa_type.python_type
+2 -2
View File
@@ -22,7 +22,7 @@ from webapi.imports.connectors.errors import ConnectorError
_DEFAULT_DIALECTS = "mysql,mariadb,postgresql,mssql"
_DEFAULT_PORTS = {"mysql": 3306, "mariadb": 3306, "postgresql": 5432, "mssql": 1433}
# SQLAlchemy dialect name -> sqlglot's name for it, where they differ.
_SQLGLOT_DIALECTS = {"postgresql": "postgres", "mssql": "tsql", "mariadb": "mysql"}
SQLGLOT_DIALECTS = {"postgresql": "postgres", "mssql": "tsql", "mariadb": "mysql"}
# Anything that writes, wherever it sits in the tree: a top-level
# `SELECT ... INTO table`/`INTO OUTFILE`, or a writable CTE
# (`WITH t AS (DELETE FROM x RETURNING *) SELECT * FROM t` still parses as a
@@ -73,7 +73,7 @@ class SqlSourcePolicy:
if not statement:
raise ConnectorError("la consulta no puede estar vacía")
try:
parsed = [node for node in sqlglot.parse(statement, read=_SQLGLOT_DIALECTS.get(dialect, dialect)) if node is not None]
parsed = [node for node in sqlglot.parse(statement, read=SQLGLOT_DIALECTS.get(dialect, dialect)) if node is not None]
except sqlglot.errors.ParseError as exc:
raise ConnectorError(f"la consulta no es SQL válido: {exc}") from exc
if len(parsed) != 1:
+305
View File
@@ -0,0 +1,305 @@
"""Target fields computed from one or more source columns, for sources whose
columns don't line up one-to-one with the target: a name and surnames kept
apart where the target wants one full name, or the reverse; an id spread
over two columns; a code that must be read out of a longer text.
A source's `derived` maps each target field to one rule,
`{"op": <name>, ...params}`, plus the optional `case` (`upper`, `lower`,
`title`) applied to the result. To add an operation, subclass `Derivation`,
declare its `params` and register it with `@register_derivation`.
"""
import re
import string
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Any, ClassVar
from webapi.imports.connectors.errors import ConnectorError
@dataclass(frozen=True)
class Param:
"""One parameter of an operation, described so a client can build its form."""
name: str
kind: str # column | columns | text | integer | mapping | boolean
label: str
required: bool = True
default: Any = None
def to_dict(self) -> dict[str, Any]:
return {"name": self.name, "kind": self.kind, "label": self.label, "required": self.required, "default": self.default}
CASES = {"upper": str.upper, "lower": str.lower, "title": str.title}
class Derivation(ABC):
op: ClassVar[str]
label: ClassVar[str]
description: ClassVar[str]
params: ClassVar[tuple[Param, ...]]
def __init__(self, rule: dict[str, Any]):
self.args: dict[str, Any] = {}
for param in self.params:
value = rule.get(param.name, param.default)
if param.required and _blank(value):
raise ConnectorError(f"la regla {self.op!r} requiere {param.name!r}")
if param.kind == "columns" and value is not None and not isinstance(value, list):
raise ConnectorError(f"{param.name!r} debe ser una lista de columnas")
self.args[param.name] = value
self.case = rule.get("case") or None
if self.case is not None and self.case not in CASES:
raise ConnectorError(f"case desconocido {self.case!r} (disponibles: {', '.join(CASES)})")
@abstractmethod
def columns(self) -> set[str]:
"""The source columns this rule reads."""
@abstractmethod
def compute(self, row: dict[str, Any]) -> Any: ...
def apply(self, row: dict[str, Any]) -> Any:
value = self.compute(row)
if isinstance(value, str):
value = " ".join(value.split())
if self.case:
value = CASES[self.case](value)
return value or None
return value
@classmethod
def describe(cls) -> dict[str, Any]:
return {
"op": cls.op,
"label": cls.label,
"description": cls.description,
"params": [param.to_dict() for param in cls.params],
}
DERIVATIONS: dict[str, type[Derivation]] = {}
def register_derivation(cls: type[Derivation]) -> type[Derivation]:
DERIVATIONS[cls.op] = cls
return cls
def build_derivation(rule: Any) -> Derivation:
if not isinstance(rule, dict):
raise ConnectorError("cada regla de 'derived' debe ser un objeto")
cls = DERIVATIONS.get(rule.get("op", ""))
if cls is None:
raise ConnectorError(f"operación desconocida {rule.get('op')!r} (disponibles: {', '.join(DERIVATIONS)})")
return cls(rule)
def _blank(value: Any) -> bool:
return value is None or (isinstance(value, str) and not value.strip()) or value == [] or value == {}
def _index(value: Any) -> int | None:
if value in (None, ""):
return None
try:
return int(value)
except (TypeError, ValueError) as exc:
raise ConnectorError(f"se esperaba un número entero, no {value!r}") from exc
def _text(value: Any) -> str:
if value is None:
return ""
if isinstance(value, float) and value.is_integer():
value = int(value)
return str(value).strip()
@register_derivation
class Column(Derivation):
op = "column"
label = "Columna"
description = "El valor de una columna, tal cual."
params = (Param("column", "column", "Columna"),)
def columns(self) -> set[str]:
return {self.args["column"]}
def compute(self, row: dict[str, Any]) -> Any:
return row.get(self.args["column"])
@register_derivation
class Concat(Derivation):
op = "concat"
label = "Unir columnas"
description = "Une los valores no vacíos de varias columnas, en orden, con un separador."
params = (
Param("columns", "columns", "Columnas"),
Param("separator", "text", "Separador", required=False, default=" "),
)
def columns(self) -> set[str]:
return set(self.args["columns"])
def compute(self, row: dict[str, Any]) -> Any:
parts = [_text(row.get(column)) for column in self.args["columns"]]
separator = self.args["separator"] if self.args["separator"] is not None else " "
return separator.join(part for part in parts if part)
@register_derivation
class Template(Derivation):
op = "template"
label = "Plantilla"
description = "Arma un texto con columnas entre llaves: `{Nombre} {Apellido}`. Las columnas vacías se omiten."
params = (Param("template", "text", "Plantilla"),)
def __init__(self, rule: dict[str, Any]):
super().__init__(rule)
try:
self._names = [name for _, name, _, _ in string.Formatter().parse(self.args["template"]) if name]
except ValueError as exc:
raise ConnectorError(f"plantilla inválida: {exc}") from exc
def columns(self) -> set[str]:
return set(self._names)
def compute(self, row: dict[str, Any]) -> Any:
values = {name: _text(row.get(name)) for name in self._names}
return string.Formatter().vformat(self.args["template"], (), _Fill(values))
class _Fill(dict):
def __missing__(self, key: str) -> str:
return ""
@register_derivation
class Split(Derivation):
op = "split"
label = "Tomar partes"
description = (
"Separa el valor de una columna y toma las partes de `start` a `stop` "
"(se cuentan desde 0; negativas desde el final): de un nombre completo, "
"el primer apellido es `start=-2, stop=-1`."
)
params = (
Param("column", "column", "Columna"),
Param("separator", "text", "Separador (vacío: espacios)", required=False, default=""),
Param("start", "integer", "Desde", required=False, default=0),
Param("stop", "integer", "Hasta (sin incluir)", required=False, default=None),
)
def columns(self) -> set[str]:
return {self.args["column"]}
def compute(self, row: dict[str, Any]) -> Any:
text = _text(row.get(self.args["column"]))
if not text:
return None
separator = self.args["separator"] or None
parts = text.split(separator) if separator else text.split()
start, stop = (_index(self.args[name]) for name in ("start", "stop"))
return (separator or " ").join(part.strip() for part in parts[start:stop] if part.strip())
@register_derivation
class Coalesce(Derivation):
op = "coalesce"
label = "Primera con valor"
description = "El valor de la primera columna, en orden, que no esté vacía."
params = (Param("columns", "columns", "Columnas"),)
def columns(self) -> set[str]:
return set(self.args["columns"])
def compute(self, row: dict[str, Any]) -> Any:
for column in self.args["columns"]:
value = row.get(column)
if not _blank(value):
return value
return None
@register_derivation
class Extract(Derivation):
op = "extract"
label = "Extraer con patrón"
description = "La parte del valor que coincide con una expresión regular (o su grupo `group`)."
params = (
Param("column", "column", "Columna"),
Param("pattern", "text", "Expresión regular"),
Param("group", "integer", "Grupo", required=False, default=0),
)
def __init__(self, rule: dict[str, Any]):
super().__init__(rule)
try:
self._regex = re.compile(self.args["pattern"], re.I)
except re.error as exc:
raise ConnectorError(f"expresión regular inválida: {exc}") from exc
def columns(self) -> set[str]:
return {self.args["column"]}
def compute(self, row: dict[str, Any]) -> Any:
match = self._regex.search(_text(row.get(self.args["column"])))
if not match:
return None
try:
return match.group(_index(self.args["group"]) or 0)
except IndexError as exc:
raise ConnectorError(f"la expresión no tiene el grupo {self.args['group']}") from exc
@register_derivation
class Translate(Derivation):
op = "map"
label = "Traducir valores"
description = "Cambia cada valor por otro según una tabla (`M` → `Masculino`), sin distinguir mayúsculas ni espacios."
params = (
Param("column", "column", "Columna"),
Param("values", "mapping", "Tabla de valores"),
Param("keep_unmatched", "boolean", "Conservar los que no estén en la tabla", required=False, default=True),
)
def __init__(self, rule: dict[str, Any]):
super().__init__(rule)
if not isinstance(self.args["values"], dict):
raise ConnectorError("'values' debe ser un objeto")
self._table = {_text(key).casefold(): value for key, value in self.args["values"].items()}
def columns(self) -> set[str]:
return {self.args["column"]}
def compute(self, row: dict[str, Any]) -> Any:
value = row.get(self.args["column"])
key = _text(value).casefold()
if key in self._table:
return self._table[key]
return value if self.args["keep_unmatched"] is not False else None
def rule_from(value: Any, *, separator: str = " | ") -> Derivation:
"""A rule given in short form: a column name, a list of columns (joined
with `separator`) or a full rule object."""
if isinstance(value, str):
return Column({"column": value})
if isinstance(value, list):
return Concat({"columns": value, "separator": separator})
return build_derivation(value)
def parse_derived(raw: Any, fields: set[str]) -> dict[str, Derivation]:
"""`{target_field: rule}` validated against the target's fields."""
if raw in (None, {}):
return {}
if not isinstance(raw, dict):
raise ConnectorError("'derived' debe ser un objeto {campo: regla}")
unknown = sorted(set(raw) - fields)
if unknown:
raise ConnectorError(f"campos desconocidos en 'derived': {unknown}")
return {field: rule_from(rule, separator=" ") for field, rule in raw.items()}
+11 -2
View File
@@ -48,9 +48,16 @@ class _NewResultado:
def match_or_mint(
discovered: list[DiscoveredField], *, proyecto: str, catalogo: Catalogo, estudio_id: str | None = None
discovered: list[DiscoveredField],
*,
proyecto: str,
catalogo: Catalogo,
estudio_id: str | None = None,
mint: bool = True,
) -> list[MatchedField]:
"""One `MatchedField` per discovered caption, in order.
"""One `MatchedField` per discovered caption, in order. With
`mint=False`, a caption nothing in the catalog matches is left out
instead of being added to the catalog file.
`estudio_id`, when the caller already knows it (the row's own
study-type column, resolved through `codigos_hospital`), scopes which
@@ -67,6 +74,8 @@ def match_or_mint(
found = _best_match(field.caption, labels)
if found is not None:
resultado, is_new = by_resultado_id[found], False
elif not mint:
continue
else:
resultado = _mint(field, proyecto=proyecto, estudio_id=estudio_id, catalogo=catalogo)
is_new = True
@@ -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,
}