Introducing Gradio 5.0
Read MoreIntroducing Gradio 5.0
Read MoreWe covered State in Interfaces, this guide takes a look at state in Blocks, which works mostly the same.
Global state in Blocks works the same as in Interface. Any variable created outside a function call is a reference shared between all users.
Gradio supports session state, where data persists across multiple submits within a page session, in Blocks apps as well. To reiterate, session data is not shared between different users of your model. To store data in a session state, you need to do three things:
gr.State()
object. If there is a default value to this stateful object, pass that into the constructor.State
object as an input and output as needed.Let's take a look at a simple example. We have a simple checkout app below where you add items to a cart. You can also see the size of the cart.
import gradio as gr
with gr.Blocks() as demo:
cart = gr.State([])
items_to_add = gr.CheckboxGroup(["Cereal", "Milk", "Orange Juice", "Water"])
def add_items(new_items, previous_cart):
cart = previous_cart + new_items
return cart
gr.Button("Add Items").click(add_items, [items_to_add, cart], cart)
cart_size = gr.Number(label="Cart Size")
cart.change(lambda cart: len(cart), cart, cart_size)
demo.launch()
Notice how we do this with state:
gr.State()
object, initialized here to be an empty list..change
listener to cart, that uses the state variable as input as well.You can think of gr.State
as an invisible Component that can store any kind of value. Here, cart
is not visible in the frontend but is used for calculations.
The .change
listener for a state variable triggers after any event listener changes the value of a state variable. If the state variable holds a sequence (like a list, set, or dict), a change is triggered if any of the elements inside change. If it holds an object or primitive, a change is triggered if the hash of the value changes. So if you define a custom class and create a gr.State
variable that is an instance of that class, make sure that the the class includes a sensible __hash__
implementation.
The value of a session State variable is cleared when the user refreshes the page. The value is stored on in the app backend for 60 minutes after the user closes the tab (this can be configured by the delete_cache
parameter in gr.Blocks
).
Learn more about State
in the docs.
Gradio also supports local state, where data persists in the browser's localStorage even after the page is refreshed or closed. This is useful for storing user preferences, settings, API keys, or other data that should persist across sessions. To use local state:
gr.BrowserState()
object. You can optionally provide an initial default value and a key to identify the data in the browser's localStorage.gr.State
component in event listeners as inputs and outputs.Here's a simple example that saves a user's username and password across sessions:
import random
import string
import gradio as gr
with gr.Blocks() as demo:
gr.Markdown("Your Username and Password will get saved in the browser's local storage. "
"If you refresh the page, the values will be retained.")
username = gr.Textbox(label="Username")
password = gr.Textbox(label="Password", type="password")
btn = gr.Button("Generate Randomly")
local_storage = gr.BrowserState(["", ""])
@btn.click(outputs=[username, password])
def generate_randomly():
u = "".join(random.choices(string.ascii_letters + string.digits, k=10))
p = "".join(random.choices(string.ascii_letters + string.digits, k=10))
return u, p
@demo.load(inputs=[local_storage], outputs=[username, password])
def load_from_local_storage(saved_values):
print("loading from local storage", saved_values)
return saved_values[0], saved_values[1]
@gr.on([username.change, password.change], inputs=[username, password], outputs=[local_storage])
def save_to_local_storage(username, password):
return [username, password]
demo.launch()