text
stringlengths
0
2k
heading1
stringlengths
4
79
source_page_url
stringclasses
177 values
source_page_title
stringclasses
177 values
), 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 def greet(name, is_morning, temperature): salutation = "Good morning" if is_morning else "Good evening" greeting = f"{salutation} {name}. It is {temperature} degrees today" celsius = (temperature - 32) * 5 / 9 return greeting, round(celsius, 2) demo = gr.Interface( fn=greet, inputs=["text", "checkbox", gr.Slider(0, 100)], outputs=["text", "number"], ) if __name__ == "__main__": demo.launch() import gradio as gr def greet(name, is_morning, temperature): salutation = "Good morning" if is_morning else "Good evening" greeting = f"{salutation} {name}. It is {temperature} degrees today" celsius = (temperature - 32) * 5 / 9 return greeting, round(celsius, 2) demo = gr.Interface( fn=greet, inputs=["text", "checkbox", gr.Slider(0, 100)], outp
Demos
https://gradio.app/docs/gradio/checkbox
Gradio - Checkbox Docs
celsius = (temperature - 32) * 5 / 9 return greeting, round(celsius, 2) demo = gr.Interface( fn=greet, inputs=["text", "checkbox", gr.Slider(0, 100)], outputs=["text", "number"], ) if __name__ == "__main__": demo.launch()
Demos
https://gradio.app/docs/gradio/checkbox
Gradio - Checkbox 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 Checkbox component supports the following event listeners. Each event listener takes the same parameters, which are listed in the Event Parameters table below. Listener | Description ---|--- `Checkbox.change(fn, ···)` | Triggered when the value of the Checkbox 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. `Checkbox.input(fn, ···)` | This listener is triggered when the user changes the value of the Checkbox. `Checkbox.select(fn, ···)` | Event listener for when the user selects or deselects the Checkbox. Uses event data gradio.SelectData to carry `value` referring to the label of the Checkbox, and `selected` to refer to state of the Checkbox. See EventData documentation on how to use this event data 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] |
Event Listeners
https://gradio.app/docs/gradio/checkbox
Gradio - Checkbox Docs
ts 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 | 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 h
Event Listeners
https://gradio.app/docs/gradio/checkbox
Gradio - Checkbox Docs
ess 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 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
Event Listeners
https://gradio.app/docs/gradio/checkbox
Gradio - Checkbox Docs
iteral['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 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 a
Event Listeners
https://gradio.app/docs/gradio/checkbox
Gradio - Checkbox Docs
ult `= 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/checkbox
Gradio - Checkbox Docs
Displays text that contains spans that are highlighted by category or numerical value.
Description
https://gradio.app/docs/gradio/highlightedtext
Gradio - Highlightedtext Docs
**As input component** : Passes the value as a list of tuples as a `list[tuple]` into the function. Each `tuple` consists of a `str` substring of the text (so the entire text is included) and `str | float | None` label, which is the category or confidence of that substring. Your function should accept one of these types: def predict( value: list[tuple[str, str | float | None]] | None ) ... **As output component** : Expects a list of (word, category) tuples, or a dictionary of two keys: "text", and "entities", which itself is a list of dictionaries, each of which have the keys: "entity" (or "entity_group"), "start", and "end" Your function should return one of these types: def predict(···) -> list[tuple[str, str | float | None]] | dict | None ... return value
Behavior
https://gradio.app/docs/gradio/highlightedtext
Gradio - Highlightedtext Docs
Parameters ▼ value: list[tuple[str, str | float | None]] | dict | Callable | None default `= None` Default value to show. If a function is provided, the function will be called each time the app loads to set the initial value of this component. color_map: dict[str, str] | None default `= None` A dictionary mapping labels to colors. The colors may be specified as hex codes or by their names. For example: {"person": "red", "location": "FFEE22"} show_legend: bool default `= False` whether to show span categories in a separate legend or inline. show_inline_category: bool default `= True` If False, will not display span category label. Only applies if show_legend=False and interactive=False. combine_adjacent: bool default `= False` If True, will merge the labels of adjacent tokens belonging to the same category. adjacent_separator: str default `= ""` Specifies the separator to be used between tokens if combine_adjacent is True. 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 display label. con
Initialization
https://gradio.app/docs/gradio/highlightedtext
Gradio - Highlightedtext Docs
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 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. visible: bool default `= True` If False, component will be hidden. 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 constru
Initialization
https://gradio.app/docs/gradio/highlightedtext
Gradio - Highlightedtext Docs
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. interactive: bool | None default `= None` If True, the component will be editable, and allow user to select spans of text and label them. rtl: bool default `= False` If True, will display the text in right-to-left direction, and the labels in the legend will also be aligned to the right.
Initialization
https://gradio.app/docs/gradio/highlightedtext
Gradio - Highlightedtext Docs
Class | Interface String Shortcut | Initialization ---|---|--- `gradio.HighlightedText` | "highlightedtext" | Uses default values
Shortcuts
https://gradio.app/docs/gradio/highlightedtext
Gradio - Highlightedtext Docs
diff_texts Open in 🎢 ↗ from difflib import Differ import gradio as gr def diff_texts(text1, text2): d = Differ() return [ (token[2:], token[0] if token[0] != " " else None) for token in d.compare(text1, text2) ] demo = gr.Interface( diff_texts, [ gr.Textbox( label="Text 1", info="Initial text", lines=3, value="The quick brown fox jumped over the lazy dogs.", ), gr.Textbox( label="Text 2", info="Text to compare", lines=3, value="The fast brown fox jumps over lazy dogs.", ), ], gr.HighlightedText( label="Diff", combine_adjacent=True, show_legend=True, color_map={"+": "red", "-": "green"}), theme=gr.themes.Base() ) if __name__ == "__main__": demo.launch() from difflib import Differ import gradio as gr def diff_texts(text1, text2): d = Differ() return [ (token[2:], token[0] if token[0] != " " else None) for token in d.compare(text1, text2) ] demo = gr.Interface( diff_texts, [ gr.Textbox( label="Text 1", info="Initial text", lines=3, value="The quick brown fox jumped over the lazy dogs.", ), gr.Textbox( label="Text 2", info="Text to compare", lines=3, value="The fast brown fox jumps over lazy dogs.", ), ], gr.HighlightedText( label="Diff", combine_adjacent=True, show_legend=True, color_map={"+": "red", "-": "green"}), theme=gr.themes.Base() ) if __name__ == "__main__": demo.launch()
Demos
https://gradio.app/docs/gradio/highlightedtext
Gradio - Highlightedtext 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 HighlightedText component supports the following event listeners. Each event listener takes the same parameters, which are listed in the Event Parameters table below. Listener | Description ---|--- `HighlightedText.change(fn, ···)` | Triggered when the value of the HighlightedText 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. `HighlightedText.select(fn, ···)` | Event listener for when the user selects or deselects the HighlightedText. Uses event data gradio.SelectData to carry `value` referring to the label of the HighlightedText, and `selected` to refer to state of the HighlightedText. See EventData documentation on how to use this event data 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
Event Listeners
https://gradio.app/docs/gradio/highlightedtext
Gradio - Highlightedtext Docs
s 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, will not put this event on the
Event Listeners
https://gradio.app/docs/gradio/highlightedtext
Gradio - Highlightedtext Docs
on 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 are allowed while pending, and "
Event Listeners
https://gradio.app/docs/gradio/highlightedtext
Gradio - Highlightedtext Docs
`= 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-renders when the key is identical.
Event Listeners
https://gradio.app/docs/gradio/highlightedtext
Gradio - Highlightedtext Docs
| 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/highlightedtext
Gradio - Highlightedtext Docs
Load a chat interface from an OpenAI API chat compatible endpoint.
Description
https://gradio.app/docs/gradio/load_chat
Gradio - Load_Chat Docs
import gradio as gr demo = gr.load_chat("http://localhost:11434/v1", model="deepseek-r1") demo.launch()
Example Usage
https://gradio.app/docs/gradio/load_chat
Gradio - Load_Chat Docs
Parameters ▼ base_url: str The base URL of the endpoint, e.g. "http://localhost:11434/v1/" model: str The name of the model you are loading, e.g. "llama3.2" token: str | None default `= None` The API token or a placeholder string if you are using a local model, e.g. "ollama" file_types: Literal['text_encoded', 'image'] | list[Literal['text_encoded', 'image']] | None default `= "text_encoded"` The file types allowed to be uploaded by the user. "text_encoded" allows uploading any text-encoded file (which is simply appended to the prompt), and "image" adds image upload support. Set to None to disable file uploads. system_message: str | None default `= None` The system message to use for the conversation, if any. streaming: bool default `= True` Whether the response should be streamed. kwargs: <class 'inspect._empty'> Additional keyword arguments to pass into ChatInterface for customization.
Initialization
https://gradio.app/docs/gradio/load_chat
Gradio - Load_Chat Docs
The FileData class is a subclass of the GradioModel class that represents a file object within a Gradio interface. It is used to store file data and metadata when a file is uploaded.
Description
https://gradio.app/docs/gradio/filedata
Gradio - Filedata Docs
from gradio_client import Client, FileData, handle_file def get_url_on_server(data: FileData): print(data['url']) client = Client("gradio/gif_maker_main", download_files=False) job = client.submit([handle_file("./cheetah.jpg")], api_name="/predict") data = job.result() video: FileData = data['video'] get_url_on_server(video)
Example Usage
https://gradio.app/docs/gradio/filedata
Gradio - Filedata Docs
Parameters ▼ path: str The server file path where the file is stored. url: Optional[str] The normalized server URL pointing to the file. size: Optional[int] The size of the file in bytes. orig_name: Optional[str] The original filename before upload. mime_type: Optional[str] The MIME type of the file. is_stream: bool Indicates whether the file is a stream. meta: dict Additional metadata used internally (should not be changed).
Attributes
https://gradio.app/docs/gradio/filedata
Gradio - Filedata Docs
Used to render arbitrary Markdown output. Can also render latex enclosed by dollar signs. As this component does not accept user input, it is rarely used as an input component.
Description
https://gradio.app/docs/gradio/markdown
Gradio - Markdown Docs
**As input component** : Passes the `str` of Markdown corresponding to the displayed value. Your function should accept one of these types: def predict( value: str | None ) ... **As output component** : Expects a valid `str` that can be rendered as Markdown. Your function should return one of these types: def predict(···) -> str | None ... return value
Behavior
https://gradio.app/docs/gradio/markdown
Gradio - Markdown Docs
Parameters ▼ value: str | I18nData | Callable | None default `= None` Value to show in Markdown component. If a function is provided, the function will be called each time the app loads to set the initial value of this component. label: str | I18nData | None default `= None` This parameter has no effect 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` This parameter has no effect. rtl: bool default `= False` If True, sets the direction of the rendered text to right-to-left. Default is False, which renders text left-to-right. latex_delimiters: list[dict[str, str | bool]] | None default `= None` A list of dicts of the form {"left": open delimiter (str), "right": close delimiter (str), "display": whether to display in newline (bool)} that will be used to render LaTeX expressions. If not provided, `latex_delimiters` is set to `[{ "left": "$$", "right": "$$", "display": True }]`, so only expressions enclosed in $$ delimiters will be rendered as LaTeX, and in a new line. Pass in an empty list to disable LaTeX rendering. For more information, see the [KaTeX documentation](https://katex.org/docs/autorender.html). visible: bool default `= True` If False, component will be hidden. 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.
Initialization
https://gradio.app/docs/gradio/markdown
Gradio - Markdown Docs
t will be hidden. 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. sanitize_html: bool default `= True` If False, will disable HTML sanitization when converted from markdown. This is not recommended, as it can lead to security vulnerabilities. line_breaks: bool default `= False` If True, will enable Github-flavored Markdown line breaks in chatbot messages. If False (default), single new lines will be ignored. header_links: bool default `= False` If True, will automatically create anchors for headings, displaying a link icon on hover. 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. If mark
Initialization
https://gradio.app/docs/gradio/markdown
Gradio - Markdown Docs
a link icon on hover. 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. If markdown content exceeds the height, the component will scroll. max_height: int | str | None default `= None` The maximum height of the component, specified in pixels if a number is passed, or in CSS units if a string is passed. If markdown content exceeds the height, the component will scroll. If markdown content is shorter than the height, the component will shrink to fit the content. Will not have any effect if `height` is set and is smaller than `max_height`. min_height: int | str | None default `= None` The minimum height of the component, specified in pixels if a number is passed, or in CSS units if a string is passed. If markdown content exceeds the height, the component will expand to fit the content. Will not have any effect if `height` is set and is larger than `min_height`. show_copy_button: bool default `= False` If True, includes a copy button to copy the text in the Markdown component. Default is False. container: bool default `= False` If True, the Markdown component will be displayed in a container. Default is False. padding: bool default `= False` If True, the Markdown component will have a certain padding (set by the `--block-padding` CSS variable) in all directions. Default is False.
Initialization
https://gradio.app/docs/gradio/markdown
Gradio - Markdown Docs
Class | Interface String Shortcut | Initialization ---|---|--- `gradio.Markdown` | "markdown" | Uses default values
Shortcuts
https://gradio.app/docs/gradio/markdown
Gradio - Markdown Docs
blocks_helloblocks_kinematics Open in 🎢 ↗ import gradio as gr def welcome(name): return f"Welcome to Gradio, {name}!" with gr.Blocks() as demo: gr.Markdown( """ Hello World! Start typing below to see the output. """) inp = gr.Textbox(placeholder="What is your name?") out = gr.Textbox() inp.change(welcome, inp, out) if __name__ == "__main__": demo.launch() import gradio as gr def welcome(name): return f"Welcome to Gradio, {name}!" with gr.Blocks() as demo: gr.Markdown( """ Hello World! Start typing below to see the output. """) inp = gr.Textbox(placeholder="What is your name?") out = gr.Textbox() inp.change(welcome, inp, out) if __name__ == "__main__": demo.launch() Open in 🎢 ↗ import pandas as pd import numpy as np import gradio as gr def plot(v, a): g = 9.81 theta = a / 180 * 3.14 tmax = ((2 * v) * np.sin(theta)) / g timemat = tmax * np.linspace(0, 1, 40) x = (v * timemat) * np.cos(theta) y = ((v * timemat) * np.sin(theta)) - ((0.5 * g) * (timemat**2)) df = pd.DataFrame({"x": x, "y": y}) return df demo = gr.Blocks() with demo: gr.Markdown( r"Let's do some kinematics! Choose the speed and angle to see the trajectory. Remember that the range $R = v_0^2 \cdot \frac{\sin(2\theta)}{g}$" ) with gr.Row(): speed = gr.Slider(1, 30, 25, label="Speed") angle = gr.Slider(0, 90, 45, label="Angle") output = gr.LinePlot( x="x", y="y", overlay_point=True, tooltip=["x", "y"], x_lim=[0, 100], y_lim=[0, 60], width=350, height=300, ) btn = gr.Button(value="Run") btn.click(plot, [speed, angle], output) if __name__ == "__main__": demo.launch() import pandas as pd import numpy as np import gradio as gr def plot(v, a): g = 9.81 theta = a / 180 * 3.14 tmax = ((2 * v) * np.sin(theta)) / g timemat = tmax * np.linspace(0, 1, 40) x = (v * timemat) * np.cos(theta) y =
Demos
https://gradio.app/docs/gradio/markdown
Gradio - Markdown Docs
g = 9.81 theta = a / 180 * 3.14 tmax = ((2 * v) * np.sin(theta)) / g timemat = tmax * np.linspace(0, 1, 40) x = (v * timemat) * np.cos(theta) y = ((v * timemat) * np.sin(theta)) - ((0.5 * g) * (timemat**2)) df = pd.DataFrame({"x": x, "y": y}) return df demo = gr.Blocks() with demo: gr.Markdown( r"Let's do some kinematics! Choose the speed and angle to see the trajectory. Remember that the range $R = v_0^2 \cdot \frac{\sin(2\theta)}{g}$" ) with gr.Row(): speed = gr.Slider(1, 30, 25, label="Speed") angle = gr.Slider(0, 90, 45, label="Angle") output = gr.LinePlot( x="x", y="y", overlay_point=True, tooltip=["x", "y"], x_lim=[0, 100], y_lim=[0, 60], width=350, height=300, ) btn = gr.Button(value="Run") btn.click(plot, [speed, angle], output) if __name__ == "__main__": demo.launch()
Demos
https://gradio.app/docs/gradio/markdown
Gradio - Markdown 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 Markdown component supports the following event listeners. Each event listener takes the same parameters, which are listed in the Event Parameters table below. Listener | Description ---|--- `Markdown.change(fn, ···)` | Triggered when the value of the Markdown 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. `Markdown.copy(fn, ···)` | This listener is triggered when the user copies content from the Markdown. Uses event data gradio.CopyData to carry information about the copied content. See EventData documentation on how to use this event data 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: s
Event Listeners
https://gradio.app/docs/gradio/markdown
Gradio - Markdown Docs
xt] | 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, 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.
Event Listeners
https://gradio.app/docs/gradio/markdown
Gradio - Markdown Docs
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 are allowed while pending, and "always_last" (default for `.change()` and `.key_up()` events) would allow a second submission after the pe
Event Listeners
https://gradio.app/docs/gradio/markdown
Gradio - Markdown Docs
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-renders when the key is identical. validator: Callable | None default `= None` Optional validation function to run before t
Event Listeners
https://gradio.app/docs/gradio/markdown
Gradio - Markdown Docs
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/markdown
Gradio - Markdown Docs
Creates a component to displays a base image and colored annotations on top of that image. Annotations can take the from of rectangles (e.g. object detection) or masks (e.g. image segmentation). As this component does not accept user input, it is rarely used as an input component.
Description
https://gradio.app/docs/gradio/annotatedimage
Gradio - Annotatedimage Docs
**As input component** : Passes its value as a `tuple` consisting of a `str` filepath to a base image and `list` of annotations. Each annotation itself is `tuple` of a mask (as a `str` filepath to image) and a `str` label. Your function should accept one of these types: def predict( value: tuple[str, list[tuple[str, str]]] | None ) ... **As output component** : Expects a a tuple of a base image and list of annotations: a `tuple[Image, list[Annotation]]`. The `Image` itself can be `str` filepath, `numpy.ndarray`, or `PIL.Image`. Each `Annotation` is a `tuple[Mask, str]`. The `Mask` can be either a `tuple` of 4 `int`'s representing the bounding box coordinates (x1, y1, x2, y2), or 0-1 confidence mask in the form of a `numpy.ndarray` of the same shape as the image, while the second element of the `Annotation` tuple is a `str` label. Your function should return one of these types: def predict(···) -> tuple[np.ndarray | PIL.Image.Image | str, list[tuple[np.ndarray | tuple[int, int, int, int], str]]] | None ... return value
Behavior
https://gradio.app/docs/gradio/annotatedimage
Gradio - Annotatedimage Docs
Parameters ▼ value: tuple[np.ndarray | PIL.Image.Image | str, list[tuple[np.ndarray | tuple[int, int, int, int], str]]] | None default `= None` Tuple of base image and list of (annotation, label) pairs. format: str default `= "webp"` Format used to save images before it is returned to the front end, such as 'jpeg' or 'png'. This parameter only takes effect when the base image is returned from the prediction function as a numpy array or a PIL Image. The format should be supported by the PIL library. show_legend: bool default `= True` If True, will show a legend of the annotations. 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. color_map: dict[str, str] | None default `= None` A dictionary mapping labels to colors. The colors must be specified as hex codes. 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] |
Initialization
https://gradio.app/docs/gradio/annotatedimage
Gradio - Annotatedimage Docs
ct 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. 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. visible: bool default `= True` If False, component will be hidden. 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/annotatedimage
Gradio - Annotatedimage Docs
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. show_fullscreen_button: bool default `= True` If True, will show a button to allow the image to be viewed in fullscreen mode.
Initialization
https://gradio.app/docs/gradio/annotatedimage
Gradio - Annotatedimage Docs
Class | Interface String Shortcut | Initialization ---|---|--- `gradio.AnnotatedImage` | "annotatedimage" | Uses default values
Shortcuts
https://gradio.app/docs/gradio/annotatedimage
Gradio - Annotatedimage Docs
image_segmentation Open in 🎢 ↗ import gradio as gr import numpy as np import random with gr.Blocks() as demo: section_labels = [ "apple", "banana", "carrot", "donut", "eggplant", "fish", "grapes", "hamburger", "ice cream", "juice", ] with gr.Row(): num_boxes = gr.Slider(0, 5, 2, step=1, label="Number of boxes") num_segments = gr.Slider(0, 5, 1, step=1, label="Number of segments") with gr.Row(): img_input = gr.Image() img_output = gr.AnnotatedImage( color_map={"banana": "a89a00", "carrot": "ffae00"} ) section_btn = gr.Button("Identify Sections") selected_section = gr.Textbox(label="Selected Section") def section(img, num_boxes, num_segments): sections = [] for a in range(num_boxes): x = random.randint(0, img.shape[1]) y = random.randint(0, img.shape[0]) w = random.randint(0, img.shape[1] - x) h = random.randint(0, img.shape[0] - y) sections.append(((x, y, x + w, y + h), section_labels[a])) for b in range(num_segments): x = random.randint(0, img.shape[1]) y = random.randint(0, img.shape[0]) r = random.randint(0, min(x, y, img.shape[1] - x, img.shape[0] - y)) mask = np.zeros(img.shape[:2]) for i in range(img.shape[0]): for j in range(img.shape[1]): dist_square = (i - y) ** 2 + (j - x) ** 2 if dist_square < r**2: mask[i, j] = round((r**2 - dist_square) / r**2 * 4) / 4 sections.append((mask, section_labels[b + num_boxes])) return (img, sections) section_btn.click(section, [img_input, num_boxes, num_segments], img_output) def select_section(evt: gr.SelectData): return section_labels[evt.index] img_output.select(select_section, None, selected_section) if __name__ == "__main__": demo.launch() import gradio as gr import numpy as np import random with gr.Blocks() as demo: section_labels = [ "apple", "banana", "carrot", "donut", "eggplant", "fish", "grapes", "hamburger", "ice cream", "juice", ] w
Demos
https://gradio.app/docs/gradio/annotatedimage
Gradio - Annotatedimage Docs
"carrot", "donut", "eggplant", "fish", "grapes", "hamburger", "ice cream", "juice", ] with gr.Row(): num_boxes = gr.Slider(0, 5, 2, step=1, label="Number of boxes") num_segments = gr.Slider(0, 5, 1, step=1, label="Number of segments") with gr.Row(): img_input = gr.Image() img_output = gr.AnnotatedImage( color_map={"banana": "a89a00", "carrot": "ffae00"} ) section_btn = gr.Button("Identify Sections") selected_section = gr.Textbox(label="Selected Section") def section(img, num_boxes, num_segments): sections = [] for a in range(num_boxes): x = random.randint(0, img.shape[1]) y = random.randint(0, img.shape[0]) w = random.randint(0, img.shape[1] - x) h = random.randint(0, img.shape[0] - y) sections.append(((x, y, x + w, y + h), section_labels[a])) for b in range(num_segments): x = random.randint(0, img.shape[1]) y = random.randint(0, img.shape[0]) r = random.randint(0, min(x, y, img.shape[1] - x, img.shape[0] - y)) mask = np.zeros(img.shape[:2]) for i in range(img.shape[0]): for j in range(img.shape[1]): dist_square = (i - y) ** 2 + (j - x) ** 2 if dist_square < r**2: mask[i, j] = round((r**2 - dist_square) / r**2 * 4) / 4 sections.append((mask, section_labels[b + num_boxes])) return (img, sections) section_btn.click(section, [img_input, num_boxes, num_segments], img_output) def select_section(evt: gr.SelectData): return section_labels[evt.index] img_output.select(select_s
Demos
https://gradio.app/docs/gradio/annotatedimage
Gradio - Annotatedimage Docs
ick(section, [img_input, num_boxes, num_segments], img_output) def select_section(evt: gr.SelectData): return section_labels[evt.index] img_output.select(select_section, None, selected_section) if __name__ == "__main__": demo.launch()
Demos
https://gradio.app/docs/gradio/annotatedimage
Gradio - Annotatedimage 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 AnnotatedImage component supports the following event listeners. Each event listener takes the same parameters, which are listed in the Event Parameters table below. Listener | Description ---|--- `AnnotatedImage.select(fn, ···)` | Event listener for when the user selects or deselects the AnnotatedImage. Uses event data gradio.SelectData to carry `value` referring to the label of the AnnotatedImage, and `selected` to refer to state of the AnnotatedImage. See EventData documentation on how to use this event data 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 (d
Event Listeners
https://gradio.app/docs/gradio/annotatedimage
Gradio - Annotatedimage Docs
] 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 it should accept a list of input values for each parameter. The lists should be of equal length (and be up to
Event Listeners
https://gradio.app/docs/gradio/annotatedimage
Gradio - Annotatedimage Docs
ault `= 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 method to run before running 'fn'. Input arguments for js method are values of 'inputs' and 'outputs', return sho
Event Listeners
https://gradio.app/docs/gradio/annotatedimage
Gradio - Annotatedimage Docs
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 successfully will the main function be called. The validator receives the same inputs as the main function and sho
Event Listeners
https://gradio.app/docs/gradio/annotatedimage
Gradio - Annotatedimage Docs
ided, 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/annotatedimage
Gradio - Annotatedimage Docs
The gr.CopyData class is a subclass of gr.EventData that specifically carries information about the `.copy()` event. When gr.CopyData is added as a type hint to an argument of an event listener method, a gr.CopyData 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/copydata
Gradio - Copydata Docs
import gradio as gr def on_copy(copy_data: gr.CopyData): return f"Copied text: {copy_data.value}" with gr.Blocks() as demo: textbox = gr.Textbox("Hello World!") copied = gr.Textbox() textbox.copy(on_copy, None, copied) demo.launch()
Example Usage
https://gradio.app/docs/gradio/copydata
Gradio - Copydata Docs
Parameters ▼ value: Any The value that was copied.
Attributes
https://gradio.app/docs/gradio/copydata
Gradio - Copydata Docs
Creates a set of checkboxes. Can be used as an input to pass a set of values to a function or as an output to display values, a subset of which are selected.
Description
https://gradio.app/docs/gradio/checkboxgroup
Gradio - Checkboxgroup Docs
**As input component** : Passes the list of checked checkboxes as a `list[str | int | float]` or their indices as a `list[int]` into the function, depending on `type`. Your function should accept one of these types: def predict( value: list[str | int | float] | list[int | None] ) ... **As output component** : Expects a `list[str | int | float]` of values or a single `str | int | float` value, the checkboxes with these values are checked. Your function should return one of these types: def predict(···) -> list[str | int | float] | str | int | float | None ... return value
Behavior
https://gradio.app/docs/gradio/checkboxgroup
Gradio - Checkboxgroup 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 checkbox button and value is the value to be passed to the function, or returned by the function. value: list[str | float | int] | str | float | int | Callable | None default `= None` Default selected list of options. If a single choice is selected, it can be passed in as a string or numeric type. 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 list of strings of the choices selected, "index" returns the list of indices of the choices 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.
Initialization
https://gradio.app/docs/gradio/checkboxgroup
Gradio - Checkboxgroup Docs
nt] | 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. 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 checkbox group will be checkable; if False, checking will be disabled. If not provided, this is inferred based on whether the component is used as an input or output. visible: bool default `= True` If False, component will be hidden. 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-render
Initialization
https://gradio.app/docs/gradio/checkboxgroup
Gradio - Checkboxgroup Docs
ssign 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/checkboxgroup
Gradio - Checkboxgroup Docs
Class | Interface String Shortcut | Initialization ---|---|--- `gradio.CheckboxGroup` | "checkboxgroup" | Uses default values
Shortcuts
https://gradio.app/docs/gradio/checkboxgroup
Gradio - Checkboxgroup Docs
sentence_builder 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="Countries",
Demos
https://gradio.app/docs/gradio/checkboxgroup
Gradio - Checkboxgroup 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()
Demos
https://gradio.app/docs/gradio/checkboxgroup
Gradio - Checkboxgroup 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 CheckboxGroup component supports the following event listeners. Each event listener takes the same parameters, which are listed in the Event Parameters table below. Listener | Description ---|--- `CheckboxGroup.change(fn, ···)` | Triggered when the value of the CheckboxGroup 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. `CheckboxGroup.input(fn, ···)` | This listener is triggered when the user changes the value of the CheckboxGroup. `CheckboxGroup.select(fn, ···)` | Event listener for when the user selects or deselects the CheckboxGroup. Uses event data gradio.SelectData to carry `value` referring to the label of the CheckboxGroup, and `selected` to refer to state of the CheckboxGroup. See EventData documentation on how to use this event data 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 | Bl
Event Listeners
https://gradio.app/docs/gradio/checkboxgroup
Gradio - Checkboxgroup Docs
ne 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 | 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 p
Event Listeners
https://gradio.app/docs/gradio/checkboxgroup
Gradio - Checkboxgroup Docs
onent 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 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 w
Event Listeners
https://gradio.app/docs/gradio/checkboxgroup
Gradio - Checkboxgroup Docs
ed 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 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.rende
Event Listeners
https://gradio.app/docs/gradio/checkboxgroup
Gradio - Checkboxgroup Docs
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/checkboxgroup
Gradio - Checkboxgroup Docs
Time plots need a datetime column on the x-axis. Here's a simple example with some flight data: $code_plot_guide_temporal $demo_plot_guide_temporal
Creating a Plot with a pd.Dataframe
https://gradio.app/guides/time-plots
Data Science And Plots - Time Plots Guide
You may wish to bin data by time buckets. Use `x_bin` to do so, using a string suffix with "s", "m", "h" or "d", such as "15m" or "1d". $code_plot_guide_aggregate_temporal $demo_plot_guide_aggregate_temporal
Aggregating by Time
https://gradio.app/guides/time-plots
Data Science And Plots - Time Plots Guide
You can use `gr.DateTime` to accept input datetime data. This works well with plots for defining the x-axis range for the data. $code_plot_guide_datetime $demo_plot_guide_datetime Note how `gr.DateTime` can accept a full datetime string, or a shorthand using `now - [0-9]+[smhd]` format to refer to a past time. You will often have many time plots in which case you'd like to keep the x-axes in sync. The `DateTimeRange` custom component keeps a set of datetime plots in sync, and also uses the `.select` listener of plots to allow you to zoom into plots while keeping plots in sync. Because it is a custom component, you first need to `pip install gradio_datetimerange`. Then run the following: $code_plot_guide_datetimerange $demo_plot_guide_datetimerange Try zooming around in the plots and see how DateTimeRange updates. All the plots updates their `x_lim` in sync. You also have a "Back" link in the component to allow you to quickly zoom in and out.
DateTime Components
https://gradio.app/guides/time-plots
Data Science And Plots - Time Plots Guide
In many cases, you're working with live, realtime date, not a static dataframe. In this case, you'd update the plot regularly with a `gr.Timer()`. Assuming there's a `get_data` method that gets the latest dataframe: ```python with gr.Blocks() as demo: timer = gr.Timer(5) plot1 = gr.BarPlot(x="time", y="price") plot2 = gr.BarPlot(x="time", y="price", color="origin") timer.tick(lambda: [get_data(), get_data()], outputs=[plot1, plot2]) ``` You can also use the `every` shorthand to attach a `Timer` to a component that has a function value: ```python with gr.Blocks() as demo: timer = gr.Timer(5) plot1 = gr.BarPlot(get_data, x="time", y="price", every=timer) plot2 = gr.BarPlot(get_data, x="time", y="price", color="origin", every=timer) ```
RealTime Data
https://gradio.app/guides/time-plots
Data Science And Plots - Time Plots Guide
Use any of the standard Gradio form components to filter your data. You can do this via event listeners or function-as-value syntax. Let's look at the event listener approach first: $code_plot_guide_filters_events $demo_plot_guide_filters_events And this would be the function-as-value approach for the same demo. $code_plot_guide_filters
Filters
https://gradio.app/guides/filters-tables-and-stats
Data Science And Plots - Filters Tables And Stats Guide
Add `gr.DataFrame` and `gr.Label` to your dashboard for some hard numbers. $code_plot_guide_tables_stats $demo_plot_guide_tables_stats
Tables and Stats
https://gradio.app/guides/filters-tables-and-stats
Data Science And Plots - Filters Tables And Stats Guide
```python from sqlalchemy import create_engine import pandas as pd engine = create_engine('sqlite:///your_database.db') with gr.Blocks() as demo: gr.LinePlot(pd.read_sql_query("SELECT time, price from flight_info;", engine), x="time", y="price") ``` Let's see a a more interactive plot involving filters that modify your SQL query: ```python from sqlalchemy import create_engine import pandas as pd engine = create_engine('sqlite:///your_database.db') with gr.Blocks() as demo: origin = gr.Dropdown(["DFW", "DAL", "HOU"], value="DFW", label="Origin") gr.LinePlot(lambda origin: pd.read_sql_query(f"SELECT time, price from flight_info WHERE origin = {origin};", engine), inputs=origin, x="time", y="price") ```
SQLite
https://gradio.app/guides/connecting-to-a-database
Data Science And Plots - Connecting To A Database Guide
If you're using a different database format, all you have to do is swap out the engine, e.g. ```python engine = create_engine('postgresql://username:password@host:port/database_name') ``` ```python engine = create_engine('mysql://username:password@host:port/database_name') ``` ```python engine = create_engine('oracle://username:password@host:port/database_name') ```
Postgres, mySQL, and other databases
https://gradio.app/guides/connecting-to-a-database
Data Science And Plots - Connecting To A Database Guide
Plots accept a pandas Dataframe as their value. The plot also takes `x` and `y` which represent the names of the columns that represent the x and y axes respectively. Here's a simple example: $code_plot_guide_line $demo_plot_guide_line All plots have the same API, so you could swap this out with a `gr.ScatterPlot`: $code_plot_guide_scatter $demo_plot_guide_scatter The y axis column in the dataframe should have a numeric type, but the x axis column can be anything from strings, numbers, categories, or datetimes. $code_plot_guide_scatter_nominal $demo_plot_guide_scatter_nominal
Creating a Plot with a pd.Dataframe
https://gradio.app/guides/creating-plots
Data Science And Plots - Creating Plots Guide
You can break out your plot into series using the `color` argument. $code_plot_guide_series_nominal $demo_plot_guide_series_nominal If you wish to assign series specific colors, use the `color_map` arg, e.g. `gr.ScatterPlot(..., color_map={'white': 'FF9988', 'asian': '88EEAA', 'black': '333388'})` The color column can be numeric type as well. $code_plot_guide_series_quantitative $demo_plot_guide_series_quantitative
Breaking out Series by Color
https://gradio.app/guides/creating-plots
Data Science And Plots - Creating Plots Guide
You can aggregate values into groups using the `x_bin` and `y_aggregate` arguments. If your x-axis is numeric, providing an `x_bin` will create a histogram-style binning: $code_plot_guide_aggregate_quantitative $demo_plot_guide_aggregate_quantitative If your x-axis is a string type instead, they will act as the category bins automatically: $code_plot_guide_aggregate_nominal $demo_plot_guide_aggregate_nominal
Aggregating Values
https://gradio.app/guides/creating-plots
Data Science And Plots - Creating Plots Guide
You can use the `.select` listener to select regions of a plot. Click and drag on the plot below to select part of the plot. $code_plot_guide_selection $demo_plot_guide_selection You can combine this and the `.double_click` listener to create some zoom in/out effects by changing `x_lim` which sets the bounds of the x-axis: $code_plot_guide_zoom $demo_plot_guide_zoom If you had multiple plots with the same x column, your event listeners could target the x limits of all other plots so that the x-axes stay in sync. $code_plot_guide_zoom_sync $demo_plot_guide_zoom_sync
Selecting Regions
https://gradio.app/guides/creating-plots
Data Science And Plots - Creating Plots Guide
Take a look how you can have an interactive dashboard where the plots are functions of other Components. $code_plot_guide_interactive $demo_plot_guide_interactive It's that simple to filter and control the data presented in your visualization!
Making an Interactive Dashboard
https://gradio.app/guides/creating-plots
Data Science And Plots - Creating Plots Guide
Adding examples to an Interface is as easy as providing a list of lists to the `examples` keyword argument. Each sublist is a data sample, where each element corresponds to an input of the prediction function. The inputs must be ordered in the same order as the prediction function expects them. If your interface only has one input component, then you can provide your examples as a regular list instead of a list of lists. Loading Examples from a Directory You can also specify a path to a directory containing your examples. If your Interface takes only a single file-type input, e.g. an image classifier, you can simply pass a directory filepath to the `examples=` argument, and the `Interface` will load the images in the directory as examples. In the case of multiple inputs, this directory must contain a log.csv file with the example values. In the context of the calculator demo, we can set `examples='/demo/calculator/examples'` and in that directory we include the following `log.csv` file: ```csv num,operation,num2 5,"add",3 4,"divide",2 5,"multiply",3 ``` This can be helpful when browsing flagged data. Simply point to the flagged directory and the `Interface` will load the examples from the flagged data. Providing Partial Examples Sometimes your app has many input components, but you would only like to provide examples for a subset of them. In order to exclude some inputs from the examples, pass `None` for all data samples corresponding to those particular components.
Providing Examples
https://gradio.app/guides/more-on-examples
Building Interfaces - More On Examples Guide
You may wish to provide some cached examples of your model for users to quickly try out, in case your model takes a while to run normally. If `cache_examples=True`, your Gradio app will run all of the examples and save the outputs when you call the `launch()` method. This data will be saved in a directory called `gradio_cached_examples` in your working directory by default. You can also set this directory with the `GRADIO_EXAMPLES_CACHE` environment variable, which can be either an absolute path or a relative path to your working directory. Whenever a user clicks on an example, the output will automatically be populated in the app now, using data from this cached directory instead of actually running the function. This is useful so users can quickly try out your model without adding any load! Alternatively, you can set `cache_examples="lazy"`. This means that each particular example will only get cached after it is first used (by any user) in the Gradio app. This is helpful if your prediction function is long-running and you do not want to wait a long time for your Gradio app to start. Keep in mind once the cache is generated, it will not be updated automatically in future launches. If the examples or function logic change, delete the cache folder to clear the cache and rebuild it with another `launch()`.
Caching examples
https://gradio.app/guides/more-on-examples
Building Interfaces - More On Examples Guide
If the state is something that should be accessible to all function calls and all users, you can create a variable outside the function call and access it inside the function. For example, you may load a large model outside the function and use it inside the function so that every function call does not need to reload the model. $code_score_tracker In the code above, the `scores` array is shared between all users. If multiple users are accessing this demo, their scores will all be added to the same list, and the returned top 3 scores will be collected from this shared reference.
Global State
https://gradio.app/guides/interface-state
Building Interfaces - Interface State Guide
Another type of data persistence Gradio supports is session state, where data persists across multiple submits within a page session. However, data is _not_ shared between different users of your model. To store data in a session state, you need to do three things: 1. Pass in an extra parameter into your function, which represents the state of the interface. 2. At the end of the function, return the updated value of the state as an extra return value. 3. Add the `'state'` input and `'state'` output components when creating your `Interface` Here's a simple app to illustrate session state - this app simply stores users previous submissions and displays them back to the user: $code_interface_state $demo_interface_state Notice how the state persists across submits within each page, but if you load this demo in another tab (or refresh the page), the demos will not share chat history. Here, we could not store the submission history in a global variable, otherwise the submission history would then get jumbled between different users. The initial value of the `State` is `None` by default. If you pass a parameter to the `value` argument of `gr.State()`, it is used as the default value of the state instead. Note: the `Interface` class only supports a single session state variable (though it can be a list with multiple elements). For more complex use cases, you can use Blocks, [which supports multiple `State` variables](/guides/state-in-blocks/). Alternatively, if you are building a chatbot that maintains user state, consider using the `ChatInterface` abstraction, [which manages state automatically](/guides/creating-a-chatbot-fast).
Session State
https://gradio.app/guides/interface-state
Building Interfaces - Interface State Guide
Gradio includes more than 30 pre-built components (as well as many [community-built _custom components_](https://www.gradio.app/custom-components/gallery)) that can be used as inputs or outputs in your demo. These components correspond to common data types in machine learning and data science, e.g. the `gr.Image` component is designed to handle input or output images, the `gr.Label` component displays classification labels and probabilities, the `gr.LinePlot` component displays line plots, and so on.
Gradio Components
https://gradio.app/guides/the-interface-class
Building Interfaces - The Interface Class Guide
We used the default versions of the `gr.Textbox` and `gr.Slider`, but what if you want to change how the UI components look or behave? Let's say you want to customize the slider to have values from 1 to 10, with a default of 2. And you wanted to customize the output text field — you want it to be larger and have a label. If you use the actual classes for `gr.Textbox` and `gr.Slider` instead of the string shortcuts, you have access to much more customizability through component attributes. $code_hello_world_2 $demo_hello_world_2
Components Attributes
https://gradio.app/guides/the-interface-class
Building Interfaces - The Interface Class Guide
Suppose you had a more complex function, with multiple outputs as well. In the example below, we define a function that takes a string, boolean, and number, and returns a string and number. $code_hello_world_3 $demo_hello_world_3 Just as each component in the `inputs` list corresponds to one of the parameters of the function, in order, each component in the `outputs` list corresponds to one of the values returned by the function, in order.
Multiple Input and Output Components
https://gradio.app/guides/the-interface-class
Building Interfaces - The Interface Class Guide
Gradio supports many types of components, such as `Image`, `DataFrame`, `Video`, or `Label`. Let's try an image-to-image function to get a feel for these! $code_sepia_filter $demo_sepia_filter When using the `Image` component as input, your function will receive a NumPy array with the shape `(height, width, 3)`, where the last dimension represents the RGB values. We'll return an image as well in the form of a NumPy array. Gradio handles the preprocessing and postprocessing to convert images to NumPy arrays and vice versa. You can also control the preprocessing performed with the `type=` keyword argument. For example, if you wanted your function to take a file path to an image instead of a NumPy array, the input `Image` component could be written as: ```python gr.Image(type="filepath") ``` You can read more about the built-in Gradio components and how to customize them in the [Gradio docs](https://gradio.app/docs).
An Image Example
https://gradio.app/guides/the-interface-class
Building Interfaces - The Interface Class Guide
You can provide example data that a user can easily load into `Interface`. This can be helpful to demonstrate the types of inputs the model expects, as well as to provide a way to explore your dataset in conjunction with your model. To load example data, you can provide a **nested list** to the `examples=` keyword argument of the Interface constructor. Each sublist within the outer list represents a data sample, and each element within the sublist represents an input for each input component. The format of example data for each component is specified in the [Docs](https://gradio.app/docscomponents). $code_calculator $demo_calculator You can load a large dataset into the examples to browse and interact with the dataset through Gradio. The examples will be automatically paginated (you can configure this through the `examples_per_page` argument of `Interface`). Continue learning about examples in the [More On Examples](https://gradio.app/guides/more-on-examples) guide.
Example Inputs
https://gradio.app/guides/the-interface-class
Building Interfaces - The Interface Class Guide
In the previous example, you may have noticed the `title=` and `description=` keyword arguments in the `Interface` constructor that helps users understand your app. There are three arguments in the `Interface` constructor to specify where this content should go: - `title`: which accepts text and can display it at the very top of interface, and also becomes the page title. - `description`: which accepts text, markdown or HTML and places it right under the title. - `article`: which also accepts text, markdown or HTML and places it below the interface. ![annotated](https://github.com/gradio-app/gradio/blob/main/guides/assets/annotated.png?raw=true) Another useful keyword argument is `label=`, which is present in every `Component`. This modifies the label text at the top of each `Component`. You can also add the `info=` keyword argument to form elements like `Textbox` or `Radio` to provide further information on their usage. ```python gr.Number(label='Age', info='In years, must be greater than 0') ```
Descriptive Content
https://gradio.app/guides/the-interface-class
Building Interfaces - The Interface Class Guide
If your prediction function takes many inputs, you may want to hide some of them within a collapsed accordion to avoid cluttering the UI. The `Interface` class takes an `additional_inputs` argument which is similar to `inputs` but any input components included here are not visible by default. The user must click on the accordion to show these components. The additional inputs are passed into the prediction function, in order, after the standard inputs. You can customize the appearance of the accordion by using the optional `additional_inputs_accordion` argument, which accepts a string (in which case, it becomes the label of the accordion), or an instance of the `gr.Accordion()` class (e.g. this lets you control whether the accordion is open or closed by default). Here's an example: $code_interface_with_additional_inputs $demo_interface_with_additional_inputs
Additional Inputs within an Accordion
https://gradio.app/guides/the-interface-class
Building Interfaces - The Interface Class Guide
You can make interfaces automatically refresh by setting `live=True` in the interface. Now the interface will recalculate as soon as the user input changes. $code_calculator_live $demo_calculator_live Note there is no submit button, because the interface resubmits automatically on change.
Live Interfaces
https://gradio.app/guides/reactive-interfaces
Building Interfaces - Reactive Interfaces Guide
Some components have a "streaming" mode, such as `Audio` component in microphone mode, or the `Image` component in webcam mode. Streaming means data is sent continuously to the backend and the `Interface` function is continuously being rerun. The difference between `gr.Audio(source='microphone')` and `gr.Audio(source='microphone', streaming=True)`, when both are used in `gr.Interface(live=True)`, is that the first `Component` will automatically submit data and run the `Interface` function when the user stops recording, whereas the second `Component` will continuously send data and run the `Interface` function _during_ recording. Here is example code of streaming images from the webcam. $code_stream_frames Streaming can also be done in an output component. A `gr.Audio(streaming=True)` output component can take a stream of audio data yielded piece-wise by a generator function and combines them into a single audio file. For a detailed example, see our guide on performing [automatic speech recognition](/guides/real-time-speech-recognition) with Gradio.
Streaming Components
https://gradio.app/guides/reactive-interfaces
Building Interfaces - Reactive Interfaces Guide
To create a demo that has both the input and the output components, you simply need to set the values of the `inputs` and `outputs` parameter in `Interface()`. Here's an example demo of a simple image filter: $code_sepia_filter $demo_sepia_filter
Standard demos
https://gradio.app/guides/four-kinds-of-interfaces
Building Interfaces - Four Kinds Of Interfaces Guide
What about demos that only contain outputs? In order to build such a demo, you simply set the value of the `inputs` parameter in `Interface()` to `None`. Here's an example demo of a mock image generation model: $code_fake_gan_no_input $demo_fake_gan_no_input
Output-only demos
https://gradio.app/guides/four-kinds-of-interfaces
Building Interfaces - Four Kinds Of Interfaces Guide
Similarly, to create a demo that only contains inputs, set the value of `outputs` parameter in `Interface()` to be `None`. Here's an example demo that saves any uploaded image to disk: $code_save_file_no_output $demo_save_file_no_output
Input-only demos
https://gradio.app/guides/four-kinds-of-interfaces
Building Interfaces - Four Kinds Of Interfaces Guide
A demo that has a single component as both the input and the output. It can simply be created by setting the values of the `inputs` and `outputs` parameter as the same component. Here's an example demo of a text generation model: $code_unified_demo_text_generation $demo_unified_demo_text_generation It may be the case that none of the 4 cases fulfill your exact needs. In this case, you need to use the `gr.Blocks()` approach!
Unified demos
https://gradio.app/guides/four-kinds-of-interfaces
Building Interfaces - Four Kinds Of Interfaces Guide
Gradio demos can be easily shared publicly by setting `share=True` in the `launch()` method. Like this: ```python import gradio as gr def greet(name): return "Hello " + name + "!" demo = gr.Interface(fn=greet, inputs="textbox", outputs="textbox") demo.launch(share=True) Share your demo with just 1 extra parameter 🚀 ``` This generates a public, shareable link that you can send to anybody! When you send this link, the user on the other side can try out the model in their browser. Because the processing happens on your device (as long as your device stays on), you don't have to worry about any packaging any dependencies. ![sharing](https://github.com/gradio-app/gradio/blob/main/guides/assets/sharing.svg?raw=true) A share link usually looks something like this: **https://07ff8706ab.gradio.live**. Although the link is served through the Gradio Share Servers, these servers are only a proxy for your local server, and do not store any data sent through your app. Share links expire after 1 week. (it is [also possible to set up your own Share Server](https://github.com/huggingface/frp/) on your own cloud server to overcome this restriction.) Tip: Keep in mind that share links are publicly accessible, meaning that anyone can use your model for prediction! Therefore, make sure not to expose any sensitive information through the functions you write, or allow any critical changes to occur on your device. Or you can [add authentication to your Gradio app](authentication) as discussed below. Note that by default, `share=False`, which means that your server is only running locally. (This is the default, except in Google Colab notebooks, where share links are automatically created). As an alternative to using share links, you can use use [SSH port-forwarding](https://www.ssh.com/ssh/tunneling/example) to share your local server with specific users.
Sharing Demos
https://gradio.app/guides/sharing-your-app
Additional Features - Sharing Your App Guide
If you'd like to have a permanent link to your Gradio demo on the internet, use Hugging Face Spaces. [Hugging Face Spaces](http://huggingface.co/spaces/) provides the infrastructure to permanently host your machine learning model for free! After you have [created a free Hugging Face account](https://huggingface.co/join), you have two methods to deploy your Gradio app to Hugging Face Spaces: 1. From terminal: run `gradio deploy` in your app directory. The CLI will gather some basic metadata, upload all the files in the current directory (respecting any `.gitignore` file that may be present in the root of the directory), and then launch your app on Spaces. To update your Space, you can re-run this command or enable the Github Actions option in the CLI to automatically update the Spaces on `git push`. 2. From your browser: Drag and drop a folder containing your Gradio model and all related files [here](https://huggingface.co/new-space). See [this guide how to host on Hugging Face Spaces](https://huggingface.co/blog/gradio-spaces) for more information, or watch the embedded video: <video autoplay muted loop> <source src="https://github.com/gradio-app/gradio/blob/main/guides/assets/hf_demo.mp4?raw=true" type="video/mp4" /> </video>
Hosting on HF Spaces
https://gradio.app/guides/sharing-your-app
Additional Features - Sharing Your App Guide