|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from io import BytesIO |
| 4 | +from typing import Any |
| 5 | + |
| 6 | +from ._internal import Context as _Context # pyright: ignore[reportMissingImports] |
| 7 | +from ._internal import version as _version # pyright: ignore[reportMissingImports] |
| 8 | + |
| 9 | +__all__ = ["Context", "__version__"] |
| 10 | + |
| 11 | +__version__ = _version() |
| 12 | + |
| 13 | +_ARROW_STREAM_MIME = "application/vnd.apache.arrow.stream" |
| 14 | + |
| 15 | + |
| 16 | +def _is_module(value: Any, prefix: str) -> bool: |
| 17 | + return type(value).__module__.startswith(prefix) |
| 18 | + |
| 19 | + |
| 20 | +def _get_pyarrow(): |
| 21 | + try: |
| 22 | + import pyarrow as pa # pyright: ignore[reportMissingImports] |
| 23 | + except ImportError as exc: # pragma: no cover - optional dependency |
| 24 | + raise ImportError( |
| 25 | + "pyarrow is required to serialize pandas/polars dataframes" |
| 26 | + ) from exc |
| 27 | + return pa |
| 28 | + |
| 29 | + |
| 30 | +def _coerce_arrow_table(value: Any): |
| 31 | + pa = _get_pyarrow() |
| 32 | + if isinstance(value, pa.Table): |
| 33 | + return value |
| 34 | + if isinstance(value, pa.RecordBatch): |
| 35 | + return pa.Table.from_batches([value]) |
| 36 | + if _is_module(value, "polars."): |
| 37 | + table = value.to_arrow() |
| 38 | + elif _is_module(value, "pandas."): |
| 39 | + table = pa.Table.from_pandas(value) |
| 40 | + elif hasattr(value, "to_arrow"): |
| 41 | + table = value.to_arrow() |
| 42 | + else: |
| 43 | + return None |
| 44 | + |
| 45 | + if isinstance(table, pa.RecordBatch): |
| 46 | + return pa.Table.from_batches([table]) |
| 47 | + if not isinstance(table, pa.Table): |
| 48 | + raise TypeError("to_arrow() did not return a pyarrow Table or RecordBatch") |
| 49 | + return table |
| 50 | + |
| 51 | + |
| 52 | +def _serialize_dataframe(value: Any): |
| 53 | + table = _coerce_arrow_table(value) |
| 54 | + if table is None: |
| 55 | + return None |
| 56 | + pa = _get_pyarrow() |
| 57 | + sink = pa.BufferOutputStream() |
| 58 | + with pa.ipc.new_stream(sink, table.schema) as writer: |
| 59 | + writer.write_table(table) |
| 60 | + return sink.getvalue().to_pybytes(), _ARROW_STREAM_MIME |
| 61 | + |
| 62 | + |
| 63 | +def _serialize_image(value: Any): |
| 64 | + if not _is_module(value, "PIL."): |
| 65 | + return None |
| 66 | + try: |
| 67 | + from PIL import Image # pyright: ignore[reportMissingImports] |
| 68 | + except ImportError as exc: # pragma: no cover - optional dependency |
| 69 | + raise ImportError("Pillow is required to serialize images") from exc |
| 70 | + if not isinstance(value, Image.Image): |
| 71 | + return None |
| 72 | + |
| 73 | + image_format = value.format or "PNG" |
| 74 | + mime = None |
| 75 | + if hasattr(value, "get_format_mimetype"): |
| 76 | + mime = value.get_format_mimetype() |
| 77 | + if not mime: |
| 78 | + mime = Image.MIME.get(image_format.upper()) |
| 79 | + if not mime: |
| 80 | + mime = "application/octet-stream" |
| 81 | + |
| 82 | + buffer = BytesIO() |
| 83 | + value.save(buffer, format=image_format) |
| 84 | + return buffer.getvalue(), mime |
| 85 | + |
| 86 | + |
| 87 | +def _normalize_content(value: Any, content_type: str | None): |
| 88 | + serialized = _serialize_dataframe(value) |
| 89 | + if serialized is not None: |
| 90 | + payload, inferred = serialized |
| 91 | + return payload, content_type or inferred |
| 92 | + serialized = _serialize_image(value) |
| 93 | + if serialized is not None: |
| 94 | + payload, inferred = serialized |
| 95 | + return payload, content_type or inferred |
| 96 | + return value, content_type |
| 97 | + |
| 98 | + |
| 99 | +class Context: |
| 100 | + def __init__(self, uri: str) -> None: |
| 101 | + self._inner = _Context.create(uri) |
| 102 | + |
| 103 | + @classmethod |
| 104 | + def create(cls, uri: str) -> Context: |
| 105 | + return cls(uri) |
| 106 | + |
| 107 | + def uri(self) -> str: |
| 108 | + return self._inner.uri() |
| 109 | + |
| 110 | + def branch(self) -> str: |
| 111 | + return self._inner.branch() |
| 112 | + |
| 113 | + def entries(self) -> int: |
| 114 | + return self._inner.entries() |
| 115 | + |
| 116 | + def add( |
| 117 | + self, |
| 118 | + role: str, |
| 119 | + content: Any, |
| 120 | + content_type: str | None = None, |
| 121 | + data_type: str | None = None, |
| 122 | + ) -> None: |
| 123 | + if content_type is not None and data_type is not None: |
| 124 | + raise ValueError("Specify only one of content_type or data_type") |
| 125 | + if content_type is None: |
| 126 | + content_type = data_type |
| 127 | + payload, resolved_type = _normalize_content(content, content_type) |
| 128 | + self._inner.add(role, payload, resolved_type) |
| 129 | + |
| 130 | + def snapshot(self, label: str | None = None) -> str: |
| 131 | + return self._inner.snapshot(label) |
| 132 | + |
| 133 | + def fork(self, branch_name: str) -> Context: |
| 134 | + inner = self._inner.fork(branch_name) |
| 135 | + return self._from_inner(inner) |
| 136 | + |
| 137 | + def checkout(self, snapshot_id: str) -> None: |
| 138 | + self._inner.checkout(snapshot_id) |
| 139 | + |
| 140 | + def __repr__(self) -> str: |
| 141 | + return ( |
| 142 | + f"Context(uri={self._inner.uri()!r}, " |
| 143 | + f"branch={self._inner.branch()!r}, " |
| 144 | + f"entries={self._inner.entries()})" |
| 145 | + ) |
| 146 | + |
| 147 | + @classmethod |
| 148 | + def _from_inner(cls, inner: _Context) -> Context: |
| 149 | + obj = cls.__new__(cls) |
| 150 | + obj._inner = inner |
| 151 | + return obj |
0 commit comments