Introduction to Gradio
Build Drag-and-Drop Style Interfaces for AI Apps
Learn how to create beautiful, interactive web interfaces for your machine learning models with just a few lines of Python — no frontend skills required.
Muhammad Rustam
~90 min read
Beginner to Advanced
1. What is Gradio?
Gradio is an open-source Python library that makes it incredibly easy to build web-based user interfaces (UIs) for your machine learning models, APIs, and data science workflows. With just a few lines of Python code, you can create interactive demos and share them with anyone.
Why Gradio Matters for AI Developers
As AI practitioners, we spend most of our time building models, but sharing and demonstrating those models is equally important. Gradio bridges the gap between your Python code and a beautiful, functional web interface.
- No Frontend Knowledge Required: You do not need to know HTML, CSS, or JavaScript. Gradio generates everything automatically.
- Instant Sharing: Share your app via a public link with one line of code. No deployment hassle.
- Works with Any Python Function: Wrap any Python function with a Gradio interface and it becomes an interactive web app.
- Built for ML/AI: Pre-built components for images, audio, video, text, chatbots, and more.
- Hugging Face Integration: Deploy your Gradio apps to Hugging Face Spaces for free hosting.
💡 Key Fact
Gradio was acquired by Hugging Face in 2021 and is now the most popular way to demo machine learning models. It has over 35,000+ stars on GitHub.
Gradio vs Other UI Tools
| Feature | Gradio | Streamlit | Flask / Django |
|---|---|---|---|
| ML-Focused | Yes (Built for ML) | Partially | No (General web) |
| Learning Curve | Very Low | Low | High |
| Sharing | 1-click public URL | Deploy needed | Deploy needed |
| Chatbot Support | Built-in ChatInterface | Manual setup | Manual setup |
| Lines of Code | 3–10 lines | 10–30 lines | 50–200+ lines |
| API Auto-generation | Yes, automatic | No | Manual |
2. Installation and Environment Setup
Step 1: Install Gradio
Open your terminal or command prompt and run:
bash
pip install gradioStep 2: Verify Installation
python
import gradio as gr
print(gr.__version__)Step 3: Recommended Environment
- Python: Version 3.9 or above
- IDE: VS Code, Jupyter Notebook, or Google Colab
- Virtual Environment: Use
venvorcondato keep your projects organized
💡 Pro Tip for Students
If you are using Google Colab, Gradio works right out of the box! Just do pip install gradio and you are ready. Colab will automatically create a public link for your app.
3. Core Concepts of Gradio
The Three Pillars of Gradio
Every Gradio app is built on three fundamental concepts:
| Concept | Description | Example |
|---|---|---|
| Input | What the user provides to your function | Textbox, Image, Audio, Slider, File Upload |
| Function | Your Python function that processes the input | def greet(name): return f"Hello {name}" |
| Output | What gets displayed back to the user | Text, Image, Audio, Video, DataFrame, Plot |
Your First Gradio App
Let us build the classic “Hello World” of Gradio. This simple app takes a name as input and returns a greeting:
python
import gradio as gr
def greet(name):
return f"Hello, {name}! Welcome to AiByTech Academy!"
# Create the interface
demo = gr.Interface(
fn=greet, # Your Python function
inputs=gr.Textbox(label="Enter Your Name"), # Input component
outputs=gr.Textbox(label="Greeting"), # Output component
title="My First Gradio App",
description="A simple greeting app built with Gradio"
)
demo.launch() # This starts the local web server🚀 What Happens When You Run This?
Gradio automatically starts a local web server (usually at http://127.0.0.1:7860), generates a beautiful UI with an input textbox and output textbox, and even provides a public URL if you set share=True in the launch() method.
4. Gradio Components — The Building Blocks
Gradio provides a rich set of pre-built components that serve as both inputs and outputs. Think of them as drag-and-drop building blocks for your AI apps.
Common Input Components
gr.Textbox()
Text input from user — prompts, queries, paragraphs
gr.Number()
Numeric input — age, quantity, threshold
gr.Slider()
Range selection — temperature, confidence score
gr.Checkbox()
True/False toggle — enable features
gr.Dropdown()
Select from options — model type, language
gr.Image()
Upload or capture images from camera
gr.Audio()
Upload or record audio files
gr.File()
Upload any file type — PDFs, CSVs, etc.
Common Output Components
| Component | Use Case |
|---|---|
gr.Textbox() | Display text output, summaries, translations |
gr.Image() | Show generated or processed images |
gr.Audio() | Play generated audio (TTS, music generation) |
gr.Label() | Show classification results with confidence scores |
gr.JSON() | Display structured JSON data |
gr.DataFrame() | Show tabular data |
gr.Plot() | Display matplotlib / plotly charts |
gr.HighlightedText() | Show text with highlighted entities (NER) |
5. Deep Dive: gr.Interface()
The gr.Interface() class is the simplest and fastest way to create a Gradio app. It automatically generates the UI based on your function signature.
Multiple Inputs and Outputs
You can pass multiple input and output components as lists:
python
import gradio as gr
def analyze_text(text, max_words):
word_count = len(text.split())
is_within_limit = word_count <= max_words
summary = f"Word count: {word_count}/{int(max_words)}"
return summary, is_within_limit
demo = gr.Interface(
fn=analyze_text,
inputs=[
gr.Textbox(label="Enter your text", lines=5),
gr.Slider(10, 500, value=100, label="Max Word Limit")
],
outputs=[
gr.Textbox(label="Analysis Result"),
gr.Checkbox(label="Within Limit?")
],
title="Text Analyzer",
description="Analyze word count and check limits"
)
demo.launch()Adding Examples
Examples help users understand what your app does. They appear as clickable buttons below the input:
python
demo = gr.Interface(
fn=greet,
inputs=gr.Textbox(label="Name"),
outputs=gr.Textbox(label="Greeting"),
examples=[
["Rustam"],
["Ahmed"],
["Fatima"],
]
)📝 Teaching Tip
Always add examples to your Gradio demos. They serve as documentation and help users quickly understand the expected input format. This is especially important when deploying apps for non-technical users.
6. Advanced Layouts with gr.Blocks()
While gr.Interface() is great for simple apps, gr.Blocks() gives you full control over layout, interactivity, and multi-step workflows. Think of Blocks as the “drag-and-drop” mode of Gradio.
Why Use Blocks?
- Custom Layouts: Arrange components in rows and columns
- Multiple Functions: Connect different buttons to different functions
- Event Chaining: Output of one function becomes input to another
- Tabs and Accordions: Organize complex UIs into sections
- State Management: Maintain state across user interactions
Blocks Layout Example
python
import gradio as gr
def translate(text, language):
# Placeholder — connect your AI model here
return f"[Translated to {language}]: {text}"
def count_chars(text):
return len(text)
with gr.Blocks(title="AI Translation Tool") as demo:
gr.Markdown("# AI Translation Tool")
gr.Markdown("Translate text to any language using AI")
with gr.Row(): # Side-by-side layout
with gr.Column():
input_text = gr.Textbox(label="Input Text", lines=5)
language = gr.Dropdown(
["Urdu", "Arabic", "French", "Spanish", "Chinese"],
label="Target Language",
value="Urdu"
)
translate_btn = gr.Button("Translate", variant="primary")
with gr.Column():
output_text = gr.Textbox(label="Translation", lines=5)
char_count = gr.Number(label="Character Count")
# Connect button to functions
translate_btn.click(
fn=translate,
inputs=[input_text, language],
outputs=output_text
)
translate_btn.click(
fn=count_chars,
inputs=input_text,
outputs=char_count
)
demo.launch()Using Tabs for Multi-Feature Apps
python
import gradio as gr
with gr.Blocks() as demo:
gr.Markdown("# AiByTech Multi-Tool")
with gr.Tab("Text Generator"):
prompt = gr.Textbox(label="Enter Prompt")
gen_btn = gr.Button("Generate")
gen_output = gr.Textbox(label="Generated Text")
with gr.Tab("Image Analyzer"):
image_input = gr.Image(label="Upload Image")
analyze_btn = gr.Button("Analyze")
analysis = gr.Textbox(label="Analysis Result")
with gr.Tab("Chatbot"):
chatbot = gr.Chatbot()
msg = gr.Textbox(label="Type a message")
send_btn = gr.Button("Send")
demo.launch()
7. Building AI Chatbots with gr.ChatInterface()
One of the most powerful features of Gradio is its built-in ChatInterface. You can create a fully functional chatbot UI with just a few lines of code.
Simple Chatbot
python
import gradio as gr
def echo_bot(message, history):
return f"You said: {message}"
demo = gr.ChatInterface(
fn=echo_bot,
title="AiByTech Chatbot",
description="A simple echo chatbot demo",
examples=["Hello!", "What is AI?", "Tell me about Gradio"],
theme="soft"
)
demo.launch()Connecting to OpenAI / Any LLM
Here is how you connect Gradio ChatInterface to a real AI model like OpenAI GPT:
python
import gradio as gr
from openai import OpenAI
client = OpenAI(api_key="your-api-key-here")
def chat_with_ai(message, history):
messages = [{"role": "system", "content": "You are a helpful assistant."}]
for user_msg, bot_msg in history:
messages.append({"role": "user", "content": user_msg})
messages.append({"role": "assistant", "content": bot_msg})
messages.append({"role": "user", "content": message})
response = client.chat.completions.create(
model="gpt-4",
messages=messages
)
return response.choices[0].message.content
demo = gr.ChatInterface(
fn=chat_with_ai,
title="AI Powered Chatbot",
description="Powered by OpenAI GPT-4"
)
demo.launch()🔒 Security Note
Never hardcode your API keys in your code! Use environment variables or .env files. Example: import os; api_key = os.getenv("OPENAI_API_KEY")
8. Real-World Project Examples
Let us look at practical AI applications you can build with Gradio:
8.1 — Image Classification App
python
import gradio as gr
from transformers import pipeline
# Load a pre-trained model from Hugging Face
classifier = pipeline("image-classification", model="google/vit-base-patch16-224")
def classify_image(image):
results = classifier(image)
return {r["label"]: r["score"] for r in results}
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 AI"
)
demo.launch()8.2 — Text Summarization App
python
import gradio as gr
from transformers import pipeline
summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
def summarize(text):
summary = summarizer(text, max_length=150, min_length=30)
return summary[0]["summary_text"]
demo = gr.Interface(
fn=summarize,
inputs=gr.Textbox(label="Paste Article", lines=10),
outputs=gr.Textbox(label="Summary"),
title="AI Text Summarizer",
description="Paste any article and get an AI-generated summary"
)
demo.launch()8.3 — Sentiment Analysis Dashboard
python
import gradio as gr
from transformers import pipeline
sentiment = pipeline("sentiment-analysis")
def analyze_sentiment(text):
result = sentiment(text)[0]
label = result["label"]
score = round(result["score"] * 100, 2)
emoji = "😄" if label == "POSITIVE" else "😞"
return f"{emoji} {label} ({score}% confidence)"
demo = gr.Interface(
fn=analyze_sentiment,
inputs=gr.Textbox(label="Enter text to analyze", lines=3),
outputs=gr.Textbox(label="Sentiment"),
title="Sentiment Analyzer",
examples=[
["I love learning AI at AiByTech Academy!"],
["This product is terrible and a waste of money."],
["The weather is okay today."]
]
)
demo.launch()
9. Theming and Customization
Gradio offers built-in themes and custom styling options to make your apps look professional.
Built-in Themes
gr.themes.Default()— Clean, standard appearancegr.themes.Soft()— Rounded corners, gentle colorsgr.themes.Glass()— Modern, translucent designgr.themes.Monochrome()— Minimalist black and white
Custom Theme Example
python
import gradio as gr
custom_theme = gr.themes.Soft(
primary_hue="blue",
secondary_hue="orange",
font=[gr.themes.GoogleFont("Poppins"), "Arial", "sans-serif"]
)
demo = gr.Interface(
fn=greet,
inputs="text",
outputs="text",
theme=custom_theme
)
demo.launch()Custom CSS
python
with gr.Blocks(css=".gradio-container {max-width: 800px; margin: auto;}") as demo:
gr.Markdown("# Styled App")
# Your components here
10. Deploying Your Gradio App
Quick Share (Temporary Link)
The simplest way to share your app:
python
demo.launch(share=True) # Creates a public URL valid for 72 hoursDeploy to Hugging Face Spaces (Free)
Hugging Face Spaces provides free hosting for Gradio apps. Here is how:
- Create a free account on huggingface.co
- Go to Spaces and click “Create New Space”
- Select “Gradio” as the SDK
- Upload your
app.pyandrequirements.txtfiles - Your app will be live at:
https://huggingface.co/spaces/your-username/your-app
requirements.txt for Deployment
text
gradio>=4.0
openai
transformers
torchOther Deployment Options
- Docker: Containerize your Gradio app for any cloud platform
- Railway / Render: Easy deployment platforms with free tiers
- AWS / GCP / Azure: Enterprise-grade deployment for production apps
🚀 Deployment Best Practice
Always use environment variables for API keys when deploying. On Hugging Face Spaces, go to Settings → Secrets and add your keys there. Never push API keys to public repositories!
11. Flagging and User Feedback
Gradio has a built-in flagging feature that allows users to flag specific inputs and outputs. This is extremely useful for collecting training data and identifying edge cases.
python
demo = gr.Interface(
fn=classify_image,
inputs=gr.Image(type="pil"),
outputs=gr.Label(),
flagging_mode="manual",
flagging_dir="flagged_data" # Saves flagged examples here
)📊 Why Flagging Matters
Flagged data can be used to fine-tune your models, identify failure cases, and continuously improve your AI application. It is a simple but powerful feedback loop.
12. Best Practices for Gradio Apps
1
Add Labels to Components
Improves accessibility and user experience
2
Include Examples
Helps users understand expected input format
3
Use gr.Blocks for Complex UIs
Full control over layout structure
4
Handle Errors Gracefully
Use try/except to prevent app crashes
5
Environment Variables for Keys
Security best practice for deployments
6
Add Descriptions & Titles
Makes your app self-documenting
7
Test with Different Inputs
Catches edge cases early
8
Use Themes
Creates polished, branded experiences
9
Enable Flagging
Builds a data collection pipeline
10
Deploy to HF Spaces
Free hosting with easy sharing
13. Homework Assignment
Complete any TWO of the following tasks before the next class:
Task 1: Greeting App
Beginner
Build a Greeting App using gr.Interface() with at least 2 inputs and add examples.
Task 2: Text Analyzer
Intermediate
Create a Text Analyzer that counts words, characters, and sentences using gr.Blocks() with Row/Column layout.
Task 3: AI Chatbot
Intermediate
Build a Chatbot using gr.ChatInterface() that connects to any LLM (OpenAI, Gemini, or local model).
Task 4: Deploy to Hugging Face
Advanced
Deploy any Gradio app to Hugging Face Spaces and share the public link.
Task 5: Multi-Tab App
Advanced
Build a multi-tab app with gr.Blocks() that includes at least 3 different AI features.
14. Resources and Further Learning
- Official Gradio Docs: gradio.app/docs
- Gradio GitHub: github.com/gradio-app/gradio
- Hugging Face Spaces: huggingface.co/spaces
- Gradio Guides: gradio.app/guides
- AiByTech Academy: aibytec.com
Key Takeaways from Today’s Lecture
- Gradio is the easiest way to build web UIs for AI models using Python
gr.Interface()is perfect for simple, quick demos with automatic UI generationgr.Blocks()gives you full layout control with rows, columns, and tabsgr.ChatInterface()makes building chatbots incredibly simple- Gradio auto-generates APIs for your functions
- Deploy for free on Hugging Face Spaces
- Gradio integrates seamlessly with any Python ML framework
Ready to Build Your First AI App?
Join AiByTech Academy’s Generative AI Course and learn to build production-ready AI applications from scratch.
Next Lecture: Building Production-Ready AI Apps with Gradio + FastAPI
AiByTech Academy | aibytec.com | Generative AI Batch 3

