text
stringlengths
0
2k
heading1
stringlengths
4
79
source_page_url
stringclasses
180 values
source_page_title
stringclasses
180 values
A typed dictionary to represent metadata for a message in the Chatbot component. An instance of this dictionary is used for the `metadata` field in a ChatMessage when the chat message should be displayed as a thought. Keys ▼ title: str The title of the 'thought' message. Only required field. id: int | str The ID of the message. Only used for nested thoughts. Nested thoughts can be nested by setting the parent_id to the id of the parent thought. parent_id: int | str The ID of the parent message. Only used for nested thoughts. log: str A string message to display next to the thought title in a subdued font. duration: float The duration of the message in seconds. Appears next to the thought title in a subdued font inside a parentheses. status: Literal['pending', 'done'] if set to `'pending'`, a spinner appears next to the thought title and the accordion is initialized open. If `status` is `'done'`, the thought accordion is initialized closed. If `status` is not provided, the thought accordion is initialized open and no spinner is displayed.
MetadataDict
https://gradio.app/docs/gradio/chatbot
Gradio - Chatbot Docs
A typed dictionary to represent an option in a ChatMessage. A list of these dictionaries is used for the `options` field in a ChatMessage. Keys ▼ value: str The value to return when the option is selected. label: str The text to display in the option, if different from the value.
OptionDict
https://gradio.app/docs/gradio/chatbot
Gradio - Chatbot Docs
The gr.LikeData class is a subclass of gr.EventData that specifically carries information about the `.like()` event. When gr.LikeData is added as a type hint to an argument of an event listener method, a gr.LikeData object will automatically be passed as the value of that argument. The attributes of this object contains information about the event that triggered the listener.
Description
https://gradio.app/docs/gradio/likedata
Gradio - Likedata Docs
import gradio as gr def test(value, like_data: gr.LikeData): return { "chatbot_value": value, "liked_message": like_data.value, "liked_index": like_data.index, "liked_or_disliked_as_bool": like_data.liked } with gr.Blocks() as demo: c = gr.Chatbot([("abc", "def")]) t = gr.JSON() c.like(test, c, t) demo.launch()
Example Usage
https://gradio.app/docs/gradio/likedata
Gradio - Likedata Docs
Parameters ▼ index: int | tuple[int, int] The index of the liked/disliked item. Is a tuple if the component is two dimensional. value: Any The value of the liked/disliked item. liked: bool True if the item was liked, False if disliked, or string value if any other feedback.
Attributes
https://gradio.app/docs/gradio/likedata
Gradio - Likedata Docs
chatbot_core_components_simple Open in 🎢 ↗ import gradio as gr import random Chatbot demo with multimodal input (text, markdown, LaTeX, code blocks, image, audio, video, & model3d). Plus shows support for streaming text. color_map = { "harmful": "crimson", "neutral": "gray", "beneficial": "green", } def html_src(harm_level): return f""" <div style="display: flex; gap: 5px;"> <div style="background-color: {color_map[harm_level]}; padding: 2px; border-radius: 5px;"> {harm_level} </div> </div> """ def print_like_dislike(x: gr.LikeData): print(x.index, x.value, x.liked) def add_message(history, message): for x in message["files"]: history.append(((x,), None)) if message["text"] is not None: history.append((message["text"], None)) return history, gr.MultimodalTextbox(value=None, interactive=False) def bot(history, response_type): if response_type == "gallery": history[-1][1] = gr.Gallery( [ "https://raw.githubusercontent.com/gradio- app/gradio/main/test/test_files/bus.png", "https://raw.githubusercontent.com/gradio- app/gradio/main/test/test_files/bus.png", ] ) elif response_type == "image": history[-1][1] = gr.Image( "https://raw.githubusercontent.com/gradio- app/gradio/main/test/test_files/bus.png" ) elif response_type == "video": history[-1][1] = gr.Video( "https://github.com/gradio- app/gradio/raw/main/gradio/media_assets/videos/world.mp4", label="test" ) elif response_type == "audio": history[-1][1] = gr.Audio( "https://github.com/gradio- app/gradio/raw/main/gradio/media_assets/audio/audio_sample.wav" ) elif response_type == "html": history[-1][1] = gr.HTML( html_src(random.choice(["harmful", "neutral", "beneficial"])) ) elif response_type == "model3d": history[-1][1] = gr.Model3D( "https://github.com/gradio- app/gradio/raw/main/gradio/media_assets/models3d/Fox.gltf" ) else: history[-1][1] = "Cool!" return history with gr.Blocks(fill_height=True) as demo: chatbot = gr.Chatbot( elem_id="chatbot", bubble_full_width=False, scale=1, ) response_type = gr.Radio( [ "ima
Demos
https://gradio.app/docs/gradio/likedata
Gradio - Likedata Docs
) else: history[-1][1] = "Cool!" return history with gr.Blocks(fill_height=True) as demo: chatbot = gr.Chatbot( elem_id="chatbot", bubble_full_width=False, scale=1, ) response_type = gr.Radio( [ "image", "text", "gallery", "video", "audio", "html", "model3d", ], value="text", label="Response Type", ) chat_input = gr.MultimodalTextbox( interactive=True, placeholder="Enter message or upload file...", show_label=False, ) chat_msg = chat_input.submit( add_message, [chatbot, chat_input], [chatbot, chat_input] ) bot_msg = chat_msg.then( bot, [chatbot, response_type], chatbot, api_name="bot_response" ) bot_msg.then(lambda: gr.MultimodalTextbox(interactive=True), None, [chat_input]) chatbot.like(print_like_dislike, None, None) if __name__ == "__main__": demo.launch() import gradio as gr import random Chatbot demo with multimodal input (text, markdown, LaTeX, code blocks, image, audio, video, & model3d). Plus shows support for streaming text. color_map = { "harmful": "crimson", "neutral": "gray", "beneficial": "green", } def html_src(harm_level): return f""" {harm_level} """ def print_like_dislike(x: gr.LikeData): print(x.index, x.value, x.liked) def add_message(history, message): for x in message["files"]: history.append(((x,), None)) if message["text"] is not None: history.append((message["text"], None)) return history, gr.MultimodalTextbox(value=None, interactive=False) def bot(history, response_type): if response_type == "gallery": history[-1][1] = gr.Gallery( [ "https://raw.githubusercontent.com/gradio-app/gradio/main/test/test_files/bus.png", "https://raw.githubusercontent.com/gradio-app/gradio/main/test/test_files/bus.png", ] )
Demos
https://gradio.app/docs/gradio/likedata
Gradio - Likedata Docs
sercontent.com/gradio-app/gradio/main/test/test_files/bus.png", "https://raw.githubusercontent.com/gradio-app/gradio/main/test/test_files/bus.png", ] ) elif response_type == "image": history[-1][1] = gr.Image( "https://raw.githubusercontent.com/gradio-app/gradio/main/test/test_files/bus.png" ) elif response_type == "video": history[-1][1] = gr.Video( "https://github.com/gradio-app/gradio/raw/main/gradio/media_assets/videos/world.mp4", label="test" ) elif response_type == "audio": history[-1][1] = gr.Audio( "https://github.com/gradio-app/gradio/raw/main/gradio/media_assets/audio/audio_sample.wav" ) elif response_type == "html": history[-1][1] = gr.HTML( html_src(random.choice(["harmful", "neutral", "beneficial"])) ) elif response_type == "model3d": history[-1][1] = gr.Model3D( "https://github.com/gradio-app/gradio/raw/main/gradio/media_assets/models3d/Fox.gltf" ) else: history[-1][1] = "Cool!" return history with gr.Blocks(fill_height=True) as demo: chatbot = gr.Chatbot( elem_id="chatbot", bubble_full_width=False, scale=1, ) response_type = gr.Radio( [ "image", "text", "gallery", "video", "audio", "html", "model3d", ], value="text", label="Response Type", ) chat_input = gr.MultimodalTextbox( interactive=True, placeholder="Enter message or upload file...", show_label=False, ) chat_msg = chat_input.submit( add_message, [chatbot, ch
Demos
https://gradio.app/docs/gradio/likedata
Gradio - Likedata Docs
interactive=True, placeholder="Enter message or upload file...", show_label=False, ) chat_msg = chat_input.submit( add_message, [chatbot, chat_input], [chatbot, chat_input] ) bot_msg = chat_msg.then( bot, [chatbot, response_type], chatbot, api_name="bot_response" ) bot_msg.then(lambda: gr.MultimodalTextbox(interactive=True), None, [chat_input]) chatbot.like(print_like_dislike, None, None) if __name__ == "__main__": demo.launch()
Demos
https://gradio.app/docs/gradio/likedata
Gradio - Likedata Docs
Creates a set of (string or numeric type) radio buttons of which only one can be selected.
Description
https://gradio.app/docs/gradio/radio
Gradio - Radio Docs
**As input component** : Passes the value of the selected radio button as a `str | int | float`, or its index as an `int` into the function, depending on `type`. Your function should accept one of these types: def predict( value: str | int | float | None ) ... **As output component** : Expects a `str | int | float` corresponding to the value of the radio button to be selected Your function should return one of these types: def predict(···) -> str | int | float | None ... return value
Behavior
https://gradio.app/docs/gradio/radio
Gradio - Radio Docs
Parameters ▼ choices: list[str | int | float | tuple[str, str | int | float]] | None default `= None` A list of string or numeric options to select from. An option can also be a tuple of the form (name, value), where name is the displayed name of the radio button and value is the value to be passed to the function, or returned by the function. value: str | int | float | Callable | None default `= None` The option selected by default. If None, no option is selected by default. If a function is provided, the function will be called each time the app loads to set the initial value of this component. type: Literal['value', 'index'] default `= "value"` Type of value to be returned by component. "value" returns the string of the choice selected, "index" returns the index of the choice selected. label: str | I18nData | None default `= None` the label for this component, displayed above the component if `show_label` is `True` and is also used as the header if there are a table of examples for this component. If None and used in a `gr.Interface`, the label will be the name of the parameter this component corresponds to. info: str | I18nData | None default `= None` additional component description, appears below the label in smaller font. Supports markdown / HTML syntax. every: Timer | float | None default `= None` Continously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer. inputs: Component | list[Component] | set[Component] | None default `= None` Components that are used as inputs to calculate `value` if `value` is a function (has no effect otherwise). `value` is recalculated any time the inputs change. show_label: bool | None default `= None` if True, will display label.
Initialization
https://gradio.app/docs/gradio/radio
Gradio - Radio Docs
value` is a function (has no effect otherwise). `value` is recalculated any time the inputs change. show_label: bool | None default `= None` if True, will display label. container: bool default `= True` If True, will place the component in a container - providing some extra padding around the border. scale: int | None default `= None` Relative width compared to adjacent Components in a Row. For example, if Component A has scale=2, and Component B has scale=1, A will be twice as wide as B. Should be an integer. min_width: int default `= 160` Minimum pixel width, will wrap if not sufficient screen space to satisfy this value. If a certain scale value results in this Component being narrower than min_width, the min_width parameter will be respected first. interactive: bool | None default `= None` If True, choices in this radio group will be selectable; if False, selection will be disabled. If not provided, this is inferred based on whether the component is used as an input or output. visible: bool | Literal['hidden'] default `= True` If False, component will be hidden. If "hidden", component will be visually hidden and not take up space in the layout but still exist in the DOM elem_id: str | None default `= None` An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. elem_classes: list[str] | str | None default `= None` An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. render: bool default `= True` If False, component will not render be rendered in the Blocks context. Should be used if the intention is to assign event listeners now but render the component later. key: int | str | tuple[int | str, ...] | None default `= None` in a gr.render, Compon
Initialization
https://gradio.app/docs/gradio/radio
Gradio - Radio Docs
Should be used if the intention is to assign event listeners now but render the component later. key: int | str | tuple[int | str, ...] | None default `= None` in a gr.render, Components with the same key across re-renders are treated as the same component, not a new component. Properties set in 'preserved_by_key' are not reset across a re-render. preserved_by_key: list[str] | str | None default `= "value"` A list of parameters from this component's constructor. Inside a gr.render() function, if a component is re-rendered with the same key, these (and only these) parameters will be preserved in the UI (if they have been changed by the user or an event listener) instead of re-rendered based on the values provided during constructor. rtl: bool default `= False` If True, the radio buttons will be displayed in right-to-left order. Default is False.
Initialization
https://gradio.app/docs/gradio/radio
Gradio - Radio Docs
Class | Interface String Shortcut | Initialization ---|---|--- `gradio.Radio` | "radio" | Uses default values
Shortcuts
https://gradio.app/docs/gradio/radio
Gradio - Radio Docs
sentence_builderblocks_essay Open in 🎢 ↗ import gradio as gr def sentence_builder(quantity, animal, countries, place, activity_list, morning): return f"""The {quantity} {animal}s from {" and ".join(countries)} went to the {place} where they {" and ".join(activity_list)} until the {"morning" if morning else "night"}""" demo = gr.Interface( sentence_builder, [ gr.Slider(2, 20, value=4, label="Count", info="Choose between 2 and 20"), gr.Dropdown( ["cat", "dog", "bird"], label="Animal", info="Will add more animals later!" ), gr.CheckboxGroup(["USA", "Japan", "Pakistan"], label="Countries", info="Where are they from?"), gr.Radio(["park", "zoo", "road"], label="Location", info="Where did they go?"), gr.Dropdown( ["ran", "swam", "ate", "slept"], value=["swam", "slept"], multiselect=True, label="Activity", info="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed auctor, nisl eget ultricies aliquam, nunc nisl aliquet nunc, eget aliquam nisl nunc vel nisl." ), gr.Checkbox(label="Morning", info="Did they do it in the morning?"), ], "text", examples=[ [2, "cat", ["Japan", "Pakistan"], "park", ["ate", "swam"], True], [4, "dog", ["Japan"], "zoo", ["ate", "swam"], False], [10, "bird", ["USA", "Pakistan"], "road", ["ran"], False], [8, "cat", ["Pakistan"], "zoo", ["ate"], True], ] ) if __name__ == "__main__": demo.launch() import gradio as gr def sentence_builder(quantity, animal, countries, place, activity_list, morning): return f"""The {quantity} {animal}s from {" and ".join(countries)} went to the {place} where they {" and ".join(activity_list)} until the {"morning" if morning else "night"}""" demo = gr.Interface( sentence_builder, [ gr.Slider(2, 20, value=4, label="Count", info="Choose between 2 and 20"), gr.Dropdown( ["cat", "dog", "bird"], label="Animal", info="Will add more animals later!" ), gr.CheckboxGroup(["USA", "Japan", "Pakistan"], label="
Demos
https://gradio.app/docs/gradio/radio
Gradio - Radio Docs
, gr.Dropdown( ["cat", "dog", "bird"], label="Animal", info="Will add more animals later!" ), gr.CheckboxGroup(["USA", "Japan", "Pakistan"], label="Countries", info="Where are they from?"), gr.Radio(["park", "zoo", "road"], label="Location", info="Where did they go?"), gr.Dropdown( ["ran", "swam", "ate", "slept"], value=["swam", "slept"], multiselect=True, label="Activity", info="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed auctor, nisl eget ultricies aliquam, nunc nisl aliquet nunc, eget aliquam nisl nunc vel nisl." ), gr.Checkbox(label="Morning", info="Did they do it in the morning?"), ], "text", examples=[ [2, "cat", ["Japan", "Pakistan"], "park", ["ate", "swam"], True], [4, "dog", ["Japan"], "zoo", ["ate", "swam"], False], [10, "bird", ["USA", "Pakistan"], "road", ["ran"], False], [8, "cat", ["Pakistan"], "zoo", ["ate"], True], ] ) if __name__ == "__main__": demo.launch() Open in 🎢 ↗ import gradio as gr countries_cities_dict = { "USA": ["New York", "Los Angeles", "Chicago"], "Canada": ["Toronto", "Montreal", "Vancouver"], "Pakistan": ["Karachi", "Lahore", "Islamabad"], } def change_textbox(choice): if choice == "short": return gr.Textbox(lines=2, visible=True), gr.Button(interactive=True) elif choice == "long": return gr.Textbox(lines=8, visible=True, value="Lorem ipsum dolor sit amet"), gr.Button(interactive=True) else: return gr.Textbox(visible=False), gr.Button(interactive=False) with gr.Blocks() as demo: radio = gr.Radio( ["short", "long", "none"], label="What kind of essay would you like to write?" ) text = gr.Textbox(lines=2, interactive=True, show_copy_button=True) with gr.Row(): num = gr.Number(minimum=0, maximum=100, label="input") out = gr.Number(label="output") minimum_slider = gr.Slider(0, 100, 0, label="min"
Demos
https://gradio.app/docs/gradio/radio
Gradio - Radio Docs
ines=2, interactive=True, show_copy_button=True) with gr.Row(): num = gr.Number(minimum=0, maximum=100, label="input") out = gr.Number(label="output") minimum_slider = gr.Slider(0, 100, 0, label="min") maximum_slider = gr.Slider(0, 100, 100, label="max") submit_btn = gr.Button("Submit", variant="primary") with gr.Row(): country = gr.Dropdown(list(countries_cities_dict.keys()), label="Country") cities = gr.Dropdown([], label="Cities") @country.change(inputs=country, outputs=cities) def update_cities(country): cities = list(countries_cities_dict[country]) return gr.Dropdown(choices=cities, value=cities[0], interactive=True) def reset_bounds(minimum, maximum): return gr.Number(minimum=minimum, maximum=maximum) radio.change(fn=change_textbox, inputs=radio, outputs=[text, submit_btn]) gr.on( [minimum_slider.change, maximum_slider.change], reset_bounds, [minimum_slider, maximum_slider], outputs=num, ) num.submit(lambda x: x, num, out) if __name__ == "__main__": demo.launch() import gradio as gr countries_cities_dict = { "USA": ["New York", "Los Angeles", "Chicago"], "Canada": ["Toronto", "Montreal", "Vancouver"], "Pakistan": ["Karachi", "Lahore", "Islamabad"], } def change_textbox(choice): if choice == "short": return gr.Textbox(lines=2, visible=True), gr.Button(interactive=True) elif choice == "long": return gr.Textbox(lines=8, visible=True, value="Lorem ipsum dolor sit amet"), gr.Button(interactive=True) else: return gr.Textbox(visible=False), gr.Button(interactive=False) with gr.Blocks() as demo: radio = gr.Radio( ["short", "long", "none"], label="What kind of essay would you like to write?" ) text = gr.Textbox(lines=2, interactive=True, show_copy_button=True) with gr.Row(): num = gr.Number(minimum=0, maximum=100, label="input") out = gr.Number(label="output") m
Demos
https://gradio.app/docs/gradio/radio
Gradio - Radio Docs
x(lines=2, interactive=True, show_copy_button=True) with gr.Row(): num = gr.Number(minimum=0, maximum=100, label="input") out = gr.Number(label="output") minimum_slider = gr.Slider(0, 100, 0, label="min") maximum_slider = gr.Slider(0, 100, 100, label="max") submit_btn = gr.Button("Submit", variant="primary") with gr.Row(): country = gr.Dropdown(list(countries_cities_dict.keys()), label="Country") cities = gr.Dropdown([], label="Cities") @country.change(inputs=country, outputs=cities) def update_cities(country): cities = list(countries_cities_dict[country]) return gr.Dropdown(choices=cities, value=cities[0], interactive=True) def reset_bounds(minimum, maximum): return gr.Number(minimum=minimum, maximum=maximum) radio.change(fn=change_textbox, inputs=radio, outputs=[text, submit_btn]) gr.on( [minimum_slider.change, maximum_slider.change], reset_bounds, [minimum_slider, maximum_slider], outputs=num, ) num.submit(lambda x: x, num, out) if __name__ == "__main__": demo.launch()
Demos
https://gradio.app/docs/gradio/radio
Gradio - Radio Docs
Description Event listeners allow you to respond to user interactions with the UI components you've defined in a Gradio Blocks app. When a user interacts with an element, such as changing a slider value or uploading an image, a function is called. Supported Event Listeners The Radio component supports the following event listeners. Each event listener takes the same parameters, which are listed in the Event Parameters table below. Listener | Description ---|--- `Radio.select(fn, ···)` | Event listener for when the user selects or deselects the Radio. Uses event data gradio.SelectData to carry `value` referring to the label of the Radio, and `selected` to refer to state of the Radio. See EventData documentation on how to use this event data `Radio.change(fn, ···)` | Triggered when the value of the Radio changes either because of user input (e.g. a user types in a textbox) OR because of a function update (e.g. an image receives a value from the output of an event trigger). See `.input()` for a listener that is only triggered by user input. `Radio.input(fn, ···)` | This listener is triggered when the user changes the value of the Radio. Event Parameters Parameters ▼ fn: Callable | None | Literal['decorator'] default `= "decorator"` the function to call when this event is triggered. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component. inputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None default `= None` List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list. outputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None default `= None` Li
Event Listeners
https://gradio.app/docs/gradio/radio
Gradio - Radio Docs
function takes no inputs, this should be an empty list. outputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None default `= None` List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list. api_name: str | None | Literal[False] default `= None` defines how the endpoint appears in the API docs. Can be a string, None, or False. If set to a string, the endpoint will be exposed in the API docs with the given name. If None (default), the name of the function will be used as the API endpoint. If False, the endpoint will not be exposed in the API docs and downstream apps (including those that `gr.load` this app) will not be able to use this event. api_description: str | None | Literal[False] default `= None` Description of the API endpoint. Can be a string, None, or False. If set to a string, the endpoint will be exposed in the API docs with the given description. If None, the function's docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs. scroll_to_output: bool default `= False` If True, will scroll to output component on completion show_progress: Literal['full', 'minimal', 'hidden'] default `= "full"` how to show the progress animation while event is running: "full" shows a spinner which covers the output component area as well as a runtime display in the upper right corner, "minimal" only shows the runtime display, "hidden" shows no progress animation at all show_progress_on: Component | list[Component] | None default `= None` Component or list of components to show the progress animation on. If None, will show the progress animation on all of the output components. queue: bool default `= True` If True, will place the request on the queue, if the queue has been enabled. If False,
Event Listeners
https://gradio.app/docs/gradio/radio
Gradio - Radio Docs
will show the progress animation on all of the output components. queue: bool default `= True` If True, will place the request on the queue, if the queue has been enabled. If False, will not put this event on the queue, even if the queue has been enabled. If None, will use the queue setting of the gradio app. batch: bool default `= False` If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component. max_batch_size: int default `= 4` Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True) preprocess: bool default `= True` If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component). postprocess: bool default `= True` If False, will not run postprocessing of component data before returning 'fn' output to the browser. cancels: dict[str, Any] | list[dict[str, Any]] | None default `= None` A list of other events to cancel when this listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish. trigger_mode: Literal['once', 'multiple', 'always_last'] | None default `= None` If "once" (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to "multiple", unlimited submissions ar
Event Listeners
https://gradio.app/docs/gradio/radio
Gradio - Radio Docs
'always_last'] | None default `= None` If "once" (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to "multiple", unlimited submissions are allowed while pending, and "always_last" (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete. js: str | Literal[True] | None default `= None` Optional frontend js method to run before running 'fn'. Input arguments for js method are values of 'inputs' and 'outputs', return should be a list of values for output components. concurrency_limit: int | None | Literal['default'] default `= "default"` If set, this is the maximum number of this event that can be running simultaneously. Can be set to None to mean no concurrency_limit (any number of this event can be running simultaneously). Set to "default" to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default). concurrency_id: str | None default `= None` If set, this is the id of the concurrency group. Events with the same concurrency_id will be limited by the lowest set concurrency_limit. show_api: bool default `= True` whether to show this event in the "view API" page of the Gradio app, or in the ".view_api()" method of the Gradio clients. Unlike setting api_name to False, setting show_api to False will still allow downstream apps as well as the Clients to use this event. If fn is None, show_api will automatically be set to False. time_limit: int | None default `= None` stream_every: float default `= 0.5` like_user_message: bool default `= False` key: int | str | tuple[int | str, ...] | None default `= None` A unique key for this event listener to be used in @gr.render(). If set, this value identifies an event as identical across re-rende
Event Listeners
https://gradio.app/docs/gradio/radio
Gradio - Radio Docs
key: int | str | tuple[int | str, ...] | None default `= None` A unique key for this event listener to be used in @gr.render(). If set, this value identifies an event as identical across re-renders when the key is identical. validator: Callable | None default `= None` Optional validation function to run before the main function. If provided, this function will be executed first with queue=False, and only if it completes successfully will the main function be called. The validator receives the same inputs as the main function and should return a `gr.validate()` for each input value.
Event Listeners
https://gradio.app/docs/gradio/radio
Gradio - Radio Docs
Button that clears the value of a component or a list of components when clicked. It is instantiated with the list of components to clear.
Description
https://gradio.app/docs/gradio/clearbutton
Gradio - Clearbutton Docs
**As input component** : (Rarely used) the `str` corresponding to the button label when the button is clicked Your function should accept one of these types: def predict( value: str | None ) ... **As output component** : string corresponding to the button label Your function should return one of these types: def predict(···) -> str | None ... return value
Behavior
https://gradio.app/docs/gradio/clearbutton
Gradio - Clearbutton Docs
Parameters ▼ components: None | list[Component] | Component default `= None` value: str default `= "Clear"` default text for the button to display. If a function is provided, the function will be called each time the app loads to set the initial value of this component. every: Timer | float | None default `= None` continuously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer. inputs: Component | list[Component] | set[Component] | None default `= None` components that are used as inputs to calculate `value` if `value` is a function (has no effect otherwise). `value` is recalculated any time the inputs change. variant: Literal['primary', 'secondary', 'stop'] default `= "secondary"` sets the background and text color of the button. Use 'primary' for main call- to-action buttons, 'secondary' for a more subdued style, 'stop' for a stop button, 'huggingface' for a black background with white text, consistent with Hugging Face's button styles. size: Literal['sm', 'md', 'lg'] default `= "lg"` size of the button. Can be "sm", "md", or "lg". icon: str | Path | None default `= None` URL or path to the icon file to display within the button. If None, no icon will be displayed. link: str | None default `= None` URL to open when the button is clicked. If None, no link will be used. visible: bool | Literal['hidden'] default `= True` If False, component will be hidden. If "hidden", component will be visually hidden and not take up space in the layout but still exist in the DOM interactive: bool default `= True` if False, the Button will be in a disabled state. elem_id: str | None default `= None` an optional string that is assigned as the id o
Initialization
https://gradio.app/docs/gradio/clearbutton
Gradio - Clearbutton Docs
interactive: bool default `= True` if False, the Button will be in a disabled state. elem_id: str | None default `= None` an optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. elem_classes: list[str] | str | None default `= None` an optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. render: bool default `= True` if False, component will not render be rendered in the Blocks context. Should be used if the intention is to assign event listeners now but render the component later. key: int | str | tuple[int | str, ...] | None default `= None` in a gr.render, Components with the same key across re-renders are treated as the same component, not a new component. Properties set in 'preserved_by_key' are not reset across a re-render. preserved_by_key: list[str] | str | None default `= "value"` A list of parameters from this component's constructor. Inside a gr.render() function, if a component is re-rendered with the same key, these (and only these) parameters will be preserved in the UI (if they have been changed by the user or an event listener) instead of re-rendered based on the values provided during constructor. scale: int | None default `= None` relative size compared to adjacent Components. For example if Components A and B are in a Row, and A has scale=2, and B has scale=1, A will be twice as wide as B. Should be an integer. scale applies in Rows, and to top-level Components in Blocks where fill_height=True. min_width: int | None default `= None` minimum pixel width, will wrap if not sufficient screen space to satisfy this value. If a certain scale value results in this Component being narrower than min_width, the min_width parameter will be respected first. api_name: str
Initialization
https://gradio.app/docs/gradio/clearbutton
Gradio - Clearbutton Docs
ent screen space to satisfy this value. If a certain scale value results in this Component being narrower than min_width, the min_width parameter will be respected first. api_name: str | None | Literal['False'] default `= None` show_api: bool default `= False`
Initialization
https://gradio.app/docs/gradio/clearbutton
Gradio - Clearbutton Docs
Class | Interface String Shortcut | Initialization ---|---|--- `gradio.ClearButton` | "clearbutton" | Uses default values
Shortcuts
https://gradio.app/docs/gradio/clearbutton
Gradio - Clearbutton Docs
Description Event listeners allow you to respond to user interactions with the UI components you've defined in a Gradio Blocks app. When a user interacts with an element, such as changing a slider value or uploading an image, a function is called. Supported Event Listeners The ClearButton component supports the following event listeners. Each event listener takes the same parameters, which are listed in the Event Parameters table below. Listener | Description ---|--- `ClearButton.add(fn, ···)` | Adds a component or list of components to the list of components that will be cleared when the button is clicked. `ClearButton.click(fn, ···)` | Triggered when the Button is clicked. Event Parameters Parameters ▼ components: None | Component | list[Component]
Event Listeners
https://gradio.app/docs/gradio/clearbutton
Gradio - Clearbutton Docs
The gr.DownloadData class is a subclass of gr.EventData that specifically carries information about the `.download()` event. When gr.DownloadData is added as a type hint to an argument of an event listener method, a gr.DownloadData object will automatically be passed as the value of that argument. The attributes of this object contains information about the event that triggered the listener.
Description
https://gradio.app/docs/gradio/downloaddata
Gradio - Downloaddata Docs
import gradio as gr def on_download(download_data: gr.DownloadData): return f"Downloaded file: {download_data.file.path}" with gr.Blocks() as demo: files = gr.File() textbox = gr.Textbox() files.download(on_download, None, textbox) demo.launch()
Example Usage
https://gradio.app/docs/gradio/downloaddata
Gradio - Downloaddata Docs
Parameters ▼ file: FileData The file that was downloaded, as a FileData object.
Attributes
https://gradio.app/docs/gradio/downloaddata
Gradio - Downloaddata Docs
Component to select a date and (optionally) a time.
Description
https://gradio.app/docs/gradio/datetime
Gradio - Datetime Docs
**As input component** : Passes text value as a `str` into the function. Your function should accept one of these types: def predict( value: float | datetime | str | None ) ... **As output component** : Expects a tuple pair of datetimes. Your function should return one of these types: def predict(···) -> float | datetime | str | None ... return value
Behavior
https://gradio.app/docs/gradio/datetime
Gradio - Datetime Docs
Parameters ▼ value: float | str | datetime | None default `= None` default value for datetime. include_time: bool default `= True` If True, the component will include time selection. If False, only date selection will be available. type: Literal['timestamp', 'datetime', 'string'] default `= "timestamp"` The type of the value. Can be "timestamp", "datetime", or "string". If "timestamp", the value will be a number representing the start and end date in seconds since epoch. If "datetime", the value will be a datetime object. If "string", the value will be the date entered by the user. timezone: str | None default `= None` The timezone to use for timestamps, such as "US/Pacific" or "Europe/Paris". If None, the timezone will be the local timezone. label: str | I18nData | None default `= None` the label for this component, displayed above the component if `show_label` is `True` and is also used as the header if there are a table of examples for this component. If None and used in a `gr.Interface`, the label will be the name of the parameter this component corresponds to. show_label: bool | None default `= None` if True, will display label. info: str | I18nData | None default `= None` additional component description, appears below the label in smaller font. Supports markdown / HTML syntax. every: float | None default `= None` If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. scale: int | None default `= None` relative size compared to adjacent Components. For example if Components A and B are in a Row, and A has scale=2, and B has scale=1, A will be twice as wide as B. Should be an integer. scale applies in Rows, and to top-level Components in B
Initialization
https://gradio.app/docs/gradio/datetime
Gradio - Datetime Docs
nents. For example if Components A and B are in a Row, and A has scale=2, and B has scale=1, A will be twice as wide as B. Should be an integer. scale applies in Rows, and to top-level Components in Blocks where fill_height=True. min_width: int default `= 160` minimum pixel width, will wrap if not sufficient screen space to satisfy this value. If a certain scale value results in this Component being narrower than min_width, the min_width parameter will be respected first. visible: bool | Literal['hidden'] default `= True` If False, component will be hidden. If "hidden", component will be visually hidden and not take up space in the layout but still exist in the DOM interactive: bool | None default `= None` elem_id: str | None default `= None` elem_classes: list[str] | str | None default `= None` An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. render: bool default `= True` If False, component will not render be rendered in the Blocks context. Should be used if the intention is to assign event listeners now but render the component later. key: int | str | tuple[int | str, ...] | None default `= None` in a gr.render, Components with the same key across re-renders are treated as the same component, not a new component. Properties set in 'preserved_by_key' are not reset across a re-render. preserved_by_key: list[str] | str | None default `= "value"` A list of parameters from this component's constructor. Inside a gr.render() function, if a component is re-rendered with the same key, these (and only these) parameters will be preserved in the UI (if they have been changed by the user or an event listener) instead of re-rendered based on the values provided during constructor.
Initialization
https://gradio.app/docs/gradio/datetime
Gradio - Datetime Docs
y have been changed by the user or an event listener) instead of re-rendered based on the values provided during constructor.
Initialization
https://gradio.app/docs/gradio/datetime
Gradio - Datetime Docs
Class | Interface String Shortcut | Initialization ---|---|--- `gradio.DateTime` | "datetime" | Uses default values
Shortcuts
https://gradio.app/docs/gradio/datetime
Gradio - Datetime Docs
Description Event listeners allow you to respond to user interactions with the UI components you've defined in a Gradio Blocks app. When a user interacts with an element, such as changing a slider value or uploading an image, a function is called. Supported Event Listeners The DateTime component supports the following event listeners. Each event listener takes the same parameters, which are listed in the Event Parameters table below. Listener | Description ---|--- `DateTime.change(fn, ···)` | Triggered when the value of the DateTime changes either because of user input (e.g. a user types in a textbox) OR because of a function update (e.g. an image receives a value from the output of an event trigger). See `.input()` for a listener that is only triggered by user input. `DateTime.submit(fn, ···)` | This listener is triggered when the user presses the Enter key while the DateTime is focused. Event Parameters Parameters ▼ fn: Callable | None | Literal['decorator'] default `= "decorator"` the function to call when this event is triggered. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component. inputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None default `= None` List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list. outputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None default `= None` List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list. api_name: str | None | Literal[False] default `= None` defines how the endpoint appears in the API docs. Can be a string, Non
Event Listeners
https://gradio.app/docs/gradio/datetime
Gradio - Datetime Docs
nction returns no outputs, this should be an empty list. api_name: str | None | Literal[False] default `= None` defines how the endpoint appears in the API docs. Can be a string, None, or False. If set to a string, the endpoint will be exposed in the API docs with the given name. If None (default), the name of the function will be used as the API endpoint. If False, the endpoint will not be exposed in the API docs and downstream apps (including those that `gr.load` this app) will not be able to use this event. api_description: str | None | Literal[False] default `= None` Description of the API endpoint. Can be a string, None, or False. If set to a string, the endpoint will be exposed in the API docs with the given description. If None, the function's docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs. scroll_to_output: bool default `= False` If True, will scroll to output component on completion show_progress: Literal['full', 'minimal', 'hidden'] default `= "full"` how to show the progress animation while event is running: "full" shows a spinner which covers the output component area as well as a runtime display in the upper right corner, "minimal" only shows the runtime display, "hidden" shows no progress animation at all show_progress_on: Component | list[Component] | None default `= None` Component or list of components to show the progress animation on. If None, will show the progress animation on all of the output components. queue: bool default `= True` If True, will place the request on the queue, if the queue has been enabled. If False, will not put this event on the queue, even if the queue has been enabled. If None, will use the queue setting of the gradio app. batch: bool default `= False` If True, then the function should process a batch of inputs, meaning that i
Event Listeners
https://gradio.app/docs/gradio/datetime
Gradio - Datetime Docs
eue has been enabled. If None, will use the queue setting of the gradio app. batch: bool default `= False` If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component. max_batch_size: int default `= 4` Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True) preprocess: bool default `= True` If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component). postprocess: bool default `= True` If False, will not run postprocessing of component data before returning 'fn' output to the browser. cancels: dict[str, Any] | list[dict[str, Any]] | None default `= None` A list of other events to cancel when this listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish. trigger_mode: Literal['once', 'multiple', 'always_last'] | None default `= None` If "once" (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to "multiple", unlimited submissions are allowed while pending, and "always_last" (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete. js: str | Literal[True] | None default `= None` Optional frontend js meth
Event Listeners
https://gradio.app/docs/gradio/datetime
Gradio - Datetime Docs
for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete. js: str | Literal[True] | None default `= None` Optional frontend js method to run before running 'fn'. Input arguments for js method are values of 'inputs' and 'outputs', return should be a list of values for output components. concurrency_limit: int | None | Literal['default'] default `= "default"` If set, this is the maximum number of this event that can be running simultaneously. Can be set to None to mean no concurrency_limit (any number of this event can be running simultaneously). Set to "default" to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default). concurrency_id: str | None default `= None` If set, this is the id of the concurrency group. Events with the same concurrency_id will be limited by the lowest set concurrency_limit. show_api: bool default `= True` whether to show this event in the "view API" page of the Gradio app, or in the ".view_api()" method of the Gradio clients. Unlike setting api_name to False, setting show_api to False will still allow downstream apps as well as the Clients to use this event. If fn is None, show_api will automatically be set to False. time_limit: int | None default `= None` stream_every: float default `= 0.5` like_user_message: bool default `= False` key: int | str | tuple[int | str, ...] | None default `= None` A unique key for this event listener to be used in @gr.render(). If set, this value identifies an event as identical across re-renders when the key is identical. validator: Callable | None default `= None` Optional validation function to run before the main function. If provided, this function will be executed first with queue=False, and only if it completes succe
Event Listeners
https://gradio.app/docs/gradio/datetime
Gradio - Datetime Docs
tor: Callable | None default `= None` Optional validation function to run before the main function. If provided, this function will be executed first with queue=False, and only if it completes successfully will the main function be called. The validator receives the same inputs as the main function and should return a `gr.validate()` for each input value.
Event Listeners
https://gradio.app/docs/gradio/datetime
Gradio - Datetime Docs
Creates an image component that can be used to upload images (as an input) or display images (as an output).
Description
https://gradio.app/docs/gradio/imageslider
Gradio - Imageslider Docs
**As input component** : Passes the uploaded image as a tuple of `numpy.array`, `PIL.Image` or `str` filepath depending on `type`. Your function should accept one of these types: def predict( value: tuple[ str | PIL.Image.Image | np.ndarray | None, str | PIL.Image.Image | np.ndarray | None ] ) ... **As output component** : Expects a tuple of `numpy.array`, `PIL.Image`, or `str` or `pathlib.Path` filepath to an image which is displayed. Your function should return one of these types: def predict(···) -> np.ndarray | PIL.Image.Image | str | Path | None ... return value
Behavior
https://gradio.app/docs/gradio/imageslider
Gradio - Imageslider Docs
Parameters ▼ value: image_tuple | Callable | None default `= None` A tuple of PIL Image, numpy array, path or URL for the default value that ImageSlider component is going to take, this pair of images should be of equal size. If a function is provided, the function will be called each time the app loads to set the initial value of this component. format: str default `= "webp"` File format (e.g. "png" or "gif"). Used to save image if it does not already have a valid format (e.g. if the image is being returned to the frontend as a numpy array or PIL Image). The format should be supported by the PIL library. Applies both when this component is used as an input or output. This parameter has no effect on SVG files. height: int | str | None default `= None` The height of the component, specified in pixels if a number is passed, or in CSS units if a string is passed. This has no effect on the preprocessed tuple of image file or numpy array, but will affect the displayed image. width: int | str | None default `= None` The width of the component, specified in pixels if a number is passed, or in CSS units if a string is passed. This has no effect on the preprocessed tuple of image file or numpy array, but will affect the displayed image. image_mode: Literal['1', 'L', 'P', 'RGB', 'RGBA', 'CMYK', 'YCbCr', 'LAB', 'HSV', 'I', 'F'] | None default `= "RGB"` The pixel format and color depth that the image should be loaded and preprocessed as. "RGB" will load the image as a color image, or "L" as black- and-white. See https://pillow.readthedocs.io/en/stable/handbook/concepts.html for other supported image modes and their meaning. This parameter has no effect on SVG or GIF files. If set to None, the image_mode will be inferred from the image file types (e.g. "RGBA" for a .png image, "RGB" in most other cases). type: Literal['numpy', 'pil', 'filepath'] default `= "numpy"` The for
Initialization
https://gradio.app/docs/gradio/imageslider
Gradio - Imageslider Docs
image_mode will be inferred from the image file types (e.g. "RGBA" for a .png image, "RGB" in most other cases). type: Literal['numpy', 'pil', 'filepath'] default `= "numpy"` The format the images are converted to before being passed into the prediction function. "numpy" converts the images to numpy arrays with shape (height, width, 3) and values from 0 to 255, "pil" converts the images to PIL image objects, "filepath" passes str paths to temporary files containing the images. To support animated GIFs in input, the `type` should be set to "filepath" or "pil". To support SVGs, the `type` should be set to "filepath". label: str | None default `= None` the label for this component. Appears above the component and is also used as the header if there are a table of examples for this component. If None and used in a `gr.Interface`, the label will be the name of the parameter this component is assigned to. every: Timer | float | None default `= None` Continously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer. inputs: Component | list[Component] | set[Component] | None default `= None` Components that are used as inputs to calculate `value` if `value` is a function (has no effect otherwise). `value` is recalculated any time the inputs change. show_label: bool | None default `= None` if True, will display label. show_download_button: bool default `= True` If True, will display button to download image. Only applies if interactive is False (e.g. if the component is used as an output). container: bool default `= True` If True, will place the component in a container - providing some extra padding around the border. scale: int | None default `= None` relative size compared to adjacent Comp
Initialization
https://gradio.app/docs/gradio/imageslider
Gradio - Imageslider Docs
= True` If True, will place the component in a container - providing some extra padding around the border. scale: int | None default `= None` relative size compared to adjacent Components. For example if Components A and B are in a Row, and A has scale=2, and B has scale=1, A will be twice as wide as B. Should be an integer. scale applies in Rows, and to top-level Components in Blocks where fill_height=True. min_width: int default `= 160` minimum pixel width, will wrap if not sufficient screen space to satisfy this value. If a certain scale value results in this Component being narrower than min_width, the min_width parameter will be respected first. interactive: bool | None default `= None` if True, will allow users to upload and edit an image; if False, can only be used to display images. If not provided, this is inferred based on whether the component is used as an input or output. visible: bool | Literal['hidden'] default `= True` If False, component will be hidden. If "hidden", component will be visually hidden and not take up space in the layout but still exist in the DOM elem_id: str | None default `= None` An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. elem_classes: list[str] | str | None default `= None` An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. render: bool default `= True` If False, component will not render be rendered in the Blocks context. Should be used if the intention is to assign event listeners now but render the component later. key: int | str | tuple[int | str, ...] | None default `= None` in a gr.render, Components with the same key across re-renders are treated as the same component, not a new component. Properties set in 'preserved_by_key'
Initialization
https://gradio.app/docs/gradio/imageslider
Gradio - Imageslider Docs
le[int | str, ...] | None default `= None` in a gr.render, Components with the same key across re-renders are treated as the same component, not a new component. Properties set in 'preserved_by_key' are not reset across a re-render. preserved_by_key: list[str] | str | None default `= "value"` A list of parameters from this component's constructor. Inside a gr.render() function, if a component is re-rendered with the same key, these (and only these) parameters will be preserved in the UI (if they have been changed by the user or an event listener) instead of re-rendered based on the values provided during constructor. show_fullscreen_button: bool default `= True` If True, will show a fullscreen icon in the corner of the component that allows user to view the image in fullscreen mode. If False, icon does not appear. slider_position: float default `= 50` The position of the slider as a percentage of the width of the image, between 0 and 100. max_height: int default `= 500` The maximum height of the image.
Initialization
https://gradio.app/docs/gradio/imageslider
Gradio - Imageslider Docs
Class | Interface String Shortcut | Initialization ---|---|--- `gradio.ImageSlider` | "imageslider" | Uses default values
Shortcuts
https://gradio.app/docs/gradio/imageslider
Gradio - Imageslider Docs
imageslider Open in 🎢 ↗ import gradio as gr from PIL import ImageFilter def img_to_slider(im): if not im: return im return (im, im.filter(filter=ImageFilter.GaussianBlur(radius=10))) def slider_to_self(im): if not im or not im[0]: return im return (im[0], im[0].filter(filter=ImageFilter.GaussianBlur(radius=10))) def slider_to_self_two(im): return im def position_to_slider(pos): return gr.ImageSlider(slider_position=pos) with gr.Blocks() as demo: gr.Markdown(" img to image slider") with gr.Row(): img1 = gr.Image(label="Blur image", type="pil") img2 = gr.ImageSlider(label="Blur image", type="pil") btn = gr.Button("Blur image") btn.click(img_to_slider, inputs=img1, outputs=img2) gr.Markdown("unified image slider") with gr.Row(): img3 = gr.ImageSlider(label="Blur image", type="pil") img3.upload(slider_to_self, inputs=img3, outputs=img3) pos = gr.Slider(label="Position", value=50, minimum=0, maximum=100, step=0.01) pos.change(position_to_slider, inputs=pos, outputs=img3, show_progress="hidden") if __name__ == "__main__": demo.launch() import gradio as gr from PIL import ImageFilter def img_to_slider(im): if not im: return im return (im, im.filter(filter=ImageFilter.GaussianBlur(radius=10))) def slider_to_self(im): if not im or not im[0]: return im return (im[0], im[0].filter(filter=ImageFilter.GaussianBlur(radius=10))) def slider_to_self_two(im): return im def position_to_slider(pos): return gr.ImageSlider(slider_position=pos) with gr.Blocks() as demo: gr.Markdown("img to image slider") with gr.Row(): img1 = gr.Image(label="Blur image", type="pil") img2 = gr.ImageSlider(label="Blur image", type="pil") btn = gr.Button("Blur image") btn.click(img_to_slider, inputs=img1, outputs=img2) gr.Markdown("unified image slider") with gr.Row()
Demos
https://gradio.app/docs/gradio/imageslider
Gradio - Imageslider Docs
r(label="Blur image", type="pil") btn = gr.Button("Blur image") btn.click(img_to_slider, inputs=img1, outputs=img2) gr.Markdown("unified image slider") with gr.Row(): img3 = gr.ImageSlider(label="Blur image", type="pil") img3.upload(slider_to_self, inputs=img3, outputs=img3) pos = gr.Slider(label="Position", value=50, minimum=0, maximum=100, step=0.01) pos.change(position_to_slider, inputs=pos, outputs=img3, show_progress="hidden") if __name__ == "__main__": demo.launch()
Demos
https://gradio.app/docs/gradio/imageslider
Gradio - Imageslider Docs
Description Event listeners allow you to respond to user interactions with the UI components you've defined in a Gradio Blocks app. When a user interacts with an element, such as changing a slider value or uploading an image, a function is called. Supported Event Listeners The ImageSlider component supports the following event listeners. Each event listener takes the same parameters, which are listed in the Event Parameters table below. Listener | Description ---|--- `ImageSlider.clear(fn, ···)` | This listener is triggered when the user clears the ImageSlider using the clear button for the component. `ImageSlider.change(fn, ···)` | Triggered when the value of the ImageSlider changes either because of user input (e.g. a user types in a textbox) OR because of a function update (e.g. an image receives a value from the output of an event trigger). See `.input()` for a listener that is only triggered by user input. `ImageSlider.stream(fn, ···)` | This listener is triggered when the user streams the ImageSlider. `ImageSlider.select(fn, ···)` | Event listener for when the user selects or deselects the ImageSlider. Uses event data gradio.SelectData to carry `value` referring to the label of the ImageSlider, and `selected` to refer to state of the ImageSlider. See EventData documentation on how to use this event data `ImageSlider.upload(fn, ···)` | This listener is triggered when the user uploads a file into the ImageSlider. `ImageSlider.input(fn, ···)` | This listener is triggered when the user changes the value of the ImageSlider. Event Parameters Parameters ▼ fn: Callable | None | Literal['decorator'] default `= "decorator"` the function to call when this event is triggered. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one out
Event Listeners
https://gradio.app/docs/gradio/imageslider
Gradio - Imageslider Docs
function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component. inputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None default `= None` List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list. outputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None default `= None` List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list. api_name: str | None | Literal[False] default `= None` defines how the endpoint appears in the API docs. Can be a string, None, or False. If set to a string, the endpoint will be exposed in the API docs with the given name. If None (default), the name of the function will be used as the API endpoint. If False, the endpoint will not be exposed in the API docs and downstream apps (including those that `gr.load` this app) will not be able to use this event. api_description: str | None | Literal[False] default `= None` Description of the API endpoint. Can be a string, None, or False. If set to a string, the endpoint will be exposed in the API docs with the given description. If None, the function's docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs. scroll_to_output: bool default `= False` If True, will scroll to output component on completion show_progress: Literal['full', 'minimal', 'hidden'] default `= "full"` how to show the progress animation while event is running: "full" shows a spinner which covers the output component area as well as a runtime display in the upper right corner, "minimal" only shows the runtime display, "hi
Event Listeners
https://gradio.app/docs/gradio/imageslider
Gradio - Imageslider Docs
ss animation while event is running: "full" shows a spinner which covers the output component area as well as a runtime display in the upper right corner, "minimal" only shows the runtime display, "hidden" shows no progress animation at all show_progress_on: Component | list[Component] | None default `= None` Component or list of components to show the progress animation on. If None, will show the progress animation on all of the output components. queue: bool default `= True` If True, will place the request on the queue, if the queue has been enabled. If False, will not put this event on the queue, even if the queue has been enabled. If None, will use the queue setting of the gradio app. batch: bool default `= False` If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component. max_batch_size: int default `= 4` Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True) preprocess: bool default `= True` If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component). postprocess: bool default `= True` If False, will not run postprocessing of component data before returning 'fn' output to the browser. cancels: dict[str, Any] | list[dict[str, Any]] | None default `= None` A list of other events to cancel when this listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functio
Event Listeners
https://gradio.app/docs/gradio/imageslider
Gradio - Imageslider Docs
ts to cancel when this listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish. trigger_mode: Literal['once', 'multiple', 'always_last'] | None default `= None` If "once" (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to "multiple", unlimited submissions are allowed while pending, and "always_last" (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete. js: str | Literal[True] | None default `= None` Optional frontend js method to run before running 'fn'. Input arguments for js method are values of 'inputs' and 'outputs', return should be a list of values for output components. concurrency_limit: int | None | Literal['default'] default `= "default"` If set, this is the maximum number of this event that can be running simultaneously. Can be set to None to mean no concurrency_limit (any number of this event can be running simultaneously). Set to "default" to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default). concurrency_id: str | None default `= None` If set, this is the id of the concurrency group. Events with the same concurrency_id will be limited by the lowest set concurrency_limit. show_api: bool default `= True` whether to show this event in the "view API" page of the Gradio app, or in the ".view_api()" method of the Gradio clients. Unlike setting api_name to False, setting show_api to False will still allow downstream apps as well as the Clients to use this event. If fn is None, show_api will automati
Event Listeners
https://gradio.app/docs/gradio/imageslider
Gradio - Imageslider Docs
thod of the Gradio clients. Unlike setting api_name to False, setting show_api to False will still allow downstream apps as well as the Clients to use this event. If fn is None, show_api will automatically be set to False. time_limit: int | None default `= None` stream_every: float default `= 0.5` like_user_message: bool default `= False` key: int | str | tuple[int | str, ...] | None default `= None` A unique key for this event listener to be used in @gr.render(). If set, this value identifies an event as identical across re-renders when the key is identical. validator: Callable | None default `= None` Optional validation function to run before the main function. If provided, this function will be executed first with queue=False, and only if it completes successfully will the main function be called. The validator receives the same inputs as the main function and should return a `gr.validate()` for each input value.
Event Listeners
https://gradio.app/docs/gradio/imageslider
Gradio - Imageslider Docs
Creates a "Sign In" button that redirects the user to sign in with Hugging Face OAuth. Once the user is signed in, the button will act as a logout button, and you can retrieve a signed-in user's profile by adding a parameter of type `gr.OAuthProfile` to any Gradio function. This will only work if this Gradio app is running in a Hugging Face Space. Permissions for the OAuth app can be configured in the Spaces README file, as described here: <https://huggingface.co/docs/hub/en/spaces-oauth.> For local development, instead of OAuth, the local Hugging Face account that is logged in (via `hf auth login`) will be available through the `gr.OAuthProfile` object.
Description
https://gradio.app/docs/gradio/loginbutton
Gradio - Loginbutton Docs
**As input component** : (Rarely used) the `str` corresponding to the button label when the button is clicked Your function should accept one of these types: def predict( value: str | None ) ... **As output component** : string corresponding to the button label Your function should return one of these types: def predict(···) -> str | None ... return value
Behavior
https://gradio.app/docs/gradio/loginbutton
Gradio - Loginbutton Docs
Parameters ▼ value: str default `= "Sign in with Hugging Face"` logout_value: str default `= "Logout ({})"` The text to display when the user is signed in. The string should contain a placeholder for the username with a call-to-action to logout, e.g. "Logout ({})". every: Timer | float | None default `= None` inputs: Component | list[Component] | set[Component] | None default `= None` variant: Literal['primary', 'secondary', 'stop', 'huggingface'] default `= "huggingface"` size: Literal['sm', 'md', 'lg'] default `= "lg"` icon: str | Path | None default `= "/home/runner/work/gradio/gradio/gradio/icons/huggingface- logo.svg"` link: str | None default `= None` visible: bool | Literal['hidden'] default `= True` interactive: bool default `= True` elem_id: str | None default `= None` elem_classes: list[str] | str | None default `= None` render: bool default `= True` key: int | str | tuple[int | str, ...] | None default `= None` preserved_by_key: list[str] | str | None default `= "value"` scale: int | None default `= None` min_width: int | None default `= None`
Initialization
https://gradio.app/docs/gradio/loginbutton
Gradio - Loginbutton Docs
Class | Interface String Shortcut | Initialization ---|---|--- `gradio.LoginButton` | "loginbutton" | Uses default values
Shortcuts
https://gradio.app/docs/gradio/loginbutton
Gradio - Loginbutton Docs
login_with_huggingface Open in 🎢 ↗ from __future__ import annotations import gradio as gr from huggingface_hub import whoami def hello(profile: gr.OAuthProfile | None) -> str: if profile is None: return "I don't know you." return f"Hello {profile.name}" def list_organizations(oauth_token: gr.OAuthToken | None) -> str: if oauth_token is None: return "Please deploy this on Spaces and log in to list organizations." org_names = [org["name"] for org in whoami(oauth_token.token)["orgs"]] return f"You belong to {', '.join(org_names)}." with gr.Blocks() as demo: gr.LoginButton() m1 = gr.Markdown() m2 = gr.Markdown() demo.load(hello, inputs=None, outputs=m1) demo.load(list_organizations, inputs=None, outputs=m2) if __name__ == "__main__": demo.launch() from __future__ import annotations import gradio as gr from huggingface_hub import whoami def hello(profile: gr.OAuthProfile | None) -> str: if profile is None: return "I don't know you." return f"Hello {profile.name}" def list_organizations(oauth_token: gr.OAuthToken | None) -> str: if oauth_token is None: return "Please deploy this on Spaces and log in to list organizations." org_names = [org["name"] for org in whoami(oauth_token.token)["orgs"]] return f"You belong to {', '.join(org_names)}." with gr.Blocks() as demo: gr.LoginButton() m1 = gr.Markdown() m2 = gr.Markdown() demo.load(hello, inputs=None, outputs=m1) demo.load(list_organizations, inputs=None, outputs=m2) if __name__ == "__main__": demo.launch()
Demos
https://gradio.app/docs/gradio/loginbutton
Gradio - Loginbutton Docs
Description Event listeners allow you to respond to user interactions with the UI components you've defined in a Gradio Blocks app. When a user interacts with an element, such as changing a slider value or uploading an image, a function is called. Supported Event Listeners The LoginButton component supports the following event listeners. Each event listener takes the same parameters, which are listed in the Event Parameters table below. Listener | Description ---|--- `LoginButton.click(fn, ···)` | Triggered when the Button is clicked. Event Parameters Parameters ▼ fn: Callable | None | Literal['decorator'] default `= "decorator"` the function to call when this event is triggered. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component. inputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None default `= None` List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list. outputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None default `= None` List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list. api_name: str | None | Literal[False] default `= None` defines how the endpoint appears in the API docs. Can be a string, None, or False. If set to a string, the endpoint will be exposed in the API docs with the given name. If None (default), the name of the function will be used as the API endpoint. If False, the endpoint will not be exposed in the API docs and downstream apps (including those that `gr.load` this app) will not be able to use this event. api_descripti
Event Listeners
https://gradio.app/docs/gradio/loginbutton
Gradio - Loginbutton Docs
API endpoint. If False, the endpoint will not be exposed in the API docs and downstream apps (including those that `gr.load` this app) will not be able to use this event. api_description: str | None | Literal[False] default `= None` Description of the API endpoint. Can be a string, None, or False. If set to a string, the endpoint will be exposed in the API docs with the given description. If None, the function's docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs. scroll_to_output: bool default `= False` If True, will scroll to output component on completion show_progress: Literal['full', 'minimal', 'hidden'] default `= "full"` how to show the progress animation while event is running: "full" shows a spinner which covers the output component area as well as a runtime display in the upper right corner, "minimal" only shows the runtime display, "hidden" shows no progress animation at all show_progress_on: Component | list[Component] | None default `= None` Component or list of components to show the progress animation on. If None, will show the progress animation on all of the output components. queue: bool default `= True` If True, will place the request on the queue, if the queue has been enabled. If False, will not put this event on the queue, even if the queue has been enabled. If None, will use the queue setting of the gradio app. batch: bool default `= False` If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component. max_batch_size: int default `= 4` Maximu
Event Listeners
https://gradio.app/docs/gradio/loginbutton
Gradio - Loginbutton Docs
ed* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component. max_batch_size: int default `= 4` Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True) preprocess: bool default `= True` If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component). postprocess: bool default `= True` If False, will not run postprocessing of component data before returning 'fn' output to the browser. cancels: dict[str, Any] | list[dict[str, Any]] | None default `= None` A list of other events to cancel when this listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish. trigger_mode: Literal['once', 'multiple', 'always_last'] | None default `= None` If "once" (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to "multiple", unlimited submissions are allowed while pending, and "always_last" (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete. js: str | Literal[True] | None default `= None` Optional frontend js method to run before running 'fn'. Input arguments for js method are values of 'inputs' and 'outputs', return should be a list of values for output components. concurrency_limit: int | None | Literal['default'] default `= "default"` If set, this is the maximum number of this event that can be running simultaneously. Can be set to None to mean no c
Event Listeners
https://gradio.app/docs/gradio/loginbutton
Gradio - Loginbutton Docs
concurrency_limit: int | None | Literal['default'] default `= "default"` If set, this is the maximum number of this event that can be running simultaneously. Can be set to None to mean no concurrency_limit (any number of this event can be running simultaneously). Set to "default" to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default). concurrency_id: str | None default `= None` If set, this is the id of the concurrency group. Events with the same concurrency_id will be limited by the lowest set concurrency_limit. show_api: bool default `= True` whether to show this event in the "view API" page of the Gradio app, or in the ".view_api()" method of the Gradio clients. Unlike setting api_name to False, setting show_api to False will still allow downstream apps as well as the Clients to use this event. If fn is None, show_api will automatically be set to False. time_limit: int | None default `= None` stream_every: float default `= 0.5` like_user_message: bool default `= False` key: int | str | tuple[int | str, ...] | None default `= None` A unique key for this event listener to be used in @gr.render(). If set, this value identifies an event as identical across re-renders when the key is identical. validator: Callable | None default `= None` Optional validation function to run before the main function. If provided, this function will be executed first with queue=False, and only if it completes successfully will the main function be called. The validator receives the same inputs as the main function and should return a `gr.validate()` for each input value.
Event Listeners
https://gradio.app/docs/gradio/loginbutton
Gradio - Loginbutton Docs
Creates a navigation bar component for multipage Gradio apps. The navbar component allows customizing the appearance of the navbar for that page. Only one Navbar component can exist per page in a Blocks app, and it can be placed anywhere within the page. The Navbar component is designed to control the appearance of the navigation bar in multipage applications. When present in a Blocks app, its properties override the default navbar behavior.
Description
https://gradio.app/docs/gradio/navbar
Gradio - Navbar Docs
**As input component** : The preprocessed input data sent to the user's function in the backend. Your function should accept one of these types: def predict( value: list[tuple[str, str]] | None ) ... **As output component** : The output data received by the component from the user's function in the backend. Your function should return one of these types: def predict(···) -> list[tuple[str, str]] | None ... return value
Behavior
https://gradio.app/docs/gradio/navbar
Gradio - Navbar Docs
Parameters ▼ value: list[tuple[str, str]] | None default `= None` If a list of tuples of (page_name, page_path) are provided, these additional pages will be added to the navbar alongside the existing pages defined in the Blocks app. The page_path can be either a relative path for internal Gradio app pages (e.g., "analytics") or an absolute URL for external links (e.g., "https://twitter.com/username"). Otherwise, only the pages defined using the `Blocks.route` method will be displayed. Example: [("Dashboard", "dashboard"), ("About", "https://twitter.com/abidlabs")] visible: bool default `= True` If True, the navbar will be visible. If False, the navbar will be hidden. main_page_name: str | Literal[False] default `= "Home"` The title to display in the navbar for the main page of the Gradio. If False, the main page will not be displayed in the navbar. elem_id: str | None default `= None` An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. elem_classes: list[str] | str | None default `= None` An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. render: bool default `= True` If False, component will not render be rendered in the Blocks context. Should be used if the intention is to assign event listeners now but render the component later. key: int | str | tuple[int | str, ...] | None default `= None` in a gr.render, Components with the same key across re-renders are treated as the same component, not a new component.
Initialization
https://gradio.app/docs/gradio/navbar
Gradio - Navbar Docs
Class | Interface String Shortcut | Initialization ---|---|--- `gradio.Navbar` | "navbar" | Uses default values
Shortcuts
https://gradio.app/docs/gradio/navbar
Gradio - Navbar Docs
Description Event listeners allow you to respond to user interactions with the UI components you've defined in a Gradio Blocks app. When a user interacts with an element, such as changing a slider value or uploading an image, a function is called. Supported Event Listeners The Navbar component supports the following event listeners. Each event listener takes the same parameters, which are listed in the Event Parameters table below. Listener | Description ---|--- `Navbar.change(fn, ···)` | Triggered when the value of the Navbar changes either because of user input (e.g. a user types in a textbox) OR because of a function update (e.g. an image receives a value from the output of an event trigger). See `.input()` for a listener that is only triggered by user input. Event Parameters Parameters ▼ fn: Callable | None | Literal['decorator'] default `= "decorator"` the function to call when this event is triggered. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component. inputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None default `= None` List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list. outputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None default `= None` List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list. api_name: str | None | Literal[False] default `= None` defines how the endpoint appears in the API docs. Can be a string, None, or False. If set to a string, the endpoint will be exposed in the API docs with the given name. If None (default), the name of t
Event Listeners
https://gradio.app/docs/gradio/navbar
Gradio - Navbar Docs
efines how the endpoint appears in the API docs. Can be a string, None, or False. If set to a string, the endpoint will be exposed in the API docs with the given name. If None (default), the name of the function will be used as the API endpoint. If False, the endpoint will not be exposed in the API docs and downstream apps (including those that `gr.load` this app) will not be able to use this event. api_description: str | None | Literal[False] default `= None` Description of the API endpoint. Can be a string, None, or False. If set to a string, the endpoint will be exposed in the API docs with the given description. If None, the function's docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs. scroll_to_output: bool default `= False` If True, will scroll to output component on completion show_progress: Literal['full', 'minimal', 'hidden'] default `= "full"` how to show the progress animation while event is running: "full" shows a spinner which covers the output component area as well as a runtime display in the upper right corner, "minimal" only shows the runtime display, "hidden" shows no progress animation at all show_progress_on: Component | list[Component] | None default `= None` Component or list of components to show the progress animation on. If None, will show the progress animation on all of the output components. queue: bool default `= True` If True, will place the request on the queue, if the queue has been enabled. If False, will not put this event on the queue, even if the queue has been enabled. If None, will use the queue setting of the gradio app. batch: bool default `= False` If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size
Event Listeners
https://gradio.app/docs/gradio/navbar
Gradio - Navbar Docs
e, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component. max_batch_size: int default `= 4` Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True) preprocess: bool default `= True` If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component). postprocess: bool default `= True` If False, will not run postprocessing of component data before returning 'fn' output to the browser. cancels: dict[str, Any] | list[dict[str, Any]] | None default `= None` A list of other events to cancel when this listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish. trigger_mode: Literal['once', 'multiple', 'always_last'] | None default `= None` If "once" (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to "multiple", unlimited submissions are allowed while pending, and "always_last" (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete. js: str | Literal[True] | None default `= None` Optional frontend js method to run before running 'fn'. Input arguments for js method are values of 'inputs' and 'outputs', return should be a list of value
Event Listeners
https://gradio.app/docs/gradio/navbar
Gradio - Navbar Docs
r | Literal[True] | None default `= None` Optional frontend js method to run before running 'fn'. Input arguments for js method are values of 'inputs' and 'outputs', return should be a list of values for output components. concurrency_limit: int | None | Literal['default'] default `= "default"` If set, this is the maximum number of this event that can be running simultaneously. Can be set to None to mean no concurrency_limit (any number of this event can be running simultaneously). Set to "default" to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default). concurrency_id: str | None default `= None` If set, this is the id of the concurrency group. Events with the same concurrency_id will be limited by the lowest set concurrency_limit. show_api: bool default `= True` whether to show this event in the "view API" page of the Gradio app, or in the ".view_api()" method of the Gradio clients. Unlike setting api_name to False, setting show_api to False will still allow downstream apps as well as the Clients to use this event. If fn is None, show_api will automatically be set to False. time_limit: int | None default `= None` stream_every: float default `= 0.5` like_user_message: bool default `= False` key: int | str | tuple[int | str, ...] | None default `= None` A unique key for this event listener to be used in @gr.render(). If set, this value identifies an event as identical across re-renders when the key is identical. validator: Callable | None default `= None` Optional validation function to run before the main function. If provided, this function will be executed first with queue=False, and only if it completes successfully will the main function be called. The validator receives the same inputs as the main function and should return a `gr.valid
Event Listeners
https://gradio.app/docs/gradio/navbar
Gradio - Navbar Docs
ll be executed first with queue=False, and only if it completes successfully will the main function be called. The validator receives the same inputs as the main function and should return a `gr.validate()` for each input value.
Event Listeners
https://gradio.app/docs/gradio/navbar
Gradio - Navbar Docs
Special component that ticks at regular intervals when active. It is not visible, and only used to trigger events at a regular interval through the `tick` event listener.
Description
https://gradio.app/docs/gradio/timer
Gradio - Timer Docs
**As input component** : The interval of the timer as a float. Your function should accept one of these types: def predict( value: float | None ) ... **As output component** : The interval of the timer as a float or None. Your function should return one of these types: def predict(···) -> float | None ... return value
Behavior
https://gradio.app/docs/gradio/timer
Gradio - Timer Docs
Parameters ▼ value: float default `= 1` Interval in seconds between each tick. active: bool default `= True` Whether the timer is active. render: bool default `= True` If False, component will not render be rendered in the Blocks context. Should be used if the intention is to assign event listeners now but render the component later.
Initialization
https://gradio.app/docs/gradio/timer
Gradio - Timer Docs
Class | Interface String Shortcut | Initialization ---|---|--- `gradio.Timer` | "timer" | Uses default values
Shortcuts
https://gradio.app/docs/gradio/timer
Gradio - Timer Docs
Description Event listeners allow you to respond to user interactions with the UI components you've defined in a Gradio Blocks app. When a user interacts with an element, such as changing a slider value or uploading an image, a function is called. Supported Event Listeners The Timer component supports the following event listeners. Each event listener takes the same parameters, which are listed in the Event Parameters table below. Listener | Description ---|--- `Timer.tick(fn, ···)` | This listener is triggered at regular intervals defined by the Timer. Event Parameters Parameters ▼ fn: Callable | None | Literal['decorator'] default `= "decorator"` the function to call when this event is triggered. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component. inputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None default `= None` List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list. outputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None default `= None` List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list. api_name: str | None | Literal[False] default `= None` defines how the endpoint appears in the API docs. Can be a string, None, or False. If set to a string, the endpoint will be exposed in the API docs with the given name. If None (default), the name of the function will be used as the API endpoint. If False, the endpoint will not be exposed in the API docs and downstream apps (including those that `gr.load` this app) will not be able to use this event.
Event Listeners
https://gradio.app/docs/gradio/timer
Gradio - Timer Docs
ill be used as the API endpoint. If False, the endpoint will not be exposed in the API docs and downstream apps (including those that `gr.load` this app) will not be able to use this event. api_description: str | None | Literal[False] default `= None` Description of the API endpoint. Can be a string, None, or False. If set to a string, the endpoint will be exposed in the API docs with the given description. If None, the function's docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs. scroll_to_output: bool default `= False` If True, will scroll to output component on completion show_progress: Literal['full', 'minimal', 'hidden'] default `= "hidden"` how to show the progress animation while event is running: "full" shows a spinner which covers the output component area as well as a runtime display in the upper right corner, "minimal" only shows the runtime display, "hidden" shows no progress animation at all show_progress_on: Component | list[Component] | None default `= None` Component or list of components to show the progress animation on. If None, will show the progress animation on all of the output components. queue: bool default `= True` If True, will place the request on the queue, if the queue has been enabled. If False, will not put this event on the queue, even if the queue has been enabled. If None, will use the queue setting of the gradio app. batch: bool default `= False` If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component. max_batch_size: int
Event Listeners
https://gradio.app/docs/gradio/timer
Gradio - Timer Docs
ction is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component. max_batch_size: int default `= 4` Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True) preprocess: bool default `= True` If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component). postprocess: bool default `= True` If False, will not run postprocessing of component data before returning 'fn' output to the browser. cancels: dict[str, Any] | list[dict[str, Any]] | None default `= None` A list of other events to cancel when this listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish. trigger_mode: Literal['once', 'multiple', 'always_last'] | None default `= None` If "once" (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to "multiple", unlimited submissions are allowed while pending, and "always_last" (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete. js: str | Literal[True] | None default `= None` Optional frontend js method to run before running 'fn'. Input arguments for js method are values of 'inputs' and 'outputs', return should be a list of values for output components. concurrency_limit: int | None | Literal['default'] default `= "default"` If set, this is the maximum number of this event that can be running simultaneously. Can be set
Event Listeners
https://gradio.app/docs/gradio/timer
Gradio - Timer Docs
t components. concurrency_limit: int | None | Literal['default'] default `= "default"` If set, this is the maximum number of this event that can be running simultaneously. Can be set to None to mean no concurrency_limit (any number of this event can be running simultaneously). Set to "default" to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default). concurrency_id: str | None default `= None` If set, this is the id of the concurrency group. Events with the same concurrency_id will be limited by the lowest set concurrency_limit. show_api: bool default `= True` whether to show this event in the "view API" page of the Gradio app, or in the ".view_api()" method of the Gradio clients. Unlike setting api_name to False, setting show_api to False will still allow downstream apps as well as the Clients to use this event. If fn is None, show_api will automatically be set to False. time_limit: int | None default `= None` stream_every: float default `= 0.5` like_user_message: bool default `= False` key: int | str | tuple[int | str, ...] | None default `= None` A unique key for this event listener to be used in @gr.render(). If set, this value identifies an event as identical across re-renders when the key is identical. validator: Callable | None default `= None` Optional validation function to run before the main function. If provided, this function will be executed first with queue=False, and only if it completes successfully will the main function be called. The validator receives the same inputs as the main function and should return a `gr.validate()` for each input value.
Event Listeners
https://gradio.app/docs/gradio/timer
Gradio - Timer Docs
each input value.
Event Listeners
https://gradio.app/docs/gradio/timer
Gradio - Timer Docs
Creates an image component that can be used to upload images (as an input) or display images (as an output).
Description
https://gradio.app/docs/gradio/image
Gradio - Image Docs
**As input component** : Passes the uploaded image as a `numpy.array`, `PIL.Image` or `str` filepath depending on `type`. Your function should accept one of these types: def predict( value: np.ndarray | PIL.Image.Image | str | None ) ... **As output component** : Expects a `numpy.array`, `PIL.Image`, or `str` or `pathlib.Path` filepath to an image which is displayed. Your function should return one of these types: def predict(···) -> np.ndarray | PIL.Image.Image | str | Path | None ... return value
Behavior
https://gradio.app/docs/gradio/image
Gradio - Image Docs
Parameters ▼ value: str | PIL.Image.Image | np.ndarray | Callable | None default `= None` A `PIL.Image`, `numpy.array`, `pathlib.Path`, or `str` filepath or URL for the default value that Image component is going to take. If a function is provided, the function will be called each time the app loads to set the initial value of this component. format: str default `= "webp"` File format (e.g. "png" or "gif"). Used to save image if it does not already have a valid format (e.g. if the image is being returned to the frontend as a numpy array or PIL Image). The format should be supported by the PIL library. Applies both when this component is used as an input or output. This parameter has no effect on SVG files. height: int | str | None default `= None` The height of the component, specified in pixels if a number is passed, or in CSS units if a string is passed. This has no effect on the preprocessed image file or numpy array, but will affect the displayed image. width: int | str | None default `= None` The width of the component, specified in pixels if a number is passed, or in CSS units if a string is passed. This has no effect on the preprocessed image file or numpy array, but will affect the displayed image. image_mode: Literal['1', 'L', 'P', 'RGB', 'RGBA', 'CMYK', 'YCbCr', 'LAB', 'HSV', 'I', 'F'] | None default `= "RGB"` The pixel format and color depth that the image should be loaded and preprocessed as. "RGB" will load the image as a color image, or "L" as black- and-white. See https://pillow.readthedocs.io/en/stable/handbook/concepts.html for other supported image modes and their meaning. This parameter has no effect on SVG or GIF files. If set to None, the image_mode will be inferred from the image file type (e.g. "RGBA" for a .png image, "RGB" in most other cases). sources: list[Literal['upload', 'webcam', 'clipboard']] | Literal['upload', 'webcam', 'clipboa
Initialization
https://gradio.app/docs/gradio/image
Gradio - Image Docs
erred from the image file type (e.g. "RGBA" for a .png image, "RGB" in most other cases). sources: list[Literal['upload', 'webcam', 'clipboard']] | Literal['upload', 'webcam', 'clipboard'] | None default `= None` List of sources for the image. "upload" creates a box where user can drop an image file, "webcam" allows user to take snapshot from their webcam, "clipboard" allows users to paste an image from the clipboard. If None, defaults to ["upload", "webcam", "clipboard"] if streaming is False, otherwise defaults to ["webcam"]. type: Literal['numpy', 'pil', 'filepath'] default `= "numpy"` The format the image is converted before being passed into the prediction function. "numpy" converts the image to a numpy array with shape (height, width, 3) and values from 0 to 255, "pil" converts the image to a PIL image object, "filepath" passes a str path to a temporary file containing the image. To support animated GIFs in input, the `type` should be set to "filepath" or "pil". To support SVGs, the `type` should be set to "filepath". label: str | I18nData | None default `= None` the label for this component. Appears above the component and is also used as the header if there are a table of examples for this component. If None and used in a `gr.Interface`, the label will be the name of the parameter this component is assigned to. every: Timer | float | None default `= None` Continously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer. inputs: Component | list[Component] | set[Component] | None default `= None` Components that are used as inputs to calculate `value` if `value` is a function (has no effect otherwise). `value` is recalculated any time the inputs change. show_label: bool | None default `= None` if True, will disp
Initialization
https://gradio.app/docs/gradio/image
Gradio - Image Docs
calculate `value` if `value` is a function (has no effect otherwise). `value` is recalculated any time the inputs change. show_label: bool | None default `= None` if True, will display label. show_download_button: bool default `= True` If True, will display button to download image. Only applies if interactive is False (e.g. if the component is used as an output). container: bool default `= True` If True, will place the component in a container - providing some extra padding around the border. scale: int | None default `= None` relative size compared to adjacent Components. For example if Components A and B are in a Row, and A has scale=2, and B has scale=1, A will be twice as wide as B. Should be an integer. scale applies in Rows, and to top-level Components in Blocks where fill_height=True. min_width: int default `= 160` minimum pixel width, will wrap if not sufficient screen space to satisfy this value. If a certain scale value results in this Component being narrower than min_width, the min_width parameter will be respected first. interactive: bool | None default `= None` if True, will allow users to upload and edit an image; if False, can only be used to display images. If not provided, this is inferred based on whether the component is used as an input or output. visible: bool | Literal['hidden'] default `= True` If False, component will be hidden. If "hidden", component will be visually hidden and not take up space in the layout but still exist in the DOM streaming: bool default `= False` If True when used in a `live` interface, will automatically stream webcam feed. Only valid is source is 'webcam'. If the component is an output component, will automatically convert images to base64. elem_id: str | None default `= None` An optional string that is assigned as the id of this component in the HTML DOM
Initialization
https://gradio.app/docs/gradio/image
Gradio - Image Docs
an output component, will automatically convert images to base64. elem_id: str | None default `= None` An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. elem_classes: list[str] | str | None default `= None` An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. render: bool default `= True` If False, component will not render be rendered in the Blocks context. Should be used if the intention is to assign event listeners now but render the component later. key: int | str | tuple[int | str, ...] | None default `= None` in a gr.render, Components with the same key across re-renders are treated as the same component, not a new component. Properties set in 'preserved_by_key' are not reset across a re-render. preserved_by_key: list[str] | str | None default `= "value"` A list of parameters from this component's constructor. Inside a gr.render() function, if a component is re-rendered with the same key, these (and only these) parameters will be preserved in the UI (if they have been changed by the user or an event listener) instead of re-rendered based on the values provided during constructor. mirror_webcam: bool | None default `= None` If True webcam will be mirrored. Default is True. webcam_options: WebcamOptions | None default `= None` show_share_button: bool | None default `= None` If True, will show a share icon in the corner of the component that allows user to share outputs to Hugging Face Spaces Discussions. If False, icon does not appear. If set to None (default behavior), then the icon appears if this Gradio app is launched on Spaces, but not otherwise. placeholder: str | None default `= None` Custom text for the upload area. Overrides default upload messages
Initialization
https://gradio.app/docs/gradio/image
Gradio - Image Docs
icon appears if this Gradio app is launched on Spaces, but not otherwise. placeholder: str | None default `= None` Custom text for the upload area. Overrides default upload messages when provided. Accepts new lines and `` to designate a heading. show_fullscreen_button: bool default `= True` If True, will show a fullscreen icon in the corner of the component that allows user to view the image in fullscreen mode. If False, icon does not appear. webcam_constraints: dict[str, Any] | None default `= None` A dictionary that allows developers to specify custom media constraints for the webcam stream. This parameter provides flexibility to control the video stream's properties, such as resolution and front or rear camera on mobile devices. See [demo/webcam_constraints](https://gradio.app/playground?demo=Blank&code=aW1wb3J0IGdyYWRpbyBhcyBncgppbXBvcnQgY3YyICAjIHR5cGU6IGlnbm9yZQoKZGVmIGdldF92aWRlb19zaGFwZSh2aWRlbyk6CiAgICBjYXAgPSBjdjIuVmlkZW9DYXB0dXJlKHZpZGVvKQogICAgd2lkdGggPSBpbnQoY2FwLmdldChjdjIuQ0FQX1BST1BfRlJBTUVfV0lEVEgpKQogICAgaGVpZ2h0ID0gaW50KGNhcC5nZXQoY3YyLkNBUF9QUk9QX0ZSQU1FX0hFSUdIVCkpCiAgICBjYXAucmVsZWFzZSgpCiAgICByZXR1cm4geyJ3aWR0aCI6IHdpZHRoLCAiaGVpZ2h0IjogaGVpZ2h0fQoKZGVmIGltYWdlX21vZChpbWFnZSk6CiAgICB3aWR0aCwgaGVpZ2h0ID0gaW1hZ2Uuc2l6ZQogICAgcmV0dXJuIHsid2lkdGgiOiB3aWR0aCwgImhlaWdodCI6IGhlaWdodH0KCgp2aWRlbyA9IGdyLkludGVyZmFjZSgKICAgIGZuPWdldF92aWRlb19zaGFwZSwKICAgIGlucHV0cz1nci5WaWRlbyh3ZWJjYW1fY29uc3RyYWludHM9eyJ2aWRlbyI6IHsid2lkdGgiOiA4MDAsICJoZWlnaHQiOiA2MDB9fSwgc291cmNlcz0id2ViY2FtIiksCiAgICBvdXRwdXRzPWdyLkpTT04oKQopCgppbWFnZSA9IGdyLkludGVyZmFjZSgKICAgICAgICBpbWFnZV9tb2QsCiAgICAgICAgZ3IuSW1hZ2UodHlwZT0icGlsIiwgd2ViY2FtX2NvbnN0cmFpbnRzPXsidmlkZW8iOiB7IndpZHRoIjogODAwLCAiaGVpZ2h0IjogNjAwfX0sIHNvdXJjZXM9IndlYmNhbSIpLAogICAgICAgIGdyLkpzb24oKSkKCndpdGggZ3IuQmxvY2tzKCkgYXMgZGVtbzoKICAgIGdyLk1hcmtkb3duKCIiIiMgV2ViY2FtIENvbnN0cmFpbnRzCiAgICAgICAgICAgICAgICBUaGUgd2ViY2FtIGNvbnN0cmFpbnRzIGFyZSBzZXQgdG8gODAweDYwMC
Initialization
https://gradio.app/docs/gradio/image
Gradio - Image Docs
NhbSIpLAogICAgICAgIGdyLkpzb24oKSkKCndpdGggZ3IuQmxvY2tzKCkgYXMgZGVtbzoKICAgIGdyLk1hcmtkb3duKCIiIiMgV2ViY2FtIENvbnN0cmFpbnRzCiAgICAgICAgICAgICAgICBUaGUgd2ViY2FtIGNvbnN0cmFpbnRzIGFyZSBzZXQgdG8gODAweDYwMCB3aXRoIHRoZSBmb2xsb3dpbmcgc3ludGF4OgogICAgICAgICAgICAgICAgYGBgcHl0aG9uCiAgICAgICAgICAgICAgICBnci5WaWRlbyh3ZWJjYW1fY29uc3RyYWludHM9eyJ2aWRlbyI6IHsid2lkdGgiOiA4MDAsICJoZWlnaHQiOiA2MDB9fSwgc291cmNlcz0id2ViY2FtIikKICAgICAgICAgICAgICAgIGBgYAogICAgICAgICAgICAgICAgIiIiKQogICAgd2l0aCBnci5UYWJzKCk6CiAgICAgICAgd2l0aCBnci5UYWIoIlZpZGVvIik6CiAgICAgICAgICAgIHZpZGVvLnJlbmRlcigpCiAgICAgICAgd2l0aCBnci5UYWIoIkltYWdlIik6CiAgICAgICAgICAgIGltYWdlLnJlbmRlcigpCgppZiBfX25hbWVfXyA9PSAiX19tYWluX18iOgogICAgZGVtby5sYXVuY2goKQ%3D%3D&reqs=b3BlbmN2LXB5dGhvbg%3D%3D) watermark: WatermarkOptions | None default `= None` If provided and this component is used to display a `value` image, the `watermark` image will be displayed on the bottom right of the `value` image, 10 pixels from the bottom and 10 pixels from the right. The watermark image will not be resized. Supports `PIL.Image`, `numpy.array`, `pathlib.Path`, and `str` filepaths. SVGs and GIFs are not supported as `watermark` images nor can they be watermarked.
Initialization
https://gradio.app/docs/gradio/image
Gradio - Image Docs
Class | Interface String Shortcut | Initialization ---|---|--- `gradio.Image` | "image" | Uses default values
Shortcuts
https://gradio.app/docs/gradio/image
Gradio - Image Docs
The `gr.Image` component can process or display any image format that is [supported by the PIL library](https://pillow.readthedocs.io/en/stable/handbook/image-file- formats.html), including animated GIFs. In addition, it also supports the SVG image format. When the `gr.Image` component is used as an input component, the image is converted into a `str` filepath, a `PIL.Image` object, or a `numpy.array`, depending on the `type` parameter. However, animated GIF and SVG images are treated differently: * Animated `GIF` images can only be converted to `str` filepaths or `PIL.Image` objects. If they are converted to a `numpy.array` (which is the default behavior), only the first frame will be used. So if your demo expects an input `GIF` image, make sure to set the `type` parameter accordingly, e.g. import gradio as gr demo = gr.Interface( fn=lambda x:x, inputs=gr.Image(type="filepath"), outputs=gr.Image() ) demo.launch() * For `SVG` images, the `type` parameter is ignored altogether and the image is always returned as an image filepath. This is because `SVG` images cannot be processed as `PIL.Image` or `numpy.array` objects.
`GIF` and `SVG` Image Formats
https://gradio.app/docs/gradio/image
Gradio - Image Docs
sepia_filterfake_diffusion Open in 🎢 ↗ import numpy as np import gradio as gr def sepia(input_img): sepia_filter = np.array([ [0.393, 0.769, 0.189], [0.349, 0.686, 0.168], [0.272, 0.534, 0.131] ]) sepia_img = input_img.dot(sepia_filter.T) sepia_img /= sepia_img.max() return sepia_img demo = gr.Interface(sepia, gr.Image(), "image") if __name__ == "__main__": demo.launch() import numpy as np import gradio as gr def sepia(input_img): sepia_filter = np.array([ [0.393, 0.769, 0.189], [0.349, 0.686, 0.168], [0.272, 0.534, 0.131] ]) sepia_img = input_img.dot(sepia_filter.T) sepia_img /= sepia_img.max() return sepia_img demo = gr.Interface(sepia, gr.Image(), "image") if __name__ == "__main__": demo.launch() Open in 🎢 ↗ import gradio as gr import numpy as np import time def fake_diffusion(steps): rng = np.random.default_rng() for i in range(steps): time.sleep(1) image = rng.random(size=(600, 600, 3)) yield image image = np.ones((1000,1000,3), np.uint8) image[:] = [255, 124, 0] yield image demo = gr.Interface(fake_diffusion, inputs=gr.Slider(1, 10, 3, step=1), outputs="image") if __name__ == "__main__": demo.launch() import gradio as gr import numpy as np import time def fake_diffusion(steps): rng = np.random.default_rng() for i in range(steps): time.sleep(1) image = rng.random(size=(600, 600, 3)) yield image image = np.ones((1000,1000,3), np.uint8) image[:] = [255, 124, 0] yield image demo = gr.Interface(fake_diffusion, inputs=gr.Slider(1, 10, 3, step=1), outputs="image") if __name__ == "__main__": demo.launch()
Demos
https://gradio.app/docs/gradio/image
Gradio - Image Docs
Description Event listeners allow you to respond to user interactions with the UI components you've defined in a Gradio Blocks app. When a user interacts with an element, such as changing a slider value or uploading an image, a function is called. Supported Event Listeners The Image component supports the following event listeners. Each event listener takes the same parameters, which are listed in the Event Parameters table below. Listener | Description ---|--- `Image.clear(fn, ···)` | This listener is triggered when the user clears the Image using the clear button for the component. `Image.change(fn, ···)` | Triggered when the value of the Image changes either because of user input (e.g. a user types in a textbox) OR because of a function update (e.g. an image receives a value from the output of an event trigger). See `.input()` for a listener that is only triggered by user input. `Image.stream(fn, ···)` | This listener is triggered when the user streams the Image. `Image.select(fn, ···)` | Event listener for when the user selects or deselects the Image. Uses event data gradio.SelectData to carry `value` referring to the label of the Image, and `selected` to refer to state of the Image. See EventData documentation on how to use this event data `Image.upload(fn, ···)` | This listener is triggered when the user uploads a file into the Image. `Image.input(fn, ···)` | This listener is triggered when the user changes the value of the Image. Event Parameters Parameters ▼ fn: Callable | None | Literal['decorator'] default `= "decorator"` the function to call when this event is triggered. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component. inputs: Component | BlockContext | list[Component | BlockCo
Event Listeners
https://gradio.app/docs/gradio/image
Gradio - Image Docs
ion should return a single value or a tuple of values, with each element in the tuple corresponding to one output component. inputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None default `= None` List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list. outputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None default `= None` List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list. api_name: str | None | Literal[False] default `= None` defines how the endpoint appears in the API docs. Can be a string, None, or False. If set to a string, the endpoint will be exposed in the API docs with the given name. If None (default), the name of the function will be used as the API endpoint. If False, the endpoint will not be exposed in the API docs and downstream apps (including those that `gr.load` this app) will not be able to use this event. api_description: str | None | Literal[False] default `= None` Description of the API endpoint. Can be a string, None, or False. If set to a string, the endpoint will be exposed in the API docs with the given description. If None, the function's docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs. scroll_to_output: bool default `= False` If True, will scroll to output component on completion show_progress: Literal['full', 'minimal', 'hidden'] default `= "full"` how to show the progress animation while event is running: "full" shows a spinner which covers the output component area as well as a runtime display in the upper right corner, "minimal" only shows the runtime display, "hidden" shows no progress animation at all show_progress_on: Component | lis
Event Listeners
https://gradio.app/docs/gradio/image
Gradio - Image Docs
ent area as well as a runtime display in the upper right corner, "minimal" only shows the runtime display, "hidden" shows no progress animation at all show_progress_on: Component | list[Component] | None default `= None` Component or list of components to show the progress animation on. If None, will show the progress animation on all of the output components. queue: bool default `= True` If True, will place the request on the queue, if the queue has been enabled. If False, will not put this event on the queue, even if the queue has been enabled. If None, will use the queue setting of the gradio app. batch: bool default `= False` If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component. max_batch_size: int default `= 4` Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True) preprocess: bool default `= True` If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component). postprocess: bool default `= True` If False, will not run postprocessing of component data before returning 'fn' output to the browser. cancels: dict[str, Any] | list[dict[str, Any]] | None default `= None` A list of other events to cancel when this listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functio
Event Listeners
https://gradio.app/docs/gradio/image
Gradio - Image Docs