integration layer; merge work on indicators from forks with existing ingestion pipeline
This commit is contained in:
@@ -0,0 +1,27 @@
|
||||
"""Import sources. Each module registers its connector class on import;
|
||||
the order here is the order the catalog lists them in."""
|
||||
from webapi.imports.connectors import csv_, excel, json_, pdf, document, edf, sql # noqa: F401 (catalog order)
|
||||
from webapi.imports.connectors.base import Connector, PreviewResult, SourceColumn, SourceTable
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
from webapi.imports.connectors.registry import (
|
||||
CONNECTORS,
|
||||
build_connector,
|
||||
catalog,
|
||||
connector_class,
|
||||
kind_for_filename,
|
||||
register_connector,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"CONNECTORS",
|
||||
"Connector",
|
||||
"ConnectorError",
|
||||
"PreviewResult",
|
||||
"SourceColumn",
|
||||
"SourceTable",
|
||||
"build_connector",
|
||||
"catalog",
|
||||
"connector_class",
|
||||
"kind_for_filename",
|
||||
"register_connector",
|
||||
]
|
||||
@@ -0,0 +1,93 @@
|
||||
import base64
|
||||
import binascii
|
||||
from abc import ABC, abstractmethod
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, ClassVar, Iterator
|
||||
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SourceColumn:
|
||||
name: str
|
||||
inferred_type: str # "string" | "integer" | "float" | "boolean" | "date" | "datetime" | "binary" | "unknown"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PreviewResult:
|
||||
columns: list[SourceColumn]
|
||||
sample_rows: list[dict[str, Any]]
|
||||
total_rows: int | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SourceTable:
|
||||
"""One table a source offers: an Excel sheet, a section of an EDF
|
||||
file. `options` is what to send back to read that table."""
|
||||
|
||||
name: str
|
||||
options: dict[str, Any] = field(default_factory=dict)
|
||||
kind: str = "table"
|
||||
|
||||
|
||||
class Connector(ABC):
|
||||
"""A data source that can be read as columns and rows.
|
||||
|
||||
Adding a source means subclassing this (or `FileConnector` for an
|
||||
uploaded file), setting the class attributes below, implementing
|
||||
`from_payload`, and decorating the class with `@register_connector`.
|
||||
The import pipeline, the `/imports/connectors` catalog and the web
|
||||
client pick it up from there.
|
||||
"""
|
||||
|
||||
kind: ClassVar[str]
|
||||
label: ClassVar[str]
|
||||
description: ClassVar[str] = ""
|
||||
category: ClassVar[str] # "file" | "database" | "document" | "signal"
|
||||
icon: ClassVar[str] = "table_view"
|
||||
extensions: ClassVar[tuple[str, ...]] = ()
|
||||
|
||||
@classmethod
|
||||
@abstractmethod
|
||||
def from_payload(cls, payload: dict[str, Any]) -> "Connector":
|
||||
"""Builds a ready-to-read connector from the JSON a client sends
|
||||
in an import request's `payload`."""
|
||||
|
||||
@abstractmethod
|
||||
def get_columns(self) -> list[SourceColumn]: ...
|
||||
|
||||
@abstractmethod
|
||||
def preview(self, *, limit: int = 20) -> PreviewResult: ...
|
||||
|
||||
@abstractmethod
|
||||
def read_rows(self, column_mapping: dict[str, str]) -> Iterator[dict[str, Any]]:
|
||||
"""`column_mapping`: source column -> target field. Yields one dict
|
||||
per row keyed by target field. Values are not validated here."""
|
||||
|
||||
def tables(self) -> list[SourceTable]:
|
||||
"""The tables this source offers, when it has more than one."""
|
||||
return []
|
||||
|
||||
def metadata(self) -> dict[str, Any]:
|
||||
"""Source-specific facts worth showing (a CSV's delimiter, ...)."""
|
||||
return {}
|
||||
|
||||
@classmethod
|
||||
def describe(cls) -> dict[str, Any]:
|
||||
return {
|
||||
"kind": cls.kind,
|
||||
"label": cls.label,
|
||||
"description": cls.description,
|
||||
"category": cls.category,
|
||||
"icon": cls.icon,
|
||||
"extensions": list(cls.extensions),
|
||||
}
|
||||
|
||||
|
||||
def decode_file(payload: dict[str, Any], key: str = "file_base64") -> bytes:
|
||||
try:
|
||||
return base64.b64decode(payload[key], validate=True)
|
||||
except KeyError as exc:
|
||||
raise ConnectorError(f"missing {key}") from exc
|
||||
except (binascii.Error, ValueError, TypeError) as exc:
|
||||
raise ConnectorError(f"{key} is not valid base64: {exc}") from exc
|
||||
@@ -0,0 +1,72 @@
|
||||
import csv
|
||||
import io
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
from webapi.imports.connectors.registry import register_connector
|
||||
from webapi.imports.connectors.tabular import FileConnector
|
||||
|
||||
_CANDIDATE_DELIMITERS = ",;\t|"
|
||||
# utf-8-sig strips the BOM Excel prepends when it exports "CSV UTF-8" (it
|
||||
# would otherwise end up glued to the first column's name); cp1252 is what
|
||||
# Excel on Windows writes for plain "CSV" in a Spanish locale.
|
||||
_FALLBACK_ENCODINGS = ("utf-8-sig", "cp1252")
|
||||
|
||||
|
||||
@register_connector
|
||||
class CsvConnector(FileConnector):
|
||||
"""Every cell is read as text: pandas' type guessing would turn the
|
||||
postal code `01000` into `1000` before validation sees it."""
|
||||
|
||||
kind = "csv"
|
||||
label = "Texto / CSV"
|
||||
description = "Archivos delimitados por comas, punto y coma o tabuladores"
|
||||
category = "file"
|
||||
icon = "table_view"
|
||||
extensions = ("csv", "txt", "tsv")
|
||||
option_names = ("delimiter", "encoding")
|
||||
|
||||
def __init__(self, raw: bytes, *, delimiter: str | None = None, encoding: str | None = None):
|
||||
self._encoding, text = _decode(raw, encoding)
|
||||
if "\x00" in text:
|
||||
raise ConnectorError("file looks binary, not a delimited text file")
|
||||
self._delimiter = delimiter or _sniff_delimiter(text)
|
||||
try:
|
||||
self._df = pd.read_csv(
|
||||
io.StringIO(text),
|
||||
sep=self._delimiter,
|
||||
dtype=str,
|
||||
keep_default_na=False,
|
||||
na_values=[""],
|
||||
skipinitialspace=True,
|
||||
)
|
||||
except Exception as exc: # pandas raises a variety of error types
|
||||
raise ConnectorError(f"could not parse CSV: {exc}") from exc
|
||||
self._df.columns = [str(c).strip() for c in self._df.columns]
|
||||
|
||||
def _dataframe(self) -> pd.DataFrame:
|
||||
return self._df
|
||||
|
||||
def metadata(self) -> dict:
|
||||
return {"delimiter": self._delimiter, "encoding": self._encoding}
|
||||
|
||||
|
||||
def _decode(raw: bytes, encoding: str | None) -> tuple[str, str]:
|
||||
for candidate in (encoding,) if encoding else _FALLBACK_ENCODINGS:
|
||||
try:
|
||||
return candidate, raw.decode(candidate)
|
||||
except (UnicodeDecodeError, LookupError):
|
||||
continue
|
||||
raise ConnectorError(f"could not decode CSV as {encoding or ' / '.join(_FALLBACK_ENCODINGS)}")
|
||||
|
||||
|
||||
def _sniff_delimiter(text: str) -> str:
|
||||
"""`csv.Sniffer` restricted to real delimiters. pandas' own `sep=None`
|
||||
sniffing picks letters as delimiters on single-column files (`id\\nH3`
|
||||
parsed as columns `['Unnamed: 0', 'd']`)."""
|
||||
sample = "\n".join(text.splitlines()[:50])
|
||||
try:
|
||||
return csv.Sniffer().sniff(sample, delimiters=_CANDIDATE_DELIMITERS).delimiter
|
||||
except csv.Error:
|
||||
return ","
|
||||
@@ -0,0 +1,229 @@
|
||||
import hashlib
|
||||
import json
|
||||
import threading
|
||||
from collections import OrderedDict
|
||||
from typing import Any, ClassVar
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from extraction import DocumentExtractor, ExtractedRecord, ExtractionError, make_segmenter, read_document, reader_for
|
||||
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.errors import ConnectorError
|
||||
from webapi.imports.connectors.registry import register_connector
|
||||
from webapi.imports.connectors.tabular import DataFrameConnector
|
||||
from webapi.imports.schemas.field_specs import field_specs_for, key_field_for
|
||||
from webapi.imports.schemas.registry import ENTITY_REGISTRY
|
||||
|
||||
DOCUMENT_COLUMN = "documento"
|
||||
IMAGE_COLUMN = "imagen"
|
||||
CONFIDENCE_COLUMN = "confianza_extraccion"
|
||||
SOURCES_COLUMN = "origen"
|
||||
|
||||
|
||||
class _ResultCache:
|
||||
"""OCR over a stack of scans is slow, and the stateless API runs the
|
||||
same extraction for preview, validation and commit. Results are kept
|
||||
per worker for the last few distinct requests."""
|
||||
|
||||
def __init__(self, size: int = 8):
|
||||
self._items: OrderedDict[str, list[ExtractedRecord]] = OrderedDict()
|
||||
self._size = size
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def get_or_compute(self, key: str, compute) -> list[ExtractedRecord]:
|
||||
with self._lock:
|
||||
if key in self._items:
|
||||
self._items.move_to_end(key)
|
||||
return self._items[key]
|
||||
value = compute()
|
||||
with self._lock:
|
||||
self._items[key] = value
|
||||
while len(self._items) > self._size:
|
||||
self._items.popitem(last=False)
|
||||
return value
|
||||
|
||||
|
||||
_CACHE = _ResultCache()
|
||||
|
||||
|
||||
@register_connector
|
||||
class DocumentConnector(DataFrameConnector):
|
||||
"""Clinical documents that are not tables: one report per patient,
|
||||
several pages per patient, many patients per file, scans, free text.
|
||||
|
||||
Every file is read page by page (text layer or OCR), split into
|
||||
per-patient records, and the target entity's fields are extracted from
|
||||
labels and narrative text. Records of the same patient found in other
|
||||
pages or files are merged. Each row also carries the record's pages as
|
||||
a PDF (`documento`), mappable to the entity's file column.
|
||||
|
||||
Corrections made while reviewing travel in `overrides`
|
||||
(`{"<row>": {"field": value}}`) and win over the extracted value.
|
||||
"""
|
||||
|
||||
kind = "document"
|
||||
label = "Documentos clínicos"
|
||||
description = "Reportes, formatos y notas en PDF o imagen; los campos se extraen del texto libre"
|
||||
category = "document"
|
||||
icon = "document_scanner"
|
||||
extensions: ClassVar[tuple[str, ...]] = tuple(supported_extensions())
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
files: list[tuple[str, bytes]],
|
||||
*,
|
||||
target: str,
|
||||
segmentation: str = "auto",
|
||||
pages_per_record: int = 1,
|
||||
ocr_mode: str = "auto",
|
||||
key_pattern: str | None = None,
|
||||
overrides: dict[str, dict[str, Any]] | None = None,
|
||||
):
|
||||
if not files:
|
||||
raise ConnectorError("no documents given")
|
||||
entity = ENTITY_REGISTRY.get(target)
|
||||
if entity is None:
|
||||
raise ConnectorError(f"unknown target: {target!r}")
|
||||
if segmentation not in SEGMENTERS:
|
||||
raise ConnectorError(f"unknown segmentation {segmentation!r} (available: {', '.join(SEGMENTERS)})")
|
||||
if ocr_mode not in ("auto", "always", "never"):
|
||||
raise ConnectorError(f"unknown ocr_mode {ocr_mode!r}")
|
||||
self.files = files
|
||||
self.target = target
|
||||
self.specs = field_specs_for(entity, key_pattern=key_pattern)
|
||||
self.key_field = key_field_for(entity)
|
||||
self.segmentation = segmentation
|
||||
self.pages_per_record = max(1, int(pages_per_record))
|
||||
self.ocr_mode = ocr_mode
|
||||
self.key_pattern = key_pattern
|
||||
self.overrides = {str(k): v for k, v in (overrides or {}).items()}
|
||||
self._df: pd.DataFrame | None = None
|
||||
|
||||
@classmethod
|
||||
def from_payload(cls, payload: dict[str, Any]) -> "DocumentConnector":
|
||||
files = [(f.get("name") or f"documento_{i}", decode_file(f)) for i, f in enumerate(payload.get("files") or [], 1)]
|
||||
return cls(
|
||||
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"),
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def describe(cls) -> dict[str, Any]:
|
||||
segmentations = [{"id": name, "label": segmenter.label} for name, segmenter in SEGMENTERS.items()]
|
||||
return {**super().describe(), "segmentations": segmentations}
|
||||
|
||||
# -- extraction -----------------------------------------------------------
|
||||
|
||||
@property
|
||||
def records(self) -> list[ExtractedRecord]:
|
||||
return _CACHE.get_or_compute(self._cache_key(), self._extract)
|
||||
|
||||
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
|
||||
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)
|
||||
|
||||
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]
|
||||
digest.update(json.dumps(config).encode())
|
||||
return digest.hexdigest()
|
||||
|
||||
# -- rows -----------------------------------------------------------------
|
||||
|
||||
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]
|
||||
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 _row(self, index: int, record: ExtractedRecord) -> dict[str, Any]:
|
||||
row: dict[str, Any] = record.row()
|
||||
row.update(self.overrides.get(str(index), {}))
|
||||
row[DOCUMENT_COLUMN] = self._record_pdf(record)
|
||||
row[IMAGE_COLUMN] = self._record_image(record)
|
||||
row[CONFIDENCE_COLUMN] = round(record.confidence, 3)
|
||||
row[SOURCES_COLUMN] = "; ".join(f"{s.document} p. {', '.join(map(str, s.page_numbers))}" for s in record.sources)
|
||||
return row
|
||||
|
||||
def _record_pdf(self, record: ExtractedRecord) -> bytes | None:
|
||||
"""The record's pages from every PDF it was found in, as one PDF."""
|
||||
by_name = dict(self.files)
|
||||
parts = [
|
||||
(by_name[source.document], source.page_numbers)
|
||||
for source in record.sources
|
||||
if source.document in by_name and PdfReader.accepts(source.document, by_name[source.document][:8])
|
||||
]
|
||||
return combine_pages(parts) if parts else None
|
||||
|
||||
def _record_image(self, record: ExtractedRecord) -> bytes | None:
|
||||
"""A PNG of the clearest picture embedded on the record's pages (a
|
||||
mammogram, a lesion photo) — mappable onto a target's own image
|
||||
column (e.g. `mast_dicom_blob`), the same way `documento` maps onto
|
||||
a PDF column. A `scan` is the page itself, not a distinct picture,
|
||||
so a `figure` wins when both are present; with several figures, the
|
||||
first one found is used."""
|
||||
by_name = dict(self.files)
|
||||
candidates = [(document, image) for document, image in record.images if document in by_name]
|
||||
if not candidates:
|
||||
return None
|
||||
figures = [c for c in candidates if c[1].kind == "figure"]
|
||||
document, image = figures[0] if figures else candidates[0]
|
||||
raw = by_name[document]
|
||||
try:
|
||||
return reader_for(document, raw).render_region(raw, image.page_number, image.bbox)
|
||||
except ExtractionError:
|
||||
return None
|
||||
|
||||
# -- review ---------------------------------------------------------------
|
||||
|
||||
def report(self) -> list[dict[str, Any]]:
|
||||
"""Per record: every extracted value with its confidence, method and
|
||||
the line it was read from, conflicts between sources, and the
|
||||
images found on its pages."""
|
||||
report = []
|
||||
for index, record in enumerate(self.records):
|
||||
overrides = self.overrides.get(str(index), {})
|
||||
fields = {name: value.to_dict() for name, value in record.values.items()}
|
||||
for name, value in overrides.items():
|
||||
fields[name] = {**fields.get(name, {}), "value": value, "method": "manual", "confidence": 1.0}
|
||||
report.append(
|
||||
{
|
||||
"index": index,
|
||||
"key": record.key,
|
||||
"confidence": round(record.confidence, 3),
|
||||
"fields": fields,
|
||||
"missing": [s.name for s in self.specs if s.required and s.name not in fields],
|
||||
"conflicts": [
|
||||
{"field": c.field, "kept": c.kept.to_dict(), "discarded": c.discarded.to_dict()}
|
||||
for c in record.conflicts
|
||||
],
|
||||
"sources": [{"document": s.document, "page_numbers": s.page_numbers} for s in record.sources],
|
||||
"images": [
|
||||
{"document": name, "page_number": image.page_number, "bbox": image.bbox.as_list(), "kind": image.kind}
|
||||
for name, image in record.images
|
||||
],
|
||||
}
|
||||
)
|
||||
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]}
|
||||
@@ -0,0 +1,104 @@
|
||||
from datetime import date, timedelta
|
||||
from pathlib import PurePath
|
||||
from typing import Any
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from extraction import ExtractionError
|
||||
from extraction.signals import EegRecording
|
||||
from webapi.imports.connectors.base import decode_file
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
from webapi.imports.connectors.registry import register_connector
|
||||
from webapi.imports.connectors.tabular import FileConnector
|
||||
|
||||
MAX_LISTED_EVENTS = 20
|
||||
|
||||
|
||||
@register_connector
|
||||
class EdfConnector(FileConnector):
|
||||
"""EEG recordings (`.edf`), one row per file, shaped for `tea.EegEstudio`:
|
||||
patient and dates from the header, an estimated background rhythm from
|
||||
the posterior channels, a text summary of the recording, and the file
|
||||
itself (column `estudio`, stored in `eeg_estudio.eeg_estudio`)."""
|
||||
|
||||
kind = "edf"
|
||||
label = "EEG (EDF)"
|
||||
description = "Registros de electroencefalografía en European Data Format"
|
||||
category = "signal"
|
||||
icon = "monitor_heart"
|
||||
extensions = ("edf",)
|
||||
option_names = ("file_name",)
|
||||
|
||||
def __init__(self, raw: bytes, *, file_name: str = "registro.edf"):
|
||||
self.files = [(file_name, raw)]
|
||||
self._df: pd.DataFrame | None = None
|
||||
|
||||
@classmethod
|
||||
def from_payload(cls, payload: dict[str, Any]) -> "EdfConnector":
|
||||
"""Accepts one file (`file_base64` + `options.file_name`) or several
|
||||
(`files: [{name, file_base64}]`)."""
|
||||
if not payload.get("files"):
|
||||
return super().from_payload(payload)
|
||||
connector = cls(b"", file_name="")
|
||||
connector.files = [(f.get("name") or f"registro_{i}.edf", decode_file(f)) for i, f in enumerate(payload["files"], 1)]
|
||||
return connector
|
||||
|
||||
def metadata(self) -> dict[str, Any]:
|
||||
return {"files": [name for name, _ in self.files]}
|
||||
|
||||
def _dataframe(self) -> pd.DataFrame:
|
||||
if self._df is None:
|
||||
self._df = pd.DataFrame([self._row(name, raw) for name, raw in self.files], dtype=object)
|
||||
return self._df
|
||||
|
||||
def _row(self, name: str, raw: bytes) -> dict[str, Any]:
|
||||
try:
|
||||
eeg = EegRecording.read(raw)
|
||||
except ExtractionError as exc:
|
||||
raise ConnectorError(f"{name}: {exc}") from exc
|
||||
patient = eeg.patient
|
||||
study_date = eeg.start.date() if eeg.start else None
|
||||
rhythm = eeg.background_rhythm()
|
||||
return {
|
||||
"id_registro_laboratorio": eeg.recording_fields["admin_code"] or PurePath(name).stem,
|
||||
"paciente": patient.code,
|
||||
"sexo": patient.sex,
|
||||
"fecha_nacimiento_declarada": patient.birthdate,
|
||||
"edad_meses": age_in_months(patient.birthdate, study_date),
|
||||
"fecha_estudio": study_date,
|
||||
"duracion_min": round(eeg.duration_seconds / 60) if eeg.duration_seconds else None,
|
||||
"ritmo_base_frecuencia": rhythm["frequency_hz"],
|
||||
"ritmo_base_amplitud": rhythm["amplitude_uv"],
|
||||
"descripcion_senal": describe(eeg),
|
||||
"archivo": name,
|
||||
"estudio": raw,
|
||||
}
|
||||
|
||||
|
||||
def describe(eeg: EegRecording) -> str:
|
||||
channels = eeg.channels
|
||||
parts = [
|
||||
f"{eeg.variant}, {len(channels)} canales a {channels[0].sample_rate:g} Hz" if channels else eeg.variant,
|
||||
f"duración {timedelta(seconds=round(eeg.duration_seconds))}",
|
||||
"montaje: " + ", ".join(c.label for c in channels),
|
||||
]
|
||||
fields = eeg.recording_fields
|
||||
if fields["equipment"]:
|
||||
parts.append(f"equipo: {fields['equipment']}")
|
||||
if fields["technician"]:
|
||||
parts.append(f"técnico: {fields['technician']}")
|
||||
events = eeg.annotations()
|
||||
if events:
|
||||
listed = "; ".join(f"{timedelta(seconds=round(e.onset_seconds))} {e.text}" for e in events[:MAX_LISTED_EVENTS])
|
||||
more = f" (+{len(events) - MAX_LISTED_EVENTS})" if len(events) > MAX_LISTED_EVENTS else ""
|
||||
parts.append(f"eventos: {listed}{more}")
|
||||
return ". ".join(parts) + "."
|
||||
|
||||
|
||||
def age_in_months(birthdate: date | None, on: date | None) -> float | None:
|
||||
if birthdate is None or on is None or on < birthdate:
|
||||
return None
|
||||
months = (on.year - birthdate.year) * 12 + (on.month - birthdate.month)
|
||||
if on.day < birthdate.day:
|
||||
months -= 1
|
||||
return float(months)
|
||||
@@ -0,0 +1,3 @@
|
||||
class ConnectorError(Exception):
|
||||
"""Raised by any `Connector` subclass for malformed input, a bad
|
||||
connection string, an unreadable file, etc."""
|
||||
@@ -0,0 +1,49 @@
|
||||
import io
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
from webapi.imports.connectors.base import SourceTable
|
||||
from webapi.imports.connectors.registry import register_connector
|
||||
from webapi.imports.connectors.tabular import FileConnector
|
||||
|
||||
|
||||
@register_connector
|
||||
class ExcelConnector(FileConnector):
|
||||
"""`dtype=object` keeps each cell as the value openpyxl read; column
|
||||
typing would turn an integer column with a blank cell into floats."""
|
||||
|
||||
kind = "excel"
|
||||
label = "Libro de Excel"
|
||||
description = "Cada hoja del libro se ofrece como tabla"
|
||||
category = "file"
|
||||
icon = "grid_on"
|
||||
extensions = ("xlsx", "xlsm")
|
||||
option_names = ("sheet_name",)
|
||||
|
||||
def __init__(self, raw: bytes, *, sheet_name: str | int | None = None):
|
||||
try:
|
||||
self._workbook = pd.ExcelFile(io.BytesIO(raw), engine="openpyxl")
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not open Excel file: {exc}") from exc
|
||||
|
||||
self._sheet = sheet_name if sheet_name not in (None, "") else self._workbook.sheet_names[0]
|
||||
if isinstance(self._sheet, str) and self._sheet not in self._workbook.sheet_names:
|
||||
raise ConnectorError(f"sheet {self._sheet!r} not found — available: {self._workbook.sheet_names}")
|
||||
try:
|
||||
self._df = self._workbook.parse(self._sheet, dtype=object)
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not read sheet {self._sheet!r}: {exc}") from exc
|
||||
self._df.columns = [str(c).strip() for c in self._df.columns]
|
||||
|
||||
def list_sheets(self) -> list[str]:
|
||||
return list(self._workbook.sheet_names)
|
||||
|
||||
def tables(self) -> list[SourceTable]:
|
||||
return [SourceTable(name, {"sheet_name": name}, kind="sheet") for name in self.list_sheets()]
|
||||
|
||||
def _dataframe(self) -> pd.DataFrame:
|
||||
return self._df
|
||||
|
||||
def metadata(self) -> dict:
|
||||
return {"sheets": self.list_sheets(), "sheet_name": self._sheet}
|
||||
@@ -0,0 +1,61 @@
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
from webapi.imports.connectors.registry import register_connector
|
||||
from webapi.imports.connectors.tabular import FileConnector
|
||||
|
||||
|
||||
@register_connector
|
||||
class JsonConnector(FileConnector):
|
||||
"""Nested objects are flattened to dotted column names
|
||||
(`paciente.sexo`) into an object-dtype DataFrame, so JSON's own types
|
||||
survive (`json_normalize` turns a sometimes-missing integer into floats)."""
|
||||
|
||||
kind = "json"
|
||||
label = "JSON"
|
||||
description = "Lista de registros; los objetos anidados se aplanan"
|
||||
category = "file"
|
||||
icon = "data_object"
|
||||
extensions = ("json",)
|
||||
option_names = ("record_path",)
|
||||
|
||||
def __init__(self, raw: bytes, *, record_path: str | None = None):
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not parse JSON: {exc}") from exc
|
||||
|
||||
if record_path:
|
||||
try:
|
||||
for key in record_path.split("."):
|
||||
data = data[key]
|
||||
except (KeyError, TypeError, IndexError) as exc:
|
||||
raise ConnectorError(f"record_path {record_path!r} not found: {exc}") from exc
|
||||
|
||||
if isinstance(data, dict):
|
||||
data = data.get("data", [data])
|
||||
if not isinstance(data, list) or not all(isinstance(record, dict) for record in data):
|
||||
raise ConnectorError("JSON source must resolve to a list of objects")
|
||||
|
||||
self._record_path = record_path
|
||||
self._df = pd.DataFrame([_flatten(record) for record in data], dtype=object)
|
||||
|
||||
def _dataframe(self) -> pd.DataFrame:
|
||||
return self._df
|
||||
|
||||
def metadata(self) -> dict:
|
||||
return {"record_path": self._record_path}
|
||||
|
||||
|
||||
def _flatten(record: dict[str, Any], prefix: str = "") -> dict[str, Any]:
|
||||
flat: dict[str, Any] = {}
|
||||
for key, value in record.items():
|
||||
name = f"{prefix}{key}"
|
||||
if isinstance(value, dict):
|
||||
flat.update(_flatten(value, f"{name}."))
|
||||
else:
|
||||
flat[name] = value
|
||||
return flat
|
||||
@@ -0,0 +1,353 @@
|
||||
"""PDF tables. Two ways to turn a PDF into rows:
|
||||
|
||||
- `select_table`: a ruled table found by pdfplumber in the text layer;
|
||||
- `extract_regions`: one drawn box per column over the rendered page. Each
|
||||
box is read from the text layer or OCR'd, and lines from all boxes on a
|
||||
page are aligned into rows by their vertical position.
|
||||
|
||||
Documents that are not tables (one report per patient, free text) go
|
||||
through `DocumentConnector` instead.
|
||||
"""
|
||||
import io
|
||||
import statistics
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
import pandas as pd
|
||||
import pdfplumber
|
||||
import pytesseract
|
||||
from pytesseract import Output
|
||||
|
||||
from extraction.ocr import DEFAULT_LANG, group_words
|
||||
from webapi.imports.connectors.base import decode_file
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
from webapi.imports.connectors.registry import register_connector
|
||||
from webapi.imports.connectors.tabular import DataFrameConnector
|
||||
|
||||
_DEFAULT_SAMPLE_PAGES = 3
|
||||
_DEFAULT_CHAR_THRESHOLD = 20
|
||||
_DEFAULT_DPI = 150
|
||||
# Rendering memory grows with dpi². Past ~300 dpi OCR gains nothing and a
|
||||
# single request could exhaust the worker.
|
||||
_MIN_DPI, _MAX_DPI = 50, 300
|
||||
# PSM 6 (one uniform block): a region is a narrow column of stacked lines;
|
||||
# full-page segmentation (PSM 3) drops short crops such as a lone "F".
|
||||
_OCR_CONFIG = "--psm 6"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TableCandidate:
|
||||
page_number: int # 1-indexed
|
||||
bbox: tuple[float, float, float, float] # PDF points, pdfplumber's native space
|
||||
grid: list[list[str | None]] # header row + data rows
|
||||
confidence: float # ranking heuristic only, not ML
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RegionSpec:
|
||||
target_field: str
|
||||
page_numbers: list[int] # 1-indexed
|
||||
bbox: tuple[float, float, float, float] # normalized 0..1 over the rendered page
|
||||
|
||||
@classmethod
|
||||
def parse(cls, raw: dict[str, Any]) -> "RegionSpec":
|
||||
try:
|
||||
return cls(str(raw["target_field"]), [int(n) for n in raw["page_numbers"]], tuple(float(v) for v in raw["bbox"]))
|
||||
except (KeyError, TypeError, ValueError) as exc:
|
||||
raise ConnectorError(f"invalid region: {exc}") from exc
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ExtractionWarning:
|
||||
page_number: int
|
||||
message: str
|
||||
|
||||
|
||||
@register_connector
|
||||
class PdfConnector(DataFrameConnector):
|
||||
kind = "pdf"
|
||||
label = "PDF (tablas)"
|
||||
description = "Tablas detectadas o columnas dibujadas sobre la página (OCR para escaneos)"
|
||||
category = "document"
|
||||
icon = "picture_as_pdf"
|
||||
extensions = ("pdf",)
|
||||
|
||||
@classmethod
|
||||
def from_payload(cls, payload: dict[str, Any]) -> "PdfConnector":
|
||||
connector = cls(decode_file(payload))
|
||||
mode = payload.get("mode", "table")
|
||||
if mode == "table":
|
||||
connector.select_table(int(payload["page_number"]), tuple(float(v) for v in payload["bbox"]))
|
||||
elif mode == "regions":
|
||||
connector.extract_regions([RegionSpec.parse(r) for r in payload["regions"]], dpi=int(payload.get("dpi", _DEFAULT_DPI)))
|
||||
else:
|
||||
raise ConnectorError(f"unknown pdf mode: {mode!r}")
|
||||
return connector
|
||||
|
||||
def __init__(self, file_bytes: bytes):
|
||||
self.file_bytes = file_bytes
|
||||
try:
|
||||
self._pdf = pdfplumber.open(io.BytesIO(file_bytes))
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not open PDF: {exc}") from exc
|
||||
|
||||
self._table_grid: list[list[str | None]] | None = None
|
||||
self._region_rows: dict[str, list[str | None]] | None = None
|
||||
self.warnings: list[ExtractionWarning] = []
|
||||
|
||||
@property
|
||||
def page_count(self) -> int:
|
||||
return len(self._pdf.pages)
|
||||
|
||||
def has_text_layer(self, sample_pages: int = _DEFAULT_SAMPLE_PAGES, char_threshold: int = _DEFAULT_CHAR_THRESHOLD) -> bool:
|
||||
return any(self._page_has_text(page, char_threshold) for page in self._pdf.pages[:sample_pages])
|
||||
|
||||
@staticmethod
|
||||
def _page_has_text(page, char_threshold: int = _DEFAULT_CHAR_THRESHOLD) -> bool:
|
||||
try:
|
||||
text = page.extract_text() or ""
|
||||
except Exception:
|
||||
return False
|
||||
return len(text.strip()) >= char_threshold
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Ruled tables found by pdfplumber in the text layer
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def detect_tables(self) -> list[TableCandidate]:
|
||||
candidates: list[TableCandidate] = []
|
||||
for page in self._pdf.pages:
|
||||
try:
|
||||
tables = page.find_tables()
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not detect tables on page {page.page_number}: {exc}") from exc
|
||||
for table in tables:
|
||||
try:
|
||||
grid = table.extract()
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not extract table on page {page.page_number}: {exc}") from exc
|
||||
if len(grid) < 2:
|
||||
continue # header + >=1 data row required
|
||||
candidates.append(
|
||||
TableCandidate(
|
||||
page_number=page.page_number,
|
||||
bbox=tuple(table.bbox),
|
||||
grid=grid,
|
||||
confidence=_table_confidence(grid),
|
||||
)
|
||||
)
|
||||
candidates.sort(key=lambda c: c.confidence, reverse=True)
|
||||
return candidates
|
||||
|
||||
def select_table(self, page_number: int, bbox: tuple[float, float, float, float]) -> None:
|
||||
page = self._page(page_number)
|
||||
try:
|
||||
cropped = page.within_bbox(bbox, strict=False)
|
||||
grid = cropped.extract_table()
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not extract table at {bbox} on page {page_number}: {exc}") from exc
|
||||
if not grid or len(grid) < 2:
|
||||
raise ConnectorError(f"no usable table found at {bbox} on page {page_number}")
|
||||
self._table_grid = grid
|
||||
self._region_rows = None
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Drawn regions over the rendered page, read from text or OCR, then aligned
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def render_page_image(self, page_number: int, dpi: int = _DEFAULT_DPI) -> bytes:
|
||||
_check_dpi(dpi)
|
||||
page = self._page(page_number)
|
||||
try:
|
||||
image = page.to_image(resolution=dpi).original
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not render page {page_number}: {exc}") from exc
|
||||
buffer = io.BytesIO()
|
||||
image.save(buffer, format="PNG")
|
||||
return buffer.getvalue()
|
||||
|
||||
def extract_regions(self, regions: list[RegionSpec], dpi: int = _DEFAULT_DPI) -> dict[str, list[str | None]]:
|
||||
if not regions:
|
||||
raise ConnectorError("no regions given")
|
||||
_check_dpi(dpi)
|
||||
|
||||
by_page: dict[int, list[RegionSpec]] = {}
|
||||
for region in regions:
|
||||
for page_number in region.page_numbers:
|
||||
by_page.setdefault(page_number, []).append(region)
|
||||
|
||||
self.warnings = []
|
||||
result: dict[str, list[str | None]] = {region.target_field: [] for region in regions}
|
||||
|
||||
for page_number in sorted(by_page):
|
||||
page = self._page(page_number)
|
||||
lines = self._lines_for_page(page, by_page[page_number], dpi)
|
||||
for row in self._cluster_rows(lines, page_number):
|
||||
for region in by_page[page_number]:
|
||||
result[region.target_field].append(row.get(region.target_field))
|
||||
|
||||
self._region_rows = result
|
||||
self._table_grid = None
|
||||
return result
|
||||
|
||||
def _lines_for_page(self, page, regions_on_page: list[RegionSpec], dpi: int) -> list[dict[str, Any]]:
|
||||
"""Collect `(target_field, y, height, text)` lines for every region
|
||||
on one page. Y is in page pixels at `dpi` whether the region was read
|
||||
from the text layer or OCR'd, so lines from all regions can be aligned."""
|
||||
scale = dpi / 72.0
|
||||
use_text_layer = self._page_has_text(page)
|
||||
rendered_image = None
|
||||
lines: list[dict[str, Any]] = []
|
||||
|
||||
for region in regions_on_page:
|
||||
x0n, y0n, x1n, y1n = region.bbox
|
||||
|
||||
if use_text_layer:
|
||||
point_bbox = self._clamp_to_page(
|
||||
(x0n * page.width, y0n * page.height, x1n * page.width, y1n * page.height),
|
||||
page,
|
||||
)
|
||||
try:
|
||||
region_lines = page.within_bbox(point_bbox, strict=False).extract_text_lines()
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not extract text for region {region.target_field!r}: {exc}") from exc
|
||||
for line in region_lines:
|
||||
text = (line.get("text") or "").strip()
|
||||
if not text:
|
||||
continue
|
||||
lines.append(
|
||||
{
|
||||
"target_field": region.target_field,
|
||||
"y": ((line["top"] + line["bottom"]) / 2) * scale,
|
||||
"height": (line["bottom"] - line["top"]) * scale,
|
||||
"text": text,
|
||||
}
|
||||
)
|
||||
else:
|
||||
if rendered_image is None:
|
||||
try:
|
||||
rendered_image = page.to_image(resolution=dpi).original
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not render page {page.page_number}: {exc}") from exc
|
||||
img_w, img_h = rendered_image.size
|
||||
crop_box = (
|
||||
max(0, round(x0n * img_w)),
|
||||
max(0, round(y0n * img_h)),
|
||||
min(img_w, round(x1n * img_w)),
|
||||
min(img_h, round(y1n * img_h)),
|
||||
)
|
||||
if crop_box[2] <= crop_box[0] or crop_box[3] <= crop_box[1]:
|
||||
continue
|
||||
cropped = rendered_image.crop(crop_box)
|
||||
try:
|
||||
data = pytesseract.image_to_data(cropped, output_type=Output.DICT, lang=DEFAULT_LANG, config=_OCR_CONFIG)
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"OCR failed for region {region.target_field!r}: {exc}") from exc
|
||||
for words in group_words(data):
|
||||
text = " ".join(w["text"] for w in words).strip()
|
||||
if not text:
|
||||
continue
|
||||
top_local = min(w["top"] for w in words)
|
||||
bottom_local = max(w["top"] + w["height"] for w in words)
|
||||
lines.append(
|
||||
{
|
||||
"target_field": region.target_field,
|
||||
"y": crop_box[1] + (top_local + bottom_local) / 2,
|
||||
"height": bottom_local - top_local,
|
||||
"text": text,
|
||||
}
|
||||
)
|
||||
return lines
|
||||
|
||||
def _cluster_rows(self, lines: list[dict[str, Any]], page_number: int) -> list[dict[str, str]]:
|
||||
if not lines:
|
||||
return []
|
||||
heights = [line["height"] for line in lines if line["height"] > 0]
|
||||
median_height = statistics.median(heights) if heights else 10.0
|
||||
gap_tolerance = 0.6 * median_height
|
||||
|
||||
ordered = sorted(lines, key=lambda line: line["y"])
|
||||
clusters: list[list[dict[str, Any]]] = [[ordered[0]]]
|
||||
for line in ordered[1:]:
|
||||
if line["y"] - clusters[-1][-1]["y"] <= gap_tolerance:
|
||||
clusters[-1].append(line)
|
||||
else:
|
||||
clusters.append([line])
|
||||
|
||||
resolved: list[list[dict[str, Any]]] = []
|
||||
for cluster in clusters:
|
||||
resolved.extend(self._split_conflicts(cluster, page_number))
|
||||
|
||||
rows = []
|
||||
for cluster in resolved:
|
||||
row: dict[str, str] = {}
|
||||
for line in cluster:
|
||||
if line["target_field"] in row:
|
||||
row[line["target_field"]] = f"{row[line['target_field']]} {line['text']}".strip()
|
||||
else:
|
||||
row[line["target_field"]] = line["text"]
|
||||
rows.append(row)
|
||||
return rows
|
||||
|
||||
def _split_conflicts(self, cluster: list[dict[str, Any]], page_number: int) -> list[list[dict[str, Any]]]:
|
||||
"""A row cluster holds at most one line per target field. When two
|
||||
lines of the same region land in one cluster, split it at its largest
|
||||
internal gap (recursively) and record a warning rather than drop data."""
|
||||
fields = [line["target_field"] for line in cluster]
|
||||
if len(fields) == len(set(fields)) or len(cluster) < 2:
|
||||
return [cluster]
|
||||
|
||||
ordered = sorted(cluster, key=lambda line: line["y"])
|
||||
gaps = [(ordered[i + 1]["y"] - ordered[i]["y"], i) for i in range(len(ordered) - 1)]
|
||||
_, split_at = max(gaps, key=lambda g: g[0])
|
||||
left, right = ordered[: split_at + 1], ordered[split_at + 1 :]
|
||||
|
||||
duplicated = sorted({f for f in fields if fields.count(f) > 1})
|
||||
self.warnings.append(
|
||||
ExtractionWarning(
|
||||
page_number=page_number,
|
||||
message=f"alignment conflict on field(s) {duplicated}: cluster split at largest internal gap",
|
||||
)
|
||||
)
|
||||
return self._split_conflicts(left, page_number) + self._split_conflicts(right, page_number)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Connector interface, usable once select_table() or extract_regions() ran
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _dataframe(self) -> pd.DataFrame:
|
||||
if self._table_grid is not None:
|
||||
header, *data_rows = self._table_grid
|
||||
columns = [name if name else f"column_{i}" for i, name in enumerate(header)]
|
||||
return pd.DataFrame(data_rows, columns=columns)
|
||||
if self._region_rows is not None:
|
||||
return pd.DataFrame(self._region_rows)
|
||||
raise ConnectorError("no table or region resolved — call select_table() or extract_regions() first")
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _page(self, page_number: int):
|
||||
if not (1 <= page_number <= self.page_count):
|
||||
raise ConnectorError(f"page_number out of range: {page_number}")
|
||||
return self._pdf.pages[page_number - 1]
|
||||
|
||||
@staticmethod
|
||||
def _clamp_to_page(bbox: tuple[float, float, float, float], page) -> tuple[float, float, float, float]:
|
||||
x0, top, x1, bottom = bbox
|
||||
px0, ptop, px1, pbottom = page.bbox
|
||||
return (max(x0, px0), max(top, ptop), min(x1, px1), min(bottom, pbottom))
|
||||
|
||||
|
||||
def _check_dpi(dpi: int) -> None:
|
||||
if not (_MIN_DPI <= dpi <= _MAX_DPI):
|
||||
raise ConnectorError(f"dpi must be between {_MIN_DPI} and {_MAX_DPI}, got {dpi}")
|
||||
|
||||
|
||||
def _table_confidence(grid: list[list[str | None]]) -> float:
|
||||
"""Ranking heuristic for the UI: capped row count plus non-empty cell rate."""
|
||||
data_rows = len(grid) - 1
|
||||
total_cells = sum(len(row) for row in grid) or 1
|
||||
filled_cells = sum(1 for row in grid for cell in row if cell not in (None, ""))
|
||||
fill_rate = filled_cells / total_cells
|
||||
row_score = min(data_rows / 5, 1.0)
|
||||
return round(0.5 * row_score + 0.5 * fill_rate, 4)
|
||||
@@ -0,0 +1,38 @@
|
||||
from typing import Any
|
||||
|
||||
from webapi.imports.connectors.base import Connector
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
|
||||
CONNECTORS: dict[str, type[Connector]] = {}
|
||||
|
||||
|
||||
def register_connector(cls: type[Connector]) -> type[Connector]:
|
||||
if cls.kind in CONNECTORS:
|
||||
raise ValueError(f"connector kind {cls.kind!r} is already registered by {CONNECTORS[cls.kind].__name__}")
|
||||
CONNECTORS[cls.kind] = cls
|
||||
return cls
|
||||
|
||||
|
||||
def connector_class(kind: str | None) -> type[Connector]:
|
||||
cls = CONNECTORS.get(kind or "")
|
||||
if cls is None:
|
||||
raise ConnectorError(f"unknown source kind {kind!r} (available: {', '.join(sorted(CONNECTORS))})")
|
||||
return cls
|
||||
|
||||
|
||||
def build_connector(kind: str | None, payload: dict[str, Any]) -> Connector:
|
||||
if not isinstance(payload, dict):
|
||||
raise ConnectorError("payload must be an object")
|
||||
try:
|
||||
return connector_class(kind).from_payload(payload)
|
||||
except KeyError as exc:
|
||||
raise ConnectorError(f"missing field in payload: {exc}") from exc
|
||||
|
||||
|
||||
def kind_for_filename(filename: str) -> str | None:
|
||||
extension = filename.lower().rsplit(".", 1)[-1]
|
||||
return next((kind for kind, cls in CONNECTORS.items() if extension in cls.extensions), None)
|
||||
|
||||
|
||||
def catalog() -> list[dict[str, Any]]:
|
||||
return [cls.describe() for cls in CONNECTORS.values()]
|
||||
@@ -0,0 +1,262 @@
|
||||
import datetime as _dt
|
||||
import importlib.util
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, ClassVar, Iterator
|
||||
|
||||
import pandas as pd
|
||||
import sqlalchemy as sa
|
||||
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.tabular import infer_type
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SqlEngine:
|
||||
"""A database server the connection form offers. Supporting another
|
||||
server is one entry in `SqlConnector.ENGINES` plus its driver package."""
|
||||
|
||||
id: str
|
||||
label: str
|
||||
drivername: str
|
||||
default_port: int
|
||||
driver_module: str
|
||||
description: str = ""
|
||||
default_schema: str | None = None
|
||||
|
||||
@property
|
||||
def available(self) -> bool:
|
||||
return importlib.util.find_spec(self.driver_module) is not None
|
||||
|
||||
def describe(self) -> dict[str, Any]:
|
||||
return {
|
||||
"id": self.id,
|
||||
"label": self.label,
|
||||
"description": self.description,
|
||||
"default_port": self.default_port,
|
||||
"default_schema": self.default_schema,
|
||||
"available": self.available,
|
||||
}
|
||||
|
||||
|
||||
@register_connector
|
||||
class SqlConnector(Connector):
|
||||
"""Reads a table or a SELECT from a client's database server.
|
||||
|
||||
Browsing (`list_schemas`/`list_tables`/`list_columns`) lives here only;
|
||||
the import pipeline uses the `Connector` methods once `select_table` or
|
||||
`select_query` has been called. Rows come straight from SQLAlchemy, so
|
||||
they keep the driver's types, previews fetch only `limit` rows and
|
||||
`read_rows` streams. Connections are read-only (see `_reading`) and
|
||||
unpooled, since every request builds its own connector.
|
||||
"""
|
||||
|
||||
kind = "sql"
|
||||
label = "Base de datos"
|
||||
description = "Tabla o consulta de un servidor SQL"
|
||||
category = "database"
|
||||
icon = "storage"
|
||||
|
||||
ENGINES: ClassVar[dict[str, SqlEngine]] = {
|
||||
engine.id: engine
|
||||
for engine in (
|
||||
SqlEngine("mysql", "MySQL", "mysql+pymysql", 3306, "pymysql", "Servidor MySQL 5.7+ / 8"),
|
||||
SqlEngine("mariadb", "MariaDB", "mariadb+pymysql", 3306, "pymysql", "Servidor MariaDB"),
|
||||
SqlEngine("postgresql", "PostgreSQL", "postgresql+psycopg2", 5432, "psycopg2", "Servidor PostgreSQL", "public"),
|
||||
SqlEngine("mssql", "SQL Server", "mssql+pymssql", 1433, "pymssql", "Microsoft SQL Server 2017+ / Azure SQL", "dbo"),
|
||||
)
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def describe(cls) -> dict[str, Any]:
|
||||
return {**super().describe(), "engines": [engine.describe() for engine in cls.ENGINES.values()]}
|
||||
|
||||
@classmethod
|
||||
def from_payload(cls, payload: dict[str, Any]) -> "SqlConnector":
|
||||
connector = cls.connect(payload)
|
||||
if payload.get("query"):
|
||||
return connector.select_query(payload["query"])
|
||||
return connector.select_table(payload["table"], schema=payload.get("schema"))
|
||||
|
||||
@classmethod
|
||||
def connect(cls, payload: dict[str, Any]) -> "SqlConnector":
|
||||
"""A connector without a table selected yet, for browsing. Takes
|
||||
either `server` (engine, host, port, database, user, password) or a
|
||||
raw SQLAlchemy `connection_string`."""
|
||||
if payload.get("server"):
|
||||
return cls(cls.server_url(payload["server"]))
|
||||
if payload.get("connection_string"):
|
||||
return cls(payload["connection_string"])
|
||||
raise ConnectorError("missing server or connection_string")
|
||||
|
||||
@classmethod
|
||||
def server_url(cls, server: dict[str, Any]) -> sa.engine.URL:
|
||||
engine = cls.ENGINES.get(server.get("engine", ""))
|
||||
if engine is None:
|
||||
raise ConnectorError(f"unknown engine {server.get('engine')!r} (available: {', '.join(cls.ENGINES)})")
|
||||
if not engine.available:
|
||||
raise ConnectorError(f"the {engine.label} driver ({engine.driver_module}) is not installed on the server")
|
||||
if not server.get("host") or not server.get("database"):
|
||||
raise ConnectorError("host and database are required")
|
||||
try:
|
||||
port = int(server.get("port") or engine.default_port)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ConnectorError("port must be a number") from exc
|
||||
return sa.engine.URL.create(
|
||||
engine.drivername,
|
||||
username=server.get("user") or None,
|
||||
password=server.get("password") or None,
|
||||
host=server["host"],
|
||||
port=port,
|
||||
database=server["database"],
|
||||
)
|
||||
|
||||
def __init__(self, connection: str | sa.engine.URL, *, policy: SqlSourcePolicy | None = None):
|
||||
self._policy = policy or SqlSourcePolicy.from_env()
|
||||
url = self._policy.check_url(connection)
|
||||
try:
|
||||
self._engine = sa.create_engine(url, poolclass=NullPool)
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"invalid connection string: {exc}") from exc
|
||||
self._table: sa.Table | None = None
|
||||
self._query: str | None = None
|
||||
|
||||
# -- browsing ---------------------------------------------------------
|
||||
|
||||
def test_connection(self) -> None:
|
||||
try:
|
||||
with self._reading() as conn:
|
||||
conn.execute(sa.text("SELECT 1"))
|
||||
except ConnectorError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not connect: {exc}") from exc
|
||||
|
||||
def get_dialect(self) -> str:
|
||||
return self._engine.dialect.name
|
||||
|
||||
def list_schemas(self) -> list[str]:
|
||||
try:
|
||||
return sa.inspect(self._engine).get_schema_names()
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not list schemas: {exc}") from exc
|
||||
|
||||
def list_tables(self, *, schema: str | None = None) -> list[str]:
|
||||
try:
|
||||
inspector = sa.inspect(self._engine)
|
||||
return inspector.get_table_names(schema=schema) + inspector.get_view_names(schema=schema)
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not list tables: {exc}") from exc
|
||||
|
||||
def list_columns(self, table_name: str, *, schema: str | None = None) -> list[SourceColumn]:
|
||||
try:
|
||||
columns = sa.inspect(self._engine).get_columns(table_name, schema=schema)
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not list columns: {exc}") from exc
|
||||
return [SourceColumn(name=c["name"], inferred_type=_sa_type_to_kind(c["type"])) for c in columns]
|
||||
|
||||
def select_table(self, table_name: str, *, schema: str | None = None) -> "SqlConnector":
|
||||
try:
|
||||
self._table = sa.Table(table_name, sa.MetaData(), schema=schema, autoload_with=self._engine)
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not open table {table_name!r}: {exc}") from exc
|
||||
self._query = None
|
||||
return self
|
||||
|
||||
def select_query(self, query: str) -> "SqlConnector":
|
||||
self._query, self._table = self._policy.check_query(query), None
|
||||
return self
|
||||
|
||||
# -- Connector ----------------------------------------------------------
|
||||
|
||||
def get_columns(self) -> list[SourceColumn]:
|
||||
return self.preview(limit=200).columns
|
||||
|
||||
def preview(self, *, limit: int = 20) -> PreviewResult:
|
||||
statement = self._selectable()
|
||||
try:
|
||||
with self._reading() as conn:
|
||||
result = conn.execute(sa.select(statement).limit(limit))
|
||||
names = list(result.keys())
|
||||
rows = [dict(row) for row in result.mappings()]
|
||||
total = conn.execute(sa.select(sa.func.count()).select_from(statement)).scalar_one()
|
||||
except ConnectorError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not read rows: {exc}") from exc
|
||||
return PreviewResult(columns=self._columns(names, rows), sample_rows=rows, total_rows=total)
|
||||
|
||||
def read_rows(self, column_mapping: dict[str, str]) -> Iterator[dict[str, Any]]:
|
||||
statement = sa.select(self._selectable())
|
||||
try:
|
||||
with self._reading() as conn:
|
||||
result = conn.execution_options(stream_results=True, yield_per=1000).execute(statement)
|
||||
for row in result.mappings():
|
||||
yield {target: row.get(source) for source, target in column_mapping.items()}
|
||||
except ConnectorError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
raise ConnectorError(f"could not read rows: {exc}") from exc
|
||||
|
||||
# -- internals ----------------------------------------------------------
|
||||
|
||||
def _selectable(self) -> sa.Subquery:
|
||||
if self._table is not None:
|
||||
return sa.select(self._table).subquery("source")
|
||||
if self._query:
|
||||
return _text_subquery(self._query)
|
||||
raise ConnectorError("no table or query selected — call select_table()/select_query() first")
|
||||
|
||||
def _columns(self, names: list[str], rows: list[dict[str, Any]]) -> list[SourceColumn]:
|
||||
if self._table is not None:
|
||||
by_name = {c.name: c for c in self._table.columns}
|
||||
return [SourceColumn(n, _sa_type_to_kind(by_name[n].type) if n in by_name else "string") for n in names]
|
||||
return [SourceColumn(n, infer_type(pd.Series([r.get(n) for r in rows], dtype=object))) for n in names]
|
||||
|
||||
@contextmanager
|
||||
def _reading(self):
|
||||
"""A connection that can't write: read-only mode where the dialect
|
||||
has one, and an unconditional rollback, so not even a SELECT calling
|
||||
a side-effecting function can commit anything. SQL Server has no
|
||||
read-only session mode; the rollback and `SqlSourcePolicy`'s
|
||||
single-SELECT rule cover it."""
|
||||
with self._engine.connect() as conn:
|
||||
dialect = conn.dialect.name
|
||||
if dialect in ("mysql", "mariadb"):
|
||||
conn.exec_driver_sql("SET SESSION TRANSACTION READ ONLY")
|
||||
elif dialect == "postgresql":
|
||||
conn.exec_driver_sql("SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY")
|
||||
elif dialect == "sqlite":
|
||||
conn.exec_driver_sql("PRAGMA query_only = ON")
|
||||
try:
|
||||
yield conn
|
||||
finally:
|
||||
conn.rollback()
|
||||
|
||||
|
||||
def _text_subquery(query: str) -> sa.Subquery:
|
||||
"""Wraps policy-checked SELECT text as a derived table, so SQLAlchemy
|
||||
composes LIMIT/TOP and COUNT(*) for whichever dialect the source speaks."""
|
||||
return sa.select(sa.literal_column("*")).select_from(sa.text(f"({query}) AS source_query")).subquery("source")
|
||||
|
||||
|
||||
def _sa_type_to_kind(sa_type: sa.types.TypeEngine) -> str:
|
||||
try:
|
||||
python_type = sa_type.python_type
|
||||
except (NotImplementedError, AttributeError):
|
||||
return "string"
|
||||
if python_type is bool:
|
||||
return "boolean"
|
||||
if python_type is int:
|
||||
return "integer"
|
||||
if python_type is float:
|
||||
return "float"
|
||||
if python_type is _dt.datetime:
|
||||
return "datetime"
|
||||
if python_type is _dt.date:
|
||||
return "date"
|
||||
return "string"
|
||||
@@ -0,0 +1,90 @@
|
||||
"""What a client-supplied connection or query may reach. The SQL
|
||||
connector is the one place where the client picks what the server connects
|
||||
to, so:
|
||||
|
||||
- dialects are allowlisted (`WEBAPI_SQL_ALLOWED_DIALECTS`); sqlite is off
|
||||
by default because its URL is a path on this server's filesystem;
|
||||
- hosts can be allowlisted (`WEBAPI_SQL_ALLOWED_HOSTS`, comma-separated);
|
||||
- the application's own databases are never a valid source;
|
||||
- custom SQL must be a single SELECT/WITH statement (on top of the
|
||||
read-only connection, not instead of it).
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
|
||||
from sqlalchemy.engine import URL, make_url
|
||||
from sqlalchemy.exc import ArgumentError
|
||||
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
|
||||
_DEFAULT_DIALECTS = "mysql,mariadb,postgresql,mssql,oracle"
|
||||
_LEADING_COMMENTS = re.compile(r"^\s*((--[^\n]*\n)|(/\*.*?\*/)|\s)*", re.S)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SqlSourcePolicy:
|
||||
allowed_dialects: frozenset[str]
|
||||
allowed_hosts: frozenset[str] | None
|
||||
|
||||
@classmethod
|
||||
def from_env(cls) -> "SqlSourcePolicy":
|
||||
dialects = os.environ.get("WEBAPI_SQL_ALLOWED_DIALECTS", _DEFAULT_DIALECTS)
|
||||
hosts = os.environ.get("WEBAPI_SQL_ALLOWED_HOSTS")
|
||||
return cls(
|
||||
allowed_dialects=frozenset(d.strip().lower() for d in dialects.split(",") if d.strip()),
|
||||
allowed_hosts=frozenset(h.strip().lower() for h in hosts.split(",") if h.strip()) if hosts else None,
|
||||
)
|
||||
|
||||
def check_url(self, connection: "str | URL") -> URL:
|
||||
try:
|
||||
url = connection if isinstance(connection, URL) else make_url(connection)
|
||||
except ArgumentError as exc:
|
||||
raise ConnectorError(f"invalid connection string: {exc}") from exc
|
||||
dialect = url.get_backend_name()
|
||||
if dialect not in self.allowed_dialects:
|
||||
raise ConnectorError(
|
||||
f"dialect {dialect!r} is not allowed for import sources (allowed: {', '.join(sorted(self.allowed_dialects))})"
|
||||
)
|
||||
if self.allowed_hosts is not None and (url.host or "").lower() not in self.allowed_hosts:
|
||||
raise ConnectorError(f"host {url.host!r} is not in the allowed import-source hosts")
|
||||
if _same_database(url, _own_database_urls()):
|
||||
raise ConnectorError("this connection points at the application's own database — not a valid import source")
|
||||
return url
|
||||
|
||||
@staticmethod
|
||||
def check_query(query: str) -> str:
|
||||
statement = query.strip().rstrip(";").strip()
|
||||
if ";" in statement:
|
||||
raise ConnectorError("custom SQL must be a single statement")
|
||||
body = _LEADING_COMMENTS.sub("", statement, count=1)
|
||||
first_word = body.split(None, 1)[0].upper() if body else ""
|
||||
if first_word not in ("SELECT", "WITH"):
|
||||
raise ConnectorError("custom SQL must be a SELECT (or WITH ... SELECT) query")
|
||||
return statement
|
||||
|
||||
|
||||
def _own_database_urls() -> list[URL]:
|
||||
from persistance.settings import settings
|
||||
|
||||
urls = []
|
||||
for raw in (
|
||||
settings.cacu_database_url,
|
||||
settings.cama_database_url,
|
||||
settings.tea_database_url,
|
||||
settings.governance_database_url,
|
||||
):
|
||||
try:
|
||||
urls.append(make_url(raw))
|
||||
except ArgumentError:
|
||||
continue
|
||||
return urls
|
||||
|
||||
|
||||
def _same_database(candidate: URL, own: list[URL]) -> bool:
|
||||
def key(url: URL) -> tuple:
|
||||
if url.get_backend_name() == "sqlite":
|
||||
return ("sqlite", os.path.realpath(url.database or ""))
|
||||
return (url.get_backend_name(), (url.host or "localhost").lower(), url.port, (url.database or "").lower())
|
||||
|
||||
return key(candidate) in {key(url) for url in own}
|
||||
@@ -0,0 +1,122 @@
|
||||
"""Connectors whose rows fit in one pandas DataFrame (CSV, Excel, JSON,
|
||||
PDF, EDF, documents): they only have to build the DataFrame."""
|
||||
|
||||
import datetime as _dt
|
||||
import math
|
||||
import re
|
||||
from abc import abstractmethod
|
||||
from typing import Any, ClassVar, Iterator
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from webapi.imports.connectors.base import Connector, PreviewResult, SourceColumn, decode_file
|
||||
|
||||
|
||||
class DataFrameConnector(Connector):
|
||||
@abstractmethod
|
||||
def _dataframe(self) -> pd.DataFrame: ...
|
||||
|
||||
def get_columns(self) -> list[SourceColumn]:
|
||||
return columns_from_dataframe(self._dataframe())
|
||||
|
||||
def preview(self, *, limit: int = 20) -> PreviewResult:
|
||||
df = self._dataframe()
|
||||
return PreviewResult(
|
||||
columns=columns_from_dataframe(df),
|
||||
sample_rows=rows_from_dataframe(df.head(limit)),
|
||||
total_rows=len(df),
|
||||
)
|
||||
|
||||
def read_rows(self, column_mapping: dict[str, str]) -> Iterator[dict[str, Any]]:
|
||||
for row in rows_from_dataframe(self._dataframe()):
|
||||
yield {target: row.get(source) for source, target in column_mapping.items()}
|
||||
|
||||
|
||||
class FileConnector(DataFrameConnector):
|
||||
"""An uploaded file. Subclasses implement `__init__(raw, **options)`
|
||||
and list the keyword options a client may pass in `option_names`."""
|
||||
|
||||
option_names: ClassVar[tuple[str, ...]] = ()
|
||||
|
||||
@classmethod
|
||||
def from_bytes(cls, raw: bytes, options: dict[str, Any] | None = None) -> "FileConnector":
|
||||
options = {k: v for k, v in (options or {}).items() if k in cls.option_names and v not in (None, "")}
|
||||
return cls(raw, **options)
|
||||
|
||||
@classmethod
|
||||
def from_payload(cls, payload: dict[str, Any]) -> "FileConnector":
|
||||
return cls.from_bytes(decode_file(payload), payload.get("options") or {})
|
||||
|
||||
|
||||
def columns_from_dataframe(df: pd.DataFrame) -> list[SourceColumn]:
|
||||
return [SourceColumn(name=str(name), inferred_type=infer_type(df[name])) for name in df.columns]
|
||||
|
||||
|
||||
_INT_RE = re.compile(r"^[+-]?\d+$")
|
||||
_FLOAT_RE = re.compile(r"^[+-]?(\d+\.\d*|\.\d+|\d+)([eE][+-]?\d+)?$")
|
||||
_DATE_RE = re.compile(r"^(\d{4}-\d{2}-\d{2}|\d{1,2}/\d{1,2}/\d{4})$")
|
||||
_DATETIME_RE = re.compile(r"^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}(:\d{2})?")
|
||||
_BOOL_VALUES = {"true", "false", "si", "sí", "no", "verdadero", "falso"}
|
||||
|
||||
|
||||
def infer_type(series: "pd.Series") -> str:
|
||||
"""Display hint for the UI only; values are never converted here."""
|
||||
kind = series.dtype.kind
|
||||
if kind in ("i", "u"):
|
||||
return "integer"
|
||||
if kind == "f":
|
||||
return "float"
|
||||
if kind == "b":
|
||||
return "boolean"
|
||||
if kind == "M":
|
||||
return "datetime"
|
||||
values = [v for v in series.head(500).tolist() if v is not None and not (isinstance(v, float) and math.isnan(v))]
|
||||
if not values:
|
||||
return "string"
|
||||
return _infer_from_values(values)
|
||||
|
||||
|
||||
def _infer_from_values(values: list[Any]) -> str:
|
||||
if all(isinstance(v, bool) for v in values):
|
||||
return "boolean"
|
||||
if all(isinstance(v, int) and not isinstance(v, bool) for v in values):
|
||||
return "integer"
|
||||
if all(isinstance(v, (int, float)) and not isinstance(v, bool) for v in values):
|
||||
return "float"
|
||||
if all(isinstance(v, _dt.datetime) for v in values):
|
||||
return "datetime"
|
||||
if all(isinstance(v, _dt.date) for v in values):
|
||||
return "date"
|
||||
if all(isinstance(v, (bytes, bytearray)) for v in values):
|
||||
return "binary"
|
||||
if not all(isinstance(v, str) for v in values):
|
||||
return "string"
|
||||
texts = [v.strip() for v in values]
|
||||
# A leading zero ("01000", "007") means the value is a code, not a number.
|
||||
if all(_INT_RE.match(t) for t in texts) and not any(len(t.lstrip("+-")) > 1 and t.lstrip("+-").startswith("0") for t in texts):
|
||||
return "integer"
|
||||
if all(_FLOAT_RE.match(t) for t in texts) and any("." in t or "e" in t.lower() for t in texts):
|
||||
return "float"
|
||||
if all(_DATETIME_RE.match(t) for t in texts):
|
||||
return "datetime"
|
||||
if all(_DATE_RE.match(t) for t in texts):
|
||||
return "date"
|
||||
if all(t.lower() in _BOOL_VALUES for t in texts):
|
||||
return "boolean"
|
||||
return "string"
|
||||
|
||||
|
||||
def rows_from_dataframe(df: pd.DataFrame) -> list[dict[str, Any]]:
|
||||
return [{key: clean_value(value) for key, value in row.items()} for row in df.to_dict(orient="records")]
|
||||
|
||||
|
||||
def clean_value(value: Any) -> Any:
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, float) and math.isnan(value):
|
||||
return None
|
||||
if value is pd.NaT:
|
||||
return None
|
||||
if hasattr(value, "to_pydatetime"): # pandas.Timestamp
|
||||
return value.to_pydatetime()
|
||||
return value
|
||||
Reference in New Issue
Block a user