How To Gradio: Understanding the basics of gradio.Interface — Parameter (outputs= #add gradio output component)

HuggyMonkey
9 min readNov 14, 2023

gradio.Interface is the main class used to build the UI using the Gradio library. In a few lines of code, you can create a web app for machine learning models, chatbots, dashboards, practically whatever your imagination can spin up. If you can translate your idea into a Python function, Gradio can handle the presentation.

In this series, Understanding the basics of gradio.Interface, we are going to help you understand as simply as possible the key concepts of using the gradio.Interface class. We will also discuss the class’s most important parameters and methods so that you can improve your app-building skills with Gradio.

Parameter (outputs= #add gradio output component)

In this article, we will dissect one of the three required parameters of the gradio.Interface class: (outputs=). You will learn different methods of setting this parameter using Gradio components as well as discuss a few important points that will assist you in becoming better at app building with Gradio.

Getting Started With Gradio

To get started with Gradio, simply install Gradio from PyPi via pip

pip install gradio

gradio.Interface(outputs=)

The gradio.Interface(outputs=) parameter expects a Gradio component or a list of Gradio components. Gradio components are the visual and interactive elements of the user interface responsible for accepting user input and displaying output for your Gradio app. Components passed to the ‘outputs=’ parameter are described as Output Components. Output components retrieve the output of the Python function and convert it into a datatype which can be passed on to the user interface, which is then sent to the UI to be displayed.

Image adapted from https://www.gradio.app/docs/interface

Above is the description of the gradio.Interface class “outputs” parameter according to the official documentation found here.

We have highlighted a few points that are important to consider when setting this parameter. Each point will be further discussed along with other additional points to help improve your understanding of the Interface class so that you can build more efficiently.

“a single Gradio component, or list of Gradio components.”

To the gradio.Interface(outputs=) parameter, you are required to pass a Gradio component able to act as a suitable output component. You can also pass a list of output components that corresponds to the number of returned values of your Python function.

  • a single Gradio component
import gradio as gr


def greet(name):
greeting = "Hello " + name
return greeting


demo = gr.Interface(fn=greet,
inputs=gr.Textbox(),
outputs=gr.Textbox(), #<-- Gradio TextBox component as an output component
)

demo.launch()
import gradio as gr
from datetime import datetime


def calculate_birth_year(age):
current_year = datetime.now().year
birth_year = current_year - age
return birth_year

demo = gr.Interface(fn=calculate_birth_year,
inputs=gr.Number(),
outputs=gr.Number(), #<-- Gradio Number component as an output component
)

demo.launch()
  • list of Gradio components
import gradio as gr
import random


def greet_number(name):
greeting = "Hello " + name
lucky_number = random.randint(1, 100)
return greeting, lucky_number

demo = gr.Interface(fn=greet_number,
inputs=gr.Textbox(),
outputs=[gr.Textbox(), gr.Number()], #<-- Multiple output components passed as list of Gradio components
)

demo.launch()

“Components can either be passed as instantiated objects, or referred to by their string shortcuts.”

To the gradio.Interface(outputs=) parameter you pass an instance of a Gradio component. Alternatively, you can pass the string shortcut representation of the Gradio component. The string shortcut method provides a convenient way of using Gradio components. The components instantiated using their string shortcuts are initialized to handle the most common use cases of the component, however, these components are fixed and can’t be customized from your code. If you want to have more control over the behavior of the component, the solution is to pass an instance of the component and customize its parameters.

  • passed as instantiated objects
import gradio as gr

def greet(name):
greeting = "Hello " + name
return greeting

demo = gr.Interface(fn=greet,
inputs=gr.Textbox(),
outputs=gr.Textbox(), #<-- Gradio component passed directly as an instantiated object
)

demo.launch()
import gradio as gr


def greet(name):
greeting = "Hello " + name
return greeting


Textbox = gr.Textbox() #<-- Create instance of Gradio component

demo = gr.Interface(fn=greet,
inputs=Textbox(),
outputs=gr.Textbox, #<-- Pass instantiated object to parameter
)

demo.launch()
  • referred to by their string shortcuts
import gradio as gr

def greet(name):
greeting = "Hello " + name
return greeting

demo = gr.Interface(fn=greet,
inputs=gr.Textbox(),
outputs="textbox", #<-- Gradio component passed using string shortcut
)

demo.launch()
import gradio as gr
import random

def greet_number(name):
greeting = "Hello " + name
lucky_number = random.randint(1, 100)
return greeting, lucky_number

demo = gr.Interface(fn=greet_number,
inputs=gr.Textbox(),
outputs=["textbox", "number"], #<-- Multiple output components passed as list of string shortcuts
)

demo.launch()

“The number of output components should match the number of values returned by fn”

Output components retrieve the Python function’s returned values and convert them into a datatype which can be passed on to the user interface. As a consequence of this behavior, it’s required to match the number of output components with the number of values returned by the function passed to gradio.Interface(fn=).

✅ Correct Matching Number Of Returned Values
-Example 1

import gradio as gr

def greet(name):
greeting = "Hello " + name
return greeting #<-- Number of values returned by function: 1

demo = gr.Interface(fn=greet,
inputs=gr.Textbox(),
outputs=gr.Textbox(), #<-- Number of output components: 1
)

demo.launch(

-Example 2

import gradio as gr
import random

def greet_number(name):
greeting = "Hello " + name
lucky_number = random.randint(1, 100)
return greeting, lucky_number #<-- Number of values returned by function: 2

demo = gr.Interface(fn=greet_number,
inputs=gr.Textbox(),
outputs=[gr.Textbox(), gr.Number()], #<-- Number of output components: 2
)

demo.launch()

❌ Incorrect Matching Number Of Returned Values
-Example 1

import gradio as gr


def greet(name):
greeting = "Hello " + name
return greeting # <-- Number of values returned by function: 1


demo = gr.Interface(fn=greet,
inputs=gr.Textbox(),
outputs=[gr.Textbox(), gr.Textbox()], # <-- Number of output components: 2
)

demo.launch()
Error when running Incorrect Matching Number Of Returned Values example 1 code
Raised Error Seen In Terminal

raise ValueError(
ValueError: An event handler (greet) didn't receive enough output values (needed: 2, received: 1).
Wanted outputs:
[textbox, textbox]
Received outputs:
["Hello Joke"]

Example 2

import gradio as gr
import random


def greet_number(name):
greeting = "Hello " + name
lucky_number = random.randint(1, 100)
return greeting, lucky_number # <-- Number of values returned by function: 2


demo = gr.Interface(fn=greet_number,
inputs=gr.Textbox(),
outputs=gr.Textbox(), # <-- Number of output components: 1
)

demo.launch()
Output when running Incorrect Matching Number Of Returned Values example 2 code

Running the above code is actually an acceptable Gradio app that will run without any errors when used. For most people, the issue would be the way in which the output is presented. In this case, most people would want the greeting and the lucky number to be presented in separate output components instead of together as a tuple in one output component. On the other hand, it could be that you want the app to work just like this, and present the multiple outputs of the function in a textbox as a tuple.

In any of those situations, what’s more important is to understand the outcome of the code. Why doesn’t it throw an error when looking at the code clearly shows that the number of returned values and output components don’t match? The simple answer is that the number of returned values and output components do match.

OK…why?

In Python, if multiple values are returned by a function, these values are stored and returned as a tuple containing those values. This means that the *greet_number* function is returning one object (a tuple containing the values for *greeting* and *lucky_number*). In regards to Gradio, if an appropriate output component is used, the concept of matching the number of returned values and output components is upheld and no error will occur when using the app.

import random


def greet_number(name):
greeting = "Hello " + name
lucky_number = random.randint(1, 100)
return greeting, lucky_number # <-- Number of values returned by function: 2


# PYTHON
returned_value = greet_number("Lottery")
print(returned_value)
# Output - Function returns multiple values as a single tuple of those values
"""
('Hello Lottery', 90)
"""



# GRADIO - one(1) Output Component
output_component_1 = greet_number("Lottery")
print(output_component_1)
# Output - Values passed to output component as a tuple if only one output component is used
"""
('Hello Lottery', 90)
"""

# GRADIO - multiple Output Components
output_component_1, output_component_2 = greet_number("Lottery") # Values unpacked to multiple output components
print("Output Component 1 value: ", output_component_1)
print("Output Component 2 value: ", output_component_2)
# Output - Values passed to output components used
"""
Output Component 1 value: Hello Lottery
Output Component 2 value: 55
"""

“If set to None, then only the input components will be displayed.”

To the gradio.Interface(outputs=) parameter, the value of “None” can be passed. To put it simply, passing “None” says to the output component; the function doesn’t return any values so don’t expect it. Therefore it’s important to keep in mind how this affects the behavior of output components when building your app.

Why would you want to pass “None” to the ‘outputs=’ parameter? It depends on your app’s design. If your app only needs to get information from the user and no response is needed, then you can achieve this by passing “None” to the ‘outputs=’ parameter. Below is an example:

import gradio as gr
import csv
from pathlib import Path

# Function to save input data to a CSV file
def save_to_csv(first_name, last_name, age):
# Define the CSV file path using Path
csv_file = Path('user_data.csv')

# Create CSV file if it doesn't exist
if not csv_file.exists():
with csv_file.open('w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['First Name', 'Last Name', 'Age'])

# Append the input data to the CSV file
with csv_file.open('a', newline='') as file:
writer = csv.writer(file)
writer.writerow([first_name, last_name, age])

return None # <-- Number of values returned by function: 0

# Gradio Interface
app = gr.Interface(
fn=save_to_csv,
inputs=["text", "text", "number"],
outputs=None, #<-- Set to None (Number of output components: 0)
)

app.launch()

“The returned datatype of the function should match the expected datatype of the output component”

Let’s look back at how output components work. Output components retrieve the Python function’s returned values and convert them into a datatype which can be passed on to the user interface.

For example, the gradio.Textbox component used as an output component would expect values of datatype str to be returned by the function. The gradio.Number component used as an output component would expect values of datatype float or int.

✅ Correct Matching of Datatypes
-Example 1

import gradio as gr

def greet(name):
greeting = "Hello " + name
return greeting # Function's Returned Value Datatype: str

demo = gr.Interface(fn=greet,
inputs=gr.Textbox(),
outputs=gr.Textbox(), #<-- Output component returned datatype: str
)

demo.launch()

-Example 2

import gradio as gr
import random

def greet_number(name):
greeting = "Hello " + name
lucky_number = random.randint(1, 100)
return greeting, lucky_number # Function's Returned Value Datatype: str, int

demo = gr.Interface(fn=greet_number,
inputs=gr.Textbox(),
outputs=[gr.Textbox(), gr.Number()], #<-- Output component returned datatype: str, int
)

demo.launch()

❌ Incorrect Matching of Datatypes
-Example 1

import gradio as gr

def greet(name):
greeting = "Hello " + name
return greeting # Function's Returned Value Datatype: str

demo = gr.Interface(fn=greet,
inputs=gr.Textbox(),
outputs=gr.Number(), #<-- Output component returned datatype: int
)

demo.launch()
Error when running Incorrect Matching of Datatypes example 1 code
Raised Error Seen In Terminal

return float(num)
ValueError: could not convert string to float: 'Hello Mermaids'

❌ Incorrect Matching of Datatypes
-Example 2

import gradio as gr
import random

def greet_number(name):
greeting = "Hello " + name
lucky_number = random.randint(1, 100)
return greeting, lucky_number # Function's Returned Value Datatype: str, int

demo = gr.Interface(fn=greet_number,
inputs=gr.Textbox(),
outputs=[gr.Number(), gr.Textbox()], #<-- Output component returned datatype: int, str
)

demo.launch()
Error when running Incorrect Matching of Datatypes example 2 code
Raised Error Seen In Terminal

return float(num)
ValueError: could not convert string to float: 'Hello Lemonade'

Running the above code in the Incorrect Matching of Datatypes section will not produce any initial warnings or errors. The code will still execute and your App will launch on the local host URL. The error will occur while using the app. You will receive the ValueError in the console.

It’s also important to note that some Output Components can accept multiple different datatype values returned by the function. For example, the Gradio Image component used as an output component expects data in the form ‘numpy.array’, ‘PIL.Image’ or ‘str’ or ‘pathlib.Path’.

Hopefully after reading, you now understand:

  • the different ways of setting the ‘outputs’ parameter of the gradio.Interface class.
  • the relationship between Gradio output components and your function’s returned values
  • the relationship between Gradio output components and the user interface
  • the importance of matching the number of output components and the function’s returned values
  • the importance of matching datatypes of output components and the function returned values

If you would like to practice building with Gradio, you can do so right in your browser for free at the Gradio Playground.

Read the official Gradio documentation regarding the gradio.Interface class here.

Read the official documentation regarding Gradio components here.

Read more in the series Understanding the basics of gradio.Interface

--

--