mlsnippet.report

class mlsnippet.report.Container(children=None)

Bases: mlsnippet.report.element.Element

Element class built up with children elements.

The Container class is a base class for implementing Element which is rendered mainly by rendering children elements one after another.

__init__(children=None)

Construct the Container.

Parameters:children – An Element, a list of Element, or a list of objects which can be converted into Element via as_element(). (default None, no children is specified)
_to_html(context)

Actual method to render this Element into HTML. Subclasses of Element should override this method.

This method is designed to be called by to_html(), with context ensured to be created, and self pushed to the call-stack of context. Note that if an element needs to render another element within this method, it should call :meth:`to_html of that element, with context passed to it.

Parameters:context (ToHtmlContext) – The context for rendering.
Returns:The rendered HTML.
Return type:str
add(child)

Add a child Element.

Parameters:child – Object which can be converted into Element by as_element().
children

Get the list of children elements.

Returns:The children elements.
Return type:list[Element]
get_libraries()

Get the libraries used by this Container, and all its children.

Returns:The list of Library.
Return type:list[Library]
class mlsnippet.report.Block(children=None)

Bases: mlsnippet.report.container.Container

Subclass of Container, which renders all its children elements within of <div class="block">...</div>.

_to_html(context)

Actual method to render this Element into HTML. Subclasses of Element should override this method.

This method is designed to be called by to_html(), with context ensured to be created, and self pushed to the call-stack of context. Note that if an element needs to render another element within this method, it should call :meth:`to_html of that element, with context passed to it.

Parameters:context (ToHtmlContext) – The context for rendering.
Returns:The rendered HTML.
Return type:str
class mlsnippet.report.Paragraph(children=None)

Bases: mlsnippet.report.container.Container

Subclass of Container, which renders all its children elements within of <p>...</p>

_to_html(context)

Actual method to render this Element into HTML. Subclasses of Element should override this method.

This method is designed to be called by to_html(), with context ensured to be created, and self pushed to the call-stack of context. Note that if an element needs to render another element within this method, it should call :meth:`to_html of that element, with context passed to it.

Parameters:context (ToHtmlContext) – The context for rendering.
Returns:The rendered HTML.
Return type:str
mlsnippet.report.paragraph_text(text)

Create a Text enclosed in a Paragraph.

Parameters:text (str) – Text content.
Returns:The Paragraph.
Return type:Paragraph
class mlsnippet.report.Section(title, children=None)

Bases: mlsnippet.report.container.Container

Subclass of Container, which renders all its children elements within <div class="section">...</div>, with a title.

__init__(title, children=None)

Construct the Section.

Parameters:
_to_html(context)

Actual method to render this Element into HTML. Subclasses of Element should override this method.

This method is designed to be called by to_html(), with context ensured to be created, and self pushed to the call-stack of context. Note that if an element needs to render another element within this method, it should call :meth:`to_html of that element, with context passed to it.

Parameters:context (ToHtmlContext) – The context for rendering.
Returns:The rendered HTML.
Return type:str
title

Get the title of this Section.

class mlsnippet.report.UniqueNames

Bases: object

Class for obtaining unique names.

__init__()

Construct the UniqueNames.

uniquify(name, obj=None)

Get a unique name according to the candidate name and the obj.

Parameters:
  • name (str) – The candidate name. Suffices _[id] will be appended to this name, in order to obtain a unique name.
  • obj (any) – If not None, the uniquified name will be memorized for this object, such that the next time uniquify() is called, the same name will be returned instead of obtaining a new one. (default None)
Returns:

The uniquified name, or the memorized name for obj.

Return type:

str

Raises:

ValueError – If obj is specified, and name does not equal to the name specified in the last call.

class mlsnippet.report.ToHtmlContext(is_ipython=False)

Bases: object

The context for mlsnippet.report.Element.to_html().

This class carries the context for mlsnippet.report.Element.to_html(). It collects the elements along the call-stack (i.e., the elements along the path of calling Element.to_html()), and provide various utilities for producing the HTML document.

__init__(is_ipython=False)

Construct the ToHtmlContext.

Parameters:is_ipython (bool) – Whether or not the elements are displayed in a Jupyter notebook? (default False)
get_unique_id(element, suffix=None)

Get a unique id for element within this context.

The unique id will be generated w.r.t. the class name of element. If element is a NamedElement, then its name will be considered instead of its class name, provided name is not None.

Parameters:
  • element (mlsnippet.report.Element) – The element instance.
  • suffix (str or None) – If not None, it will be appended to the class name or name of the element, when obtaining the unique id. (default None)
Returns:

The unique id for element.

Return type:

str

is_ipython

Whether or not the elements are displayed in a Jupyter notebook?

iter_elements()

Get an iterator of the Element along the call-stack.

push(**kwds)

Push an mlsnippet.report.Element onto the call-stack, and open a context.

Parameters:

element (mlsnippet.report.Element) – The element to be pushed. If it is a mlsnippet.report.Section, then the section_level counter will be increased by one within the opened context.

Yields:

A context where the element is on the call-stack.

Raises:
section_level

Get the opened section level.

Returns:
The section level counter, starting from 1.
If no section has been opened, return 0.
Return type:int
section_title_tag()

Get the tag for section title at current level.

Returns:One of {“h3”, “h4”, “h5”, “h6”, “h7”}.
Return type:str
Raises:RuntimeError – If no section has been opened.
mlsnippet.report.demo_report()

Get a demonstration Report.

Returns:The demonstration report.
Return type:Report
class mlsnippet.report.Element

Bases: object

Base class for report elements.

_repr_html_()

Render this Element into HTML in a Jupyter notebook.

Returns:The rendered HTML.
Return type:str
_to_html(context)

Actual method to render this Element into HTML. Subclasses of Element should override this method.

This method is designed to be called by to_html(), with context ensured to be created, and self pushed to the call-stack of context. Note that if an element needs to render another element within this method, it should call :meth:`to_html of that element, with context passed to it.

Parameters:context (ToHtmlContext) – The context for rendering.
Returns:The rendered HTML.
Return type:str
get_libraries()

Get the libraries used by this element.

Returns:
The list of Library, or
None if no Library is used.
Return type:list[Library] or None
to_html(context=None)

Render this Element into HTML.

Parameters:context (ToHtmlContext) – Context for rendering Element into HTML. If not specified, will create a default context.
Returns:The rendered HTML.
Return type:str
mlsnippet.report.as_element(obj)

Convert obj into Element.

It will be converted according the following rules in order:

  1. Return obj itself if it is a Element.
  2. A HTML will be constructed if obj is a str.
  3. The conversion function will be called, if the type of obj has been designated a function via register_as_element(). The registered conversion functions will be tried in the order of registration. The first function which can successfully convert the object is selected.
  4. A MagicHTML will be constructed if obj has a magic method __html__.
Parameters:obj – The object to be converted.
Returns:An instance of Element converted from obj.
Return type:Element
Raises:TypeError – If obj cannot be converted by any of the above rules.
mlsnippet.report.register_as_element(typ_, convert_func)

Register a conversion function which converts objects of particular type into Element.

Parameters:
  • typ – The type which this conversion function is designed for.
  • convert_func – The conversion function which converts objects of type_ into Element.
Raises:

TypeError – If typ_ is not a class.

class mlsnippet.report.NamedElement(name=None)

Bases: mlsnippet.report.element.Element

Base class for Element with name.

__init__(name=None)

Construct the NamedElement.

Parameters:name (str or None) – If specified, it will be used as the name of this element.
name

Get the name of this element.

Returns:
The name specified in construction, or None
if not specified.
Return type:str or None
class mlsnippet.report.Text(text)

Bases: mlsnippet.report.element.Element

Plain text element.

__init__(text)

Construct the Text.

Parameters:text (str) – The text content. The HTML entities in text will be escaped when rendered as HTML.
_to_html(context)

Actual method to render this Element into HTML. Subclasses of Element should override this method.

This method is designed to be called by to_html(), with context ensured to be created, and self pushed to the call-stack of context. Note that if an element needs to render another element within this method, it should call :meth:`to_html of that element, with context passed to it.

Parameters:context (ToHtmlContext) – The context for rendering.
Returns:The rendered HTML.
Return type:str
text

Get the text content.

class mlsnippet.report.HTML(content)

Bases: mlsnippet.report.element.Element

HTML content element.

__init__(content)

Construct the HTML.

Parameters:content (str) – The HTML content. The HTML entities will be output as-is when rendered as HTML.
_to_html(context)

Actual method to render this Element into HTML. Subclasses of Element should override this method.

This method is designed to be called by to_html(), with context ensured to be created, and self pushed to the call-stack of context. Note that if an element needs to render another element within this method, it should call :meth:`to_html of that element, with context passed to it.

Parameters:context (ToHtmlContext) – The context for rendering.
Returns:The rendered HTML.
Return type:str
content

Get the HTML content.

class mlsnippet.report.MagicHTML(obj, cacheable=False)

Bases: mlsnippet.report.element.Element

Wrapping object with __html__ method into Element.

__init__(obj, cacheable=False)

Construct the MagicHTML.

Parameters:
  • obj – The object to be wrapped.
  • cacheable (bool) – Whether or not to cache the output of __html__ method? (default False)
_to_html(context)

Actual method to render this Element into HTML. Subclasses of Element should override this method.

This method is designed to be called by to_html(), with context ensured to be created, and self pushed to the call-stack of context. Note that if an element needs to render another element within this method, it should call :meth:`to_html of that element, with context passed to it.

Parameters:context (ToHtmlContext) – The context for rendering.
Returns:The rendered HTML.
Return type:str
cacheable

Whether or not the output of __html__ is cacheable?

obj

Get the wrapped object.

class mlsnippet.report.InlineMath(mathjax)

Bases: mlsnippet.report.element.MathEquation

Inline math equation.

_to_html(context)

Actual method to render this Element into HTML. Subclasses of Element should override this method.

This method is designed to be called by to_html(), with context ensured to be created, and self pushed to the call-stack of context. Note that if an element needs to render another element within this method, it should call :meth:`to_html of that element, with context passed to it.

Parameters:context (ToHtmlContext) – The context for rendering.
Returns:The rendered HTML.
Return type:str
class mlsnippet.report.BlockMath(mathjax)

Bases: mlsnippet.report.element.MathEquation

Block math equation.

_to_html(context)

Actual method to render this Element into HTML. Subclasses of Element should override this method.

This method is designed to be called by to_html(), with context ensured to be created, and self pushed to the call-stack of context. Note that if an element needs to render another element within this method, it should call :meth:`to_html of that element, with context passed to it.

Parameters:context (ToHtmlContext) – The context for rendering.
Returns:The rendered HTML.
Return type:str
class mlsnippet.report.Resource(data, mime_type, title=None)

Bases: mlsnippet.report.element.Element

Base class for resource elements.

Resources are particular types of binary data, for example, images and CSV files. This class provides utilities to embed such resources in a report, as HTML content.

__init__(data, mime_type, title=None)

Construct the Resource.

Parameters:
  • data (bytes) – Binary data of the resource.
  • mime_type (str) – Mime-type of the resource.
  • title (str or None) – Title of the resource. (default None)
data

Get the binary data of the resource.

get_uri(context)

Get the URI for embedding the resource into HTML.

Parameters:context (ToHtmlContext) – The context for rendering HTML.
Returns:The URI string.
Return type:str
classmethod guess_extension(mime_type)

Get the preferred file extension for specified mime-type.

Return value is a string giving a filename extension, including the leading dot “.”.

Parameters:mime_type (str) – The mime-type.
Returns:
The extension, or None if mime_type
is not registered.
Return type:str or None
classmethod guess_mime_type(extension)

Get the preferred mime-type for specified file extension.

Parameters:extension (str) – The filename extension, including the leading dot “.”.
Returns:
The mime-type, or None if extension
is not registered.
Return type:str or None
mime_type

Get the mime-type of the resource.

title

Get the title of the resource.

Returns:The title, or None if no title is specified.
Return type:str or None
class mlsnippet.report.Attachment(data, mime_type, title=None)

Bases: mlsnippet.report.element.Resource

Subclass of Resource, rendered as a download link.

_to_html(context)

Actual method to render this Element into HTML. Subclasses of Element should override this method.

This method is designed to be called by to_html(), with context ensured to be created, and self pushed to the call-stack of context. Note that if an element needs to render another element within this method, it should call :meth:`to_html of that element, with context passed to it.

Parameters:context (ToHtmlContext) – The context for rendering.
Returns:The rendered HTML.
Return type:str
class mlsnippet.report.Image(data, mime_type, title=None, inline=False)

Bases: mlsnippet.report.element.Resource

Subclass of Resource, rendered as an image.

__init__(data, mime_type, title=None, inline=False)

Construct the Image.

Parameters:
  • data (bytes) – Binary data of the image.
  • mime_type (str) – Mime-type of the image.
  • title (str or None) – Title of the image. (default None)
  • inline (bool) – Whether or not to render this image as inline HTML element? (default False)
_to_html(context)

Actual method to render this Element into HTML. Subclasses of Element should override this method.

This method is designed to be called by to_html(), with context ensured to be created, and self pushed to the call-stack of context. Note that if an element needs to render another element within this method, it should call :meth:`to_html of that element, with context passed to it.

Parameters:context (ToHtmlContext) – The context for rendering.
Returns:The rendered HTML.
Return type:str
classmethod from_figure(figure, dpi=None, tight_bbox=True, title=None, inline=False)

Construct a Image from matplotlib.pyplot.Figure.

Parameters:
  • figure (matplotlib.pyplot.Figure) – The matplotlib figure.
  • dpi (int or None) – DPI for rendering the figure. (default None, use the DPI of figure)
  • tight_bbox (bool) – Whether to have a tight bounding box? (default True)
  • title (str or None) – Title of the image. (default None)
  • inline (bool) – Whether or not to render this image as inline HTML element? (default False)
Returns:

The Image object, carrying a PNG image of

rendered figure.

Return type:

Image

Raises:

TypeError – If figure is not a matplotlib.pyplot.Figure.

classmethod from_image(image, format='PNG', title=None, inline=False)

Construct a Image from PIL.Image.Image.

Parameters:
  • image (PIL.Image.Image) – The PIL image object.
  • format (str) – The format of the image to be saved as. One of {“PNG”, “JPG”, “JPEG”, “BMP”}.
  • title (str or None) – Title of the image. (default None)
  • inline (bool) – Whether or not to render this image as inline HTML element? (default False)
Returns:

The Image object.

Return type:

Image

Raises:
inline

Get whether or not to render this image as inline HTML element.

class mlsnippet.report.DataFrameTable(data_frame)

Bases: mlsnippet.report.element.Element

Element to render pandas.DataFrame as an HTML table.

__init__(data_frame)

Construct the DataFrameTable.

Parameters:data_frame (pandas.DataFrame) – The data frame object.
Raises:TypeError – If data_frame is not a pandas.DataFrame.
_to_html(context)

Actual method to render this Element into HTML. Subclasses of Element should override this method.

This method is designed to be called by to_html(), with context ensured to be created, and self pushed to the call-stack of context. Note that if an element needs to render another element within this method, it should call :meth:`to_html of that element, with context passed to it.

Parameters:context (ToHtmlContext) – The context for rendering.
Returns:The rendered HTML.
Return type:str
data_frame

Get the DataFrame object.

class mlsnippet.report.Library

Bases: object

Base class for HTML libraries.

An HTML library carries stylesheets and scripts, which will be output at the end of HEAD (stylesheets) and BODY (scripts).

get_scripts()

Get the scripts of this library.

Derived classes should override this method to provide the source code of the scripts, including the “<script>” tag. For example:

class JQuery(Library):

    def get_scripts(self):
        return '<script src="https://cdnjs.cloudflare.com/ajax/'                         'libs/jquery/3.2.1/jquery.min.js"></script>'

The scripts will be output at the end of BODY tag in the rendered HTML.

Returns:
Source code of the scripts, or None
if no script is provided.
Return type:str or None
get_styles()

Get the stylesheets of this library.

Derived classes should override this method to provide the source code of the stylesheets, including the “<style>” or “<link>” tag. For example:

class Bootstrap(Library):

    def get_styles(self):
        return '<link rel="stylesheet" '                         'href="https://cdnjs.cloudflare.com/ajax/libs/'                         'twitter-bootstrap/3.3.7/css/bootstrap.min.css" />'

The stylesheets will be output at the end of HEAD tag in the rendered HTML.

Returns:
Source code of the stylesheets, or None
if no stylesheet is provided.
Return type:str or None
class mlsnippet.report.SingletonLibrary

Bases: mlsnippet.report.library.Library

Base for singleton Library classes.

Subclasses of SingletonLibrary would become singleton. For example, JQuery is a subclass of SingletonLibrary, such that the following assertion holds:

assert(JQuery() is JQuery())
static __new__(S, ...) → a new object with type S, a subtype of T
class mlsnippet.report.JQuery

Bases: mlsnippet.report.library.SingletonLibrary

JQuery library, loaded via requirejs(["jquery"]).

get_scripts()

Get the scripts of this library.

Derived classes should override this method to provide the source code of the scripts, including the “<script>” tag. For example:

class JQuery(Library):

    def get_scripts(self):
        return '<script src="https://cdnjs.cloudflare.com/ajax/'                         'libs/jquery/3.2.1/jquery.min.js"></script>'

The scripts will be output at the end of BODY tag in the rendered HTML.

Returns:
Source code of the scripts, or None
if no script is provided.
Return type:str or None
class mlsnippet.report.MathJax

Bases: mlsnippet.report.library.SingletonLibrary

MathJax library, loaded via requirejs(["mathjax"]).

get_scripts()

Get the scripts of this library.

Derived classes should override this method to provide the source code of the scripts, including the “<script>” tag. For example:

class JQuery(Library):

    def get_scripts(self):
        return '<script src="https://cdnjs.cloudflare.com/ajax/'                         'libs/jquery/3.2.1/jquery.min.js"></script>'

The scripts will be output at the end of BODY tag in the rendered HTML.

Returns:
Source code of the scripts, or None
if no script is provided.
Return type:str or None
class mlsnippet.report.Report(title, children, description=None)

Bases: object

Class for building report.

__init__(title, children, description=None)

Construct the Report.

Parameters:
  • title (str) – The title of the report.
  • children – List of objects which can be converted into Element via as_element().
  • description (str or None) – Optional description of this report. (default None)
body

Get the body Container, which contains all Element objects converted from children.

Returns:The body container.
Return type:Container
description

Get the description of the report.

Returns:The description of the report.
Return type:str or None
save(path_or_file)

Save the rendered HTML as file.

Parameters:path_or_file – The file path, or a file-like object to write.
title

Get the title report.

to_html()

Render this report as HTML.

Returns:The rendered HTML.
Return type:str
mlsnippet.report.escape(s)

Escape HTML entities in s.

mlsnippet.report.camel_to_underscore(name)

Convert a camel-case name to underscore.