Skip to content

Commit

Permalink
[skip ci] Fix comments at once
Browse files Browse the repository at this point in the history
  • Loading branch information
thomass-dev committed Jan 17, 2025
1 parent f132c62 commit cfa9437
Show file tree
Hide file tree
Showing 20 changed files with 91 additions and 138 deletions.
6 changes: 4 additions & 2 deletions skore/src/skore/persistence/item/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,12 @@ def object_to_item(

if display_as is not None:
if not isinstance(object, str):
raise TypeError("`object` must be a str if `display_as` is specified")
raise TypeError("`object` must be a string if `display_as` is specified")

if display_as not in MediaType.__members__:
raise ValueError(f"`display_as` must be in {list(MediaType.__members__)}")
raise ValueError(
f"`display_as` must be one of {', '.join(MediaType.__members__)}"
)

return MediaItem.factory(object, MediaType[display_as].value, note=note)

Expand Down
2 changes: 1 addition & 1 deletion skore/src/skore/persistence/item/altair_chart_item.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ def chart(self) -> AltairChart:
return altair.Chart.from_json(self.chart_str)

def as_serializable_dict(self):
"""Return item as a JSONable dict to export to frontend."""
"""Convert item to a JSON-serializable dict to used by frontend."""
import base64

chart_bytes = self.chart_str.encode("utf-8")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ def reporter(self) -> CrossValidationReporter:
return joblib.load(stream)

def as_serializable_dict(self):
"""Get a serializable dict from the item."""
"""Convert item to a JSON-serializable dict to used by frontend."""
# Get tabular results (the cv results in a dataframe-like structure)
cv_results = {
key: value.tolist()
Expand Down
6 changes: 3 additions & 3 deletions skore/src/skore/persistence/item/item.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,10 +117,10 @@ def read_asset_content(path):
return template.render(**context)

def as_serializable_dict(self):
"""Get a serializable dict from the item.
"""Convert item to a JSON-serializable dict to used by frontend.
Derived class must call their super implementation
and merge the result with their output.
Derived class must call their super implementation and merge the result with
their output.
"""
return {
"updated_at": self.updated_at,
Expand Down
2 changes: 1 addition & 1 deletion skore/src/skore/persistence/item/matplotlib_figure_item.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ def figure(self) -> Figure:
return joblib.load(stream)

def as_serializable_dict(self) -> dict:
"""Return item as a JSONable dict to export to frontend."""
"""Convert item to a JSON-serializable dict to used by frontend."""
with BytesIO() as stream:
self.figure.savefig(stream, format="svg", bbox_inches="tight")

Expand Down
6 changes: 3 additions & 3 deletions skore/src/skore/persistence/item/media_item.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def lazy_is_instance(object: Any, cls_fullname: str) -> bool:


class MediaType(Enum):
"""Enum used to map aliases and media types."""
"""A media type of a string."""

HTML = "text/html"
MARKDOWN = "text/markdown"
Expand Down Expand Up @@ -63,7 +63,7 @@ def factory(
cls,
media: str,
/,
media_type: Optional[str] = "text/markdown",
media_type: Optional[str] = MediaType.MARKDOWN.value,
**kwargs,
) -> MediaItem:
"""
Expand All @@ -90,7 +90,7 @@ def factory(
return cls(media, media_type, **kwargs)

def as_serializable_dict(self):
"""Return item as a JSONable dict to export to frontend."""
"""Convert item to a JSON-serializable dict to used by frontend."""
return super().as_serializable_dict() | {
"media_type": self.media_type,
"value": self.media,
Expand Down
22 changes: 7 additions & 15 deletions skore/src/skore/persistence/item/numpy_array_item.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,21 +59,6 @@ def array(self) -> numpy.ndarray:

return numpy.asarray(loads(self.array_json))

def as_serializable_dict(self):
"""Get a serializable dict from the item.
Derived class must call their super implementation
and merge the result with their output.
"""
d = super().as_serializable_dict()
d.update(
{
"media_type": "text/markdown",
"value": self.array.tolist(),
}
)
return d

@classmethod
def factory(cls, array: numpy.ndarray, /, **kwargs) -> NumpyArrayItem:
"""
Expand All @@ -95,3 +80,10 @@ def factory(cls, array: numpy.ndarray, /, **kwargs) -> NumpyArrayItem:
raise ItemTypeError(f"Type '{array.__class__}' is not supported.")

return cls(array_json=dumps(array.tolist()), **kwargs)

def as_serializable_dict(self):
"""Convert item to a JSON-serializable dict to used by frontend."""
return super().as_serializable_dict() | {
"media_type": "text/markdown",
"value": self.array.tolist(),
}
22 changes: 7 additions & 15 deletions skore/src/skore/persistence/item/pandas_dataframe_item.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,21 +77,6 @@ def dataframe(self) -> pandas.DataFrame:

return dataframe

def as_serializable_dict(self):
"""Get a serializable dict from the item.
Derived class must call their super implementation
and merge the result with their output.
"""
d = super().as_serializable_dict()
d.update(
{
"media_type": "application/vnd.dataframe",
"value": self.dataframe.fillna("NaN").to_dict(orient="tight"),
}
)
return d

@classmethod
def factory(cls, dataframe: pandas.DataFrame, /, **kwargs) -> PandasDataFrameItem:
"""
Expand Down Expand Up @@ -146,3 +131,10 @@ def factory(cls, dataframe: pandas.DataFrame, /, **kwargs) -> PandasDataFrameIte
dataframe_json=dataframe.to_json(orient=PandasDataFrameItem.ORIENT),
**kwargs,
)

def as_serializable_dict(self):
"""Convert item to a JSON-serializable dict to used by frontend."""
return super().as_serializable_dict() | {
"media_type": "application/vnd.dataframe",
"value": self.dataframe.fillna("NaN").to_dict(orient="tight"),
}
22 changes: 7 additions & 15 deletions skore/src/skore/persistence/item/pandas_series_item.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,21 +82,6 @@ def series(self) -> pandas.Series:

return series

def as_serializable_dict(self):
"""Get a serializable dict from the item.
Derived class must call their super implementation
and merge the result with their output.
"""
d = super().as_serializable_dict()
d.update(
{
"value": self.series.fillna("NaN").to_list(),
"media_type": "text/markdown",
}
)
return d

@classmethod
def factory(cls, series: pandas.Series, /, **kwargs) -> PandasSeriesItem:
"""
Expand Down Expand Up @@ -138,3 +123,10 @@ def factory(cls, series: pandas.Series, /, **kwargs) -> PandasSeriesItem:
series_json=series.to_json(orient=PandasSeriesItem.ORIENT),
**kwargs,
)

def as_serializable_dict(self):
"""Convert item to a JSON-serializable dict to used by frontend."""
return super().as_serializable_dict() | {
"value": self.series.fillna("NaN").to_list(),
"media_type": "text/markdown",
}
9 changes: 4 additions & 5 deletions skore/src/skore/persistence/item/pickle_item.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,8 @@

class PickleItem(Item):
"""
A class to represent any object item.
An item used to persist objects that cannot be otherwise, using binary protocols.
This class is generally used to persist objects that cannot be otherwise.
It encapsulates the object with its pickle representaton, its creation and update
timestamps.
"""
Expand Down Expand Up @@ -52,7 +51,7 @@ def __init__(
@classmethod
def factory(cls, object: Any, /, **kwargs) -> PickleItem:
"""
Create a new PickleItem with any object.
Create a new PickleItem from ``object``.
Parameters
----------
Expand All @@ -76,11 +75,11 @@ def object(self) -> Any:
return joblib.load(stream)

def as_serializable_dict(self):
"""Get a JSON serializable representation of the item."""
"""Convert item to a JSON-serializable dict to used by frontend."""
try:
object = self.object
except Exception as e:
value = "UnpicklingError"
value = "Item cannot be displayed"
traceback = "".join(format_exception(None, e, e.__traceback__))
note = "".join(
(
Expand Down
2 changes: 1 addition & 1 deletion skore/src/skore/persistence/item/pillow_image_item.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ def image(self) -> PIL.Image.Image:
)

def as_serializable_dict(self):
"""Return item as a JSONable dict to export to frontend."""
"""Convert item to a JSON-serializable dict to used by frontend."""
import base64
import io

Expand Down
13 changes: 9 additions & 4 deletions skore/src/skore/persistence/item/plotly_figure_item.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from .media_item import lazy_is_instance

if TYPE_CHECKING:
import plotly.basedatatypes as plotly
import plotly.basedatatypes


class PlotlyFigureItem(Item):
Expand Down Expand Up @@ -43,7 +43,12 @@ def __init__(
self.figure_str = figure_str

@classmethod
def factory(cls, figure: plotly.BaseFigure, /, **kwargs) -> PlotlyFigureItem:
def factory(
cls,
figure: plotly.basedatatypes.BaseFigure,
/,
**kwargs,
) -> PlotlyFigureItem:
"""
Create a new PlotlyFigureItem instance from a Plotly figure.
Expand All @@ -65,14 +70,14 @@ def factory(cls, figure: plotly.BaseFigure, /, **kwargs) -> PlotlyFigureItem:
return cls(plotly.io.to_json(figure, engine="json"), **kwargs)

@property
def figure(self) -> plotly.BaseFigure:
def figure(self) -> plotly.basedatatypes.BaseFigure:
"""The figure from the persistence."""
import plotly.io

return plotly.io.from_json(self.figure_str)

def as_serializable_dict(self):
"""Return item as a JSONable dict to export to frontend."""
"""Convert item to a JSON-serializable dict to used by frontend."""
import base64

figure_bytes = self.figure_str.encode("utf-8")
Expand Down
24 changes: 7 additions & 17 deletions skore/src/skore/persistence/item/polars_dataframe_item.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,23 +68,6 @@ def dataframe(self) -> polars.DataFrame:
dataframe = polars.read_json(df_stream)
return dataframe

def as_serializable_dict(self):
"""Get a serializable dict from the item.
Derived class must call their super implementation
and merge the result with their output.
"""
d = super().as_serializable_dict()
d.update(
{
"value": self.dataframe.to_pandas()
.fillna("NaN")
.to_dict(orient="tight"),
"media_type": "application/vnd.dataframe",
}
)
return d

@classmethod
def factory(cls, dataframe: polars.DataFrame, /, **kwargs) -> PolarsDataFrameItem:
"""
Expand Down Expand Up @@ -115,3 +98,10 @@ def factory(cls, dataframe: polars.DataFrame, /, **kwargs) -> PolarsDataFrameIte
raise PolarsToJSONError("Conversion to JSON failed") from e

return cls(dataframe_json=dataframe_json, **kwargs)

def as_serializable_dict(self):
"""Convert item to a JSON-serializable dict to used by frontend."""
return super().as_serializable_dict() | {
"value": self.dataframe.to_pandas().fillna("NaN").to_dict(orient="tight"),
"media_type": "application/vnd.dataframe",
}
22 changes: 7 additions & 15 deletions skore/src/skore/persistence/item/polars_series_item.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,21 +65,6 @@ def series(self) -> polars.Series:

return series

def as_serializable_dict(self):
"""Get a serializable dict from the item.
Derived class must call their super implementation
and merge the result with their output.
"""
d = super().as_serializable_dict()
d.update(
{
"value": self.series.to_list(),
"media_type": "text/markdown",
}
)
return d

@classmethod
def factory(cls, series: polars.Series, /, **kwargs) -> PolarsSeriesItem:
"""
Expand All @@ -101,3 +86,10 @@ def factory(cls, series: polars.Series, /, **kwargs) -> PolarsSeriesItem:
raise ItemTypeError(f"Type '{series.__class__}' is not supported.")

return cls(series_json=series.to_frame().write_json(), **kwargs)

def as_serializable_dict(self):
"""Convert item to a JSON-serializable dict to used by frontend."""
return super().as_serializable_dict() | {
"value": self.series.to_list(),
"media_type": "text/markdown",
}
22 changes: 7 additions & 15 deletions skore/src/skore/persistence/item/primitive_item.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,21 +70,6 @@ def __init__(

self.primitive = primitive

def as_serializable_dict(self):
"""Get a serializable dict from the item.
Derived class must call their super implementation
and merge the result with their output.
"""
d = super().as_serializable_dict()
d.update(
{
"media_type": "text/markdown",
"value": self.primitive,
}
)
return d

@classmethod
def factory(cls, primitive: Primitive, /, **kwargs) -> PrimitiveItem:
"""
Expand All @@ -104,3 +89,10 @@ def factory(cls, primitive: Primitive, /, **kwargs) -> PrimitiveItem:
raise ItemTypeError(f"Type '{primitive.__class__}' is not supported.")

return cls(primitive=primitive, **kwargs)

def as_serializable_dict(self):
"""Convert item to a JSON-serializable dict to used by frontend."""
return super().as_serializable_dict() | {
"media_type": "text/markdown",
"value": self.primitive,
}
22 changes: 7 additions & 15 deletions skore/src/skore/persistence/item/sklearn_base_estimator_item.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,21 +71,6 @@ def estimator(self) -> sklearn.base.BaseEstimator:
self.estimator_skops, trusted=self.estimator_skops_untrusted_types
)

def as_serializable_dict(self):
"""Get a serializable dict from the item.
Derived class must call their super implementation
and merge the result with their output.
"""
d = super().as_serializable_dict()
d.update(
{
"value": self.estimator_html_repr,
"media_type": "application/vnd.sklearn.estimator+html",
}
)
return d

@classmethod
def factory(
cls,
Expand Down Expand Up @@ -128,3 +113,10 @@ def factory(
estimator_skops_untrusted_types=estimator_skops_untrusted_types,
**kwargs,
)

def as_serializable_dict(self):
"""Convert item to a JSON-serializable dict to used by frontend."""
return super().as_serializable_dict() | {
"value": self.estimator_html_repr,
"media_type": "application/vnd.sklearn.estimator+html",
}
Loading

0 comments on commit cfa9437

Please sign in to comment.