Skip to main content

Mastering Gradio Inputs and Outputs: Make Your Models Interactive

 

Chapter-2
Introduction

In Chapter-1, you saw how easy it is to build a basic Gradio app. But the real power of Gradio comes from its rich variety of input and output components. Whether you're working with images, text, audio, video, or files — Gradio provides ready-made UI elements to make your models interactive with just a few lines of code.

In this article, we’ll explore:

  • All major inputs and outputs

  • Parameter tuning for customization

  • How to chain multiple components/functions together

Textbox

Use When:

You want the user to input plain text (sentences, prompts, numbers as strings, etc.)

Key Parameters:

  • label: Display name

  • lines: Height of textbox (default = 1)

  • placeholder: Hint inside the box

  • value: Default value

Example:
import gradio as gr

def reverse(text):
    return text[::-1]

gr.Interface(fn=reverse, inputs=gr.Textbox(label="Enter text"), outputs="text").launch()

Image

 Use When:

You're building an image classifier, object detector, drawing interface, etc.

Key Parameters:

  • type: "numpy" (for models), "pil" (PIL Image), or "file" (file path)

  • image_mode: "RGB", "L" (grayscale), etc.

  • shape: Resized output shape

  • tool: "editor" (free drawing), "select" (crop), or "sketch"

Example
def shape(image):
    return image.shape

gr.Interface(fn=shape, inputs=gr.Image(type="numpy"), outputs="text").launch()

Audio

Use When:

You're working with speech-to-text, audio classification, or waveform manipulation.

 Key Parameters:

  • type: "numpy" (tuple of sample rate and array) or "file" (file path)

  • label, source: Upload or microphone

  • interactive: Record live audio

Example
def audio_length(audio):
    sr, data = audio
    duration = len(data) / sr
    return f"{duration:.2f} seconds"

gr.Interface(fn=audio_length, inputs=gr.Audio(type="numpy"), outputs="text").launch()

Video

Use When:

You're building action recognition, frame prediction, or captioning tools.

Key Parameters:

  • type: "numpy" (for video array) or "file" (path)

  • format: Accepts .mp4, .webm, etc.

Example:
def video_echo(video):
    return video

gr.Interface(fn=video_echo, inputs=gr.Video(), outputs="video").launch()

File

Use When:

You want users to upload any document — CSVs, PDFs, images, etc.

Key Parameters:

  • file_types: Restrict file types like [".csv", ".pdf"]

  • type: "file" (returns path) or "binary"

Example:
import os
import gradio as gr

def file_details(file_path):
    size_kb = os.path.getsize(file_path) / 1024
    name = os.path.basename(file_path)
    return f"Name: {name}, Size: {size_kb:.1f} KB"

gr.Interface(fn=file_details, inputs=gr.File(), outputs="text").launch()

Slider

Use When:

You want a numeric input within a specific range.

Key Parameters:

  • minimum, maximum, step

  • value (default)

  • label

Example:
def double(x):
    return x * 2

gr.Interface(fn=double, inputs=gr.Slider(0, 100, step=5, label="Choose a number"), outputs="number").launch()

Checkbox

Use When:

You want a binary yes/no or true/false input.

Example:
def check_status(checked):
    return "Enabled" if checked else "Disabled"

gr.Interface(fn=check_status, inputs=gr.Checkbox(label="Enable feature"), outputs="text").launch()

Radio Buttons

Use When:

You want the user to select one from multiple options.

Key Parameters:

  • choices: List of options

Example:
def favorite_color(choice):
    return f"Nice choice: {choice}"

gr.Interface(fn=favorite_color, inputs=gr.Radio(["Red", "Green", "Blue"]), outputs="text").launch()

Dropdown

Use When:

You want a collapsible list of options (can also allow multiple selections).

Key Parameters:

  • choices, multiselect, value

Example:
import gradio as gr
def color_summary(color):
    return f"You selected: {color}"

gr.Interface(fn=color_summary, inputs=gr.Dropdown(choices=["Red", "Green", "Blue"]), outputs="text").launch()

Dataframe

Use When:

You want users to input/edit tabular data like CSVs.

Key Parameters:

  • headers, datatype, row_count, col_count

Example:
import gradio as gr
import pandas as pd

def mean_col(data):
    # Convert to DataFrame
    df = pd.DataFrame(data, columns=["A", "B", "C"])
    try:
        # Ensure numeric computation
        df = df.apply(pd.to_numeric, errors='coerce')  # Handles string values too
        means = df.mean()
        return means.to_frame(name="Mean").T  # return as DataFrame for display
    except Exception as e:
        return f"Error: {e}"

gr.Interface(
    fn=mean_col,
    inputs=gr.Dataframe(
        headers=["A", "B", "C"],
        row_count=3,
        col_count=3,
        datatype=["number", "number", "number"],
        label="Enter numbers"
    ),
    outputs=gr.Dataframe(label="Column Means")
).launch()

Machine Translation
Startupology



Comments

Popular Post

Apply for Google Summer Internship-2025

Google is offering a summer internship in 2025 for students interested in technology, software engineering , and innovation. This program provides hands-on experience, mentorship, and opportunities to work on impactful projects. Ideal for students aiming to enhance their skills and gain industry insights. To apply for the Google summer internship 2025, you'll need an updated CV or resume and a current unofficial or official transcript in English. Click 'Apply' on the internship page and upload the following documents (PDFs preferred): In the 'Resume Section,' attach your updated CV or resume. In the 'Education Section,' attach your current or recent unofficial or official transcript in English. Under 'Degree Status,' select 'Now attending' to upload your transcript. You can choose your preferred working location from Bengaluru, Hyderabad, or Pune in India when applying. Minimum qualifications: Currently studying for a Bachelor's or Maste...

IIRS-ISRO offers AI/ML for Geo Data Analysis: A Free Course

AI has captured our imagination and research focus since the Dartmouth Conferences in 1956, where the field was born. Defined as programs that can sense, reason, act, and adapt, AI has been heralded as the key to a brighter future. Machine Learning (ML) involves algorithms that improve with data over time, while Deep Learning, a subset of ML, utilizes multilayered neural networks to learn from vast data. Technological advancements have enabled the processing and analysis of unprecedented data volumes, driven by the proliferation of internet-connected devices. These advancements bring us closer to creating intelligent machines seen in everyday applications like online recommendations and auto-generated photo tags. The main applications of deep learning AI include computer vision, natural language processing (NLP), and reinforcement learning. This course, scheduled from August 19-24, 2024 , covers AI, ML, Deep Learning, and data processing techniques, with case studies in geospatial dat...

Apply for Microsoft Software Engineering Internship

Join Microsoft as an intern to build community, explore your passions, and work on real-world projects. Software engineers collaborate to solve problems and create innovative solutions. Interns have fun while working globally, contributing to Microsoft's mission to empower everyone. Embrace a growth mindset, innovate , and build a culture of inclusion where all can thrive. Qualifications: Currently pursuing a bachelor's or master's degree in engineering, computer science, or a related field. Must have at least one more quarter/semester of college remaining after the internship. One year of experience programming in an object-oriented language . Responsibilities: Apply engineering principles to creatively solve complex problems. Quickly learn and integrate new engineering methods into workflows. Seek and apply feedback and best practices to improve technical solutions. Manage time effectively to complete software projects in a collaborative team environment. Click the bel...