Skip to content

The platform for continuously improving AI agents.

4.9 KB
Raw Blame
"""XLSX workbooks → rows, one sheet at a time.

The first row of a sheet is its header. Formulas stay their source text, never a computed
value; dates become ISO text and durations seconds. Each row's ``_overmind_evidence``
names its sheet and row and the cells whose stored value is a formula, an error, a date or
a duration.
"""

from __future__ import annotations

import datetime as dt
import itertools
from collections.abc import Iterator
from contextlib import contextmanager
from pathlib import Path
from typing import Any
from zipfile import BadZipFile, ZipFile

from openpyxl import load_workbook
from openpyxl.utils.exceptions import InvalidFileException

from overbae.core.errors import InputValidationError
from overbae.services.datasets.store import EVIDENCE

MAX_BYTES = 100 * 1024**2
MAX_EXPANDED_BYTES = 512 * 1024**2
_NONLITERAL = {"f": "formula", "e": "error"}


class SpreadsheetError(InputValidationError):
    pass


@contextmanager
def _workbook(path: Path):
    try:
        with ZipFile(path) as archive:
            if sum(member.file_size for member in archive.infolist()) > MAX_EXPANDED_BYTES:
                raise SpreadsheetError("The workbook expands to more than 512 MiB.")
        # Staged uploads have no extension, which load_workbook needs for a path.
        with path.open("rb") as stream:
            workbook = load_workbook(stream, read_only=True, data_only=False, keep_links=False)
            try:
                yield workbook
            finally:
                workbook.close()
    except SpreadsheetError:
        raise
    except (BadZipFile, InvalidFileException, OSError, ValueError, KeyError, SyntaxError) as exc:
        raise SpreadsheetError("The file is not a readable XLSX workbook.") from exc


def _header(sheet: str, cells) -> list[str]:
    from overbae.services.datasets.files import (
        FileError,
        clean_names,
    )  # lazy: files imports this module

    values = [cell.value for cell in cells]
    while values and values[-1] is None:
        values.pop()
    if any(cell.data_type in _NONLITERAL for cell in cells[: len(values)]):
        raise SpreadsheetError(f"Sheet {sheet!r} has a formula or error in its header row.")
    names = ["" if value is None else str(value) for value in values]
    if any(name.strip().lower() == EVIDENCE for name in names):
        raise SpreadsheetError(f"Sheet {sheet!r} has a column named {EVIDENCE}. Rename it.")
    try:
        return clean_names(names)
    except FileError as exc:
        raise SpreadsheetError(f"Sheet {sheet!r}: {exc.detail}") from exc


def _rows(worksheet) -> Iterator[tuple[int, tuple]]:
    worksheet.reset_dimensions()
    for number, cells in enumerate(worksheet.iter_rows(), start=1):
        if any(cell.value is not None for cell in cells):
            yield number, cells


def sheets(path: Path) -> list[str]:
    """The sheets that hold a header and at least one row, in workbook order."""
    found = []
    with _workbook(path) as workbook:
        for worksheet in workbook:
            rows = _rows(worksheet)
            if next(rows, None) is not None and next(rows, None) is not None:
                found.append(worksheet.title)
    return found


def rows(path: Path, sheet: str, *, header: bool = True) -> Iterator[dict[str, Any]]:
    """Without ``header`` the first row is data and the columns are ``column_N``."""
    with _workbook(path) as workbook:
        if sheet not in workbook.sheetnames:
            raise SpreadsheetError(f"The workbook has no sheet {sheet!r}.")
        numbered = _rows(workbook[sheet])
        first = next(numbered, None)
        if first is None:
            return
        if header:
            names = _header(sheet, first[1])
        else:
            values = [cell.value for cell in first[1]]
            while values and values[-1] is None:
                values.pop()
            names = [f"column_{index}" for index in range(1, len(values) + 1)]
            numbered = itertools.chain([first], numbered)
        for number, cells in numbered:
            if any(cell.value is not None for cell in cells[len(names) :]):
                raise SpreadsheetError(
                    f"Sheet {sheet!r} row {number} has a value right of its last header cell."
                )
            record: dict[str, Any] = dict.fromkeys(names)
            kinds = {}
            for name, cell in zip(names, cells, strict=False):
                value = cell.value
                if isinstance(value, dt.timedelta):
                    kinds[name] = "duration_seconds"
                    value = value.total_seconds()
                elif isinstance(value, (dt.datetime, dt.date, dt.time)):
                    kinds[name] = type(value).__name__
                    value = value.isoformat()
                elif cell.data_type in _NONLITERAL:
                    kinds[name] = _NONLITERAL[cell.data_type]
                record[name] = value
            record[EVIDENCE] = {"sheet": sheet, "row": number, "cells": kinds}
            yield record