Introducing Gradio Clients

Watch
  1. Helpers
  2. Examples

New to Gradio? Start here: Getting Started

See the Release History

Examples

gradio.Examples(ยทยทยท)

Description

This class is a wrapper over the Dataset component and can be used to create Examples for Blocks / Interfaces. Populates the Dataset component with examples and assigns event listener so that clicking on an example populates the input/output components. Optionally handles example caching for fast inference.

Initialization

Parameters
examples: list[Any] | list[list[Any]] | str

example inputs that can be clicked to populate specific components. Should be nested list, in which the outer list consists of samples and each inner list consists of an input corresponding to each input component. A string path to a directory of examples can also be provided but it should be within the directory with the python file running the gradio app. If there are multiple input components and a directory is provided, a log.csv file must be present in the directory to link corresponding inputs.

inputs: Component | list[Component]

the component or list of components corresponding to the examples

outputs: Component | list[Component] | None
default = None

optionally, provide the component or list of components corresponding to the output of the examples. Required if `cache_examples` is not False.

fn: Callable | None
default = None

optionally, provide the function to run to generate the outputs corresponding to the examples. Required if `cache_examples` is not False. Also required if `run_on_click` is True.

cache_examples: bool | None
default = None

If True, caches examples in the server for fast runtime in examples. If "lazy", then examples are cached (for all users of the app) after their first use (by any user of the app). If None, will use the GRADIO_CACHE_EXAMPLES environment variable, which should be either "true" or "false". In HuggingFace Spaces, this parameter is True (as long as `fn` and `outputs` are also provided). The default option otherwise is False.

cache_mode: Literal['eager', 'lazy'] | None
default = None

if "lazy", examples are cached after their first use. If "eager", all examples are cached at app launch. If None, will use the GRADIO_CACHE_MODE environment variable if defined, or default to "eager".

examples_per_page: int
default = 10

how many examples to show per page.

label: str | None
default = "Examples"

the label to use for the examples component (by default, "Examples")

elem_id: str | None
default = None

an optional string that is assigned as the id of this component in the HTML DOM.

run_on_click: bool
default = False

if cache_examples is False, clicking on an example does not run the function when an example is clicked. Set this to True to run the function when an example is clicked. Has no effect if cache_examples is True.

preprocess: bool
default = True

if True, preprocesses the example input before running the prediction function and caching the output. Only applies if `cache_examples` is not False.

postprocess: bool
default = True

if True, postprocesses the example output after running the prediction function and before caching. Only applies if `cache_examples` is not False.

api_name: str | Literal[False]
default = "load_example"

Defines how the event associated with clicking on the examples appears in the API docs. Can be a string or False. If set to a string, the endpoint will be exposed in the API docs with the given name. If False, the endpoint will not be exposed in the API docs and downstream apps (including those that `gr.load` this app) will not be able to use the example function.

batch: bool
default = False

If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. Used only if cache_examples is not False.

example_labels: list[str] | None
default = None

A list of labels for each example. If provided, the length of this list should be the same as the number of examples, and these labels will be used in the UI instead of rendering the example values.

visible: bool
default = True

If False, the examples component will be hidden in the UI.

Attributes

Parameters
dataset: gradio.Dataset

The `gr.Dataset` component corresponding to this Examples object.

load_input_event: gradio.events.Dependency

The Gradio event that populates the input values when the examples are clicked. You can attach a `.then()` or a `.success()` to this event to trigger subsequent events to fire after this event.

cache_event: gradio.events.Dependency | None

The Gradio event that populates the cached output values when the examples are clicked. You can attach a `.then()` or a `.success()` to this event to trigger subsequent events to fire after this event. This event is `None` if `cache_examples` if False, and is the same as `load_input_event` if `cache_examples` is `'lazy'`.

Examples

Updating Examples

In this demo, we show how to update the examples by updating the samples of the underlying dataset. Note that this only works if cache_examples=False as updating the underlying dataset does not update the cache.

import gradio as gr

def update_examples(country):
    if country == "USA":
        return gr.Dataset(samples=[["Chicago"], ["Little Rock"], ["San Francisco"]])
    else:
        return gr.Dataset(samples=[["Islamabad"], ["Karachi"], ["Lahore"]])

with gr.Blocks() as demo:
    dropdown = gr.Dropdown(label="Country", choices=["USA", "Pakistan"], value="USA")
    textbox = gr.Textbox()
    examples = gr.Examples([["Chicago"], ["Little Rock"], ["San Francisco"]], textbox)
    dropdown.change(update_examples, dropdown, examples.dataset)
    
demo.launch()

Demos

import gradio as gr

def calculator(num1, operation, num2):
    if operation == "add":
        return num1 + num2
    elif operation == "subtract":
        return num1 - num2
    elif operation == "multiply":
        return num1 * num2
    elif operation == "divide":
        return num1 / num2

with gr.Blocks() as demo:
    with gr.Row():
        with gr.Column():
            num_1 = gr.Number(value=4)
            operation = gr.Radio(["add", "subtract", "multiply", "divide"])
            num_2 = gr.Number(value=0)
            submit_btn = gr.Button(value="Calculate")
        with gr.Column():
            result = gr.Number()

    submit_btn.click(
        calculator, inputs=[num_1, operation, num_2], outputs=[result], api_name=False
    )
    examples = gr.Examples(
        examples=[
            [5, "add", 3],
            [4, "divide", 2],
            [-4, "multiply", 2.5],
            [0, "subtract", 1.2],
        ],
        inputs=[num_1, operation, num_2],
    )

if __name__ == "__main__":
    demo.launch(show_api=False)

		

Guides