Build Your First Hugging Face Space with Gradio: A Beginner’s Guide 🌭

Sara Pieri
5 min readNov 4, 2023

--

After months of meticulous model training, you’ve finally perfected your machine learning model. It’s a masterpiece, and it’s ready to be shown to the world. But the question looms — how do you make this complex code tangible and interactive for others? Enter Gradio, the hero that turns your script into an accessible experience, and Hugging Face Spaces, the stage where your model gets the ovation it deserves. The best part? They can bring your model to a live demo in under 10 minutes.

HuggingFace Spaces: Your ML Model’s New Home

HuggingFace Spaces is the magic behind making your models accessible. It’s easy to use and hooks right into the HuggingFace ecosystem, providing interactive applications like model exploration and visualization tools. Whether you’re leveraging the HuggingFace Model Hub or the transformative Transformers library, deploying your models and creating applications is astonishingly simple.

Getting Started with HuggingFace Spaces

Our recipe is simple but sophisticated: we’re creating a machine learning model that can tell you whether that tasty snack we’re about to chow down on is a hot dog or not. By the end of this, you’ll not only have a nifty hot dog classifier but also the know-how to grill up your own ML models for the world to enjoy.

Let’s slice up the buns, line up the condiments, and prepare your coding appetite for a delicious ML project. Our ingredients include a pinch of Python, a slice of Gradio, and a whole lot of machine learning seasoning courtesy of Hugging Face.

Step 1: Create an Account

  1. Head over to the HuggingFace Spaces homepage.
  2. Hit “Get started for free”.
  3. Sign up using Google, GitHub, or email and follow the setup steps.

Step 2: Create a New Space

  1. Click “Create a new Space” on your dashboard.
  2. Select Gradio (or Streamlit or FastAPI, but we’re all about Gradio here).
  3. Name your Space and write a short description. A URL will be crafted for you.
  4. Opt for GPU or other hardware acceleration if needed (just select the default CPU basic for this tutorial).
  5. Decide if you want your Space to be public or private.

Building Your First Space: A Hot Dog Classifier

Step 1: Set Up the Stage

Go to Files and create a new file requirements.txt in your Space. Paste these libraries in the text field before saving it:

transformers
torch

Step 2: Your App’s Debut

Create another file called app.py, copy this Python script:


import gradio as gr
from transformers import pipeline

pipeline = pipeline(task="image-classification", model="julien-c/hotdog-not-hotdog")

def predict(image):
predictions = pipeline(image)
return {p["label"]: p["score"] for p in predictions}

gr.Interface(
predict,
inputs=gr.Image(label="Upload hot dog candidate", type="filepath"),
outputs=gr.Label(num_top_classes=2),
title="Hot Dog? Or Not?",
).launch()

What is going on?

This script brings the pretrained ‘julien-c/hotdog-not-hotdog’ model from HuggingFace onto the Gradio stage. This model, as you might guess, has been trained to differentiate between images of hot dogs and… not hot dogs.

First, we import the necessary libraries — gradio and transformers. Gradio will be our front-end wizard, crafting the interface that users will interact with. The transformers library, particularly the pipeline, is the workhorse that will perform the image classification.

Following the imports, we invoke a pipeline from the transformers library. This specific pipeline is tuned for "image-classification".

We also define a function named predict, we take an image as input and pass it through the pipeline. The pipeline processes the image and outputs predictions, which we then format into a dictionary where each label (e.g., "hotdog" or "not hotdog") is associated with its prediction score.

The creation of the user interface is achieved through Gradio’s Interface class. Let's break down its components:

Defining the Functionality

  • predict: This argument specifies the function that Gradio will execute when the user uploads an image. It links the user interface to the backend logic we just discussed.

Setting Up the Inputs and Outputs

  • inputs: Here, we define what kind of data the user will submit. gr.inputs.Image sets up an image upload button, allowing users to upload images for classification. The label "Upload your hot dog contender" is a clear instruction that will be displayed on the button.
  • outputs: This outlines how the predictions are displayed. gr.outputs.Label will show the prediction results as labels. By setting num_top_classes to 2, we instruct Gradio to display the two highest-scoring predictions.

Adding the Finishing Touches

  • title: This is a straightforward attribute where you can set the title of your Gradio app. It's the first thing users will see, so we've chosen a fun and descriptive title: "Is it a Hot Dog or Not?".

Launching the App

  • .launch(): This method activates the Gradio interface. Once this method is called, your web-based application is live and users can start uploading images for classification.

Step 3: Save Your Scripts

Once the setup is done, visit the App tab and watch as your application comes to life!

Step 4: The Big Reveal

Upload an image and let the app deliver the grand verdict: hot dog or not. Play around with different images and bask in the glory of your creation.

What about this one, for example? I say sandwich…

Conclusion

You’ve journeyed through the essentials of HuggingFace Spaces, set up your account, and unveiled your first application. This platform not only eases the sharing and collaboration of machine learning models but also opens a world of advanced application creation thanks to the vast resources within the HuggingFace ecosystem. Remember that you can always draw inspiration from the code of existing projects or fork them to accelerate your progress. Some of them truly are amazing (take a look at this one, for example : Pokemon-GAI)!

Congratulations on setting the stage for your AI model, and I hope this guide will be instrumental in your HuggingFace Spaces journey.

Happy coding! ☕️

--

--

Sara Pieri

Researcher @mbzuai. Navigating the AI universe with rich cups of coffee. Tech enthusiast and ever-curious mind. Let's brew ideas! ☕️