Overview

10 Building Web-Based UI using Gradio

This chapter introduces Gradio as a fast, Pythonic way to turn machine learning functions into interactive web apps, emphasizing how developers can showcase models without front-end expertise. It explains the high-level Interface API—where you bind a Python function to inputs and outputs—along with default UI behavior (submit/clear/flag) and how data flows from widgets to functions and back. Beyond local demos, it covers sharing apps temporarily via Gradio’s share servers and making them reliably public by deploying to Hugging Face Spaces.

Readers learn practical configuration and customization: installing and launching apps, setting titles and components, enabling user feedback with flagging (including custom labels and CSV logging), protecting apps with authentication (inline credentials or custom auth functions), and exposing services by choosing host/port for local or network access. The chapter then surveys key components and patterns—Textbox customization, Audio processing with NumPy arrays, Image handling via NumPy or PIL, curated example inputs, selection widgets like Dropdown and Slider, managing multiple outputs, and organizing multiple demos with TabbedInterface—illustrating how to assemble polished, multi-modal interfaces with minimal code.

Finally, the chapter builds a conversational UI using the lower-level Blocks API to create bespoke layouts and event-driven behavior. A Chatbot component displays the dialogue, a Textbox captures user messages sent on submit/Enter, and a handler appends user and assistant turns to chat_history before clearing the input. A “Clear Conversation” button wires a click event to reset the interface, demonstrating how Blocks coordinates components, inputs/outputs, and events. Swapping in an actual model or LLM completes a production-ready chatbot that feels natural to use.

The Gradio application with one single input and one single output
The various components of your Gradio application
How values are passed in from the inputs to the bounded function and returned to the outputs
Displaying the Gradio app in a new browser window
Viewing the content of log.csv
The three flagging options
Viewing the content of log.csv
Prompting the user to login before using the application
Viewing the content of log.csv
A public link will be created for your Gradio application
The Gradio application hosted on HuggingFace Spaces
Configuring the Textbox component
Submitting the text and obtaining the output
You can drag and drop an audio file, or record from your microphone
Choosing your microphone and recording the audio
You can playback the original recording, as well as playback the reversed audio
Using the Image component in Gradio
Converting an image to gray scale
Rotating the image 90 degrees clockwise
Besides using your own images, you can now select one of the example images provided
Selecting an example image and rotating it 90 degrees clockwise
Using the Dropdown, Slider, and Textbox components for the inputs and outputs
Submitting the selected values and obtaining the output
There are two components in the output now
Wrapping the values in a tuple to send to one output
Returning values will be dropped if they are not properly formed
The first tab of the Gradio application
The second tab of the Gradio application
The components used for our chatbot UI
Typing a message in the Textbox and sending it to the Chatbot component

Summary

  • To build a simple Gradio application, you can use the Interface class. The Interface class is Gradio’s main high-level class that allows you to build a web UI with just a few lines of code.
  • The Textbox component allows users to send text content to the Gradio application.
  • The Audio component allows users to send audio streams to the Gradio application.
  • The Image component allows users to send images (as NumPy array or PIL image) to the Gradio application.
  • You can implement authentication for your Gradio application using the auth parameter in the launch() method.
  • The Flag option logs messages in the log.csv file.
  • You can share the Gradio application with your users on the local network or create a shared link to share with other internet users.
  • You can deploy your Gradio application on HuggingFace Spaces.
  • You can group multiple interfaces using the TabbedInterface class.
  • To create chatbot UI, use the Blocks class together with other Gradio components.

FAQ

What is Gradio and how do I install it?Gradio is an open-source Python library that lets you quickly build web UIs to demo machine learning apps. Install it with: pip install gradio. After installation, you can launch demo apps directly from notebooks or Python scripts.
How do I create a basic Gradio app with Interface?Use gr.Interface to wrap a Python function with inputs and outputs: - fn: the function to run - inputs/outputs: component types (for example, "text", "image", "audio") or component instances - title: UI title Call interface.launch() to start the app. By default, it shows Clear, Submit, and Flag buttons. User input flows into your function, and the return value is displayed in the output component.
What does the Flag button do and how can I customize flagging?The Flag button logs inputs/outputs and metadata to CSV files in .gradio/flagged (for example, dataset1.csv). To add labeled flagging options (like “correct”, “wrong”), set flagging_options=[...] in gr.Interface. When the logging schema changes (for example, adding a new “flag” column), Gradio creates a new dataset file (for example, dataset2.csv). If authentication is enabled, the username is recorded too.
How do I restrict access to my Gradio app (authentication)?You can password-protect the app: - Quick: interface.launch(auth=("username","password")) - Custom: define a function authentication(username, password) -> bool and pass auth=authentication Note: Third-party cookies must be enabled in the browser for auth to work (Safari and Chrome Incognito commonly block them).
How do I set the host and port and make my app reachable on my network?Use launch(server_name=..., server_port=...): - server_name="127.0.0.1": accessible only on the local machine - server_name="0.0.0.0": accessible from other devices on the same network (use http://:) Tip: In Jupyter, if you reuse a fixed port and see “port in use,” restart the kernel.
How can I share my app temporarily over the internet?Set share=True in launch(). Gradio creates a temporary public URL via its share servers (acting as a proxy; they don’t store your app data). The app must keep running (notebook kernel or script). Shared links expire after 72 hours.
How do I deploy my Gradio app to Hugging Face Spaces?Steps: - Put your app code (for example, mygradio.py) in a folder. - Create a WRITE token at https://huggingface.co/settings/tokens. - In Terminal: cd then run gradio deploy and follow prompts (title, app file, hardware, secrets, etc.). Your Space will be available at https://huggingface.co/spaces//. Hosting is free with upgrade options.
How do I work with audio and images in Gradio? - Audio: gr.Audio(sources=["upload","microphone"], type="numpy") passes a tuple (sample_rate_hz, data_array). Your function should return audio in the same format for playback. - Image: gr.Image(type="numpy") (default) passes a NumPy array; gr.Image(type="pil") passes a PIL image. Users can upload, paste, or capture via webcam. You can also provide example images via the examples=[...] parameter.
How do I use selection widgets like Dropdown and Slider, and handle multiple outputs? - Dropdown: define choices; set type="index" to receive the selected index (or omit for value). - Slider: configure minimum, maximum, step, and default value. - Multiple outputs: pass a list of output components. If one output needs multiple values, return them as a tuple matching that component’s expected structure; otherwise results may be truncated.
How do I build a chatbot-like UI with Blocks and the Chatbot component?Use gr.Blocks for custom layouts: - Within with gr.Blocks(): create gr.Chatbot(type="messages"), a gr.Textbox for input, and a Clear button. - Wire textbox.submit(fn=chat, inputs=[textbox, chatbot], outputs=[textbox, chatbot]) where chat(message, chat_history) appends user/assistant messages to chat_history and returns ("", chat_history) to clear the Textbox and update the Chatbot. - Wire clear.click(...) to a function that returns an empty Chatbot state to clear the conversation. Replace the placeholder response logic with calls to your LLM.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Hugging Face in Action ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Hugging Face in Action ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Hugging Face in Action ebook for free