Skip to content

ui

The ui class is a Python class that is only available when comet_ml is used within the context of Python Code Panels and can be used to add interactivity to the panels.

ui contains three sets of methods:

  • Display methods: To visualize different kinds of Python objects on the Panel canvas area.
  • Widgets methods: To add interactivity to panels through elements that have a UI representation.
  • Utility methods: To update the styling of panels.

To use comet_ml.ui, you need only import it:

from comet_ml import ui

choice = ui.dropdown("Choose one:", ["A", "B", "C"])
ui.display("You picked", choice)

ui display methods

These are the display methods:

  • ui.display
  • ui.display_figure
  • ui.display_image
  • ui.display_text
  • ui.display_markdown

These methods are described below.

ui.display

The ui.display method is used to visualize different kinds of Python objects in the Panel canvas area.

ui.display(*items, format=None, **kwargs)

You can use ui.display on one (or more) of any of the following types of Python items:

  • Pillow Python images library (PIL) images
  • HTML strings (including SVG images)
  • Matplotlib figures
  • Plotly plots
  • Pandas' Dataframes
  • Any object that has a _repr_*_ method

In addition, there are specialized display methods for text, markdown, and images represented as raw strings (as logged as image assets, for example). Each of those methods is described below.

If you wish to send multiple items to the display area, pass them to ui.display() or call ui.display() repeatedly:

from comet_ml import ui

ui.display("hello")
ui.display("world")

# or

ui.display("hello", "world")

The format argument can be either text, markdown, html or None. The default is html or None.

kwargs are optional, and varying, depending on the type of item being displayed. For example, if the item is a pandas Dataframe, then you may also pass in these keyword arguments:

  • theme: name of a color theme (see below)
  • font_size: name of the size, for example, 'normal'
  • font_family: name of the font family
  • text_align: which side to align to
  • width: width of table, for example, 'auto'
  • index: index to highlight
  • even_color: color of even rows
  • even_bg_color: background color of even rows

Theme names: 'yellow light', 'grey light', 'blue light', 'orange light', 'green light', 'red light', 'yellow dark', 'grey dark', 'blue dark', 'orange dark', 'green dark', 'red dark', or 'comet'.

For more details on ui.display, see Python Panel Examples.

ui.display_figure

This method is used to display a Matplotlib figure.

ui.display_figure(plt)
ui.display_figure(figure)

Displays a matplotlib figure.

Examples

from comet_ml import ui
import matplotlib.pyplot as plt

# plt commands here

ui.display(plt)

Or calling with the figure:

from comet_ml import ui
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

# Figure commands here

ui.display(fig)

ui.display_image

This method is used to display an image, either from a logged asset, or from a PIL Image.

Example from a logged asset

from comet_ml import API, ui

api = API()

for experiment in api.get_panel_experiments():
    for json in experiment.get_asset_list("image"):
        if json["fileName"].endswith("jpg"):
            data = experiment.get_asset(json["assetId"])
            ui.display_image(data, format="jpg")

Displays image strings in the given format ("jpg", "gif", or "png").

Example from a PIL image

from comet_ml import ui
from PIL import Image
import random

# Create a PIL image

image = Image.new("RGB", (500, 500))
# process image here
ui.display(image)

For more details, see Python Panel Examples.

ui.display_text

This method is useful for displaying plain text.

ui.display_text(text)

Displays text that otherwise would have characters interpreted as HTML.

ui.display_markdown

This method is useful for displaying text formatted as markdown.

ui.display_markdown(*text)

Displays text as markdown, ignoring any indentation.

ui widget methods

This section describes so-called widgets. These are elements that have a GUI representation and that trigger a change to re-run your code.

This is best shown through an example.

Consider the following Python code:

from comet_ml import ui
if ui.button("Click me!"):
    ui.display("You clicked the button")
    ui.display("Now waiting for you to click the button again")
else:
    ui.display("Waiting for you to click the button")

Running this code in the Python Code Panel editor looks similar to this:

Project View

First, note that the ui component is used directly by calling ui.button().

Also note that there is no explicit loop. However, whenever a widget is changed (or clicked) your code will run again, this time reflecting the change. For this example, the flow is:

  1. The code is run.
  2. The message "Waiting for you to click the button" is displayed.
  3. You click the button.
  4. The code runs again.
  5. This time, the messages "You clicked the button" and "Now waiting for you to click the button again" are displayed.
  6. If you click the button again, you go back to step 4, and the cycle repeats.

All of the following widgets have this same effect. Therefore, you will need to be mindful when writing Python Code Panels that the values of ui components will change, ordering of the widgets matter, and that your code will run repeatedly. This has a number of implications, such as all of the code will run repeatedly (even long-running initialization code). However, there are techniques to handle such issues (see below).

ui.dropdown

The ui.dropdown element does two things at once:

  • Creates a dropdown (selection) list of options on the Panel canvas.
  • Returns the selected item.
choice = ui.dropdown(label, options, index=0, format_func=None,
                     key=None, on_change=None, args=None,
                     kwargs=None, multiple=False, classes=None)

Example

from comet_ml import ui

choice = ui.dropdown("Choose one:", ["A", "B", "C"])
ui.display("You picked", choice)

When you first run this code, you will see:

Python Panels Dropdown - 1

Note that this is very different from the usual manner of creating GUI elements. In this manner, there are no "callbacks" but merely the above code. By default, the dropdown has been shown on the screen and the default options (index=0) has been selected. The code continues, and so you see choice "A" already set as the choice.

If you then select a different item, your code runs again, updating the GUI and the selected item:

Python Panels Dropdown - 2

If you would like to separate code that should only run once (say, because it is expensive to compute) you can separate the code to run when the GUI is updated by placing it in a main function, like this:

from comet_ml import ui

# Code that is expensive to run:
choices = ...

def main():
    # The fast GUI-based code:

    choice = ui.dropdown("Choose one:", choices)
    ui.display("You picked", choice)

You may provide a parameter index as a numeric value representing the row to show as the initial choice.

The format_func is a function that takes a row from options, and returns a string to be used in the dropdown selection list. This is useful if you would like to provide to options something other than what you would like displayed. For example, consider:

from comet_ml import API, ui

api = API()

api_experiments = api.get_panel_experiments()

api_experiment = ui.dropdown(
    "Choose an experiment by key:",
    api_experiments,
    format_func= lambda experiment: experiment.key
)

In this example, the experiment's key is used in the dropdown list, but options is a list of APIExperiments. In this manner, you can pass in options in any format, but you should then provide a format_func for easy selection.

Arguments

  • label: (str) label for the dropdown list
  • options: (list) list of choices to choose from
  • index: (int or list, optional) use initial index for single choice, or use a list of strings if multiple choice
  • format_func: (function, optional) function that takes an option and returns a string to use in the option list
  • key: (str, optional) when generating dropdowns in a loop - this is useful to assign unique keys for the dropdown
  • on_change: (function, optional) function to run when an option is selected
  • args: (list or tuple, optional) positional args to send to on_change function
  • kwargs: (dict, optional) keyword args to send to on_change function
  • multiple: (bool, optional) if True, allow user to select multiple options
  • classes: (list, optional) list of CSS class names to attach to the dropdown

ui.input

The ui.input() widget is used in order to get textual input from the user. Pressing TAB or ENTER will rerun the script.

Signature and Use

value = ui.input(label, value="", key=None, on_click=None,
                 args=None, kwargs=None, classes=None)

Arguments

  • label: (str) textual description that preceeds the input area
  • value: (str, optional) default text in input area
  • key: (str, optional) when generating in a loop - this is useful to assign unique keys for the input widget
  • on_click: (function, optional) function to run when text is ready
  • args: (list or tuple, optional) positional args to send to on_change function
  • kwargs: (dict, optional) keyword args to send to on_click function
  • classes: (list, optional) list of CSS class names to attach to the input widget

ui.checkbox

The ui.checkbox() widget is used in order to get a binary choice from the user.

Signature and Use

value = ui.checkbox(label, value=False, key=None, on_click=None, args=None,
                    kwargs=None, classes=None)

Arguments

  • label: (str) textual description that follows the checkbox widget
  • value: (bool, optional) default value of checkbox
  • key: (str, optional) when generating in a loop - this is useful to assign unique keys for the checkbox widget
  • on_click: (function, optional) function to run when text is ready
  • args: (list or tuple, optional) positional args to send to on_change function
  • kwargs: (dict, optional) keyword args to send to on_click function
  • classes: (list, optional) list of CSS class names to attach to the checkbox widget

ui.button

The ui.button() widget is used to trigger an action at a specific time.

Signature and Use

if ui.button(label, key=None, on_click=None, args=None, kwargs=None, classes=None):
    # do action
else:
    # wait for button to be pressed
Arguments
  • label: (str) textual description that appears on the button
  • key: (str, optional) when generating in a loop - this is useful to assign unique keys for the button
  • on_click: (function, optional) function to run when text is ready
  • args: (list or tuple, optional) positional args to send to on_change function
  • kwargs: (dict, optional) keyword args to send to on_click function
  • classes: (list, optional) list of CSS class names to attach to the button

ui.progress

The ui.progress() widget is used in order to show progress for long-running processes.

Use

from comet_ml import ui
import time
def long_running_process():
    start_time = time.time()
    while time.time() - start_time < 3:
        pass
if ui.progress("Getting started", 0):
    # initialize panel, don't do anything yet!
    pass
elif ui.progress("Processing 25% done...", 25):
    long_running_process() # first 25%
elif ui.progress("Half-way done", 50):
    long_running_process() # second 25%
elif ui.progress("Almost done!", 75):
    long_running_process() # running 3rd 25%
elif ui.progress("Done!", 100): # clears screen
    long_running_process() # last 25%
else:
    ui.display("Ok! What's next?")

Arguments

  • label: (str) a label for the dropdown list
  • percent: (int) a number between 1 and 100
  • on_load: (function, optional) function to run
  • args: (list or tuple, optional) positional args to send to on_load function
  • kwargs: (dict, optional) keyword args to send to on_load function
  • classes: (list, optional) a list of CSS class names to attach to the progress widget

ui.columns

The ui.columns() widget is used to break the current display area into a series of columns. Columns can be nested.

Signature and Use

columns = ui.columns(items, classes=None, **styles)

By default, any item on which you perform ui.display() goes to the top-level Panel area. However, if you would like, you can place displayed items into different columns using this widget.

Examples

columns = ui.columns(3)
for i, column in enumerate(columns):
    column.display("Column %s" % i)
columns = ui.columns([1, 3, 1])
# middle column is thre times the width of first and third
columns[0].display("Column one")
columns[1].display("Column two is wide")
columns[2].display("Column three")

Arguments

  • items: (int, or list of numbers) if an integer, then break the current area into even columns; if a list of numbers, then divide proportionally by the number's value divided by sum of numbers.
  • classes: (list, optional) a list of CSS class names to attach to the columns
  • styles: a dictionary of CSS items to apply to the columns

ui utility methods

These are the ui utility methods:

  • ui.get_theme_names
  • ui.set_css(css_text)
  • ui.add_css(css_text)

Descriptions follow.

ui.get_theme_names

Get the names of color themes for displaying pandas' Dataframes.

Example

from comet_ml import ui

color_theme_names = ui.get_theme_names()
color_theme_name = ui.dropdown.dropdown(
    "Select a theme:",
    color_theme_name
)
# create a dataframe here
ui.display(df, theme=color_theme_name)

As shown, the color_theme_names could be useful in creating a dropdown selection showing a Dataframe.

ui.set_css

This method allows you to set additional CSS for items for display.

Warning

This is experimental and may be removed in a future version.

ui.add_css

This method allows you to add CSS for items for display.

Warning

This is experimental and may be removed in a future version.

Mar. 27, 2024