Getting Started

Quick Start

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 + "!"

gr.Interface(fn=greet, inputs="text", outputs="text").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.

The Interface

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.

The core Interface class is initialized with three parameters:

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?

Customizable Components

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 + "!"

gr.Interface(
  greet, 
  gr.inputs.Textbox(lines=2, placeholder="Name Here..."), 
  "text").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)

gr.Interface(
  greet, 
  ["text", "checkbox", gr.inputs.Slider(0, 100)],
  ["text", "number"]).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

gr.Interface(
  sepia, gr.inputs.Image(shape=(200, 200)), "image").launch()

Additionally, our 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.

Interpretation

Most models are black boxes such that the internal logic of the function is hidden from the end user. To encourage transparency, we've added the ability for interpretation so that users can understand what parts of the input are responsible for the output. Take a look at the simple interface below:

import gradio as gr

male_words, female_words = ["he", "his", "him"], ["she", "her"]
def gender_of_sentence(sentence):
  male_count = len([word for word in sentence.split() if word.lower() in male_words])
  female_count = len([word for word in sentence.split() if word.lower() in female_words])
  total = max(male_count + female_count, 1)
  return {"male": male_count / total, "female": female_count / total}

iface = gr.Interface(
  fn=gender_of_sentence, inputs=gr.inputs.Textbox(default="She went to his house to get her keys."),
  outputs="label", interpretation="default").launch()

Notice the interpretation keyword argument. We're going to use Gradio's default interpreter here. After you submit and click Interpret, you'll see the interface automatically highlights the parts of the text that contributed to the final output orange! The parts that conflict with the output are highlight blue.

Gradio's default interpretation works with a limited set of interface setups, such as text-to-label, or image-to-label. We're working on expanding the default interpreter to be much more customizable and support more interfaces.

You can also write your own interpretation function. The demo below adds custom interpretation to the previous demo. This function will take the same inputs as the main wrapped function. The output of this interpretation function will be used to highlight the input of each input interface - therefore the number of outputs here corresponds to the number of input interfaces. To see the format for interpretation for each input interface, check the Documentation

# ... continued from above
import re            
def interpret_gender(sentence):
  result = gender_of_sentence(sentence)
  is_male = result["male"] > result["female"]
  interpretation = []
  for word in re.split('( )', sentence):
    score = 0
    token = word.lower()
    if (is_male and token in male_words) or (not is_male and token in female_words):
      score = 1
    elif  (is_male and token in female_words) or (not is_male and token in male_words):
      score = -1
    interpretation.append((word, score))
  return interpretation
        
iface = gr.Interface(
  fn=gender_of_sentence, inputs=gr.inputs.Textbox(default="She went to his house to get her keys."),
  outputs="label", interpretation=interpret_gender).launch()

Next Steps

That's all you need to get started with Gradio! To see a list of all the components available, check out the Docs. To see some examples of machine learning models using Gradio, check out the ML Examples page.

Let us know what interfaces we should add next, or feel free to contribute to the open-source library.

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.

Links expire after 6 hours. Need longer links, or private links? Contact us for Gradio Teams.