Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(pandas): Annotated[pd.DataFrame, DataframeSchema(columns=["a"])] output spec #4799

Merged
merged 2 commits into from
Jun 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion src/_bentoml_sdk/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,10 @@ def validate(self, obj: t.Any) -> t.Any:
@attrs.frozen(unsafe_hash=True)
class DataframeSchema:
orient: str = "records"
columns: list[str] | None = None
columns: tuple[str] | None = attrs.field(
default=None,
converter=lambda x: tuple(x) if x else None,
)

def __get_pydantic_json_schema__(
self, schema: core_schema.CoreSchema, handler: GetJsonSchemaHandler
Expand Down
26 changes: 26 additions & 0 deletions tests/unit/bentoml_io/test_decorators.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
from typing import Generator

import pandas as pd
import pytest
from typing_extensions import Annotated

import bentoml
from bentoml.validators import DataframeSchema


@pytest.mark.asyncio
Expand Down Expand Up @@ -90,3 +93,26 @@ def stream(self, name: str) -> Generator[str, None, None]:
"Hello, world! 1",
"Hello, world! 2",
]


def test_api_decorator_pandas():
@bentoml.api
def pandas_func(
_, # The decorator assumes `self` is the first arg.
df1: pd.DataFrame,
df2: Annotated[pd.DataFrame, DataframeSchema(columns=("b",))],
) -> Annotated[
pd.DataFrame,
DataframeSchema(orient="columns", columns=["a", "b"]),
]:
return pd.concat([df1, df2], axis=1)

pandas_func.input_spec.model_fields["df1"].annotation is pd.DataFrame
pandas_func.input_spec.model_fields["df2"].annotation is Annotated[
pd.DataFrame,
DataframeSchema(columns=("b",)),
]
pandas_func.output_spec.model_fields["root"].annotation is Annotated[
pd.DataFrame,
DataframeSchema(orient="columns", columns=("a", "b")),
]
Loading