73 lines
2.7 KiB
Python
73 lines
2.7 KiB
Python
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("el archivo parece binario, no un texto delimitado")
|
|
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"no se pudo leer el 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"no se pudo decodificar el CSV como {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 ","
|