from __future__ import annotations import base64 import re from pathlib import Path from typing import Iterator from skops.card._model_card import Section def process_card_for_rendering(rendered: str) -> tuple[str, str]: idx = rendered[1:].index("\n---") + 1 metadata = rendered[3:idx] rendered = rendered[idx + 4 :] # noqa: E203 # below is a hack to display the images in streamlit # https://discuss.streamlit.io/t/image-in-markdown/13274/10 The problem is # that streamlit does not display images in markdown, so we need to replace # them with html. However, we only want that in the rendered markdown, not # in the card that is produced for the hub def markdown_images(markdown): # example image markdown: # ![Test image](images/test.png "Alternate text") images = re.findall( r'(!\[(?P[^\]]+)\]\((?P[^\)"\s]+)\s*([^\)]*)\))', markdown, ) return images def img_to_bytes(img_path): img_bytes = Path(img_path).read_bytes() encoded = base64.b64encode(img_bytes).decode() return encoded def img_to_html(img_path, img_alt): img_format = img_path.split(".")[-1] img_html = ( f'' ) return img_html def markdown_insert_images(markdown): images = markdown_images(markdown) for image in images: image_markdown = image[0] image_alt = image[1] image_path = image[2] markdown = markdown.replace( image_markdown, img_to_html(image_path, image_alt) ) return markdown rendered_with_img = markdown_insert_images(rendered) return metadata, rendered_with_img def iterate_key_section_content( data: dict[str, Section], parent_section: str = "", parent_keys: list[str] | None = None, ) -> Iterator[tuple[str, str, str, bool]]: parent_keys = parent_keys or [] for key, val in data.items(): if parent_section: title = "/".join((parent_section, val.title)) else: title = val.title if not getattr(val, "visible", True): continue return_key = key if not parent_keys else "/".join(parent_keys + [key]) is_fig = getattr(val, "is_fig", False) yield return_key, title, val.content, is_fig if val.subsections: yield from iterate_key_section_content( val.subsections, parent_section=title, parent_keys=parent_keys + [key], )