To get Gradio running with a simple example, follow these three steps:
1. Install Gradio from pip.
pip install gradio
2. Run the code below as a Python script or in a Python notebook (or in a colab notebook).
import gradio as gr def greet(name): return "Hello " + name + "!!" iface = gr.Interface(fn=greet, inputs="text", outputs="text") iface.launch()
3. The interface below will appear automatically within the Python notebook, or pop in a browser on http://localhost:7860 if running from a script.
Gradio can wrap almost any Python function with an easy to use interface. That function could be anything from a simple tax calculator to a pretrained model.
Interface class is initialized with three parameters:
fn: the function to wrap
inputs: the input component type(s)
outputs: the output component type(s)
With these three arguments, we can quickly create interfaces and
launch() them. But what if you want to change how the UI components look or behave?
What if we wanted to customize the input text field - for example, we wanted it to be larger and have a text hint? If we use the actual input class for
Textbox instead of using the string shortcut, we have access to much more customizability. To see a list of all the components we support and how you can customize them, check out the Docs
import gradio as gr def greet(name): return "Hello " + name + "!" iface = gr.Interface( fn=greet, inputs=gr.inputs.Textbox(lines=2, placeholder="Name Here..."), outputs="text") iface.launch()
Multiple Inputs and Outputs
Let's say we had a much more complex function, with multiple inputs and outputs. In the example below, we have a function that takes a string, boolean, and number, and returns a string and number. Take a look how we pass a list of input and output components.
import gradio as gr def greet(name, is_morning, temperature): salutation = "Good morning" if is_morning else "Good evening" greeting = "%s %s. It is %s degrees today" % ( salutation, name, temperature) celsius = (temperature - 32) * 5 / 9 return greeting, round(celsius, 2) iface = gr.Interface( fn=greet, inputs=["text", "checkbox", gr.inputs.Slider(0, 100)], outputs=["text", "number"]) iface.launch()
We simply wrap the components in a list. Furthermore, if we wanted to compare multiple functions that have the same input and return types, we can even pass a list of functions for quick comparison.
Working with Images
Let's try an image to image function. When using the
Image component, your function will receive a numpy array of your specified size, with the shape
(width, height, 3), where the last dimension represents the RGB values. We'll return an image as well in the form of a numpy array.
import gradio as gr import numpy as np def sepia(img): sepia_filter = np.array([[.393, .769, .189], [.349, .686, .168], [.272, .534, .131]]) sepia_img = img.dot(sepia_filter.T) sepia_img /= sepia_img.max() return sepia_img iface = gr.Interface(sepia, gr.inputs.Image(shape=(200, 200)), "image") iface.launch()
Image input interface comes with an 'edit' button which opens tools for cropping, flipping, rotating, drawing over, and applying filters to images. We've found that manipulating images in this way will often reveal hidden flaws in a model.
You can provide example data that a user can easily load into the model. This can be helpful to demonstrate the types of inputs the model expects, as well as to provide a way to explore your dataset in conjunction with your model. To load example data, you provide a nested list to the
examples= keyword argument of the Interface constructor. Each sublist within the outer list represents a data sample, and each element within the sublist represents an input for each input component. The format of example data for each component is specified in the Docs.
import gradio as gr import random def calculator(num1, operation, num2): print(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 iface = gr.Interface(calculator, ["number", gr.inputs.Radio(["add", "subtract", "multiply", "divide"]), "number"], "number", examples=[ [5, "add", 3], [4, "divide", 2], [-4, "multiply", 2.5], [0, "subtract", 1.2], ], title="test calculator", description="heres a sample toy calculator. enjoy!", flagging_options=["this", "or", "that"] ) iface.launch()
You can load a large dataset into the examples to browse and interact with the dataset through Gradio. The examples will be automatically paginated (you can configure this through the
examples_per_page argument of Interface) and you can use CTRL + arrow keys to navigate through the examples quickly.
Underneath the output interfaces, there is a button marked "Flag". When a user testing your model sees input with interesting output, such as erroneous or unexpected model behaviour, they can flag the input for the interface creator to review. Within the directory provided by the
flagging_dir= argument to the Interface constructor, a CSV file will log the flagged inputs. If the interface involves file data, such as for Image and Audio components, folders will be created to store those flagged data as well.
For example, with the calculator interface shown above, we would have the flagged data stored in the flagged directory shown below:
+-- calculator.py +-- flagged/ | +-- logs.csv
num1,operation,num2,Output 5,add,7,12 6,subtract,1.5,4.5
With the sepia interface shown above, we would have the flagged data stored in the flagged directory shown below:
+-- sepia.py +-- flagged/ | +-- logs.csv | +-- im/ | | +-- 0.png | | +-- 1.png | +-- Output/ | | +-- 0.png | | +-- 1.png
im,Output im/0.png,Output/0.png im/1.png,Output/1.png
You can review these flagged inputs by manually exploring the flagging directory, or load them into the examples of the Gradio interface by pointing the
examples= argument to the flagged directory. If you wish for the user to provide a reason for flagging, you can pass a list of strings to the
flagging_options argument of Interface. Users will have to select one of the strings when flagging, which will be saved as an additional column to the CSV.
Sharing Interfaces Publicly & Privacy
Interfaces can be easily shared publicly by setting
share=True in the
launch() method. Like this:
gr.Interface(classify_image, "image", "label").launch(share=True)
This generates a public, shareable link that you can send to anybody! When you send this link, the user on the other side can try out the model in their browser. Because the processing happens on your device (as long as your device stays on!), you don't have to worry about any dependencies. If you're working out of colab notebook, a share link is always automatically created. It usually looks something like this: XXXXX.gradio.app. Although the link is served through a gradio link, we are only a proxy for your local server, and do not store any data sent through the interfaces.
Keep in mind, however, that these links are publicly accessible, meaning that anyone can use your model for prediction! Therefore, make sure not to expose any sensitive information through the functions you write, or allow any critical changes to occur on your device. If you set
share=False (the default), only a local link is created, which can be shared by port-forwarding with specific users.
Share links expire after 72 hours. For permanent hosting, see below.
You can share your interface publicly and permanently by hosting on Gradio's infrastructure. You will need to create a Gradio premium account. First, log into Gradio on gradio.app and click Sign In at the top. Once you've logged in with your Github account, you can specify which repositories from your Github profile you'd like to have hosted by Gradio. You must also specify the file within the repository that runs the Gradio
launch() command. Once you've taken these steps, Gradio will launch your interface and provide a public link you can share.
That's all you need to get started with Gradio! To dive a little deeper, check out:
- Advanced Features to read about additional powerful features Gradio provides,
- Introduction to Hosted to see how you can permanently host your model online on the Hub,
- Documentation to view all the components available through Gradio.