Gradio: Beyond the Interface

Author:Murphy  |  View: 26535  |  Time: 2025-03-22 21:53:32

Gradio: Advanced Layouts

Don't use the interface, use Blocks instead

When using Gradio for the first time, you'll likely end up using the Interface method to display your GUI. The reason for this is the simplicity it offers and if your page layouts are uncomplicated this is all you'll probably need. In this article, we'll investigate what to do when your Gradio layouts outgrow the Interface.

Before continuing, if Gradio is new to you please check out my other article (linked below) where I introduce what it is. The TL;DR though is that it's an incredibly useful and easy-to-code Python-based GUI that allows you to quickly stand up a local frontend to make it easy for the user to interact with whatever you're coding.

Gradio: Rapid GUI Prototyping

Also, as we'll be doing some coding, the best practice is to set up a new development environment so any work we do won't interfere with any of our other projects. I do most of my coding for articles using Python and Jupyter and I have an article here on how I set up my development environment which explains what you need to do.

Once you're set, make sure you have the Gradio and Jupyter libraries imported to your environment via pip, e.g.

pip install gradio jupyter

Example 1 – Using the Interface class

Here's a quick example using the Interface class which is Gradio's high-level abstraction for creating windows and components such as text boxes etc…

This is the equivalent of the "hello world" of Gradio apps I guess. We have specified three components in total, two inputs (a textbox and a slider control) and one output (another textbox).

import gradio as gr

def greet(name, intensity):
    return "Hello, " + name + "!" * int(intensity)

demo = gr.Interface(
    fn=greet,
    inputs=["text", "slider"],
    outputs=["text"],
)

demo.launch()

You can run this from your Jupyter Notebook and when you do you should see this.

Image by Author

This is all good, but how was it decided that the Output textbox would be placed on the right-hand side?

Well, it seems that Gradio operates on the following set of rules for its Interface method. If there are both input and output components to view on-screen, then

  1. Inputs appear on the left-hand side of the screen
  2. If there are multiple inputs, each subsequent one appears under the previous input on the same side.
  3. Outputs appear on the right-hand side of the screen
  4. If there are multiple outputs, each subsequent one appears under the previous output on the same side.

So, basically using the Interface method, while OK for simple layouts, gives you as the designer almost no control over how graphical components appear on the screen.

Example 2 – More complicated layouts using Blocks

Let me tell you about one of the snags I hit with a Gradio screen I was designing. You see I had three inputs and one output but I wanted one of my inputs to be above the sole output on the right-hand side of the screen.

I was putting together a little POC for a simplified Google Translate type of utility. I wanted my screen to look something like this:

Image by Author

Now, as I said, the problem was that the Output Languagedrop-down list, despite its name, is actually an input component from Gradio's perspective, as we want the user to be able to click on it and change the desired output language. When using the Gradio interface method it would naturally want to put that component on the left-hand side underneath the Enter Textbox. And that's exactly what it did do and as far as I could tell there was no easy way to circumvent this.

Gradio Blocks to the Rescue

Luckily for me, there is an alternative layout system that Gradio can use called a Block and Blocks offer a more flexible system for positioning components.

The basic usage of Blocks is as follows:-

Create a Blocks object, then use it as a context (with a "with" statement), then define layouts, components, or events within the Blocks context. Finally, call the launch() method to launch the app.

The best way to learn about Blocks is to look at an example and we might as well jump straight into the problem I was trying to solve to see how I used Blocks to do that.

Here is the code. I've commented it extensively so it should be fairly easy to follow along with what is happening. But if you run it you will see that it produces exactly the layout I was wanting.

languages = ['English', 'Spanish', 'French', 'German', 'Latin', 'Greek']

# Create a Gradio interface using the Blocks API.
with gr.Blocks() as demo:
    # Create a row that will contain two columns.
    with gr.Row():
        # The first column for input language and text.
         # Within each row we specify two columns
        with gr.Column():
            # Column 1 contains a dropdown for selecting the input 
            # language, defaulting to 'English'...
            input_language = gr.Dropdown(label="Input Language", value='English', choices=languages)
            # ... and an input  textbox for users to enter the text they 
            # want to translate.
            enter_text = gr.Textbox(label="Enter Text")

        # The second column for output language and displaying the translation result.
        with gr.Column():
            # Column 2 contains adropdown for our third input component, a 
            # drop-down for selecting the output language, defaulting 
            # to 'Spanish'...
            output_language = gr.Dropdown(label="Output Language", value='Spanish', choices=languages)
            # ... and an output textbox that will display the translated text.
            translated_text = gr.Textbox(label="Translated Text")

    # A button that users click to submit their request.
    submit_button = gr.Button("Submit")
    # When the button is clicked, it can call , for example, a translate function using the selected
    # input language, output language, and the entered text, then shows the result in the translated text box.
    submit_button.click(
        fn=None,  # The function to call when the button is clicked. Set to None here but would be something like a 'translate' method
        inputs=[input_language, output_language, enter_text],  # The inputs to pass to the function.
        outputs=translated_text  # Where to display the function's output.
    )

# Launch the Gradio interface.
demo.launch()

In fact, the only thing you would need to do with this code to make it really useful is to code up an appropriate Python function to pass into the submit_button.click() event.

But how do we know this wasn't just some kind of fluke? Easy, change the order of the components within the gr.Row() context like this and see what happens,

with gr.Column():

   # The second column for output language and displaying the translation result.
   # A dropdown for selecting the output language, defaulting to 'Spanish'.
   output_language = gr.Dropdown(label="Output Language", value='Spanish', choices=languages)
   # A textbox that will display the translated text.
   translated_text = gr.Textbox(label="Translated Text")

with gr.Column():

  # A dropdown for selecting the input language, defaulting to 'English'.
  input_language = gr.Dropdown(label="Input Language", value='English', choices=languages)
  # A textbox for users to enter the text they want to translate.
  enter_text = gr.Textbox(label="Enter Text")

As expected, the inputs are now on the right-hand side and the outputs are on the left.

Image by Author

For more information on all things Gradio-related, check out their official documentation on their website here for more details.

_That's all for me for now. Hopefully, you found this article useful. If you did, please check out my profile page at this link. From there, you can see my other published stories and subscribe to get notified when I post new content._

If you liked this content, you might find these articles interesting too.

Testing Meta's Llama 3 model

Need for Speed: cuDF Pandas vs. Pandas

Tags: Gradio GUI Machine Learning Programming Python

Comment