Skip to content

The platform for continuously improving AI agents.

21.5 KB
Raw Blame
"""Files → rows, and the chunked upload that stages them.

Parsing yields plain dict rows: JSON stays nested (the store makes it a JSON
column); CSV/TSV cells are strings, numbers when every cell spells one exactly.
No row is skipped and no value is altered: a bad line, a row wider than the
header or a repeated column name is a ``FileError`` the caller shows.
"""

from __future__ import annotations

import csv
import gzip
import io
import itertools
import json
import logging
import math
import os
import re
import shutil
import uuid
from collections.abc import Iterator
from pathlib import Path
from typing import Any

import pyarrow as pa
import pyarrow.parquet as pq

from overbae.core.errors import InputValidationError
from overbae.services.datasets import documents, spreadsheets
from overbae.services.datasets.store import EVIDENCE

logger = logging.getLogger(__name__)

ALLOWED_SUFFIXES = (
    ".csv",
    ".tsv",
    ".json",
    ".jsonl",
    ".ndjson",
    ".parquet",
    ".xlsx",
    *documents.SUFFIXES,
)
CHUNK_BYTES = 8 * 1024 * 1024
MAX_UPLOAD_BYTES = 2 * 1024 * 1024 * 1024
JSON_ARRAY_MAX_BYTES = 256 * 1024 * 1024
_SAFE_NAME = re.compile(r"[^A-Za-z0-9._-]+")
UNSUPPORTED = (
    "Use a CSV, TSV, JSON, JSONL, Parquet, XLSX, PDF, DOCX, Markdown, text, PNG, JPEG or WebP file."
)

# How a delimited file or a workbook is read, as the import review sets it. An option that is
# absent keeps the default: a sniffed separator, UTF-8, a header row, every sheet.
DELIMITERS = {"comma": ",", "tab": "\t", "semicolon": ";", "pipe": "|"}
ENCODING_NAMES = {"utf-8-sig": "UTF-8", "utf-16": "UTF-16", "windows-1252": "Windows-1252"}
ENCODINGS = tuple(ENCODING_NAMES)
PREVIEW_ROWS = 5
PREVIEW_COLUMNS = 100
PREVIEW_CELL_CHARS = 500

# A transcript cell is far longer than the csv module's 128 KB default.
csv.field_size_limit(MAX_UPLOAD_BYTES)


class FileError(InputValidationError):
    """A parse or upload problem the user can act on."""


def _iter_jsonl(fh: io.TextIOBase) -> Iterator[dict[str, Any]]:
    for lineno, line in enumerate(fh, start=1):
        line = line.strip()
        if not line:
            continue
        try:
            value = json.loads(line)
        except ValueError as exc:
            raise FileError(f"Line {lineno} is not valid JSON.") from exc
        yield value if isinstance(value, dict) else {"value": value}


def _iter_json(fh: io.TextIOBase, rows_field: str | None = None) -> Iterator[dict[str, Any]]:
    """One JSON document, or JSON Lines under a ``.json`` name."""
    text = fh.read()
    try:
        value = json.loads(text)
    except json.JSONDecodeError as exc:
        if rows_field:
            raise FileError("An explicit JSON rows field requires one JSON object.") from exc
        if exc.msg != "Extra data":
            raise FileError(f"Not valid JSON at line {exc.lineno}, column {exc.colno}.") from exc
        yield from _iter_jsonl(io.StringIO(text))
        return
    if rows_field:
        if not isinstance(value, dict) or not isinstance(value.get(rows_field), list):
            raise FileError("The selected JSON rows field is missing or is not an array.")
        value = value[rows_field]
    elif isinstance(value, dict):
        # {"data": [...]} / {"rows": [...]} wrappers are common exports.
        for key in ("data", "rows", "items", "examples"):
            if isinstance(value.get(key), list):
                value = value[key]
                break
        else:
            value = [value]
    if not isinstance(value, list):
        raise FileError("A JSON file must hold an object or an array of objects.")
    for item in value:
        yield item if isinstance(item, dict) else {"value": item}


def _sniff_delimiter(sample: str, fallback: str) -> str:
    try:
        return csv.Sniffer().sniff(sample, delimiters=",\t;|").delimiter
    except csv.Error:
        return fallback


def read_options(raw: dict | None) -> dict[str, Any]:
    """The reading options a person chose, checked; unknown keys and values are refused."""
    options = dict(raw or {})
    if set(options) - {"delimiter", "encoding", "header", "sheet"}:
        raise FileError("Unsupported file reading option.")
    if options.get("delimiter", "comma") not in DELIMITERS:
        raise FileError("Choose a comma, tab, semicolon or pipe separator.")
    if options.get("encoding", "utf-8-sig") not in ENCODINGS:
        raise FileError("Choose UTF-8, UTF-16 or Windows-1252.")
    if not isinstance(options.get("header", True), bool):
        raise FileError("Say whether the first row holds the column names.")
    if not isinstance(options.get("sheet", ""), str):
        raise FileError("Choose a sheet by its name.")
    return options


def _iter_delimited(
    fh: io.TextIOBase, delimiter: str, options: dict | None = None
) -> Iterator[dict[str, Any]]:
    options = options or {}
    head = fh.read(64 * 1024)
    fh.seek(0)
    chosen = DELIMITERS.get(options.get("delimiter", ""))
    reader = csv.reader(fh, delimiter=chosen or _sniff_delimiter(head, delimiter))
    try:
        first = next(reader, None)
        if not first:
            raise FileError("The file has no header row.")
        if options.get("header", True):
            header, body = clean_names(first), reader
        else:
            header = [f"column_{index}" for index in range(1, len(first) + 1)]
            body = itertools.chain([first], reader)
        for cells in body:
            if not cells:
                continue
            if len(cells) > len(header):
                raise FileError(
                    f"Row {reader.line_num} has {len(cells)} cells; the header has "
                    f"{len(header)}. Quote a cell that holds the delimiter."
                )
            yield dict(zip(header, cells + [None] * (len(header) - len(cells)), strict=True))
    except csv.Error as exc:
        raise FileError(f"Row {reader.line_num} is not valid delimited text.") from exc


def clean_names(names: list[Any]) -> list[str]:
    """Names are stripped, a blank name becomes ``column_N``, and two names
    that differ only by case are refused: the frame store matches names
    case-insensitively, so one of them would be lost."""
    clean = [str(name).strip() or f"column_{i}" for i, name in enumerate(names, start=1)]
    seen: set[str] = set()
    for name in clean:
        if name.lower() in seen:
            raise FileError(f"Column {name!r} appears twice. Rename one of them.")
        seen.add(name.lower())
    return clean


def _normalise_names(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
    raw = list(dict.fromkeys(name for row in rows for name in row))
    names = dict(zip(raw, clean_names(raw), strict=True))
    if all(k == v for k, v in names.items()):
        return rows
    return [{names[k]: v for k, v in row.items()} for row in rows]


_INT = re.compile(r"-?(0|[1-9]\d{0,17})")


def _number(text: str) -> int | float | None:
    """The number ``text`` spells exactly, or None. ``007``, ``1_000``, ``nan``
    and a 19-digit id stay text because a number would not print back the same."""
    if _INT.fullmatch(text):
        return int(text)
    try:
        value = float(text)
    except ValueError:
        return None
    return value if math.isfinite(value) and repr(value) == text else None


def _coerce_numeric_columns(rows: list[dict[str, Any]]) -> None:
    """CSV cells are strings; a column becomes numeric only when every filled
    cell is the same kind of number and none would change when written back."""
    for name in {k for row in rows for k in row}:
        filled = [row[name] for row in rows if row.get(name) not in (None, "")]
        parsed = [_number(v) for v in filled]
        if not parsed or None in parsed or len({type(v) for v in parsed}) > 1:
            continue
        it = iter(parsed)
        for row in rows:
            if name in row:
                row[name] = next(it) if row[name] not in (None, "") else None


def _open_text(path: Path, name: str, encoding: str = "utf-8-sig") -> io.TextIOBase:
    if name.endswith(".gz"):
        return io.TextIOWrapper(gzip.open(path, "rb"), encoding=encoding, newline="")
    return open(path, encoding=encoding, newline="")


def iter_stream_rows(
    fh: io.TextIOBase,
    *,
    filename: str,
    json_rows_field: str | None = None,
    options: dict | None = None,
) -> Iterator[dict[str, Any]]:
    """Rows from an open text stream, keyed off the file extension."""
    name = (filename or "").lower().removesuffix(".gz")
    if name.endswith((".jsonl", ".ndjson")):
        yield from _iter_jsonl(fh)
    elif name.endswith(".json"):
        yield from _iter_json(fh, json_rows_field)
    elif name.endswith(".tsv"):
        yield from _iter_delimited(fh, "\t", options)
    elif name.endswith(".csv"):
        yield from _iter_delimited(fh, ",", options)
    else:
        raise FileError(UNSUPPORTED)


def _text_rows(fh: io.TextIOBase, name: str) -> list[dict[str, Any]]:
    rows = _normalise_names(list(iter_stream_rows(fh, filename=name)))
    if name.endswith((".csv", ".tsv")):
        _coerce_numeric_columns(rows)
    return rows


def iter_file_rows(
    path: Path,
    *,
    filename: str,
    json_rows_field: str | None = None,
    sheet: str | None = None,
    options: dict | None = None,
) -> Iterator[dict[str, Any]]:
    """``sheet`` names the one sheet of a workbook to read; ``options`` are the reading
    options from :func:`read_options`."""
    options = options or {}
    name = (filename or "").lower()
    if name.endswith(".xlsx"):
        try:
            yield from spreadsheets.rows(path, sheet or "", header=options.get("header", True))
            return
        except spreadsheets.SpreadsheetError as exc:
            raise FileError(exc.detail) from exc
    if name.endswith(documents.SUFFIXES):
        try:
            return documents.extract(path, filename=filename)[0]
        except documents.DocumentError as exc:
            raise FileError(exc.detail) from exc
    bare = name.removesuffix(".gz")
    if bare.endswith(".parquet"):
        try:
            for batch in pq.ParquetFile(path).iter_batches(batch_size=10_000):
                yield from batch.to_pylist()
            return
        except (pa.ArrowException, OSError) as exc:
            raise FileError("The file is not readable Parquet.") from exc
    if bare.endswith(".json") and stored_stat(path).st_size > JSON_ARRAY_MAX_BYTES:
        raise FileError(
            f"A .json file is read whole and capped at {JSON_ARRAY_MAX_BYTES // 1024**2} MB "
            "— use JSONL for larger files."
        )
    try:
        with _open_text(path, name, options.get("encoding", "utf-8-sig")) as fh:
            yield from iter_stream_rows(
                fh, filename=bare, json_rows_field=json_rows_field, options=options
            )
    except UnicodeDecodeError as exc:
        raise FileError(not_decoded(options)) from exc
    except (gzip.BadGzipFile, EOFError) as exc:
        raise FileError("The file is not readable gzip.") from exc


def not_decoded(options: dict) -> str:
    name = ENCODING_NAMES[options.get("encoding", "utf-8-sig")]
    return f"The file is not {name}. Choose its encoding in the file settings."


class FileRows:
    def __init__(
        self,
        path: Path,
        *,
        filename: str,
        json_rows_field: str | None = None,
        sheet: str | None = None,
        options: dict | None = None,
    ):
        self.path, self.filename, self.sheet = path, filename, sheet
        self.json_rows_field, self.options = json_rows_field, options
        self.count = 0
        names = {}
        numeric = {}
        delimited = filename.lower().removesuffix(".gz").endswith((".csv", ".tsv"))
        for row in iter_file_rows(
            path, filename=filename, json_rows_field=json_rows_field, sheet=sheet, options=options
        ):
            self.count += 1
            for key, value in row.items():
                names.setdefault(key, None)
                if delimited and value not in (None, ""):
                    numeric.setdefault(key, set()).add(type(_number(value)))
        self.names = dict(zip(names, clean_names(list(names)), strict=True))
        self.numeric = {k for k, types in numeric.items() if types in ({int}, {float})}

    def __len__(self):
        return self.count

    def __iter__(self):
        for row in iter_file_rows(
            self.path,
            filename=self.filename,
            json_rows_field=self.json_rows_field,
            sheet=self.sheet,
            options=self.options,
        ):
            yield {
                self.names[key]: (_number(value) if value not in (None, "") else None)
                if key in self.numeric
                else value
                for key, value in row.items()
            }


def inspect_upload(
    upload_id: str,
    *,
    size: int,
    json_rows_field: str | None = None,
    preview: bool = False,
    options: dict | None = None,
) -> dict[str, Any]:
    """Count the upload's rows as ``options`` read them, and keep both for its landing.
    With ``preview``, also return the first rows, their columns and a workbook's sheets."""
    filename = upload_filename(upload_id)
    if not filename or upload_received(upload_id) != size:
        raise FileError("The upload is incomplete or has expired.")
    if size == 0:
        raise FileError("The file has no rows.")
    path = upload_data_path(upload_id)
    bare = filename.lower().removesuffix(".gz")
    if bare.endswith(documents.SUFFIXES):
        if size > documents.MAX_BYTES:
            raise FileError("Documents are capped at 100 MB.")
        record = {"bytes": size, "mtime_ns": stored_stat(path).st_mtime_ns, "rows": None}
        _inspection_path(upload_id).write_text(json.dumps(record), encoding="utf-8")
        return {"filename": filename, "bytes": size, "rows": None}
    options = read_options(options)
    sample: list[dict[str, Any]] = []
    sheets: list[str] = []
    try:
        if bare.endswith((".csv", ".tsv")):
            encoding = options.setdefault("encoding", "utf-8-sig")
            with _open_text(path, filename.lower(), encoding) as fh:
                fallback = "\t" if bare.endswith(".tsv") else ","
                sniffed = _sniff_delimiter(fh.read(64 * 1024), fallback)
            options.setdefault("delimiter", {v: k for k, v in DELIMITERS.items()}[sniffed])
            options.setdefault("header", True)
        if bare.endswith(".xlsx"):
            sheets = spreadsheets.sheets(path)
            if options.get("sheet") is not None and options["sheet"] not in sheets:
                raise FileError("The workbook has no rows on that sheet.")
            rows = 0
            for sheet in [options["sheet"]] if "sheet" in options else sheets:
                for row in iter_file_rows(path, filename=filename, sheet=sheet, options=options):
                    rows += 1
                    if (
                        preview
                        and len(sample) < PREVIEW_ROWS
                        and sheet == (options.get("sheet") or sheets[0])
                    ):
                        sample.append(row)
        elif bare.endswith(".parquet") and not preview:
            rows = pq.ParquetFile(path).metadata.num_rows
        else:
            if bare.endswith(".json") and size > JSON_ARRAY_MAX_BYTES:
                raise FileError(
                    f"JSON files are capped at {JSON_ARRAY_MAX_BYTES // 1024**2} MB. "
                    "Use JSONL for larger files."
                )
            rows = 0
            for row in iter_file_rows(
                path, filename=filename, json_rows_field=json_rows_field, options=options
            ):
                rows += 1
                if preview and len(sample) < PREVIEW_ROWS:
                    sample.append(row)
    except FileError:
        raise
    except spreadsheets.SpreadsheetError as exc:
        raise FileError(exc.detail) from exc
    except UnicodeDecodeError as exc:
        raise FileError(not_decoded(options)) from exc
    except (gzip.BadGzipFile, EOFError) as exc:
        raise FileError("The file is not readable gzip.") from exc
    except (OSError, ValueError, csv.Error, pa.ArrowException) as exc:
        logger.exception("Upload %s inspection failed", upload_id)
        message = (
            "The file is not readable Parquet."
            if bare.endswith(".parquet")
            else "The uploaded file could not be read. Upload it again."
        )
        raise FileError(message) from exc
    if not rows:
        raise FileError("The file has no rows.")
    record = {
        "bytes": size,
        "mtime_ns": stored_stat(path).st_mtime_ns,
        "rows": rows,
        "json_rows_field": json_rows_field,
        "options": options,
    }
    _inspection_path(upload_id).write_text(json.dumps(record), encoding="utf-8")
    result = {"filename": filename, "bytes": size, "rows": rows}
    if preview:
        result |= {"options": options, "sheets": sheets, **_preview(sample)}
    return result


def _preview(sample: list[dict[str, Any]]) -> dict[str, Any]:
    columns = list(dict.fromkeys(key for row in sample for key in row if key != EVIDENCE))[
        :PREVIEW_COLUMNS
    ]
    rows = [
        {
            column: "" if row.get(column) is None else str(row[column])[:PREVIEW_CELL_CHARS]
            for column in columns
        }
        for row in sample
    ]
    return {"columns": columns, "preview": rows}


def _inspection_path(upload_id: Any) -> Path:
    return upload_dir(upload_id) / "inspection.json"


def inspection(upload_id: Any) -> dict[str, Any] | None:
    try:
        record = json.loads(_inspection_path(upload_id).read_text(encoding="utf-8"))
        stat = stored_stat(upload_data_path(upload_id))
    except (OSError, ValueError):
        return None
    if (record.get("bytes"), record.get("mtime_ns")) != (stat.st_size, stat.st_mtime_ns):
        return None
    return record


def parse_text(text: str, *, filename: str = "") -> list[dict[str, Any]]:
    """Pasted rows: JSON or JSON Lines when the text opens with a bracket, else CSV."""
    body = text.strip()
    if not body:
        raise FileError("Nothing to read.")
    if not filename:
        filename = "paste.json" if body[:1] in "[{" else "paste.csv"
    return _text_rows(io.StringIO(body), filename.lower())


def upload_dir(upload_id: Any) -> Path:
    from django.conf import settings

    return Path(settings.MEDIA_ROOT) / "uploads" / str(uuid.UUID(str(upload_id)))


def upload_data_path(upload_id: Any) -> Path:
    return upload_dir(upload_id) / "data"


def safe_filename(name: str) -> str:
    base = os.path.basename(name or "").strip() or "upload"
    return _SAFE_NAME.sub("_", base)[:200]


def begin_upload(filename: str, *, upload_id=None, managed=False) -> tuple[str, str]:
    safe = safe_filename(filename)
    lowered = safe.lower()
    if lowered.endswith((".parquet.gz", ".xlsx.gz")):
        raise FileError("Parquet and XLSX are already compressed. Upload them without gzip.")
    if lowered.endswith(".gz") and lowered.removesuffix(".gz").endswith(documents.SUFFIXES):
        raise FileError("Upload documents without gzip compression.")
    if not lowered.removesuffix(".gz").endswith(ALLOWED_SUFFIXES):
        raise FileError(UNSUPPORTED)
    upload_id = str(upload_id or uuid.uuid4())
    directory = upload_dir(upload_id)
    directory.mkdir(parents=True, exist_ok=True)
    if managed:
        (directory / "managed").touch()
    (directory / "name").write_text(safe, encoding="utf-8")
    upload_data_path(upload_id).touch()
    return upload_id, safe


def managed_upload(upload_id):
    return (upload_dir(upload_id) / "managed").exists()


def upload_filename(upload_id: Any) -> str:
    try:
        return (upload_dir(upload_id) / "name").read_text(encoding="utf-8").strip()
    except OSError:
        return ""


def stored_stat(path: Path) -> os.stat_result:
    """The file's size and mtime as the file server holds them.

    Uploads live on EFS, which several API and worker tasks mount over NFS. A
    path ``stat()`` is answered from the client's attribute cache for up to a
    minute, so chunks another task appended stay invisible; ``open()``
    revalidates the attributes (close-to-open consistency).
    """
    fd = os.open(path, os.O_RDONLY)
    try:
        return os.fstat(fd)
    finally:
        os.close(fd)


def upload_received(upload_id: Any) -> int:
    try:
        return stored_stat(upload_data_path(upload_id)).st_size
    except OSError:
        return 0


def upload_byte_limit(filename: str) -> int:
    if filename.lower().endswith(".xlsx"):
        return spreadsheets.MAX_BYTES
    return (
        documents.MAX_BYTES if filename.lower().endswith(documents.SUFFIXES) else MAX_UPLOAD_BYTES
    )


def append_chunk(upload_id: Any, offset: int, chunk: bytes) -> int:
    """Writes the chunk at its offset, never appended, so a retry that races or
    follows an earlier attempt rewrites the same bytes instead of duplicating them."""
    if offset < 0:
        raise FileError("The chunk offset is negative.")
    limit = upload_byte_limit(upload_filename(upload_id))
    if offset + len(chunk) > limit:
        raise FileError(f"This file type is capped at {limit} bytes.")
    try:
        fh = upload_data_path(upload_id).open("r+b")
    except FileNotFoundError as exc:
        raise FileError("This upload has expired. Start it again.") from exc
    with fh:
        size = os.fstat(fh.fileno()).st_size
        if offset > size:
            raise FileError(f"Chunk starts at {offset} but {size} bytes are stored.")
        if offset + len(chunk) > size:
            fh.seek(offset)
            fh.write(chunk)
            fh.flush()
            os.fsync(fh.fileno())
        return max(size, offset + len(chunk))


def discard_upload(upload_id: Any) -> None:
    if upload_id:
        shutil.rmtree(upload_dir(upload_id), ignore_errors=True)