UI Frameworks
🎛️

Gradio

Build and share interactive ML model demos with simple Python code

Beginner open-source self-hosted python machine-learning demos

Alternative To

  • • Streamlit
  • • Dash
  • • Flask

Difficulty Level

Beginner

Suitable for users with basic technical knowledge. Easy to set up and use.

Overview

Gradio is an open-source Python library that enables developers to quickly create customizable web interfaces for machine learning models and data science workflows. With just a few lines of Python code, you can transform complex ML models into interactive demos that anyone can use through a web browser, without requiring any web development experience.

Gradio is specifically designed for machine learning practitioners who want to demo their models, get feedback from users, and share their work with collaborators. The library offers a wide range of input and output components (text, images, audio, video, etc.) that can be easily combined to create interfaces for any type of ML model, from simple classifiers to complex generative systems.

System Requirements

  • Python: 3.10 or higher
  • CPU: 2+ cores (more for resource-intensive models)
  • RAM: 4GB+ (8GB+ recommended for handling larger models)
  • GPU: Optional, depending on the ML models being served
  • Storage: 1GB+ for base installation
  • Operating System: Windows, macOS, or Linux

Installation Guide

Prerequisites

  • Python 3.10 or higher
  • Pip package manager

Basic Installation

Install Gradio using pip:

pip install gradio

For a more isolated environment, use a virtual environment:

# Create a virtual environment
python -m venv gradio-env

# Activate on Windows
gradio-env\Scripts\activate

# Activate on macOS/Linux
source gradio-env/bin/activate

# Install Gradio
pip install gradio

Installing with Extra Features

For additional functionality, install with extras:

# For plotting capabilities
pip install "gradio[plots]"

# For audio processing
pip install "gradio[audio]"

# For all optional dependencies
pip install "gradio[all]"

Client-Only Installation

If you only need the client for accessing Gradio apps programmatically:

pip install gradio-client

Practical Exercise: Building an Image Classifier Demo

Let’s create a simple image classification demo using a pre-trained model:

import gradio as gr
import torch
from torchvision import transforms
from torchvision.models import resnet50, ResNet50_Weights

# Load pre-trained model
model = resnet50(weights=ResNet50_Weights.DEFAULT)
model.eval()

# Image preprocessing
preprocess = transforms.Compose([
    transforms.Resize(256),
    transforms.CenterCrop(224),
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406],
                        std=[0.229, 0.224, 0.225]),
])

# Class labels
with open("imagenet_classes.txt") as f:
    categories = [s.strip() for s in f.readlines()]

# Classification function
def classify_image(image):
    if image is None:
        return None

    # Preprocess the image
    image_tensor = preprocess(image).unsqueeze(0)

    # Get predictions
    with torch.no_grad():
        output = model(image_tensor)
        probabilities = torch.nn.functional.softmax(output[0], dim=0)

    # Return top 5 predictions
    top5_prob, top5_catid = torch.topk(probabilities, 5)
    result = []
    for i in range(5):
        result.append((categories[top5_catid[i]], float(top5_prob[i])))

    return result

# Create Gradio interface
demo = gr.Interface(
    fn=classify_image,
    inputs=gr.Image(type="pil"),
    outputs=gr.Label(num_top_classes=5),
    title="Image Classifier",
    description="Upload an image to classify it using ResNet50 trained on ImageNet.",
    examples=[
        ["examples/dog.jpg"],
        ["examples/cat.jpg"]
    ]
)

# Launch the app
if __name__ == "__main__":
    demo.launch()

Advanced Example: Creating a Chatbot Interface

Here’s how to create a chatbot interface using Gradio’s specialized components:

import gradio as gr
import random
import time

# Mock chat response function
def chat_response(message, history):
    # Simulate typing
    for i in range(random.randint(3, 10)):
        time.sleep(0.3)
        yield "Thinking" + "." * (i % 4)

    # Based on the input, generate a response
    if "hello" in message.lower() or "hi" in message.lower():
        response = "Hello there! How can I help you today?"
    elif "how are you" in message.lower():
        response = "I'm just a computer program, but thanks for asking! What can I do for you?"
    elif "bye" in message.lower():
        response = "Goodbye! Have a great day!"
    elif "help" in message.lower():
        response = "I can assist with answering questions, providing information, or just chatting. What would you like to know?"
    elif "weather" in message.lower():
        response = "I'm sorry, I don't have access to real-time weather data. You might want to check a weather website or app for that information."
    else:
        responses = [
            "That's interesting. Tell me more.",
            "I understand. How can I help with that?",
            "Could you elaborate on that?",
            "I see. Is there anything specific you'd like to know?",
            "Thanks for sharing. What else would you like to discuss?"
        ]
        response = random.choice(responses)

    # Simulate typing the response
    for i in range(len(response)):
        time.sleep(0.05)
        yield response[:i+1]

# Create the Gradio chatbot interface
demo = gr.ChatInterface(
    fn=chat_response,
    title="Simple Chatbot Demo",
    description="A demo of Gradio's ChatInterface component with a simple rule-based bot.",
    examples=["Hello", "How are you?", "Tell me about yourself", "What's the weather like?"],
    theme="soft"
)

# Launch the app
if __name__ == "__main__":
    demo.launch()

Key Features

Gradio offers numerous features that make it ideal for machine learning demonstrations:

  • Simple API: Create interfaces with just a few lines of code
  • Multiple UI Components: Support for text, images, audio, video, dataframes, and more
  • Flexible Layouts: Build complex interfaces with the Blocks API
  • Instant Sharing: Generate temporary public URLs to share your demos
  • Flagging Mechanism: Collect user feedback and problematic inputs
  • API Generation: Automatically create APIs for programmatic access
  • HuggingFace Integration: Seamlessly deploy to Hugging Face Spaces
  • Themes and Customization: Style your interfaces with built-in themes
  • Queueing System: Handle multiple concurrent users efficiently
  • Client Libraries: Access Gradio apps programmatically in Python or JavaScript
  • Streaming Support: Stream outputs for real-time feedback
  • Gradio Lite: Run Python code entirely in the browser with Pyodide

Resources

Official Resources

Community Resources

Suggested Projects

You might also be interested in these similar projects:

🐍

Rio

Build web apps and GUIs in pure Python with no HTML, CSS, or JavaScript required

Difficulty: Beginner
Updated: Mar 3, 2025

Create interactive data apps with pure Python in minutes

Difficulty: Beginner
Updated: Mar 3, 2025

Self-host Supervision, a Python library with reusable computer vision tools for easy annotation, detection, tracking, and dataset management

Difficulty: Beginner
Updated: Mar 1, 2025