gradio
Python library for building ML demo UIs with minimal code. Create interactive web interfaces for models with text, image, audio, and video inputs/outputs. Share demos via public links or deploy to Hugging Face Spaces.
What this skill does
# Gradio
## Installation
```bash
# Install Gradio
pip install gradio
```
## Quick Start — Simple Interface
```python
# hello.py — Minimal Gradio app with a text interface
import gradio as gr
def greet(name: str, intensity: int) -> str:
return "Hello, " + name + "!" * intensity
demo = gr.Interface(
fn=greet,
inputs=["text", gr.Slider(1, 10, value=1, label="Excitement")],
outputs="text",
title="Greeting Generator",
description="Enter your name and excitement level.",
)
demo.launch() # Opens http://localhost:7860
```
## Chat Interface
```python
# chatbot.py — Build a chatbot UI with streaming responses
import gradio as gr
from openai import OpenAI
client = OpenAI()
def chat(message: str, history: list) -> str:
messages = [{"role": "system", "content": "You are a helpful assistant."}]
for h in history:
messages.append({"role": "user", "content": h[0]})
if h[1]:
messages.append({"role": "assistant", "content": h[1]})
messages.append({"role": "user", "content": message})
response = client.chat.completions.create(
model="gpt-4",
messages=messages,
stream=True,
)
partial = ""
for chunk in response:
if chunk.choices[0].delta.content:
partial += chunk.choices[0].delta.content
yield partial
demo = gr.ChatInterface(
fn=chat,
title="AI Chat",
description="Chat with GPT-4",
examples=["Tell me a joke", "Explain quantum computing"],
)
demo.launch()
```
## Image Classification
```python
# image_classifier.py — Image classification demo with a pre-trained model
import gradio as gr
from transformers import pipeline
classifier = pipeline("image-classification", model="google/vit-base-patch16-224")
def classify(image):
results = classifier(image)
return {r["label"]: r["score"] for r in results}
demo = gr.Interface(
fn=classify,
inputs=gr.Image(type="pil"),
outputs=gr.Label(num_top_classes=5),
title="Image Classifier",
examples=["cat.jpg", "dog.jpg"],
)
demo.launch()
```
## Blocks API (Custom Layouts)
```python
# blocks_app.py — Build complex layouts with the Blocks API
import gradio as gr
def process_text(text: str, operation: str) -> str:
if operation == "Uppercase":
return text.upper()
elif operation == "Lowercase":
return text.lower()
elif operation == "Word Count":
return f"Word count: {len(text.split())}"
return text
with gr.Blocks(title="Text Processor", theme=gr.themes.Soft()) as demo:
gr.Markdown("# Text Processing Tool")
with gr.Row():
with gr.Column(scale=2):
text_input = gr.Textbox(label="Input Text", lines=5, placeholder="Enter text here...")
operation = gr.Radio(
choices=["Uppercase", "Lowercase", "Word Count"],
label="Operation",
value="Uppercase",
)
submit_btn = gr.Button("Process", variant="primary")
with gr.Column(scale=1):
output = gr.Textbox(label="Result", lines=5)
submit_btn.click(fn=process_text, inputs=[text_input, operation], outputs=output)
demo.launch()
```
## File Upload and Download
```python
# file_processing.py — Handle file uploads and provide downloadable outputs
import gradio as gr
import pandas as pd
def analyze_csv(file) -> tuple[str, str]:
df = pd.read_csv(file.name)
summary = f"Rows: {len(df)}, Columns: {len(df.columns)}\n\n"
summary += f"Columns: {', '.join(df.columns)}\n\n"
summary += df.describe().to_string()
output_path = "/tmp/summary.csv"
df.describe().to_csv(output_path)
return summary, output_path
demo = gr.Interface(
fn=analyze_csv,
inputs=gr.File(label="Upload CSV"),
outputs=[gr.Textbox(label="Summary"), gr.File(label="Download Summary")],
)
demo.launch()
```
## Authentication and Sharing
```python
# auth_and_share.py — Add authentication and create a public share link
import gradio as gr
def secret_fn(text):
return f"Secret processed: {text}"
demo = gr.Interface(fn=secret_fn, inputs="text", outputs="text")
# Launch with auth and public link
demo.launch(
auth=("admin", "password123"), # Simple auth
share=True, # Creates a public URL (72h)
server_port=7860,
)
```
## Deploy to Hugging Face Spaces
```bash
# Create a Space on Hugging Face
pip install huggingface_hub
huggingface-cli repo create my-demo --type space --space-sdk gradio
# Clone and push
git clone https://huggingface.co/spaces/username/my-demo
cd my-demo
# Add app.py and requirements.txt, then push
git add . && git commit -m "Initial demo" && git push
```
```txt
# requirements.txt — Dependencies for Hugging Face Spaces deployment
gradio==4.44.0
transformers
torch
```
## API Access
```python
# api_client.py — Use any Gradio app as an API
from gradio_client import Client
client = Client("username/my-demo") # Or local URL
result = client.predict(
"Hello world", # Input text
api_name="/predict",
)
print(result)
```
## Key Concepts
- **`gr.Interface`**: Simple function-to-UI mapping — one function, inputs, outputs
- **`gr.Blocks`**: Flexible layout system for complex multi-step applications
- **`gr.ChatInterface`**: Purpose-built chatbot UI with history management
- **Sharing**: `share=True` creates a temporary public URL; Spaces for permanent hosting
- **Components**: 30+ built-in components — Image, Audio, Video, File, DataFrame, Plot, etc.
- **API**: Every Gradio app automatically gets a REST API at `/api/`
- **Queuing**: Built-in request queuing for handling concurrent users
Related in Image & Video
watch
IncludedWatch a video (URL or local path). Downloads with yt-dlp, extracts auto-scaled frames with ffmpeg, pulls the transcript from captions (or Whisper API fallback), and hands the result to Claude so it can answer questions about what's in the video.
physical-ai-defect-image-generation
IncludedUse when the user wants to orchestrate defect image generation, run associated setup, or handle outputs on OSMO. The Day 0 path handles cold-start with USD-to-ROI, image-edit augmentation, and AnomalyGen to create initial PCBA datasets. The Day 1 path performs inference and labeling on real images. This skill helps with first-time asset setup, creation of finetuning checkpoints, and configuring deployment. Trigger keywords: defect image generation, dig workflow, dig pipeline, defect image detection workflow, aoi pipeline, aoi anomalygen, usd2roi anomalygen, day 0 pcba, day 1 pcba, day 1 real-photo alignment, day 1 manual roi, metal surface anomaly, glass defect, anomalygen finetune, setup_pcb, setup_metal, setup_glass, setup_pretrained, dig setup, dig datasets, dig pretrained checkpoint, dig image-edit endpoint.
accelint-react-best-practices
IncludedReact performance optimization and best practices. ALWAYS use this skill when working with any React code - writing components, hooks, JSX; refactoring; optimizing re-renders, memoization, state management; reviewing for performance; fixing hydration mismatches; debugging infinite re-renders, stale closures, input focus loss, animations restarting; preventing remounting; implementing transitions, lazy initialization, effect dependencies. Even simple React tasks benefit from these patterns. Covers React 19+ (useEffectEvent, Activity, ref props). Triggers - useEffect, useState, useMemo, useCallback, memo, inline components, nested components, components inside components, re-render, performance, hydration, SSR, Next.js, useDeferredValue, combined hooks.
elevenlabs-agents
IncludedBuild conversational AI voice agents with ElevenLabs Platform using React, JavaScript, React Native, or Swift SDKs. Configure agents, tools (client/server/MCP), RAG knowledge bases, multi-voice, and Scribe real-time STT. Use when: building voice chat interfaces, implementing AI phone agents with Twilio, configuring agent workflows or tools, adding RAG knowledge bases, testing with CLI "agents as code", or troubleshooting deprecated @11labs packages, Android audio cutoff, CSP violations, dynamic variables, or WebRTC config. Keywords: ElevenLabs Agents, ElevenLabs voice agents, AI voice agents, conversational AI, @elevenlabs/react, @elevenlabs/client, @elevenlabs/react-native, @elevenlabs/elevenlabs-js, @elevenlabs/agents-cli, elevenlabs SDK, voice AI, TTS, text-to-speech, ASR, speech recognition, turn-taking model, WebRTC voice, WebSocket voice, ElevenLabs conversation, agent system prompt, agent tools, agent knowledge base, RAG voice agents, multi-voice agents, pronunciation dictionary, voice speed control, elevenlabs scribe, @11labs deprecated, Android audio cutoff, CSP violation elevenlabs, dynamic variables elevenlabs, case-sensitive tool names, webhook authentication
humanizer
IncludedHumanize AI-generated text by detecting and removing patterns typical of LLM output. Rewrites text to sound natural, specific, and human. Uses 28 pattern detectors, 560+ AI vocabulary terms across 3 tiers, and statistical analysis (burstiness, type-token ratio, readability) for comprehensive detection. Use when asked to humanize text, de-AI writing, make content sound more natural/human, review writing for AI patterns, score text for AI detection, or improve AI-generated drafts. Covers content, language, style, communication, and filler categories.
generating-mermaid-diagrams
IncludedSalesforce architecture diagrams using Mermaid with ASCII fallback. Use this skill when generating text-based diagrams for Salesforce architecture, OAuth flows, ERDs, integration sequences, or Agentforce structure. TRIGGER when: user says "diagram", "visualize", "ERD", or asks for sequence diagrams, flowcharts, class diagrams, or architecture visualizations in Mermaid. DO NOT TRIGGER when: user wants PNG/SVG image output (use generating-visual-diagrams), or asks about non-Salesforce systems.