Source code for npfc.notebook

"""
Module notebook
================

A module with helper functions for Jupyterlab notebooks.

"""
import IPython
from IPython import display
from IPython.display import HTML
from IPython.display import Image


# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ FUNCTIONS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #


def _src_from_data(data):
    """Base64 encodes image bytes for inclusion in an HTML img element.

    Very strongly inspired after:
    https://mindtrove.info/

    :param data: the image data
    :return: the src image code to embed in the HTML
    """
    img_obj = Image(data=data)
    for bundle in img_obj._repr_mimebundle_():
        for mimetype, b64value in bundle.items():
            if mimetype.startswith('image/'):
                return f'data:{mimetype};base64,{b64value}'





[docs]def display_image_table(imgs: list, max_img_per_row: int = 4) -> str: """Display a table filled with images. :param imgs: an iterable containing images :param max_img_per_row: the maximum number of images per row :return: the HTML code for displaying the images in a table in Jupyterlab. """ table = """ <table> <tr> """ for i, img in enumerate(imgs): if i % max_img_per_row == 0: table += """ </tr> <tr> """ table += f"<td>{img}</td>\n" table += """ </tr> </table> """ return HTML(table)