gradio_ml_apps

Gradio Complete Guide for Beginners

In this article, we shall take a look at Gradio Complete Guide for beginners.

Gradio- Build shareable Machine Learning Web Apps

Writing Machine Learning code in Jupyter Notebook/Colab is a good practice but what if you need to share the Machine Learning Code for a non-programmer to try? Do you think sharing Jupyter Notebook or Colab is a good practice? Gradio and Streamlit comes to the resue. Gradio and Streamlit help the programmer to develop good looking ML Web App without any HTML and CSS code. Both Gradio and Streamlit provide a wide range of components/widgets that are used to build one Web App. We already covered everything about Streamlit.

What is Gradio?

Gradio is an open-source Python library that is used to Build sharable Machine Learning, Deep Learning, and Data Science Web Apps within a few minutes. With Gradio, you can quickly create a beautiful user interface around your machine learning models or data science workflow and let people “try it out” by dragging and dropping in their own images, pasting text, recording their own voice, and interacting with your demo, all through the browser.

Use cases of Gradio:

  1. Building a Machine Learning models demo for users to try.
  2. Provides interpretation tools to debug the model interactively during the development.
  3. Generates automatic shareable links that help for model deployment.

[Source: GitHub Gradio]

Gradio Complete Guide: Quickstart

Before we start exploring Gradio components and blocks, we need to install gradio first.

pip install gradio

Interface and Launch

Interface class can wrap any Python function with a user interface.

def first_gradio(text):
    return f"Anime Vyuh Gradio Blog \n Your Entered Text: {text}"

gr.Interface(fn=first_gradio,
             inputs="text",
             outputs="text").launch()
fn, inputs and outputs are positional arguments that should be mentioned while defining Interface:

fn - Fn stands for Function, that is used to Wrap UI
inputs- Gradio component used for input
outputs- Component used for output to be displayed. 

In our case both inputs and outputs are text. 

Finally, with help of the launch method publish the Interface to the Web Browser or Web App.

In order to visualize the Web App, run the program just like a normal Python Program. At the code execution, you will receive a localhost link “http://127.0.0.1:7860/”. Another alternative is to run the code using:

gradio app.py

In the first program, we looked at only a single component used for Input and Output. Let’s explore more of the Gradio components.

Basic Components for Gradio complete guide

In the following codes, import gradio as gr is not mentioned. It is self-understood that the module is already imported and is not mentioned in all the examples.

Text

Text is the fundamental component of any GUI/Web App. We have already looked at a Text program previously, and the following code is no different.

def write_something(text):
    return f"Typed message:{text}"

gr.Interface(fn=write_something, 
             inputs= "text",
             outputs="text").launch()

Slider and Number

Slider ranges from `minimum` to `maximum` with a step size of `step`. By default minimum=0, maximum=100 and step=1. The number is used as the output to display the active position of the slider.

def move_slider(length):
    return length

demo = gr.Interface(fn=move_slider,
             inputs="slider",
             outputs="number")
demo.launch()

Let’s create our Custom Slider with our different minimum and maximum value.

def move_slider(value):
    return value

gr.Interface(fn=move_slider,
             inputs=gr.Slider(minimum=10,maximum=50,step=10),
             outputs="number").launch()

Checkbox

Checkbox returns True or False, True when the user marks the checkbox, False otherwise.

def watch_anime(ask):
    if ask:
        return "Hello Weeb"
    else:
        return "Hello Normie"

gr.Interface(fn=watch_anime,
             inputs=gr.Checkbox(label="Do you watch Anime?"),
             outputs="text").launch()

Button

The button triggers boolean results, based on whether it is clicked or not.

def click_button(check):
    if check:
        return "Button Clicked"
    else:
        return "Button not clicked"

gr.Interface(fn=click_button, 
             inputs= "button",
             outputs="text").launch()

Radio

The Radio component is a set of Buttons, where you can choose only one. Here in this example, we have 4 sets of Radio buttons, where we Trigger the total_episodes function to display the number of Episodes that the selected Anime contains.

def total_episode(anime):
    if anime == "One Piece":
        return 1035
    elif anime == "Naruto":
        return 720
    elif anime == "Bleach":
        return 366
    else:
        return 328
    
def favourite(check):
    episode = total_episode(check)
    return f"You choosed: {check}\n{check} has {episode} episodes."

gr.Interface(fn=favourite,
             inputs=gr.Radio(["One Piece","Naruto", "Bleach", "Fairy Tail"]),
             outputs="text").launch()

Image

While dealing with Computer Vision and Deep Learning, Image is the most used Gradio component. Without the Image component, it is difficult to create Image Classification, Image Segmentation, and Stable Diffusion space/Web App. The return type is the NumPy array.

def display_image(img):
    return f"Image uploaded {img}"

gr.Interface(fn=display_image,
             inputs=gr.Image("tfug.jpeg"),
             outputs="text").launch()

Sketchpad

Sketchpad provides a drawing board interface that returns a NumPy array.

import numpy as np
import gradio as gr

def sketch(img):
    return np.argmax(img)

gr.Interface(fn=sketch, 
             inputs="sketchpad",
             outputs="text",
             live=True, streaming=True).launch()

Explore more Gradio components along with Examples. Visit Gradio Documentation.

Machine Learning Web App Demo

gradio complete guide
Gradio- ML Demo

It’s finally time to build a small demo to implement Machine Learning or Deep Learning model on Gradio. The demo is built on Tensorflow Framework, if you are interested to learn Tensorflow check out my GitHub repository.

Import the required libraries

import gradio as gr
import tensorflow as tf
import numpy as np
from tensorflow.keras.preprocessing.image import img_to_array
from keras.datasets import mnist

We shall use the basics Keras mnist dataset for this demo. Normalize or Scale the dataset before passing it to the Neural Network.

(X_train, y_train), (X_test, y_test) = mnist.load_data()

X_train = X_train/255.0
X_test = X_test/255.0

Build a Neural Network with help of Keras API.

model = tf.keras.models.Sequential([
    tf.keras.layers.Flatten(input_shape=(28, 28)),
    tf.keras.layers.Dense(units=128, activation='relu'),
    tf.keras.layers.Dropout(0.5),
    tf.keras.layers.Dense(units=10,activation="softmax")
])

Compile the Neural Network by providing optimizer, loss, and metrics.

model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy']
)
history = model.fit(X_train,y_train,epochs=10,validation_data=(X_test,y_test))

The Neural Network is trained, it’s time to create an Interface to wrap the UI for the model.

def predict(img):
    x = img_to_array(img)
    x = np.expand_dims(x,axis=0)
    target = model.predict(x)
    target = np.argmax(target)
    return target
demo = gr.Interface(fn=predict, 
             inputs="sketchpad",
             outputs="number",
             live=True, streaming=True)

Share the Model

The main goal of using a Machine Learning Web app is used to make it shareable. Gradio demos can be easily shared publicly by setting share=True in the launch() method.

demo.launch(share=True)

Gradio Complete Guide Demo

import gradio as gr
import tensorflow as tf
import numpy as np
from tensorflow.keras.preprocessing.image import img_to_array
from keras.datasets import mnist

(X_train, y_train), (X_test, y_test) = mnist.load_data()

X_train = X_train/255.0
X_test = X_test/255.0

model = tf.keras.models.Sequential([
    tf.keras.layers.Flatten(input_shape=(28, 28)),
    tf.keras.layers.Dense(units=128, activation='relu'),
    tf.keras.layers.Dropout(0.5),
    tf.keras.layers.Dense(units=10,activation="softmax")
])

model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy']
)
history = model.fit(X_train,y_train,epochs=10,validation_data=(X_test,y_test))

def predict(img):
    x = img_to_array(img)
    x = np.expand_dims(x,axis=0)
    target = model.predict(x)
    target = np.argmax(target)
    return target

demo = gr.Interface(fn=predict, 
             inputs="sketchpad",
             outputs="number",
             live=True, streaming=True)

demo.launch() 
#when we publish Demo to Hugging Face share=True is not required

You can try the demo on Hugging Face Space.

How to publish Gradio App to HuggingFace Space?

Follow these steps to push the Gradio app to the HuggingFace space:

  1. Create your Hugging Face account.
  2. Create a new space.
  3. Clone the space in the local system: git clone https://huggingface.co/spaces/your_hf_name/space_name
  4. cd space_name
  5. Create an app.py and requirements.txt file within the repo directory(space_name).
  6. git add *
  7. git commit -m “My first space”
  8. git push.

You can try the above demo on Hugging Face Space.

Conclusion

This blog was the starting point to get started with Gradio. In the next article, we shall take a look at Gradio: Building with Blocks and more components. We will also build a Real-Time Car price prediction Machine Learning model on Gradio which will make use of various components at once.

Until then…

Join our Discord Server and become a part of the Anime Vyuh Community. We share content on 100DaysOfCodeAnime ReviewOne Piece Theory, and Character Analysis articles.

Subscribe to our Newsletter to never miss out on the content: https://animevyuh.org/newsletter. Join our Newsletter now for fantastic Anime recommendationsPython, and Machine Learning Content.

Support Us: https://www.buymeacoffee.com/trjtarunhttps://ko-fi.com/tarunrjain751.
GitHub: https://github.com/lucifertrj.
Twitter: https://twitter.com/TRJ_0751.

Want to learn Machine Learning with Proper Roadmap and resources? If yes, then check this Repository: 

https://github.com/lucifertrj/100DaysOfML

Reference: https://www.gradio.app/