# ⚠️ WARNING - both `document` and `window` are added at runtime import base64 import html import io import re _MIME_METHODS = { "__repr__": "text/plain", "_repr_html_": "text/html", "_repr_markdown_": "text/markdown", "_repr_svg_": "image/svg+xml", "_repr_png_": "image/png", "_repr_pdf_": "application/pdf", "_repr_jpeg_": "image/jpeg", "_repr_latex": "text/latex", "_repr_json_": "application/json", "_repr_javascript_": "application/javascript", "savefig": "image/png", } def _render_image(mime, value, meta): # If the image value is using bytes we should convert it to base64 # otherwise it will return raw bytes and the browser will not be able to # render it. if isinstance(value, bytes): value = base64.b64encode(value).decode("utf-8") # This is the pattern of base64 strings base64_pattern = re.compile( r"^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$" ) # If value doesn't match the base64 pattern we should encode it to base64 if len(value) > 0 and not base64_pattern.match(value): value = base64.b64encode(value.encode("utf-8")).decode("utf-8") data = f"data:{mime};charset=utf-8;base64,{value}" attrs = " ".join(['{k}="{v}"' for k, v in meta.items()]) return f'' def _identity(value, meta): return value _MIME_RENDERERS = { "text/plain": html.escape, "text/html": _identity, "image/png": lambda value, meta: _render_image("image/png", value, meta), "image/jpeg": lambda value, meta: _render_image("image/jpeg", value, meta), "image/svg+xml": _identity, "application/json": _identity, "application/javascript": lambda value, meta: f"