Files

120 lines
4.4 KiB
Python

"""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 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