Gradio provides several helper functions and classes to enhance your interface functionality.
Examples
gr.Examples(
examples,
inputs,
outputs=None,
fn=None,
cache_examples=None,
cache_mode=None,
examples_per_page=10,
label="Examples",
elem_id=None,
run_on_click=False,
preprocess=True,
postprocess=True,
api_visibility="undocumented",
api_name="load_example",
api_description=None,
batch=False,
example_labels=None,
visible=True,
preload=0
)
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 listeners so that clicking on an example populates the input/output components.
Parameters
examples
list[Any] | list[list[Any]] | str
required
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.
inputs
Component | Sequence[Component]
required
The component or list of components corresponding to the examples.
outputs
Component | Sequence[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.
cache_examples
bool | None
default:"None"
If True, caches examples in the server for fast runtime in examples. If “lazy”, then examples are cached after their first use.
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.
How many examples to show per page.
label
str | I18nData | None
default:"'Examples'"
The label to use for the examples component.
An optional string that is assigned as the id of this component in the HTML DOM.
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.
If True, preprocesses the example input before running the prediction function and caching the output.
If True, postprocesses the example output after running the prediction function and before caching.
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.
visible
bool | Literal['hidden']
default:"True"
If False, the examples component will be hidden in the UI.
preload
int | Literal[False]
default:"0"
If an integer is provided, the example at that index will be preloaded when the Gradio app is first loaded.
Example
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():
num1 = gr.Number()
operation = gr.Radio(["add", "subtract", "multiply", "divide"])
num2 = gr.Number()
output = gr.Number()
btn = gr.Button("Calculate")
btn.click(calculator, [num1, operation, num2], output)
gr.Examples(
examples=[
[5, "add", 3],
[10, "subtract", 2],
[4, "multiply", 6],
[8, "divide", 2]
],
inputs=[num1, operation, num2],
outputs=output,
fn=calculator,
)
demo.launch()
Progress
gr.Progress(track_tqdm=False)
The Progress class provides a custom progress tracker that is used in a function signature. To attach a Progress tracker to a function, simply add a parameter right after the input parameters that has a default value set to a gr.Progress() instance.
Parameters
If True, the Progress object will track any tqdm.tqdm iterations with the tqdm library in the function.
Methods
call
progress(progress, desc=None, total=None, unit="steps")
Updates progress tracker with progress and message text.
progress
float | tuple[int, int | None] | None
If float, should be between 0 and 1 representing completion. If tuple, first number represents steps completed, and second value represents total steps or None if unknown. If None, hides progress bar.
total
int | float | None
default:"None"
Estimated total number of steps.
tqdm
progress.tqdm(iterable, desc=None, total=None, unit="steps")
Attaches progress tracker to iterable, like tqdm.
Iterable to attach progress tracker to.
total
int | float | None
default:"None"
Estimated total number of steps.
Example
import gradio as gr
import time
def my_function(x, progress=gr.Progress()):
progress(0, desc="Starting...")
time.sleep(1)
for i in progress.tqdm(range(100)):
time.sleep(0.1)
return x
gr.Interface(my_function, gr.Textbox(), gr.Textbox()).launch()
update
gr.update(
elem_id=None,
elem_classes=None,
visible=None,
**kwargs
)
Updates a component’s properties. When a function passed into a Gradio Interface or Blocks events returns a value, it typically updates the value of the output component. But it is also possible to update the properties of an output component by returning gr.update(...) with any arbitrary parameters to update.
Parameters
Use this to update the id of the component in the HTML DOM.
elem_classes
list[str] | str | None
default:"None"
Use this to update the classes of the component in the HTML DOM.
visible
bool | Literal['hidden'] | None
default:"None"
Use this to update the visibility of the component.
Any other keyword arguments to update the component’s properties.
Example
import gradio as gr
with gr.Blocks() as demo:
radio = gr.Radio([1, 2, 4], label="Set the value of the number")
number = gr.Number(value=2, interactive=True)
radio.change(fn=lambda value: gr.update(value=value), inputs=radio, outputs=number)
demo.launch()
skip
A special function that can be returned from a Gradio function to skip updating the output component. This may be useful when you want to update the output component conditionally.
Example
import gradio as gr
def conditional_update(value):
if value > 10:
return value * 2
else:
return gr.skip()
with gr.Blocks() as demo:
inp = gr.Number()
out = gr.Number()
btn = gr.Button("Submit")
btn.click(conditional_update, inp, out)
demo.launch()
validate
gr.validate(is_valid, message)
A special function that can be returned from a Gradio function to set the validation error of an output component.
Parameters
Whether the value is valid.
The validation message to display.