๐ŸŽจ Gradio Cheat Sheet

๐ŸŽจ Gradio Cheat Sheet #

Build and share delightful machine learning apps in Python

๐Ÿ“ฆ Installation & Setup #

Basic Installation #

# Install Gradio (requires Python 3.10+)
pip install gradio

# With virtual environment (recommended)
python -m venv gradio_env
source gradio_env/bin/activate  # Linux/Mac
pip install gradio

# Update to latest version
pip install --upgrade gradio

Quick Verification #

import gradio as gr
print(gr.__version__)  # Check version

๐Ÿš€ Core Concepts #

๐ŸŽฏ Interface Class #

The main class for creating ML model UIs with inputs โ†’ function โ†’ outputs

import gradio as gr

def greet(name, intensity):
    return f"Hello, {name}!" * int(intensity)

demo = gr.Interface(
    fn=greet,                    # Function to wrap
    inputs=["text", "slider"],   # Input components
    outputs="text"               # Output components
)
demo.launch()

๐Ÿงฑ Blocks API #

Low-level API for custom layouts and advanced UIs

import gradio as gr

with gr.Blocks() as demo:
    gr.Markdown("# My Custom App")
    
    with gr.Row():
        input_text = gr.Textbox(label="Input")
        output_text = gr.Textbox(label="Output")
    
    btn = gr.Button("Process")
    btn.click(fn=process_function, inputs=input_text, outputs=output_text)

demo.launch()

๐ŸŽ›๏ธ Essential Components #

๐Ÿ“ Input Components #

# Text inputs
gr.Textbox(label="Enter text", placeholder="Type here...")
gr.TextArea(lines=5, label="Long text")
gr.Markdown("**Instructions**")

# Numbers & selections
gr.Number(label="Enter number", value=0)
gr.Slider(minimum=0, maximum=100, value=50, label="Slider")
gr.Dropdown(choices=["A", "B", "C"], label="Select option")
gr.Radio(choices=["Yes", "No"], label="Choose one")
gr.Checkbox(label="Enable feature")

# Media inputs
gr.Image(label="Upload image", type="pil")  # PIL, numpy, filepath
gr.Audio(label="Upload audio", type="numpy")
gr.Video(label="Upload video")
gr.File(label="Upload file", file_types=[".pdf", ".txt"])

# Advanced inputs
gr.Dataframe(headers=["Name", "Age"], datatype=["str", "number"])
gr.ColorPicker(label="Choose color")
gr.DateTime(label="Select date/time")

๐Ÿ“ค Output Components #

# Display outputs
gr.Textbox(label="Result", interactive=False)
gr.Image(label="Generated image")
gr.Audio(label="Generated audio")
gr.Video(label="Generated video")
gr.Plot(label="Chart")  # matplotlib, plotly
gr.HTML("<h1>Custom HTML</h1>")
gr.JSON({"key": "value"})
gr.Label({"cat": 0.8, "dog": 0.2})  # Classification results
gr.Gallery(label="Image gallery")

๐ŸŽฎ Interactive Components #

# Buttons & controls
gr.Button("Submit", variant="primary")
gr.ClearButton([input1, input2], value="Clear All")
gr.UploadButton("Upload Files", file_types=[".jpg", ".png"])

# Layout components
with gr.Row():          # Horizontal layout
    comp1 = gr.Textbox()
    comp2 = gr.Textbox()

with gr.Column():       # Vertical layout
    comp3 = gr.Textbox()
    comp4 = gr.Textbox()

with gr.Tab("Tab 1"):   # Tabbed interface
    gr.Textbox(label="Content 1")

with gr.Accordion("Advanced Options", open=False):
    gr.Slider(label="Advanced setting")

๐Ÿ’ฌ Chatbot Creation #

๐Ÿค– Simple Chatbot (Interface) #

import gradio as gr

def chat_function(message, history):
    # Process message and return response
    response = f"You said: {message}"
    history.append((message, response))
    return history, ""

demo = gr.Interface(
    fn=chat_function,
    inputs=["text", "state"],
    outputs=["chatbot", "text"],
    allow_flagging="never"
)
demo.launch()

๐ŸŽฏ Advanced Chatbot (Blocks) #

import gradio as gr
import random
import time

with gr.Blocks() as demo:
    chatbot = gr.Chatbot(type="messages")
    msg = gr.Textbox(label="Message")
    clear = gr.ClearButton([msg, chatbot])
    
    def respond(message, chat_history):
        bot_message = random.choice([
            "How are you?", 
            "Today is a great day", 
            "I'm very hungry"
        ])
        
        chat_history.append({"role": "user", "content": message})
        chat_history.append({"role": "assistant", "content": bot_message})
        time.sleep(1)
        return "", chat_history
    
    msg.submit(respond, [msg, chatbot], [msg, chatbot])

demo.launch()

๐ŸŒŠ Streaming Chatbot #

def respond_stream(message, chat_history):
    chat_history.append({"role": "user", "content": message})
    
    # Simulate streaming response
    response = ""
    for char in "This is a streaming response...":
        response += char
        chat_history[-1] = {"role": "assistant", "content": response}
        yield "", chat_history
        time.sleep(0.05)

msg.submit(respond_stream, [msg, chatbot], [msg, chatbot])

๐ŸŽจ Customization & Theming #

๐ŸŽญ Built-in Themes #

import gradio as gr

# Use built-in themes
demo = gr.Interface(
    fn=my_function,
    inputs="text",
    outputs="text",
    theme=gr.themes.Soft()  # Soft, Monochrome, Glass, etc.
)

# Custom theme
custom_theme = gr.themes.Default(
    primary_hue="blue",
    secondary_hue="pink",
    neutral_hue="gray",
    font="Arial"
)

demo = gr.Interface(
    fn=my_function,
    inputs="text",
    outputs="text",
    theme=custom_theme
)

๐ŸŽจ Custom CSS #

css = """
.gradio-container {
    background: linear-gradient(45deg, #ff6b6b, #4ecdc4);
}

#custom-textbox {
    border: 2px solid #ff6b6b;
    border-radius: 10px;
}
"""

with gr.Blocks(css=css) as demo:
    gr.Textbox(label="Custom Styled", elem_id="custom-textbox")

๐Ÿ“ฑ Component Customization #

# Detailed component customization
gr.Textbox(
    label="Custom Input",
    placeholder="Enter text here...",
    lines=3,
    max_lines=10,
    info="This is helper text",
    show_copy_button=True,
    container=True,
    scale=2,  # Relative width in Row
    elem_id="my-textbox",
    elem_classes=["custom-class"]
)

# Image with specific settings
gr.Image(
    label="Upload Image",
    type="pil",  # pil, numpy, filepath
    image_mode="RGB",
    sources=["upload", "webcam", "clipboard"],
    width=300,
    height=200
)

๐Ÿ”„ Event Handling & State #

๐ŸŽฏ Event Listeners #

with gr.Blocks() as demo:
    textbox = gr.Textbox()
    button = gr.Button("Submit")
    output = gr.Textbox()
    
    # Multiple event types
    button.click(fn=process, inputs=textbox, outputs=output)
    textbox.submit(fn=process, inputs=textbox, outputs=output)
    textbox.change(fn=live_update, inputs=textbox, outputs=output)
    textbox.focus(fn=on_focus, inputs=textbox)

๐Ÿ’พ State Management #

import gradio as gr

def update_state(current_state, new_input):
    current_state.append(new_input)
    return current_state, f"State: {current_state}"

with gr.Blocks() as demo:
    state = gr.State([])  # Initialize empty list
    input_box = gr.Textbox()
    output_box = gr.Textbox()
    
    input_box.submit(
        fn=update_state,
        inputs=[state, input_box],
        outputs=[state, output_box]
    )

๐Ÿ”„ Dynamic Updates #

def update_choices(category):
    if category == "Fruits":
        return gr.Dropdown(choices=["Apple", "Banana", "Orange"])
    else:
        return gr.Dropdown(choices=["Car", "Bike", "Train"])

with gr.Blocks() as demo:
    category = gr.Radio(["Fruits", "Vehicles"], label="Category")
    items = gr.Dropdown(label="Items")
    
    category.change(fn=update_choices, inputs=category, outputs=items)

๐Ÿš€ Deployment & Sharing #

๐ŸŒ Local Development #

# Basic launch
demo.launch()

# Development options
demo.launch(
    server_name="0.0.0.0",    # Allow external access
    server_port=7860,         # Custom port
    share=False,              # Don't create public link
    debug=True,               # Enable debug mode
    show_error=True,          # Show detailed errors
    inbrowser=True            # Auto-open browser
)

# Hot reload during development
# Command line: gradio app.py

๐Ÿ”— Public Sharing #

# Temporary public link (72 hours)
demo.launch(share=True)

# Returns: Running on public URL: https://abc123.gradio.live

๐Ÿ  Hugging Face Spaces #

# Deploy to Hugging Face Spaces
# Command line from project directory:
# gradio deploy

# Or create requirements.txt and push to HF Spaces repo

๐Ÿณ Docker Deployment #

# Dockerfile
FROM python:3.10

WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt

COPY . .
EXPOSE 7860

CMD ["python", "app.py"]

๐Ÿ”’ Authentication & Security #

๐Ÿ” Basic Authentication #

demo.launch(
    auth=("username", "password"),  # Single user
    # OR
    auth=[("user1", "pass1"), ("user2", "pass2")]  # Multiple users
)

๐Ÿ›ก๏ธ Custom Authentication #

def custom_auth(username, password):
    # Custom authentication logic
    return username == "admin" and password == "secret"

demo.launch(auth=custom_auth)

โšก Performance & Best Practices #

๐Ÿš€ Optimization Tips #

# 1. Use appropriate component types
gr.Image(type="numpy")  # Faster for ML models

# 2. Implement caching for expensive operations
import functools

@functools.lru_cache(maxsize=128)
def expensive_function(input_text):
    # Expensive computation
    return result

# 3. Use streaming for long responses
def stream_response():
    for chunk in generate_chunks():
        yield chunk

# 4. Batch processing for multiple inputs
def process_batch(inputs):
    return [process_single(inp) for inp in inputs]

๐Ÿ“Š Queue Management #

# Enable queuing for high traffic
demo.queue(
    concurrency_count=3,      # Max concurrent users
    max_size=20,              # Max queue size
    api_open=False            # Disable API access
)

demo.launch()

๐Ÿ” Error Handling #

def safe_function(input_text):
    try:
        result = risky_operation(input_text)
        return result
    except Exception as e:
        return f"Error: {str(e)}"

# Show errors in interface
demo = gr.Interface(
    fn=safe_function,
    inputs="text",
    outputs="text",
    show_error=True  # Display errors to users
)

๐ŸŽฏ Common Use Cases #

๐Ÿ–ผ๏ธ Image Processing #

import gradio as gr
from PIL import Image, ImageFilter

def blur_image(image, blur_radius):
    return image.filter(ImageFilter.GaussianBlur(radius=blur_radius))

demo = gr.Interface(
    fn=blur_image,
    inputs=[
        gr.Image(type="pil"),
        gr.Slider(0, 20, value=5, label="Blur Radius")
    ],
    outputs=gr.Image(type="pil"),
    title="Image Blur Tool"
)

๐ŸŽต Audio Processing #

import gradio as gr
import numpy as np

def process_audio(audio_file, effect):
    sr, audio = audio_file
    if effect == "reverse":
        return (sr, audio[::-1])
    elif effect == "amplify":
        return (sr, audio * 2)
    return (sr, audio)

demo = gr.Interface(
    fn=process_audio,
    inputs=[
        gr.Audio(type="numpy"),
        gr.Radio(["reverse", "amplify", "none"], label="Effect")
    ],
    outputs=gr.Audio(type="numpy")
)

๐Ÿ“Š Data Analysis #

import gradio as gr
import pandas as pd
import matplotlib.pyplot as plt

def analyze_data(csv_file):
    df = pd.read_csv(csv_file.name)
    
    # Create plot
    fig, ax = plt.subplots()
    df.plot(ax=ax)
    
    # Return summary and plot
    summary = df.describe().to_string()
    return summary, fig

demo = gr.Interface(
    fn=analyze_data,
    inputs=gr.File(file_types=[".csv"]),
    outputs=[gr.Textbox(label="Summary"), gr.Plot()]
)

๐Ÿ”ง Advanced Features #

๐ŸŽช Multi-step Workflows #

with gr.Blocks() as demo:
    gr.Markdown("# Multi-step Process")
    
    # Step 1
    with gr.Group():
        gr.Markdown("## Step 1: Upload Data")
        file_input = gr.File()
        process_btn1 = gr.Button("Process File")
    
    # Step 2
    with gr.Group():
        gr.Markdown("## Step 2: Configure Settings")
        settings = gr.Slider(0, 100, label="Setting")
        process_btn2 = gr.Button("Apply Settings")
    
    # Results
    results = gr.Textbox(label="Results")
    
    # Chain the steps
    process_btn1.click(step1_function, file_input, settings)
    process_btn2.click(step2_function, [file_input, settings], results)

๐ŸŽจ Custom Components #

# Create custom component (advanced)
class CustomSlider(gr.components.Component):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
    
    def preprocess(self, x):
        return x
    
    def postprocess(self, y):
        return y

๐Ÿ”Œ API Integration #

# Access Gradio app as API
import requests

# If demo.launch(share=True) creates public URL
response = requests.post(
    "https://abc123.gradio.live/api/predict",
    json={"data": ["input_text"]}
)
result = response.json()

๐Ÿ› Troubleshooting #

โŒ Common Issues #

# Issue: Components not updating
# Solution: Return correct number of outputs
def my_function(input1, input2):
    return output1, output2  # Match number of outputs

# Issue: State not persisting
# Solution: Use gr.State() properly
state = gr.State(initial_value)

# Issue: Large files causing memory issues
# Solution: Process in chunks or use streaming
def process_large_file(file):
    for chunk in read_in_chunks(file):
        yield process_chunk(chunk)

๐Ÿ” Debugging #

# Enable debug mode
demo.launch(debug=True, show_error=True)

# Add logging
import logging
logging.basicConfig(level=logging.DEBUG)

# Print component values
def debug_function(*args):
    print(f"Inputs received: {args}")
    return process_inputs(*args)

๐Ÿ“š Resources & Learning #

๐Ÿ“– Official Documentation #

๐ŸŽฎ Interactive Learning #

๐Ÿ› ๏ธ Development Tools #

# Hot reload during development
gradio app.py

# Deploy to Hugging Face Spaces
gradio deploy

# Create new Gradio app template
gradio create my-app

๐ŸŽฏ Quick Reference Commands #

# Essential imports
import gradio as gr

# Basic interface
gr.Interface(fn=func, inputs="text", outputs="text").launch()

# Blocks for custom layout
with gr.Blocks() as demo:
    # Components here
    pass
demo.launch()

# Common components
gr.Textbox(), gr.Button(), gr.Image(), gr.Audio()
gr.Slider(), gr.Dropdown(), gr.Radio(), gr.Checkbox()

# Launch options
demo.launch(share=True, debug=True, auth=("user", "pass"))

๐ŸŽ‰ Ready to build amazing ML interfaces with Gradio! Start with a simple Interface, then explore Blocks for advanced layouts and custom components for specialized needs.