improve ingestion system to match isssteleon setup
This commit is contained in:
@@ -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()}
|
||||
Reference in New Issue
Block a user