168 lines
7.4 KiB
Python
168 lines
7.4 KiB
Python
"""Documents stored in the columns of any tabular source: a SQL table or
|
|
query, a CSV or Excel sheet, a JSON list. Each non-empty cell of a document
|
|
column becomes one document; the rest of its row travels with it as values
|
|
the extraction must trust over the page, and an optional grouping decides
|
|
which documents form one record.
|
|
|
|
A cell may hold the file itself (binary), the same file written as hex or
|
|
base64 text, or plain text; `document_bytes` tells them apart.
|
|
"""
|
|
import base64
|
|
import binascii
|
|
import re
|
|
from dataclasses import dataclass, field
|
|
from typing import Any, Iterable
|
|
|
|
from webapi.imports.connectors.errors import ConnectorError
|
|
from webapi.imports.mapping.derived import Derivation, rule_from
|
|
|
|
_HEX = re.compile(r"^(?:0x)?(?:[0-9a-fA-F]{2})+$")
|
|
_BASE64 = re.compile(r"^[A-Za-z0-9+/\r\n]+={0,2}$")
|
|
DOCUMENT_MAGIC = (b"%PDF", b"\x89PNG", b"\xff\xd8\xff", b"II*\x00", b"MM\x00*", b"BM", b"RIFF", b"GIF8")
|
|
|
|
|
|
def document_bytes(raw: Any) -> bytes:
|
|
"""A stored document as bytes. Binary values pass through; text is
|
|
checked for a binary file written out as hex or base64 before being
|
|
taken as plain UTF-8 text."""
|
|
if isinstance(raw, memoryview):
|
|
raw = raw.tobytes()
|
|
if isinstance(raw, (bytes, bytearray)):
|
|
return bytes(raw)
|
|
text = str(raw).strip()
|
|
if len(text) >= 16 and _HEX.match(text):
|
|
decoded = bytes.fromhex(text[2:] if text[:2].lower() == "0x" else text)
|
|
if decoded.startswith(DOCUMENT_MAGIC):
|
|
return decoded
|
|
if len(text) >= 16 and _BASE64.match(text):
|
|
try:
|
|
decoded = base64.b64decode(text, validate=False)
|
|
except (binascii.Error, ValueError):
|
|
decoded = b""
|
|
if decoded.startswith(DOCUMENT_MAGIC):
|
|
return decoded
|
|
return text.encode("utf-8")
|
|
|
|
|
|
def is_document(raw: Any) -> bool:
|
|
"""Whether a cell holds a file a document reader opens (as opposed to
|
|
a plain value), whatever way it was stored."""
|
|
if raw is None or isinstance(raw, (int, float, bool)):
|
|
return False
|
|
return document_bytes(raw).startswith(DOCUMENT_MAGIC)
|
|
|
|
|
|
@dataclass
|
|
class DocumentBatch:
|
|
"""What the extractor receives: one `(name, bytes)` per document and,
|
|
per document name, its authoritative values and the record it joins.
|
|
`rows` and `row_numbers` keep, per document name, the values of the row
|
|
it came from and that row's position (from 1)."""
|
|
|
|
files: list[tuple[str, bytes]] = field(default_factory=list)
|
|
source_fields: dict[str, dict[str, Any]] = field(default_factory=dict)
|
|
record_keys: dict[str, str] = field(default_factory=dict)
|
|
rows: dict[str, dict[str, Any]] = field(default_factory=dict)
|
|
row_numbers: dict[str, int] = field(default_factory=dict)
|
|
without_documents: list[dict[str, Any]] = field(default_factory=list)
|
|
|
|
|
|
@dataclass
|
|
class DocumentColumns:
|
|
"""How to read documents out of a source's rows.
|
|
|
|
`columns`: the columns holding documents (one or several per row).
|
|
`name_by`: names each row in reports (default: its row number).
|
|
`group_by`: rows giving the same value form one record, apart from
|
|
the same patient's other rows; without it, documents merge by the
|
|
target's key field, as uploaded files do.
|
|
`fields`: target fields filled from the row, trusted over the page.
|
|
The last three take a column name, a list of columns or a `derived`
|
|
rule (`webapi.imports.mapping.derived`)."""
|
|
|
|
columns: list[str]
|
|
name_by: Derivation | None = None
|
|
group_by: Derivation | None = None
|
|
fields: dict[str, Derivation] = field(default_factory=dict)
|
|
|
|
@classmethod
|
|
def parse(cls, raw: Any) -> "DocumentColumns":
|
|
if not isinstance(raw, dict):
|
|
raise ConnectorError("'documents' debe ser un objeto")
|
|
columns = raw.get("columns", raw.get("column"))
|
|
columns = [columns] if isinstance(columns, str) else list(columns or [])
|
|
if not columns or not all(isinstance(column, str) and column for column in columns):
|
|
raise ConnectorError("indique la columna (o columnas) con los documentos")
|
|
fields = raw.get("fields") or {}
|
|
if not isinstance(fields, dict):
|
|
raise ConnectorError("'fields' debe ser un objeto {campo: columna o regla}")
|
|
name_by = raw.get("name_by", raw.get("key_column"))
|
|
group_by = raw.get("group_by", raw.get("group_column"))
|
|
parsed = cls(
|
|
columns=columns,
|
|
name_by=rule_from(name_by) if name_by else None,
|
|
group_by=rule_from(group_by) if group_by else None,
|
|
fields={name: rule_from(rule, separator=" ") for name, rule in fields.items()},
|
|
)
|
|
roles = {"name_by (key_column)": [parsed.name_by], "group_by (group_column)": [parsed.group_by], "fields": list(parsed.fields.values())}
|
|
for role, rules in roles.items():
|
|
reused = set().union(*(rule.columns() for rule in rules if rule is not None)) & set(columns)
|
|
if reused:
|
|
raise ConnectorError(f"{sorted(reused)} contiene los documentos; no puede usarse también en {role}")
|
|
return parsed
|
|
|
|
def columns_read_by_rules(self) -> set[str]:
|
|
read: set[str] = set()
|
|
for rule in [self.name_by, self.group_by, *self.fields.values()]:
|
|
if rule is not None:
|
|
read |= rule.columns()
|
|
return read
|
|
|
|
def source_columns(self) -> set[str]:
|
|
return set(self.columns) | self.columns_read_by_rules()
|
|
|
|
def assemble(
|
|
self, raw_rows: Iterable[dict[str, Any]], mapped_rows: Iterable[dict[str, Any]] | None = None
|
|
) -> DocumentBatch:
|
|
"""`raw_rows` keyed by source column; `mapped_rows`, when the source
|
|
also has a mapping, the same rows already mapped to target fields,
|
|
whose values join `fields` as values to trust."""
|
|
batch = DocumentBatch()
|
|
seen: dict[str, int] = {}
|
|
mapped = iter(mapped_rows) if mapped_rows is not None else None
|
|
for number, raw in enumerate(raw_rows, start=1):
|
|
values = dict(next(mapped)) if mapped is not None else {}
|
|
values.update({name: rule.apply(raw) for name, rule in self.fields.items()})
|
|
values = {name: value for name, value in values.items() if not _blank(value)}
|
|
contents = [(column, raw.get(column)) for column in self.columns if not _blank(raw.get(column))]
|
|
if not contents:
|
|
batch.without_documents.append(values)
|
|
continue
|
|
base = _text(self.name_by.apply(raw)) if self.name_by else ""
|
|
base = base or str(number)
|
|
group = _text(self.group_by.apply(raw)) if self.group_by else ""
|
|
for column, content in contents:
|
|
name = base if len(self.columns) == 1 else f"{base}:{column}"
|
|
seen[name] = seen.get(name, 0) + 1
|
|
if seen[name] > 1:
|
|
name = f"{name}#{seen[name]}"
|
|
batch.files.append((name, document_bytes(content)))
|
|
batch.source_fields[name] = values
|
|
batch.rows[name] = values
|
|
batch.row_numbers[name] = number
|
|
if group:
|
|
batch.record_keys[name] = group
|
|
return batch
|
|
|
|
|
|
def _blank(value: Any) -> bool:
|
|
return value is None or (isinstance(value, str) and not value.strip())
|
|
|
|
|
|
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()
|