Getting Started

How to Create a Hugging Face Space: A Beginner's Guide

If you're new to Hugging Face and want to set up a space for your machine learning model or app, you're in the right place. Follow these simple steps to get your project up and running, even if you're a beginner!

If you experience any difficulties or have questions, join our Community where one of our team will be happy to help.

1. Create an Account

First, head to Hugging Face and create an account. It’s a quick process—just enter your details and follow the steps to sign up.

2. Confirm Your Email Address

Once you’ve signed up, check your email to confirm your account. This ensures you can start using all of Hugging Face’s features, including Spaces.

3. Head to Spaces

After confirming your email, log in and click on Spaces in the main navigation bar. This is where you'll manage and deploy your models and apps.

4. Create a New Space

Click Create New Space.

You'll be asked to fill in a few details about your project.

We recommend the following configurations:

  • Owner: This should match the name of your Hugging Face account
  • Space name: Call this whatever you’d like. We opted for ‘marqo-classification’ as this is what our Hugging Face Space will do. We encourage you to do the same.
  • Short Description: This is optional and we leave it out for this example.
  • License: Again, this is optional and we leave it out for this example.
  • Space SDK: We use Gradio for this Hugging Face Space. This must be selected for this tutorial.
  • Gradio template: We keep this ‘Blank’.
  • Space hardware: We keep this as ‘CPU basic • 2 CPU • 16 GB • FREE’ as this is the free Hugging Face Space.
  • Privacy: We select a 'Public' Space so we can share it with our friends later.

Awesome, once you’ve selected those configurations. Click ‘Create Space’.

This is what should appear:

5. Install Git

Once your space is created, you’ll want to clone it to your local computer. But first, you need to set up Git if you don’t have it already. If you already have Git, then jump to the next step. Git helps manage versions of your code and allows you to push updates to Hugging Face.

  • To install Git: Head to Git's official page and download it for your operating system. Follow the instructions to install it.
  • To set it up: Once Git is installed, open a terminal (or Command Prompt) and type git --version to check if Git is working.
  • If you see the version number, you’re all set!

6. Clone the Hugging Face Space

Now, clone your Hugging Face Space:


git clone https://huggingface.co/spaces/your-username/your-space

Replace your-username and your-space with your username and space, respectively. Copy this command, open your terminal, navigate to where you want to clone the repository and run it to clone the space to your local machine. For our example, we’d do cd Documents to navigate to our Documents and then,


git clone 

to clone the Hugging Face Space.

7. Open the Folder in VSCode

Navigate to the cloned folder and open it in Visual Studio Code (VSCode). This is where you’ll edit your code.

Notice how the Space is pretty empty. We only have a .gitattributes and README.md file. In order to create a Space, we need an app.py file.

8. Create an app.py File

In VSCode, create a new file named app.py. This is where the code for your app will go. For this guide, we’ll be building a simple fashion item classifier. Copy and paste the code below into your app.py file.


import gradio as gr
from transformers import AutoModel, AutoProcessor
import torch
import requests
from PIL import Image
from io import BytesIO

fashion_items = ['top', 'trousers', 'jumper']

# Load model and processor
model_name = 'Marqo/marqo-fashionSigLIP'
model = AutoModel.from_pretrained(model_name, trust_remote_code=True)
processor = AutoProcessor.from_pretrained(model_name, trust_remote_code=True)

# Preprocess and normalize text data
with torch.no_grad():
    # Ensure truncation and padding are activated
    processed_texts = processor(
        text=fashion_items,
        return_tensors="pt",
        truncation=True,  # Ensure text is truncated to fit model input size
        padding=True      # Pad shorter sequences so that all are the same length
    )['input_ids']
    
    text_features = model.get_text_features(processed_texts)
    text_features = text_features / text_features.norm(dim=-1, keepdim=True)

# Prediction function
def predict_from_url(url):
    # Check if the URL is empty
    if not url:
        return {"Error": "Please input a URL"}
    
    try:
        image = Image.open(BytesIO(requests.get(url).content))
    except Exception as e:
        return {"Error": f"Failed to load image: {str(e)}"}
    
    processed_image = processor(images=image, return_tensors="pt")['pixel_values']
    
    with torch.no_grad():
        image_features = model.get_image_features(processed_image)
        image_features = image_features / image_features.norm(dim=-1, keepdim=True)
        text_probs = (100 * image_features @ text_features.T).softmax(dim=-1)
        
    return {fashion_items[i]: float(text_probs[0, i]) for i in range(len(fashion_items))}

# Gradio interface
demo = gr.Interface(
    fn=predict_from_url, 
    inputs=gr.Textbox(label="Enter Image URL"),
    outputs=gr.Label(label="Classification Results"), 
    title="Fashion Item Classifier",
    allow_flagging="never"
)

# Launch the interface
demo.launch()

9. Add Dependencies

Now you need to let Hugging Face (and your local environment) know what libraries your app requires. Create a file called requirements.txt in the same folder and add the following:


transformers
torch
requests
Pillow
open_clip_torch
ftfy

# This is only needed for local deployment
gradio

10. Test Your App

Before deploying to Hugging Face, we’re going to test our app locally. To do this, create a virtual environment and install the dependencies listed in requirements.txt. To do this, run these commands in your terminal:


python3 -m venv venv
source venv/bin/activate  # On Windows, use `venv\Scripts\activate`
pip install -r requirements.txt
python3 app.py

This will download the model and then launch the app locally. Gradio will provide you with a local link where you can test your app. Note that Gradio is only needed for local testing, not for Hugging Face.

Your terminal should look like this.

As we can see, it says our app is running on local URL http://127.0.0.1:7861/ which we navigate to. It should look like this:

Awesome! Let’s input an image URL. For this example, we’ll use this image URL which is an image of a red jumper.

When we copy and paste this into the text box, our model classifies the image correctly with 78% probability of it being a jumper. Pretty awesome!

Why don’t you try adding more items in the fashion_items list and test out different image URLS to see how well the models classify them.

11. Upload to Hugging Face Hub

Now that your app works locally, it’s time to push it to Hugging Face so others can use it!

Create a .gitignore File

Before pushing your code, create a .gitignore file in your folder to avoid uploading unnecessary files, like your virtual environment. Here’s an example .gitignore:

# Virtual environments
venv

Commit and Push Your Code

Open another terminal window, navigate to your project folder, and run:


git status

This will tell you what files will be pushed to your Hugging Face Space. As you can see, we will be committing .gitignore, app.py and requirements.txt.

Now you’re ready to push them. To do this, enter the following:


git add .
git commit -m "Initial commit"
git push origin main

This will push your app to Hugging Face and trigger the deployment. As you can see, it has pushed successfully.

We now visit,


https://huggingface.co/spaces/elliesleightholm/marqo-classification

(or the equivalent for your Space) to see our Hugging Face Space in action.

Note, it will begin building as in the image below.

Once your Space is built, it will look as follows:

Your Hugging Face Space is deployed. Now you can test it out live! Share the link with your friends and colleagues so they can try it out too.

Conclusion and Next Steps

You’ve set up your first Hugging Face Space, built a Gradio app, and shared it with the world - awesome! Why don't you try adding more fashion items and see if the model can identify other image URLs.

Questions?

If you experience any difficulties or have questions, join our Community where one of our team will be happy to help.

Links

Hugging Face Space

Community

Ellie Sleightholm
Head of Developer Relations