"""Response shapes for the `/imports/sources/*` routes: previews with auto-match suggestions, PDF table detection and region extraction, and document extraction reports.""" from typing import Any import pandas as pd from webapi.imports.connectors import Connector, ConnectorError from webapi.imports.connectors.document import DocumentConnector from webapi.imports.connectors.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 from webapi.imports.schemas.registry import ENTITY_REGISTRY def suggest_mapping(source_columns: list[str], target_key: str | None) -> list[dict[str, Any]]: if not target_key: return [] spec = ENTITY_REGISTRY.get(target_key) if spec is None: raise ConnectorError(f"destino desconocido: {target_key!r}") matches = column_matcher.suggest_mapping(source_columns, list(spec.schema.model_fields.keys())) return [ {"source_column": m.source_column, "target_field": m.target_field, "confidence": m.confidence, "reason": m.reason} for m in matches ] def preview_with_suggestions(connector: Connector, target_key: str | None, *, limit: int = 50) -> dict[str, Any]: preview = connector.preview(limit=limit) return { "columns": [{"name": c.name, "inferred_type": c.inferred_type} for c in preview.columns], "sample_rows": preview.sample_rows, "total_rows": preview.total_rows, "suggested_mapping": suggest_mapping([c.name for c in preview.columns], target_key), "tables": [{"name": t.name, "options": t.options, "kind": t.kind} for t in connector.tables()], "source_metadata": connector.metadata(), "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.""" connector = PdfConnector(raw) return { "page_count": connector.page_count, "has_text_layer": connector.has_text_layer(), "table_candidates": [ { "page_number": candidate.page_number, "bbox": list(candidate.bbox), "column_count": len(candidate.grid[0]) if candidate.grid else 0, "row_count": len(candidate.grid) - 1 if candidate.grid else 0, "preview_grid": candidate.grid, } for candidate in connector.detect_tables() ], } def extract_pdf_regions(raw: bytes, regions: list[dict[str, Any]], *, dpi: int = 150, target_key: str | None = None) -> dict[str, Any]: connector = PdfConnector(raw) resolved = connector.extract_regions([RegionSpec.parse(r) for r in regions], dpi=dpi) df = pd.DataFrame(resolved, dtype=object) columns = columns_from_dataframe(df) return { "columns": [{"name": c.name, "inferred_type": c.inferred_type} for c in columns], "rows": rows_from_dataframe(df), "warnings": [{"page_number": w.page_number, "message": w.message} for w in connector.warnings], "suggested_mapping": suggest_mapping([c.name for c in columns], target_key), } def document_report(payload: dict[str, Any]) -> dict[str, Any]: """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(), "skipped": connector.skipped, "nlp_version": connector.nlp_version, }