
From Code to App: Learn Gradio in 10 Minutes
October-03-2024
In the world of machine learning (ML) and artificial intelligence (AI), the ability to easily showcase models and applications is crucial for researchers, developers, and educators. While the intricacies of machine learning can make it difficult for non-experts to interact with or understand models, Gradio comes to the rescue by providing an intuitive and simple interface to share and test ML models. Whether you're building a machine learning model for image classification, natural language processing, or any other task, Gradio helps make the model accessible to anyone with a web browser without any installation or coding knowledge.
This article explores what Gradio is, how it works, its key features, and why it's such a valuable tool in the AI community.
What is Gradio?
Gradio is incredibly simple to use and allows you to build a functional web interface with just a few lines of Python code. Here's a step-by-step explanation of how Gradio works, along with an example to showcase how you can use it to build a machine learning demo.
Basic Steps to Use Gradio
1. Install Gradio: First, you need to install Gradio using pip:
pip install gradio
2. Define Your Function: The core of your Gradio interface will be the function that takes input, processes it, and returns output. This function could be anything from a simple function that adds two numbers to a sophisticated machine learning model that makes predictions.
3. Create a Gradio Interface: Gradio provides an easy way to define the input and output types of your function. The gr.Interface
function wraps your function with the appropriate input and output components.
4. Launch the Interface: Once the interface is defined, you can launch it locally or share it with others using a public link.
Example 1: A Simple Addition Function
Let’s start with a simple example: a function that adds two numbers. We will use Gradio to create a user interface that accepts two numbers as input and returns their sum.
Code:
import gradio as gr
# Define a function that adds two numbers
def add_numbers(a, b):
return a + b
# Create a Gradio interface with two number inputs and a number output
interface = gr.Interface(fn=add_numbers, inputs=["number", "number"], outputs="number")
# Launch the interface
interface.launch()

How It Works:
- The function
add_numbers
takes two inputs,a
andb
, and returns their sum. gr.Interface()
creates the web interface, specifying that we want two number inputs and one number output.interface.launch()
runs the interface locally and provides a link to the web app.
When you run the code, Gradio will automatically create a simple web interface where users can input two numbers and see the result of the addition.
Example 2: A Simple Image Classification Model
Now let’s build a more advanced example, using a pre-trained image classification model. For this example, we’ll use the MobileNetV2 model from Keras to classify images.
Code:
import gradio as gr
from tensorflow.keras.applications.mobilenet_v2 import MobileNetV2, decode_predictions, preprocess_input
from tensorflow.keras.preprocessing import image
import numpy as np
# Load the pre-trained model
model = MobileNetV2(weights='imagenet')
# Define a function to classify an image
def classify_image(img):
img = image.img_to_array(img)
img = np.expand_dims(img, axis=0)
img = preprocess_input(img)
preds = model.predict(img)
return decode_predictions(preds, top=3)[0] # Return top 3 predictions
# Create a Gradio interface with an image input and text output
interface = gr.Interface(fn=classify_image, inputs="image", outputs="label")
# Launch the interface
interface.launch()

How It Works:
- We load the pre-trained MobileNetV2 model using Keras, which is capable of classifying images into 1000 categories from the ImageNet dataset.
- The function
classify_image
takes an image, processes it, and returns the top 3 predicted labels. - Gradio’s
gr.Interface()
is used to create an interface with an image input and a label output. - Once again,
interface.launch()
opens the web interface.
When you run this code, you’ll get a web interface where you can upload an image, and the model will classify it, returning the top 3 predictions with their confidence scores.
Example 3: Sentiment Analysis with Text Input
Let’s try a third example: sentiment analysis using a text input. For this, we’ll use a simple pre-trained model from Hugging Face's transformers
library.
Code:
import gradio as gr
from transformers import pipeline
# Load a sentiment-analysis pipeline
classifier = pipeline("sentiment-analysis")
# Define a function to classify the sentiment of text
def classify_sentiment(text):
return classifier(text)[0]
# Create a Gradio interface with text input and label output
interface = gr.Interface(fn=classify_sentiment, inputs="text", outputs="label")
# Launch the interface
interface.launch()

How It Works:
- We use the
transformers
library to load a pre-trained sentiment analysis model. - The
classify_sentiment
function takes text input and returns the model's sentiment prediction (positive or negative). - Gradio’s
gr.Interface()
creates an interface with text input and label output. interface.launch()
runs the web app where users can input a text and get its sentiment analyzed.
Key Features of Gradio
- Flexible Input/Output Options: Gradio supports a wide variety of input and output types such as text, images, audio, video, sliders, and more. This makes it suitable for a wide range of applications.
- Instant Sharing: Once you launch a Gradio interface, it provides a public link that you can share with others. This is especially useful for collaborating or demonstrating models without needing to deploy a full-fledged app.
- Ease of Use: One of Gradio’s greatest strengths is its simplicity. You don’t need web development or frontend experience to build a working interface.
- Integration with Machine Learning Libraries: Gradio works well with popular ML libraries like TensorFlow, PyTorch, Hugging Face, and others. This makes it easy to turn your models into user-friendly applications.
Conclusion
Gradio is an excellent tool for machine learning developers who want to quickly create and share web-based interfaces for their models. Whether you're creating an app for image classification, sentiment analysis, or any other task, Gradio simplifies the process. With just a few lines of code, you can build interactive and shareable web apps that allow anyone to experience your machine learning models.
Gradio is versatile, intuitive, and makes it easy to bridge the gap between machine learning code and real-world users. If you’re working in AI or data science, Gradio is a must-have in your toolkit!