diff --git a/docs/changes.rst b/docs/changes.rst index ad0e7afd..0f31eb3e 100644 --- a/docs/changes.rst +++ b/docs/changes.rst @@ -13,6 +13,8 @@ v0.8 ---- - Adds the abillity to set the :attr:`.Section.folded` property when using :meth:`.Card.add`. :pr:`361` by :user:`Thomas Lazarus `. +- Add HTML representation of the :class:`skops.card.Card` instances in Jupyter + notebooks. :pr:`372` by `Adrin Jalali`_. v0.7 ---- diff --git a/skops/_min_dependencies.py b/skops/_min_dependencies.py index d66b554f..caaa33b7 100644 --- a/skops/_min_dependencies.py +++ b/skops/_min_dependencies.py @@ -36,6 +36,8 @@ "catboost": ("1.0", "tests", "python_version < '3.11'"), "fairlearn": ("0.7.0", "docs, tests", None), "rich": ("12", "tests, rich", None), + # Required for the documentation build with sphinx-gallery + "markdown": ("3.4", "docs", None), } diff --git a/skops/card/_model_card.py b/skops/card/_model_card.py index 9cb1c742..1327868e 100644 --- a/skops/card/_model_card.py +++ b/skops/card/_model_card.py @@ -17,6 +17,7 @@ import joblib from huggingface_hub import ModelCardData from sklearn.utils import estimator_html_repr +from sklearn.utils.metaestimators import available_if from tabulate import tabulate # type: ignore from skops.card._templates import CONTENT_PLACEHOLDER, SKOPS_TEMPLATE, Templates @@ -1477,6 +1478,35 @@ def render(self) -> str: """ return "\n".join(self._generate_card()) + def _repr_markdown_(self) -> str: + """Render the model card as markdown in a Jupyter Notebook. + + Jupyter understands this method and if it exists, uses it to render the + markdown. + """ + return self.render() + + def _markdown_installed(self): + try: + import markdown # type: ignore[import] # noqa: F401 + + return True + except ImportError: + return False + + @available_if(_markdown_installed) + def _repr_html_(self) -> str: + """Render the model card as HTML in a Jupyter Notebook. + + This is only available if the user has `markdown` package installed. + This is only used in our documentation build, since sphinx-gallery + doesn't support `_repr_markdown_`. In a Jupyter notebook, + `_repr_markdown_` is used. + """ + import markdown + + return markdown.markdown(self.render()) + def _iterate_key_section_content( self, data: dict[str, Section],