Files
WebApi/webapi/blueprints/imports.py
T
rockdrigo 113b792a7b The import's catalog matching and commit read the WebApi's catalog, silver batch and table maps; add_resultado moves here
How: `catalog_matching`, `catalog_commit_service` and the imports blueprint import `Catalogo`,
`catalogo_desde_toml`, `ruta_de_catalogo`, `CatalogoInvalido`, `LotePlata`, `valor_de_observacion` and
`tablas_de` from `webapi.orchestration`; the commit writes through `carga_repository.save_load` and
`catalog_repository.sync`. `add_resultado` and its tests come over unchanged from the indicator kit.

Implications: the import path no longer needs the indicator kit, which isn't a dependency.
2026-11-13 15:24:02 -06:00

436 lines
16 KiB
Python

"""Import routes. They only parse the request and shape the response; the
work happens in `webapi.imports`. Errors map to HTTP 400 in one place."""
import json
import logging
from flask import Blueprint, Response, jsonify, request
from sqlalchemy.exc import SQLAlchemyError
from extraction import BBox, ExtractionError
from extraction.readers import reader_for
from webapi.imports import audit as import_audit
from webapi.imports.connectors import ConnectorError, build_connector, catalog, connector_class, kind_for_filename
from webapi.imports.connectors.base import decode_file
from webapi.imports.connectors.pdf import PdfConnector
from webapi.orchestration.reference.catalogs import CatalogoInvalido
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,
)
from webapi.recomputation import DOMAINS, RecomputationQueue
from webapi.imports.services.introspection_service import (
detect_pdf,
document_report,
extract_pdf_regions,
preview_with_suggestions,
suggest_mapping,
)
imports_bp = Blueprint("imports", __name__)
log = logging.getLogger(__name__)
class BadRequest(Exception):
"""Missing or malformed request parameter."""
@imports_bp.errorhandler(BadRequest)
@imports_bp.errorhandler(ConnectorError)
@imports_bp.errorhandler(ExtractionError)
@imports_bp.errorhandler(ImportRequestError)
def _bad_request(exc: Exception):
return jsonify({"error": str(exc)}), 400
def _json_body() -> dict:
body = request.get_json(silent=True)
if not isinstance(body, dict):
raise BadRequest("el cuerpo de la solicitud debe ser un objeto JSON")
return body
def _require(mapping: dict, key: str):
value = mapping.get(key)
if value in (None, ""):
raise BadRequest(f"falta {key}")
return value
def _uploaded_file() -> tuple[str, bytes]:
if "file" not in request.files:
raise BadRequest("falta el archivo")
upload = request.files["file"]
return upload.filename or "", upload.read()
def _form_int(key: str, default: int | None = None) -> int:
raw = request.form.get(key)
if raw is None:
if default is None:
raise BadRequest(f"falta {key}")
return default
try:
return int(raw)
except ValueError as exc:
raise BadRequest(f"{key} debe ser un número entero") from exc
def _form_json(key: str, default=None):
raw = request.form.get(key)
if raw in (None, ""):
return default
try:
return json.loads(raw)
except json.JSONDecodeError as exc:
raise BadRequest(f"{key} debe ser JSON válido: {exc}") from exc
def _outcome(exc: Exception) -> str:
"""How an attempt that raised is logged."""
if isinstance(exc, DatabaseRefused):
return "rechazada_por_la_base"
if isinstance(exc, (BadRequest, ConnectorError, ExtractionError, ImportRequestError)):
return "solicitud_invalida"
return "fallida"
# -- catalog -------------------------------------------------------------------
@imports_bp.get("/connectors")
def get_connectors():
"""Every source kind the server can read, with what the client needs to
offer it (accepted extensions, SQL engines and whether their driver is
installed, document segmentation strategies)."""
return jsonify({"connectors": catalog()})
@imports_bp.get("/targets")
def get_targets():
targets = []
for key, spec in ENTITY_REGISTRY.items():
schema_json = spec.schema.model_json_schema()
required = set(schema_json.get("required", []))
fields = [
{"name": name, "required": name in required, "type": _json_schema_type(prop)}
for name, prop in schema_json.get("properties", {}).items()
]
domain, _, table = key.partition(".")
targets.append(
{
"key": key,
"domain": domain,
"table": table,
"conflict_fields": list(spec.conflict_fields) if spec.conflict_fields else None,
"fields": fields,
}
)
return jsonify({"targets": targets})
def _json_schema_type(prop: dict) -> str:
"""`Optional[X]` renders as `anyOf: [X, null]`: report X and its format."""
candidates = prop.get("anyOf") or [prop]
for candidate in candidates:
if candidate.get("type") and candidate["type"] != "null":
return candidate.get("format") or candidate["type"]
return "string"
# -- generic preview --------------------------------------------------------------
@imports_bp.post("/sources/file/preview")
def preview_file():
"""Multipart upload of any file connector (`source_kind` may be omitted
and is then inferred from the file name)."""
name, raw = _uploaded_file()
kind = request.form.get("source_kind") or kind_for_filename(name)
cls = connector_class(kind)
if not issubclass(cls, FileConnector):
raise BadRequest(f"{kind!r} no es una fuente de archivo")
options = _form_json("options", {}) or {}
if "file_name" in cls.option_names:
options.setdefault("file_name", name)
connector = cls.from_bytes(raw, options)
return jsonify(preview_with_suggestions(connector, request.form.get("target")))
@imports_bp.post("/sources/<kind>/preview")
def preview_source(kind: str):
"""JSON preview for any connector: `{"payload": {...}, "target": "cacu.Paciente"}`,
the same payload an import source carries."""
body = _json_body()
payload = _require(body, "payload")
if kind == "document":
payload = {**payload, "target": payload.get("target") or body.get("target")}
return jsonify(preview_with_suggestions(build_connector(kind, payload), body.get("target")))
# -- SQL browsing -------------------------------------------------------------------
@imports_bp.post("/sources/sql/test-connection")
def sql_test_connection():
connector = SqlConnector.connect(_json_body())
connector.test_connection()
return jsonify({"ok": True, "dialect": connector.get_dialect()})
@imports_bp.post("/sources/sql/schemas")
def sql_schemas():
return jsonify({"schemas": SqlConnector.connect(_json_body()).list_schemas()})
@imports_bp.post("/sources/sql/tables")
def sql_tables():
body = _json_body()
return jsonify({"tables": SqlConnector.connect(body).list_tables(schema=body.get("schema"))})
@imports_bp.post("/sources/sql/columns")
def sql_columns():
body = _json_body()
columns = SqlConnector.connect(body).list_columns(_require(body, "table"), schema=body.get("schema"))
return jsonify({"columns": [{"name": c.name, "inferred_type": c.inferred_type} for c in columns]})
@imports_bp.post("/sources/sql/preview")
def sql_preview():
body = _json_body()
connector = SqlConnector.connect(body)
if body.get("query"):
connector.select_query(body["query"])
else:
connector.select_table(_require(body, "table"), schema=body.get("schema"))
return jsonify(preview_with_suggestions(connector, body.get("target")))
# -- PDF tables -------------------------------------------------------------------------
@imports_bp.post("/sources/pdf/detect")
def pdf_detect():
return jsonify(detect_pdf(_uploaded_file()[1]))
@imports_bp.post("/sources/pdf/page-image")
def pdf_page_image():
png = PdfConnector(_uploaded_file()[1]).render_page_image(_form_int("page_number"), dpi=_form_int("dpi", 150))
return Response(png, mimetype="image/png")
@imports_bp.post("/sources/pdf/table/preview")
def pdf_table_preview():
raw = _uploaded_file()[1]
page_number = _form_int("page_number")
bbox = _form_json("bbox")
if not isinstance(bbox, list) or len(bbox) != 4:
raise BadRequest("falta page_number o bbox")
connector = PdfConnector(raw)
connector.select_table(page_number, tuple(float(v) for v in bbox))
return jsonify(preview_with_suggestions(connector, request.form.get("target")))
@imports_bp.post("/sources/pdf/regions/extract")
def pdf_regions_extract():
body = _json_body()
raw = decode_file(body)
regions = _require(body, "regions")
return jsonify(extract_pdf_regions(raw, regions, dpi=int(body.get("dpi", 150)), target_key=body.get("target")))
# -- documents ------------------------------------------------------------------------------
@imports_bp.post("/sources/document/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?,
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")
return jsonify(document_report(body))
@imports_bp.post("/sources/document/page-image")
def document_page_image():
"""PNG of one page of any supported document; with `bbox` (normalized,
JSON list) only that region, e.g. an embedded image."""
name, raw = _uploaded_file()
reader = reader_for(name, raw)
page_number = _form_int("page_number")
dpi = min(max(_form_int("dpi", 150), 50), 300)
bbox = _form_json("bbox")
if bbox is None:
return Response(reader.render_page(raw, page_number, dpi=dpi), mimetype="image/png")
if not isinstance(bbox, list) or len(bbox) != 4:
raise BadRequest("bbox debe ser [x0, y0, x1, y1]")
return Response(reader.render_region(raw, page_number, BBox(*map(float, bbox)), dpi=dpi), mimetype="image/png")
# -- 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")
audit = import_audit.ImportAudit("validacion")
try:
result = validate_source(source, audit=audit)
except Exception as exc:
audit.fail(exc, _outcome(exc))
raise
else:
audit.succeed()
finally:
import_audit.record(audit)
return jsonify(
{
"total_rows": result.total_rows,
"valid_count": result.valid_count,
"error_count": result.error_count,
"errors": serialize_errors(result),
}
)
def _commit_catalog_fallback(raw_sources: list) -> list[dict]:
"""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("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]
if not domain:
continue
payload = {**(raw.get("payload") or {}), "target": target}
try:
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, ImportRequestError) as exc:
log.warning("catalog_fallback: %s no se pudo procesar: %s", raw.get("label") or target, exc)
continue
reports.append(
{
"label": raw.get("label"),
"domain": result.proyecto,
"records_written": result.records_written,
"records_without_patient": result.records_without_patient,
"fields_matched": result.fields_matched,
"fields_minted": result.fields_minted,
"fields_unmatched": result.fields_unmatched,
}
)
return reports
@imports_bp.post("/commit")
def commit():
"""`{sources: [...], on_conflict: "reject"|"upsert", merge_duplicates: bool}`.
With `merge_duplicates`, rows of different sources sharing a natural key
are combined into one record before writing."""
body = _json_body()
on_conflict = body.get("on_conflict", "reject")
merge = bool(body.get("merge_duplicates", False))
audit = import_audit.ImportAudit("carga", {"on_conflict": on_conflict, "merge_duplicates": merge})
try:
results = commit_sources(_require(body, "sources"), on_conflict=on_conflict, merge=merge, audit=audit)
except Exception as exc:
audit.fail(exc, _outcome(exc))
raise
else:
audit.succeed()
finally:
import_audit.record(audit)
recalculating = False
if audit.domain in DOMAINS and any(r.created or r.updated for r in results):
try:
RecomputationQueue().request_run(audit.domain)
recalculating = True
except OSError:
# The rows are already saved; failing here would invite a duplicate retry.
log.exception("no se pudo solicitar el recálculo de %s", audit.domain)
return jsonify(
{
"ok": all(r.rejected == 0 for r in results),
"audit_id": audit.id,
"indicadores_en_recalculo": recalculating,
"catalog_fallback": _commit_catalog_fallback(body.get("sources") or []),
"results": [
{
"target": r.target,
"label": r.label,
"total": r.total,
"created": r.created,
"updated": r.updated,
"rejected": r.rejected,
"merged": r.merged,
"errors": r.errors,
"warnings": r.warnings,
"linked": r.linked,
}
for r in results
],
}
)