Integrate HF Spaces & Gradio with a React application
/ 3 min read
This article will provide a quick introduction to create & deploy a Machine Learning Model and to integrate with React application. Here is an overview of technologies we will be using
Hugging Face is a platform where we can host Machine Learning Models and Create Spaces to use them with any of the models available.
Gradio is a platform which enables to build user interfaces for interacting with or demoing our Machine Learning models.
Create a Space in Hugging Face
Let’s start by creating a space of hugging face here. Choose a name for the space and under Spaces SDK choose Gradio
You can leave the other options as default and proceed to create space. Clone the created spaces to your machine and create app.py
with the following contents
Once these are are done, commit and push your changes to your space. Hugging face should build this automatically and shows the gradio interface of our app like this
Now we have built a gradio app with basic interface and hosted it in hugging face spaces. Let’s look into extending the functionality our app in the next section.
Note: You need to create a write token here in order to push your changes to hugging face spaces
Create a Vision Classifier Model
We are going to use fast.ai to create a simple classification which predicts whether a given image is a cat or not.
First, let’s get path of the training images dataset. fast.ai provides lot of datasets already, we’ll use one from that. Here are the steps to train & export the model
After you have run this, there should be a model file generated in the same directory. You can then use this for predictions.
Then launch gradio using the predict method above
To see your changes in action, push your changes to hugging face.
Note: Since the size of the generated model will be large, you need to use Git LFS to track the changes
Then you should able to upload any image and find if its a cat or not
Integrate with React application
One of the advantages of using gradio is that, it gives us an API to access our model. We will look into how to integrate it with React.
If you scroll to bottom in our deployed model in hugging face, you can see a button called use via Api
where you will find the details to connect to the api. We will be using @gradio/client
package to connect to api. Here is the sample code to connect to model & get the results
You can see it in action for our model here
Here are the links for all the code & demo