HuggingFace Spaces & Gradio
HuggingFace Spaces is the fastest way to share ML demos with the world. Spaces host Gradio or Streamlit applications for free, with GPU acceleration available. If you build an ML model, Spaces is where you show it off.
Creating a Space
- Go to huggingface.co/new-space
- Choose a name (e.g.,
your-username/sentiment-analyzer) - Select Gradio as the SDK
- Choose hardware: Free CPU (sufficient for most demos)
- Click Create Space
Or use the CLI:
bash
# Install the HuggingFace Hub library
uv add huggingface-hub
# Login (requires a HuggingFace token from https://huggingface.co/settings/tokens)
huggingface-cli login
# Create a Space
huggingface-cli repo create sentiment-analyzer --type space --space-sdk gradio
Building a Gradio App
Gradio creates web interfaces for ML models with minimal code:
python
# app.py
import gradio as gr
from transformers import pipeline
# Load a pre-trained model
classifier = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")
def analyze_sentiment(text):
result = classifier(text)[0]
label = "Positive 😊" if result["label"] == "POSITIVE" else "Negative 😞"
return label, result["score"]
# Create the interface
demo = gr.Interface(
fn=analyze_sentiment,
inputs=gr.Textbox(
lines=5,
placeholder="Enter text to analyze...",
label="Input Text"
),
outputs=[
gr.Text(label="Sentiment"),
gr.Number(label="Confidence Score", precision=4)
],
title="Sentiment Analyzer",
description="Enter any English text and get its sentiment analysis.",
examples=[
["I love this product! It's amazing."],
["The weather is terrible today."],
["The movie was okay, nothing special."],
],
theme=gr.themes.Soft(),
)
if __name__ == "__main__":
demo.launch()
Advanced Gradio Components
python
import gradio as gr
# Multiple inputs and outputs
def process_data(text, threshold, model_choice):
# Process with different models
result = f"Analyzed with {model_choice} at threshold {threshold}"
chart_data = {"positive": 0.8, "negative": 0.15, "neutral": 0.05}
return result, chart_data
with gr.Blocks(title="Advanced ML Demo") as demo:
gr.Markdown("# Multi-Model Text Analyzer")
with gr.Row():
with gr.Column():
text_input = gr.Textbox(label="Input Text", lines=3)
threshold = gr.Slider(0.0, 1.0, value=0.5, label="Confidence Threshold")
model = gr.Dropdown(
choices=["distilbert", "roberta", "deberta"],
value="distilbert",
label="Model"
)
analyze_btn = gr.Button("Analyze", variant="primary")
with gr.Column():
result_text = gr.Textbox(label="Result")
result_chart = gr.Label(label="Distribution")
analyze_btn.click(
fn=process_data,
inputs=[text_input, threshold, model],
outputs=[result_text, result_chart]
)
demo.launch()
Requirements and Configuration
Create a requirements.txt for your Space:
text
gradio>=4.0
transformers>=4.35
torch>=2.1
For more control, use a Dockerfile instead:
dockerfile
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 7860
CMD ["python", "app.py"]
Use Docker Spaces for complex dependencies
If your demo needs system-level packages (like ffmpeg for audio processing), choose a Docker Space instead of the default Gradio SDK. Docker Spaces give you full control over the environment.
Managing Secrets
Space secrets are set via the Settings tab or the CLI:
bash
# Set a secret
huggingface-cli repo secrets set API_KEY your-secret-value --repo-type space
# In your app.py, access via environment variable
import os
api_key = os.environ.get("API_KEY")
Embedding Spaces
You can embed your Space in any website:
html
<iframe
src="https://your-username-sentiment-analyzer.hf.space"
width="100%"
height="600"
frameborder="0"
></iframe>