[{"title":"Interface","slug":"/main/docs/gradio/interface","content":"Interface ```\ngradio.Interface(···)\n``` Description Interface is Gradio's main high-level class, and allows you to create a web-based GUI / demo around a machine learning model (or any Python function) in a few lines of code. You must specify three parameters: (1) the function to create a GUI for (2) the desired input components and (3) the desired output components. Additional parameters can be used to control the appearance and behavior of the demo.  Example Usage ```\nimport gradio as gr\n\ndef image_classifier(inp):\n    return {'cat': 0.3, 'dog': 0.7}\n\ndemo = gr.Interface(fn=image_classifier, inputs=\"image\", outputs=\"label\")\ndemo.launch()\n``` Initialization Parameters ▼ 🔗 ```\nfn: Callable\n```  the function to wrap an interface around. Often a machine learning model&#039;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.🔗 ```\ninputs: str | Component | list[str | Component] | None\n```  a single Gradio component, or list of Gradio components. Components can either be passed as instantiated objects, or referred to by their string shortcuts. The number of input components should match the number of parameters in fn. If set to None, then only the output components will be displayed.🔗 ```\noutputs: str | Component | list[str | Component] | None\n```  a single Gradio component, or list of Gradio components. Components can either be passed as instantiated objects, or referred to by their string shortcuts. The number of output components should match the number of values returned by fn. If set to None, then only the input components will be displayed.🔗 ```\nexamples: list[Any] | list[list[Any]] | str | None\n``` default = None sample inputs for the function; if provided, appear below the UI components and can be clicked to populate the interface. Should be nested list, in which the outer list consists of samples and each inner list consists of an input corresponding to each input component. A string path to a directory of examples can also be provided, but it should be within the directory with the python file running the gradio app. If there are multiple input components and a directory is provided, a log.csv file must be present in the directory to link corresponding inputs.🔗 ```\ncache_examples: bool | None\n``` default = None If True, caches examples in the server for fast runtime in examples. If &quot;lazy&quot;, then examples are cached (for all users of the app) after their first use (by any user of the app). If None, will use the GRADIO_CACHE_EXAMPLES environment variable, which should be either &quot;true&quot; or &quot;false&quot;. In HuggingFace Spaces, this parameter defaults to True (as long as `fn` and `outputs` are also provided).  Note that examples are cached separately from Gradio&#039;s queue() so certain features, such as gr.Progress(), gr.Info(), gr.Warning(), etc. will not be displayed in Gradio&#039;s UI for cached examples.🔗 ```\ncache_mode: Literal['eager', 'lazy'] | None\n``` default = None if &quot;lazy&quot;, examples are cached after their first use. If &quot;eager&quot;, all examples are cached at app launch. If None, will use the GRADIO_CACHE_MODE environment variable if defined, or default to &quot;eager&quot;. In HuggingFace Spaces, this parameter defaults to &quot;eager&quot; except for ZeroGPU Spaces, in which case it defaults to &quot;lazy&quot;.🔗 ```\nexamples_per_page: int\n``` default = 10 if examples are provided, how many to display per page.🔗 ```\nexample_labels: list[str] | None\n``` default = None a list of labels for each example. If provided, the length of this list should be the same as the number of examples, and these labels will be used in the UI instead of rendering the example values.🔗 ```\npreload_example: int | Literal[False]\n``` default = 0 If an integer is provided (and examples are being cached eagerly and none of the input components have a developer-provided `value`), the example at that index in the examples list will be preloaded when the Gradio app is first loaded. If False, no example will be preloaded.🔗 ```\nlive: bool\n``` default = False whether the interface should automatically rerun if any of the inputs change.🔗 ```\ntitle: str | I18nData | None\n``` default = None a title for the interface; if provided, appears above the input and output components in large font. Also used as the tab title when opened in a browser window.🔗 ```\ndescription: str | None\n``` default = None a description for the interface; if provided, appears above the input and output components and beneath the title in regular font. Accepts Markdown and HTML content.🔗 ```\narticle: str | None\n``` default = None an expanded article explaining the interface; if provided, appears below the input and output components in regular font. Accepts Markdown and HTML content. If it is an HTTP(S) link to a downloadable remote file, the content of this file is displayed.🔗 ```\nflagging_mode: Literal['never'] | Literal['auto'] | Literal['manual'] | None\n``` default = None one of &quot;never&quot;, &quot;auto&quot;, or &quot;manual&quot;. If &quot;never&quot; or &quot;auto&quot;, users will not see a button to flag an input and output. If &quot;manual&quot;, users will see a button to flag. If &quot;auto&quot;, every input the user submits will be automatically flagged, along with the generated output. If &quot;manual&quot;, both the input and outputs are flagged when the user clicks flag button. This parameter can be set with environmental variable GRADIO_FLAGGING_MODE; otherwise defaults to &quot;manual&quot;.🔗 ```\nflagging_options: list[str] | list[tuple[str, str]] | None\n``` default = None if provided, allows user to select from the list of options when flagging. Only applies if flagging_mode is &quot;manual&quot;. Can either be a list of tuples of the form (label, value), where label is the string that will be displayed on the button and value is the string that will be stored in the flagging CSV; or it can be a list of strings [&quot;X&quot;, &quot;Y&quot;], in which case the values will be the list of strings and the labels will [&quot;Flag as X&quot;, &quot;Flag as Y&quot;], etc.🔗 ```\nflagging_dir: str\n``` default = \".gradio/flagged\" path to the directory where flagged data is stored. If the directory does not exist, it will be created.🔗 ```\nflagging_callback: FlaggingCallback | None\n``` default = None either None or an instance of a subclass of FlaggingCallback which will be called when a sample is flagged. If set to None, an instance of gradio.flagging.CSVLogger will be created and logs will be saved to a local CSV file in flagging_dir. Default to None.🔗 ```\nanalytics_enabled: bool | None\n``` default = None whether to allow basic telemetry. If None, will use GRADIO_ANALYTICS_ENABLED environment variable if defined, or default to True.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 the maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" Controls the visibility of the prediction endpoint. Can be &quot;public&quot; (shown in API docs and callable), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable).🔗 ```\napi_name: str | None\n``` default = None defines how the prediction endpoint appears in the API docs. Can be a string or None. If set to a string, the endpoint will be exposed in the API docs with the given name. If None, the name of the function will be used.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nallow_duplication: bool\n``` default = False if True, then will show a &#039;Duplicate Spaces&#039; button on Hugging Face Spaces.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `.queue()`, which itself is 1 by default).🔗 ```\nadditional_inputs: str | Component | list[str | Component] | None\n``` default = None a single Gradio component, or list of Gradio components. Components can either be passed as instantiated objects, or referred to by their string shortcuts. These components will be rendered in an accordion below the main input components. By default, no additional input components will be displayed.🔗 ```\nadditional_inputs_accordion: str | Accordion | None\n``` default = None if a string is provided, this is the label of the `gr.Accordion` to use to contain additional inputs. A `gr.Accordion` object can be provided as well to configure other properties of the container holding the additional inputs. Defaults to a `gr.Accordion(label=&quot;Additional Inputs&quot;, open=False)`. This parameter is only used if `additional_inputs` is provided.🔗 ```\nsubmit_btn: str | Button\n``` default = \"Submit\" the button to use for submitting inputs. Defaults to a `gr.Button(&quot;Submit&quot;, variant=&quot;primary&quot;)`. This parameter does not apply if the Interface is output-only, in which case the submit button always displays &quot;Generate&quot;. Can be set to a string (which becomes the button label) or a `gr.Button` object (which allows for more customization).🔗 ```\nstop_btn: str | Button\n``` default = \"Stop\" the button to use for stopping the interface. Defaults to a `gr.Button(&quot;Stop&quot;, variant=&quot;stop&quot;, visible=False)`. Can be set to a string (which becomes the button label) or a `gr.Button` object (which allows for more customization).🔗 ```\nclear_btn: str | Button | None\n``` default = \"Clear\" the button to use for clearing the inputs. Defaults to a `gr.Button(&quot;Clear&quot;, variant=&quot;secondary&quot;)`. Can be set to a string (which becomes the button label) or a `gr.Button` object (which allows for more customization). Can be set to None, which hides the button.🔗 ```\ndelete_cache: tuple[int, int] | None\n``` default = None a tuple corresponding [frequency, age] both expressed in number of seconds. Every `frequency` seconds, the temporary files created by this Blocks instance will be deleted if more than `age` seconds have passed since the file was created. For example, setting this to (86400, 86400) will delete temporary files every day. The cache will be deleted entirely when the server restarts. If None, no cache deletion will occur.🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nfill_width: bool\n``` default = False whether to horizontally expand to fill container fully. If False, centers and constrains app to a maximum width.🔗 ```\ntime_limit: int | None\n``` default = 30 The time limit for the stream to run. Default is 30 seconds. Parameter only used for streaming images or audio if the interface is live and the input components are set to &quot;streaming=True&quot;.🔗 ```\nstream_every: float\n``` default = 0.5 The latency (in seconds) at which stream chunks are sent to the backend. Defaults to 0.5 seconds. Parameter only used for streaming images or audio if the interface is live and the input components are set to &quot;streaming=True&quot;.🔗 ```\ndeep_link: str | DeepLinkButton | bool | None\n``` default = None a string or `gr.DeepLinkButton` object that creates a unique URL you can use to share your app and all components **as they currently are** with others. Automatically enabled on Hugging Face Spaces unless explicitly set to False.🔗 ```\nvalidator: Callable | None\n``` default = None a function that takes in the inputs and can optionally return a gr.validate() object for each input. Demos hello_worldhello_world_2hello_world_3  Methods launch  ```\ngradio.Interface.launch(···)\n``` Description  Launches a simple web server that serves the demo. Can also be used to create a public link used by anyone to access the demo from their browser by setting share=True. Example Usage  ```\nimport gradio as gr\ndef reverse(text):\n    return text[::-1]\ndemo = gr.Interface(reverse, \"text\", \"text\")\ndemo.launch(share=True, auth=(\"username\", \"password\"))\n``` Parameters ▼ 🔗 ```\ninline: bool | None\n``` default = None whether to display in the gradio app inline in an iframe. Defaults to True in python notebooks; False otherwise.🔗 ```\ninbrowser: bool\n``` default = False whether to automatically launch the gradio app in a new tab on the default browser.🔗 ```\nshare: bool | None\n``` default = None whether to create a publicly shareable link for the gradio app. Creates an SSH tunnel to make your UI accessible from anywhere. If not provided, it is set to False by default every time, except when running in Google Colab. When localhost is not accessible (e.g. Google Colab), setting share=False is not supported. Can be set by environment variable GRADIO_SHARE=True.🔗 ```\ndebug: bool\n``` default = False if True, blocks the main thread from running. If running in Google Colab, this is needed to print the errors in the cell output.🔗 ```\nmax_threads: int\n``` default = 40 the maximum number of total threads that the Gradio app can generate in parallel. The default is inherited from the starlette library (currently 40).🔗 ```\nauth: Callable[[str, str], bool] | tuple[str, str] | list[tuple[str, str]] | None\n``` default = None If provided, username and password (or list of username-password tuples) required to access app. Can also provide function that takes username and password and returns True if valid login.🔗 ```\nauth_message: str | None\n``` default = None If provided, HTML message provided on login page.🔗 ```\nprevent_thread_lock: bool\n``` default = False By default, the gradio app blocks the main thread while the server is running. If set to True, the gradio app will not block and the gradio server will terminate as soon as the script finishes.🔗 ```\nshow_error: bool\n``` default = False If True, any errors in the gradio app will be displayed in an alert modal and printed in the browser console log. They will also be displayed in the alert modal of downstream apps that gr.load() this app.🔗 ```\nserver_name: str | None\n``` default = None to make app accessible on local network, set this to &quot;0.0.0.0&quot;. Can be set by environment variable GRADIO_SERVER_NAME. If None, will use &quot;127.0.0.1&quot;.🔗 ```\nserver_port: int | None\n``` default = None will start gradio app on this port (if available). Can be set by environment variable GRADIO_SERVER_PORT. If None, will search for an available port starting at 7860.🔗 ```\nheight: int\n``` default = 500 The height in pixels of the iframe element containing the gradio app (used if inline=True)🔗 ```\nwidth: int | str\n``` default = \"100%\" The width in pixels of the iframe element containing the gradio app (used if inline=True)🔗 ```\nfavicon_path: str | Path | None\n``` default = None If a path to a file (.png, .gif, or .ico) is provided, it will be used as the favicon for the web page.🔗 ```\nssl_keyfile: str | None\n``` default = None If a path to a file is provided, will use this as the private key file to create a local server running on https.🔗 ```\nssl_certfile: str | None\n``` default = None If a path to a file is provided, will use this as the signed certificate for https. Needs to be provided if ssl_keyfile is provided.🔗 ```\nssl_keyfile_password: str | None\n``` default = None If a password is provided, will use this with the ssl certificate for https.🔗 ```\nssl_verify: bool\n``` default = True If False, skips certificate validation which allows self-signed certificates to be used.🔗 ```\nquiet: bool\n``` default = False If True, suppresses most print statements.🔗 ```\nfooter_links: list[Literal['api', 'gradio', 'settings', 'runs'] | dict[str, str]] | None\n``` default = None The links to display in the footer of the app. Accepts a list, where each element of the list must be one of &quot;api&quot;, &quot;gradio&quot;, &quot;settings&quot;, or &quot;runs&quot; corresponding to the API docs, &quot;built with Gradio&quot;, the settings page, and the run history page respectively. The &quot;runs&quot; link only appears if `run_history` is True and the browser has at least one saved run for this app. If None, all four links will be shown in the footer. An empty list means that no footer is shown.🔗 ```\nrun_history: bool | None\n``` default = None If True, users can review and reload calls from the run history page at /gradio_api/runs. Runs are saved privately in the browser by default; from that page, a user can instead connect a Hugging Face bucket and save future runs there. Browser history is scoped to the logged-in user if the app uses `auth`. If False, nothing is recorded, the run history page is disabled, and any runs previously saved by this app are deleted from the browser. If None, will use the GRADIO_RUN_HISTORY environment variable or default to True.🔗 ```\nallowed_paths: list[str] | None\n``` default = None List of complete filepaths or parent directories that gradio is allowed to serve. Must be absolute paths. Warning: if you provide directories, any files in these directories or their subdirectories are accessible to all users of your app. Can be set by comma separated environment variable GRADIO_ALLOWED_PATHS. These files are generally assumed to be secure and will be displayed in the browser when possible.🔗 ```\nblocked_paths: list[str] | None\n``` default = None List of complete filepaths or parent directories that gradio is not allowed to serve (i.e. users of your app are not allowed to access). Must be absolute paths. Warning: takes precedence over `allowed_paths` and all other directories exposed by Gradio by default. Can be set by comma separated environment variable GRADIO_BLOCKED_PATHS.🔗 ```\nroot_path: str | None\n``` default = None The root path (or &quot;mount point&quot;) of the application, if it&#039;s not served from the root (&quot;/&quot;) of the domain. Often used when the application is behind a reverse proxy that forwards requests to the application. For example, if the application is served at &quot;https://example.com/myapp&quot;, the `root_path` should be set to &quot;/myapp&quot;. A full URL beginning with http:// or https:// can be provided, which will be used as the root path in its entirety. Can be set by environment variable GRADIO_ROOT_PATH. Defaults to &quot;&quot;.🔗 ```\napp_kwargs: dict[str, Any] | None\n``` default = None Additional keyword arguments to pass to the underlying FastAPI app as a dictionary of parameter keys and argument values. For example, `{&quot;docs_url&quot;: &quot;/docs&quot;}`🔗 ```\nstate_session_capacity: int\n``` default = 10000 The maximum number of sessions whose information to store in memory. If the number of sessions exceeds this number, the oldest sessions will be removed. Reduce capacity to reduce memory usage when using gradio.State or returning updated components from functions. Defaults to 10000.🔗 ```\nshare_server_address: str | None\n``` default = None Use this to specify a custom FRP server and port for sharing Gradio apps (only applies if share=True). If not provided, will use the default FRP server at https://gradio.live. See https://github.com/huggingface/frp for more information.🔗 ```\nshare_server_protocol: Literal['http', 'https'] | None\n``` default = None Use this to specify the protocol to use for the share links. Defaults to &quot;https&quot;, unless a custom share_server_address is provided, in which case it defaults to &quot;http&quot;. If you are using a custom share_server_address and want to use https, you must set this to &quot;https&quot;.🔗 ```\nshare_server_tls_certificate: str | None\n``` default = None The path to a TLS certificate file to use when connecting to a custom share server. This parameter is not used with the default FRP server at https://gradio.live. Otherwise, you must provide a valid TLS certificate file (e.g. a &quot;cert.pem&quot;) relative to the current working directory, or the connection will not use TLS encryption, which is insecure.🔗 ```\nauth_dependency: Callable[[fastapi.Request], str | None | Awaitable[str | None]] | None\n``` default = None A function that takes a FastAPI request and returns a string user ID or None. If the function returns None for a specific request, that user is not authorized to access the app (they will see a 401 Unauthorized response). To be used with external authentication systems like OAuth. Cannot be used with `auth`.🔗 ```\nmax_file_size: str | int | None\n``` default = None The maximum file size in bytes that can be uploaded. Can be a string of the form &quot;&lt;value&gt;&lt;unit&gt;&quot;, where value is any positive integer and unit is one of &quot;b&quot;, &quot;kb&quot;, &quot;mb&quot;, &quot;gb&quot;, &quot;tb&quot;. If None, no limit is set.🔗 ```\nenable_monitoring: bool | None\n``` default = None Enables traffic monitoring of the app through the /monitoring endpoint. By default is None, which enables this endpoint. If explicitly True, will also print the monitoring URL to the console. If False, will disable monitoring altogether.🔗 ```\nstrict_cors: bool\n``` default = True If True, prevents external domains from making requests to a Gradio server running on localhost. If False, allows requests to localhost that originate from localhost but also, crucially, from &quot;null&quot;. This parameter should normally be True to prevent CSRF attacks but may need to be False when embedding a *locally-running Gradio app* using web components.🔗 ```\nnode_server_name: str | None\n``` default = None 🔗 ```\nnode_port: int | None\n``` default = None 🔗 ```\nssr_mode: bool | None\n``` default = None If True, the Gradio app will be rendered using server-side rendering mode, which is typically more performant and provides better SEO, but this requires Node 20+ to be installed on the system. If False, the app will be rendered using client-side rendering mode. If None, will use GRADIO_SSR_MODE environment variable or default to False.🔗 ```\npwa: bool | None\n``` default = None If True, the Gradio app will be set up as an installable PWA (Progressive Web App). If set to None (default behavior), then the PWA feature will be enabled if this Gradio app is launched on Spaces, but not otherwise.🔗 ```\nmcp_server: bool | None\n``` default = None If True, the Gradio app will be set up as an MCP server and documented functions will be added as MCP tools. If None (default behavior), then the GRADIO_MCP_SERVER environment variable will be used to determine if the MCP server should be enabled.🔗 ```\nnum_workers: int | None\n``` default = None Number of background workers to launch in the background to serve file I/O and static assets. This offloads traffic from the main server and reduces latency. Only has an effect if ssr mode is set.🔗 ```\ni18n: I18n | None\n``` default = None An I18n instance containing custom translations, which are used to translate strings in our components (e.g. the labels of components or Markdown strings). This feature can only be used to translate static text in the frontend, not values in the backend.🔗 ```\ntheme: Theme | str | None\n``` default = None A Theme object or a string representing a theme. If a string, will look for a built-in theme with that name (e.g. &quot;soft&quot; or &quot;default&quot;), or will attempt to load a theme from the Hugging Face Hub (e.g. &quot;gradio/monochrome&quot;). If None, will use the Default theme.🔗 ```\ncss: str | None\n``` default = None Custom css as a code string. This css will be included in the demo webpage.🔗 ```\ncss_paths: str | Path | list[str | Path] | None\n``` default = None Custom css as a pathlib.Path to a css file or a list of such paths. This css files will be read, concatenated, and included in the demo webpage. If the `css` parameter is also set, the css from `css` will be included first.🔗 ```\njs: str | Literal[True] | None\n``` default = None Custom JavaScript provided as either a function or a raw code string. A function is automatically invoked; otherwise the code is executed directly when the page loads. To run JavaScript as a document-level `&lt;script&gt;` tag, use the `head` parameter.🔗 ```\nhead: str | None\n``` default = None Custom html code to insert into the head of the demo webpage. This can be used to add custom meta tags, multiple scripts, stylesheets, etc. to the page.🔗 ```\nhead_paths: str | Path | list[str | Path] | None\n``` default = None Custom html code as a pathlib.Path to a html file or a list of such paths. This html files will be read, concatenated, and included in the head of the demo webpage. If the `head` parameter is also set, the html from `head` will be included first.load  ```\ngradio.Interface.load(block, ···)\n``` Description  This listener is triggered when the Interface initially loads in the browser.  Parameters ▼ 🔗 ```\nblock: Block | None\n```  🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.from_pipeline  ```\ngradio.Interface.from_pipeline(pipeline, ···)\n``` Description  Class method that constructs an Interface from a Hugging Face transformers.Pipeline or diffusers.DiffusionPipeline object. The input and output components are automatically determined from the pipeline. Example Usage  ```\nimport gradio as gr\nfrom transformers import pipeline\npipe = pipeline(\"image-classification\")\ngr.Interface.from_pipeline(pipe).launch()\n``` Parameters ▼ 🔗 ```\npipeline: Pipeline | DiffusionPipeline\n```  the pipeline object to use.integrate  ```\ngradio.Interface.integrate(···)\n``` Description  A catch-all method for integrating with other libraries. This method should be run after launch()  Parameters ▼ 🔗 ```\ncomet_ml: \n``` default = None If a comet_ml Experiment object is provided, will integrate with the experiment and appear on Comet dashboard🔗 ```\nwandb: ModuleType | None\n``` default = None If the wandb module is provided, will integrate with it and appear on WandB dashboard🔗 ```\nmlflow: ModuleType | None\n``` default = None If the mlflow module  is provided, will integrate with the experiment and appear on ML Flow dashboardqueue  ```\ngradio.Interface.queue(···)\n``` Description  By enabling the queue you can control when users know their position in the queue, and set a limit on maximum number of events allowed. Example Usage  ```\ndemo = gr.Interface(image_generator, gr.Textbox(), gr.Image())\ndemo.queue(max_size=20)\ndemo.launch()\n``` Parameters ▼ 🔗 ```\nstatus_update_rate: float | Literal['auto']\n``` default = \"auto\" If &quot;auto&quot;, Queue will send status estimations to all clients whenever a job is finished. Otherwise Queue will send status at regular intervals set by this parameter as the number of seconds.🔗 ```\napi_open: bool | None\n``` default = None If True, the REST routes of the backend will be open, allowing requests made directly to those endpoints to skip the queue.🔗 ```\nmax_size: int | None\n``` default = None The maximum number of events the queue will store at any given moment. If the queue is full, new events will not be added and a user will receive a message saying that the queue is full. If None, the queue size will be unlimited.🔗 ```\ndefault_concurrency_limit: int | None | Literal['not_set']\n``` default = \"not_set\" The default value of `concurrency_limit` to use for event listeners that don&#039;t specify a value. Can be set by environment variable GRADIO_DEFAULT_CONCURRENCY_LIMIT. Defaults to 1 if not set otherwise.  The Interface ClassInterface StateReactive InterfacesFour Kinds Of InterfacesSharing Your App","type":"DOCS"},{"title":"ChatInterface","slug":"/main/docs/gradio/chatinterface","content":"ChatInterface ```\ngradio.ChatInterface(fn, ···)\n``` Description ChatInterface is Gradio's high-level abstraction for creating chatbot UIs, and allows you to create a web-based demo around a chatbot model in a few lines of code. Only one parameter is required: fn, which takes a function that governs the response of the chatbot based on the user input and chat history. Additional parameters can be used to control the appearance and behavior of the demo.  Example Usage Basic Example: A chatbot that echoes back the users’s message ```\nimport gradio as gr\n\ndef echo(message, history):\n    return message\n\ndemo = gr.ChatInterface(fn=echo, examples=[\"hello\", \"hola\", \"merhaba\"], title=\"Echo Bot\")\ndemo.launch()\n``` Custom Chatbot: A gr.ChatInterface with a custom gr.Chatbot that includes a placeholder as well as upvote/downvote buttons. The upvote/downvote buttons are automatically added when a .like() event is attached to a gr.Chatbot. In order to attach event listeners to your custom chatbot, wrap the gr.Chatbot as well as the gr.ChatInterface inside of a gr.Blocks like this: ```\nimport gradio as gr\n\ndef yes(message, history):\n    return \"yes\"\n\ndef vote(data: gr.LikeData):\n    if data.liked:\n        print(\"You upvoted this response: \" + data.value[\"value\"])\n    else:\n        print(\"You downvoted this response: \" + data.value[\"value\"])\n\nwith gr.Blocks() as demo:\n    chatbot = gr.Chatbot(placeholder=\"&lt;strong>Your Personal Yes-Man&lt;/strong>&lt;br>Ask Me Anything\")\n    chatbot.like(vote, None, None)\n    gr.ChatInterface(fn=yes, chatbot=chatbot)\n    \ndemo.launch()\n``` Initialization Parameters ▼ 🔗 ```\nfn: Callable\n```  the function to wrap the chat interface around. The function should accept two parameters: a `str` representing the input message and `list` of openai-style dictionaries: {&quot;role&quot;: &quot;user&quot; | &quot;assistant&quot;, &quot;content&quot;: `str` | {&quot;path&quot;: `str`} | `gr.Component`} representing the chat history. The function should return/yield a `str` (for a simple message), a supported Gradio component (e.g. gr.Image to return an image), a `dict` (for a complete openai-style message response), or a `list` of such messages.🔗 ```\nmultimodal: bool\n``` default = False if True, the chat interface will use a `gr.MultimodalTextbox` component for the input, which allows for the uploading of multimedia files. If False, the chat interface will use a gr.Textbox component for the input. If this is True, the first argument of `fn` should accept not a `str` message but a `dict` message with keys &quot;text&quot; and &quot;files&quot;🔗 ```\nchatbot: Chatbot | None\n``` default = None an instance of the gr.Chatbot component to use for the chat interface, if you would like to customize the chatbot properties. If not provided, a default gr.Chatbot component will be created.🔗 ```\ntextbox: Textbox | MultimodalTextbox | None\n``` default = None an instance of the gr.Textbox or gr.MultimodalTextbox component to use for the chat interface, if you would like to customize the textbox properties. If not provided, a default gr.Textbox or gr.MultimodalTextbox component will be created.🔗 ```\nadditional_inputs: str | Component | list[str | Component] | None\n``` default = None an instance or list of instances of gradio components (or their string shortcuts) to use as additional inputs to the chatbot. If the components are not already rendered in a surrounding Blocks, then the components will be displayed under the chatbot, in an accordion. The values of these components will be passed into `fn` as arguments in order after the chat history.🔗 ```\nadditional_inputs_accordion: str | Accordion | None\n``` default = None if a string is provided, this is the label of the `gr.Accordion` to use to contain additional inputs. A `gr.Accordion` object can be provided as well to configure other properties of the container holding the additional inputs. Defaults to a `gr.Accordion(label=&quot;Additional Inputs&quot;, open=False)`. This parameter is only used if `additional_inputs` is provided.🔗 ```\nadditional_outputs: Component | list[Component] | None\n``` default = None an instance or list of instances of gradio components to use as additional outputs from the chat function. These must be components that are already defined in the same Blocks scope. If provided, the chat function should return additional values for these components. See $demo/chatinterface_artifacts.🔗 ```\neditable: bool\n``` default = False if True, users can edit past messages to regenerate responses.🔗 ```\nexamples: list[str] | list[MultimodalValue] | list[list] | None\n``` default = None sample inputs for the function; if provided, appear within the chatbot and can be clicked to populate the chatbot input. Should be a list of strings representing text-only examples, or a list of dictionaries (with keys `text` and `files`) representing multimodal examples. If `additional_inputs` are provided, the examples must be a list of lists, where the first element of each inner list is the string or dictionary example message and the remaining elements are the example values for the additional inputs -- in this case, the examples will appear under the chatbot.🔗 ```\nexample_labels: list[str] | None\n``` default = None labels for the examples, to be displayed instead of the examples themselves. If provided, should be a list of strings with the same length as the examples list. Only applies when examples are displayed within the chatbot (i.e. when `additional_inputs` is not provided).🔗 ```\nexample_icons: list[str] | None\n``` default = None icons for the examples, to be displayed above the examples. If provided, should be a list of string URLs or local paths with the same length as the examples list. Only applies when examples are displayed within the chatbot (i.e. when `additional_inputs` is not provided).🔗 ```\nrun_examples_on_click: bool\n``` default = True if True, clicking on an example will run the example through the chatbot fn and the response will be displayed in the chatbot. If False, clicking on an example will only populate the chatbot input with the example message. Has no effect if `cache_examples` is True🔗 ```\ncache_examples: bool | None\n``` default = None if True, caches examples in the server for fast runtime in examples. The default option in HuggingFace Spaces is True. The default option elsewhere is False.  Note that examples are cached separately from Gradio&#039;s queue() so certain features, such as gr.Progress(), gr.Info(), gr.Warning(), etc. will not be displayed in Gradio&#039;s UI for cached examples.🔗 ```\ncache_mode: Literal['eager', 'lazy'] | None\n``` default = None if &quot;eager&quot;, all examples are cached at app launch. If &quot;lazy&quot;, examples are cached for all users after the first use by any user of the app. If None, will use the GRADIO_CACHE_MODE environment variable if defined, or default to &quot;eager&quot;.🔗 ```\ntitle: str | I18nData | None\n``` default = None a title for the interface; if provided, appears above chatbot in large font. Also used as the tab title when opened in a browser window.🔗 ```\ndescription: str | None\n``` default = None a description for the interface; if provided, appears above the chatbot and beneath the title in regular font. Accepts Markdown and HTML content.🔗 ```\nflagging_mode: Literal['never', 'manual'] | None\n``` default = None one of &quot;never&quot;, &quot;manual&quot;. If &quot;never&quot;, users will not see a button to flag an input and output. If &quot;manual&quot;, users will see a button to flag.🔗 ```\nflagging_options: list[str] | tuple[str, ...] | None\n``` default = ('Like', 'Dislike') a list of strings representing the options that users can choose from when flagging a message. Defaults to [&quot;Like&quot;, &quot;Dislike&quot;]. These two case-sensitive strings will render as &quot;thumbs up&quot; and &quot;thumbs down&quot; icon respectively next to each bot message, but any other strings appear under a separate flag icon.🔗 ```\nflagging_dir: str\n``` default = \".gradio/flagged\" path to the the directory where flagged data is stored. If the directory does not exist, it will be created.🔗 ```\nanalytics_enabled: bool | None\n``` default = None whether to allow basic telemetry. If None, will use GRADIO_ANALYTICS_ENABLED environment variable if defined, or default to True.🔗 ```\nautofocus: bool\n``` default = True if True, autofocuses to the textbox when the page loads.🔗 ```\nautoscroll: bool\n``` default = True If True, will automatically scroll to the bottom of the chatbot when a new message appears, unless the user scrolls up. If False, will not scroll to the bottom of the chatbot automatically.🔗 ```\nsubmit_btn: str | bool | None\n``` default = True If True, will show a submit button with a submit icon within the textbox. If a string, will use that string as the submit button text in place of the icon. If False, will not show a submit button.🔗 ```\nstop_btn: str | bool | None\n``` default = True If True, will show a button with a stop icon during generator executions, to stop generating. If a string, will use that string as the submit button text in place of the stop icon. If False, will not show a stop button.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` default = \"default\" if set, this is the maximum number of chatbot submissions that can be running simultaneously. Can be set to None to mean no limit (any number of chatbot submissions can be running simultaneously). Set to &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `.queue()`, which is 1 by default).🔗 ```\ndelete_cache: tuple[int, int] | None\n``` default = None a tuple corresponding [frequency, age] both expressed in number of seconds. Every `frequency` seconds, the temporary files created by this Blocks instance will be deleted if more than `age` seconds have passed since the file was created. For example, setting this to (86400, 86400) will delete temporary files every day. The cache will be deleted entirely when the server restarts. If None, no cache deletion will occur.🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"minimal\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nfill_height: bool\n``` default = True if True, the chat interface will expand to the height of window.🔗 ```\nfill_width: bool\n``` default = False Whether to horizontally expand to fill container fully. If False, centers and constrains app to a maximum width.🔗 ```\napi_name: str | None\n``` default = None defines how the chat endpoint appears in the API docs. Can be a string or None. If set to a string, the endpoint will be exposed in the API docs with the given name. If None, the name of the function will be used.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" Controls the visibility of the chat endpoint. Can be &quot;public&quot; (shown in API docs and callable), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable).🔗 ```\nsave_history: bool\n``` default = False if True, will save the chat history to the browser&#039;s local storage and display previous conversations in a side panel.🔗 ```\nvalidator: Callable | None\n``` default = None a function that takes in the inputs and can optionally return a gr.validate() object for each input. Demos chatinterface_random_responsechatinterface_streaming_echochatinterface_artifacts   Creating A Chatbot FastChatinterface ExamplesAgents And Tool UsageChatbot Specific Events","type":"DOCS"},{"title":"TabbedInterface","slug":"/main/docs/gradio/tabbedinterface","content":"TabbedInterface ```\ngradio.TabbedInterface(interface_list, ···)\n``` Description A TabbedInterface is created by providing a list of Interfaces or Blocks, each of which gets rendered in a separate tab. Only the components from the Interface/Blocks will be rendered in the tab.  Initialization Parameters ▼ 🔗 ```\ninterface_list: list[Blocks]\n```  A list of Interfaces (or Blocks) to be rendered in the tabs.🔗 ```\ntab_names: list[str] | None\n``` default = None A list of tab names. If None, the tab names will be &quot;Tab 1&quot;, &quot;Tab 2&quot;, etc.🔗 ```\ntitle: str | None\n``` default = None The tab title to display when this demo is opened in a browser window.🔗 ```\nanalytics_enabled: bool | None\n``` default = None Whether to allow basic telemetry. If None, will use GRADIO_ANALYTICS_ENABLED environment variable or default to True.🔗 ```\ntabs_kwargs: dict[str, Any] | None\n``` default = None Additional keyword arguments to pass to the internal `gr.Tabs` layout. Demos tabbed_interface_lite   ","type":"DOCS"},{"title":"Blocks","slug":"/main/docs/gradio/blocks","content":"Blocks ```\nwith gradio.Blocks():\n``` Description Blocks is Gradio's low-level API that allows you to create more custom web applications and demos than Interfaces (yet still entirely in Python).   Compared to the Interface class, Blocks offers more flexibility and control over: (1) the layout of components (2) the events that trigger the execution of functions (3) data flows (e.g. inputs can trigger outputs, which can trigger the next level of outputs). Blocks also offers ways to group together related demos such as with tabs.   The basic usage of Blocks is as follows: create a Blocks object, then use it as a context (with the \"with\" statement), and then define layouts, components, or events within the Blocks context. Finally, call the launch() method to launch the demo.  Example Usage ```\nimport gradio as gr\ndef update(name):\n    return f\"Welcome to Gradio, {name}!\"\n\nwith gr.Blocks() as demo:\n    gr.Markdown(\"Start typing below and then click **Run** to see the output.\")\n    with gr.Row():\n        inp = gr.Textbox(placeholder=\"What is your name?\")\n        out = gr.Textbox()\n    btn = gr.Button(\"Run\")\n    btn.click(fn=update, inputs=inp, outputs=out)\n\ndemo.launch()\n``` Initialization Parameters ▼ 🔗 ```\nanalytics_enabled: bool | None\n``` default = None Whether to allow basic telemetry. If None, will use GRADIO_ANALYTICS_ENABLED environment variable or default to True.🔗 ```\nmode: str\n``` default = \"blocks\" A human-friendly name for the kind of Blocks or Interface being created. Used internally for analytics.🔗 ```\ntitle: str | I18nData\n``` default = \"Gradio\" The tab title to display when this is opened in a browser window.🔗 ```\nfill_height: bool\n``` default = False Whether to vertically expand top-level child components to the height of the window. If True, expansion occurs when the scale value of the child components &gt;= 1.🔗 ```\nfill_width: bool\n``` default = False Whether to horizontally expand to fill container fully. If False, centers and constrains app to a maximum width. Only applies if this is the outermost `Blocks` in your Gradio app.🔗 ```\ndelete_cache: tuple[int, int] | None\n``` default = None A tuple corresponding [frequency, age] both expressed in number of seconds. Every `frequency` seconds, the temporary files created by this Blocks instance will be deleted if more than `age` seconds have passed since the file was created. For example, setting this to (86400, 86400) will delete temporary files every day. The cache will be deleted entirely when the server restarts. If None, no cache deletion will occur. Demos blocks_helloblocks_flipperblocks_kinematics  Methods launch  ```\ngradio.Blocks.launch(···)\n``` Description  Launches a simple web server that serves the demo. Can also be used to create a public link used by anyone to access the demo from their browser by setting share=True. Example Usage  ```\nimport gradio as gr\ndef reverse(text):\n    return text[::-1]\nwith gr.Blocks() as demo:\n    button = gr.Button(value=\"Reverse\")\n    button.click(reverse, gr.Textbox(), gr.Textbox())\ndemo.launch(share=True, auth=(\"username\", \"password\"))\n``` Parameters ▼ 🔗 ```\ninline: bool | None\n``` default = None whether to display in the gradio app inline in an iframe. Defaults to True in python notebooks; False otherwise.🔗 ```\ninbrowser: bool\n``` default = False whether to automatically launch the gradio app in a new tab on the default browser.🔗 ```\nshare: bool | None\n``` default = None whether to create a publicly shareable link for the gradio app. Creates an SSH tunnel to make your UI accessible from anywhere. If not provided, it is set to False by default every time, except when running in Google Colab. When localhost is not accessible (e.g. Google Colab), setting share=False is not supported. Can be set by environment variable GRADIO_SHARE=True.🔗 ```\ndebug: bool\n``` default = False if True, blocks the main thread from running. If running in Google Colab, this is needed to print the errors in the cell output.🔗 ```\nmax_threads: int\n``` default = 40 the maximum number of total threads that the Gradio app can generate in parallel. The default is inherited from the starlette library (currently 40).🔗 ```\nauth: Callable[[str, str], bool] | tuple[str, str] | list[tuple[str, str]] | None\n``` default = None If provided, username and password (or list of username-password tuples) required to access app. Can also provide function that takes username and password and returns True if valid login.🔗 ```\nauth_message: str | None\n``` default = None If provided, HTML message provided on login page.🔗 ```\nprevent_thread_lock: bool\n``` default = False By default, the gradio app blocks the main thread while the server is running. If set to True, the gradio app will not block and the gradio server will terminate as soon as the script finishes.🔗 ```\nshow_error: bool\n``` default = False If True, any errors in the gradio app will be displayed in an alert modal and printed in the browser console log. They will also be displayed in the alert modal of downstream apps that gr.load() this app.🔗 ```\nserver_name: str | None\n``` default = None to make app accessible on local network, set this to &quot;0.0.0.0&quot;. Can be set by environment variable GRADIO_SERVER_NAME. If None, will use &quot;127.0.0.1&quot;.🔗 ```\nserver_port: int | None\n``` default = None will start gradio app on this port (if available). Can be set by environment variable GRADIO_SERVER_PORT. If None, will search for an available port starting at 7860.🔗 ```\nheight: int\n``` default = 500 The height in pixels of the iframe element containing the gradio app (used if inline=True)🔗 ```\nwidth: int | str\n``` default = \"100%\" The width in pixels of the iframe element containing the gradio app (used if inline=True)🔗 ```\nfavicon_path: str | Path | None\n``` default = None If a path to a file (.png, .gif, or .ico) is provided, it will be used as the favicon for the web page.🔗 ```\nssl_keyfile: str | None\n``` default = None If a path to a file is provided, will use this as the private key file to create a local server running on https.🔗 ```\nssl_certfile: str | None\n``` default = None If a path to a file is provided, will use this as the signed certificate for https. Needs to be provided if ssl_keyfile is provided.🔗 ```\nssl_keyfile_password: str | None\n``` default = None If a password is provided, will use this with the ssl certificate for https.🔗 ```\nssl_verify: bool\n``` default = True If False, skips certificate validation which allows self-signed certificates to be used.🔗 ```\nquiet: bool\n``` default = False If True, suppresses most print statements.🔗 ```\nfooter_links: list[Literal['api', 'gradio', 'settings', 'runs'] | dict[str, str]] | None\n``` default = None The links to display in the footer of the app. Accepts a list, where each element of the list must be one of &quot;api&quot;, &quot;gradio&quot;, &quot;settings&quot;, or &quot;runs&quot; corresponding to the API docs, &quot;built with Gradio&quot;, the settings page, and the run history page respectively. The &quot;runs&quot; link only appears if `run_history` is True and the browser has at least one saved run for this app. If None, all four links will be shown in the footer. An empty list means that no footer is shown.🔗 ```\nrun_history: bool | None\n``` default = None If True, users can review and reload calls from the run history page at /gradio_api/runs. Runs are saved privately in the browser by default; from that page, a user can instead connect a Hugging Face bucket and save future runs there. Browser history is scoped to the logged-in user if the app uses `auth`. If False, nothing is recorded, the run history page is disabled, and any runs previously saved by this app are deleted from the browser. If None, will use the GRADIO_RUN_HISTORY environment variable or default to True.🔗 ```\nallowed_paths: list[str] | None\n``` default = None List of complete filepaths or parent directories that gradio is allowed to serve. Must be absolute paths. Warning: if you provide directories, any files in these directories or their subdirectories are accessible to all users of your app. Can be set by comma separated environment variable GRADIO_ALLOWED_PATHS. These files are generally assumed to be secure and will be displayed in the browser when possible.🔗 ```\nblocked_paths: list[str] | None\n``` default = None List of complete filepaths or parent directories that gradio is not allowed to serve (i.e. users of your app are not allowed to access). Must be absolute paths. Warning: takes precedence over `allowed_paths` and all other directories exposed by Gradio by default. Can be set by comma separated environment variable GRADIO_BLOCKED_PATHS.🔗 ```\nroot_path: str | None\n``` default = None The root path (or &quot;mount point&quot;) of the application, if it&#039;s not served from the root (&quot;/&quot;) of the domain. Often used when the application is behind a reverse proxy that forwards requests to the application. For example, if the application is served at &quot;https://example.com/myapp&quot;, the `root_path` should be set to &quot;/myapp&quot;. A full URL beginning with http:// or https:// can be provided, which will be used as the root path in its entirety. Can be set by environment variable GRADIO_ROOT_PATH. Defaults to &quot;&quot;.🔗 ```\napp_kwargs: dict[str, Any] | None\n``` default = None Additional keyword arguments to pass to the underlying FastAPI app as a dictionary of parameter keys and argument values. For example, `{&quot;docs_url&quot;: &quot;/docs&quot;}`🔗 ```\nstate_session_capacity: int\n``` default = 10000 The maximum number of sessions whose information to store in memory. If the number of sessions exceeds this number, the oldest sessions will be removed. Reduce capacity to reduce memory usage when using gradio.State or returning updated components from functions. Defaults to 10000.🔗 ```\nshare_server_address: str | None\n``` default = None Use this to specify a custom FRP server and port for sharing Gradio apps (only applies if share=True). If not provided, will use the default FRP server at https://gradio.live. See https://github.com/huggingface/frp for more information.🔗 ```\nshare_server_protocol: Literal['http', 'https'] | None\n``` default = None Use this to specify the protocol to use for the share links. Defaults to &quot;https&quot;, unless a custom share_server_address is provided, in which case it defaults to &quot;http&quot;. If you are using a custom share_server_address and want to use https, you must set this to &quot;https&quot;.🔗 ```\nshare_server_tls_certificate: str | None\n``` default = None The path to a TLS certificate file to use when connecting to a custom share server. This parameter is not used with the default FRP server at https://gradio.live. Otherwise, you must provide a valid TLS certificate file (e.g. a &quot;cert.pem&quot;) relative to the current working directory, or the connection will not use TLS encryption, which is insecure.🔗 ```\nauth_dependency: Callable[[fastapi.Request], str | None | Awaitable[str | None]] | None\n``` default = None A function that takes a FastAPI request and returns a string user ID or None. If the function returns None for a specific request, that user is not authorized to access the app (they will see a 401 Unauthorized response). To be used with external authentication systems like OAuth. Cannot be used with `auth`.🔗 ```\nmax_file_size: str | int | None\n``` default = None The maximum file size in bytes that can be uploaded. Can be a string of the form &quot;&lt;value&gt;&lt;unit&gt;&quot;, where value is any positive integer and unit is one of &quot;b&quot;, &quot;kb&quot;, &quot;mb&quot;, &quot;gb&quot;, &quot;tb&quot;. If None, no limit is set.🔗 ```\nenable_monitoring: bool | None\n``` default = None Enables traffic monitoring of the app through the /monitoring endpoint. By default is None, which enables this endpoint. If explicitly True, will also print the monitoring URL to the console. If False, will disable monitoring altogether.🔗 ```\nstrict_cors: bool\n``` default = True If True, prevents external domains from making requests to a Gradio server running on localhost. If False, allows requests to localhost that originate from localhost but also, crucially, from &quot;null&quot;. This parameter should normally be True to prevent CSRF attacks but may need to be False when embedding a *locally-running Gradio app* using web components.🔗 ```\nnode_server_name: str | None\n``` default = None 🔗 ```\nnode_port: int | None\n``` default = None 🔗 ```\nssr_mode: bool | None\n``` default = None If True, the Gradio app will be rendered using server-side rendering mode, which is typically more performant and provides better SEO, but this requires Node 20+ to be installed on the system. If False, the app will be rendered using client-side rendering mode. If None, will use GRADIO_SSR_MODE environment variable or default to False.🔗 ```\npwa: bool | None\n``` default = None If True, the Gradio app will be set up as an installable PWA (Progressive Web App). If set to None (default behavior), then the PWA feature will be enabled if this Gradio app is launched on Spaces, but not otherwise.🔗 ```\nmcp_server: bool | None\n``` default = None If True, the Gradio app will be set up as an MCP server and documented functions will be added as MCP tools. If None (default behavior), then the GRADIO_MCP_SERVER environment variable will be used to determine if the MCP server should be enabled.🔗 ```\nnum_workers: int | None\n``` default = None Number of background workers to launch in the background to serve file I/O and static assets. This offloads traffic from the main server and reduces latency. Only has an effect if ssr mode is set.🔗 ```\ni18n: I18n | None\n``` default = None An I18n instance containing custom translations, which are used to translate strings in our components (e.g. the labels of components or Markdown strings). This feature can only be used to translate static text in the frontend, not values in the backend.🔗 ```\ntheme: Theme | str | None\n``` default = None A Theme object or a string representing a theme. If a string, will look for a built-in theme with that name (e.g. &quot;soft&quot; or &quot;default&quot;), or will attempt to load a theme from the Hugging Face Hub (e.g. &quot;gradio/monochrome&quot;). If None, will use the Default theme.🔗 ```\ncss: str | None\n``` default = None Custom css as a code string. This css will be included in the demo webpage.🔗 ```\ncss_paths: str | Path | list[str | Path] | None\n``` default = None Custom css as a pathlib.Path to a css file or a list of such paths. This css files will be read, concatenated, and included in the demo webpage. If the `css` parameter is also set, the css from `css` will be included first.🔗 ```\njs: str | Literal[True] | None\n``` default = None Custom JavaScript provided as either a function or a raw code string. A function is automatically invoked; otherwise the code is executed directly when the page loads. To run JavaScript as a document-level `&lt;script&gt;` tag, use the `head` parameter.🔗 ```\nhead: str | None\n``` default = None Custom html code to insert into the head of the demo webpage. This can be used to add custom meta tags, multiple scripts, stylesheets, etc. to the page.🔗 ```\nhead_paths: str | Path | list[str | Path] | None\n``` default = None Custom html code as a pathlib.Path to a html file or a list of such paths. This html files will be read, concatenated, and included in the head of the demo webpage. If the `head` parameter is also set, the html from `head` will be included first.queue  ```\ngradio.Blocks.queue(···)\n``` Description  By enabling the queue you can control when users know their position in the queue, and set a limit on maximum number of events allowed. Example Usage  ```\nwith gr.Blocks() as demo:\n    button = gr.Button(label=\"Generate Image\")\n    button.click(fn=image_generator, inputs=gr.Textbox(), outputs=gr.Image())\ndemo.queue(max_size=10)\ndemo.launch()\n``` Parameters ▼ 🔗 ```\nstatus_update_rate: float | Literal['auto']\n``` default = \"auto\" If &quot;auto&quot;, Queue will send status estimations to all clients whenever a job is finished. Otherwise Queue will send status at regular intervals set by this parameter as the number of seconds.🔗 ```\napi_open: bool | None\n``` default = None If True, the REST routes of the backend will be open, allowing requests made directly to those endpoints to skip the queue.🔗 ```\nmax_size: int | None\n``` default = None The maximum number of events the queue will store at any given moment. If the queue is full, new events will not be added and a user will receive a message saying that the queue is full. If None, the queue size will be unlimited.🔗 ```\ndefault_concurrency_limit: int | None | Literal['not_set']\n``` default = \"not_set\" The default value of `concurrency_limit` to use for event listeners that don&#039;t specify a value. Can be set by environment variable GRADIO_DEFAULT_CONCURRENCY_LIMIT. Defaults to 1 if not set otherwise.integrate  ```\ngradio.Blocks.integrate(···)\n``` Description  A catch-all method for integrating with other libraries. This method should be run after launch()  Parameters ▼ 🔗 ```\ncomet_ml: \n``` default = None If a comet_ml Experiment object is provided, will integrate with the experiment and appear on Comet dashboard🔗 ```\nwandb: ModuleType | None\n``` default = None If the wandb module is provided, will integrate with it and appear on WandB dashboard🔗 ```\nmlflow: ModuleType | None\n``` default = None If the mlflow module  is provided, will integrate with the experiment and appear on ML Flow dashboardload  ```\ngradio.Blocks.load(block, ···)\n``` Description  This listener is triggered when the Blocks initially loads in the browser.  Parameters ▼ 🔗 ```\nblock: Block | None\n```  🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.unload  ```\ngradio.Blocks.unload(fn, ···)\n``` Description  This listener is triggered when the user closes or refreshes the tab, ending the user session. It is useful for cleaning up resources when the app is closed. Example Usage  ```\nimport gradio as gr\nwith gr.Blocks() as demo:\n    gr.Markdown(\"# When you close the tab, hello will be printed to the console\")\n    demo.unload(lambda: print(\"hello\"))\ndemo.launch()\n``` Parameters ▼ 🔗 ```\nfn: Callable[..., Any]\n```  Callable function to run to clear resources. The function should not take any arguments and the output is not used.  Blocks And Event ListenersControlling LayoutState In BlocksMore Blocks Features","type":"DOCS"},{"title":"Server","slug":"/main/docs/gradio/server","content":"Server ```\ngradio.Server(···)\n``` Description Server is the Gradio API engine exposed on a FastAPI application (Server mode). It inherits from FastAPI, so all standard FastAPI methods (.get(), .post(), .add_middleware(), .include_router(), etc.) work directly on this instance.  New methods added on top of FastAPI:     api(): Decorator to register a Gradio API endpoint with queue,         SSE streaming, and concurrency control.     mcp: Namespace with .tool(), .resource(), and .prompt() decorators         to tag functions with MCP metadata.     launch(): Creates an internal Blocks, registers deferred API         endpoints, and starts the server.  Example Usage ```\nfrom gradio import Server\n\napp = Server()\n\n@app.api(name=\"hello\")\ndef hello(name: str) -> str:\n    return f\"Hello {name}\"\n\n@app.get(\"/\")\ndef root():\n    return {\"message\": \"Hello World\"}\n\napp.launch()\n``` Initialization Parameters ▼ 🔗 ```\ndebug: bool\n``` default = False Enable debug mode for detailed error tracebacks.🔗 ```\ntitle: str\n``` default = \"FastAPI\" The title of the API, shown in the OpenAPI docs.🔗 ```\nsummary: str | None\n``` default = None A short summary of the API.🔗 ```\ndescription: str\n``` default = \"\" A longer description of the API. Supports Markdown.🔗 ```\nversion: str\n``` default = \"0.1.0\" The version of the API.🔗 ```\nopenapi_url: str | None\n``` default = \"/openapi.json\" The URL path for the OpenAPI schema. Set to None to disable.🔗 ```\nopenapi_tags: list[dict[str, Any]] | None\n``` default = None Tags for organizing endpoints in the OpenAPI docs.🔗 ```\nservers: list[dict[str, Any]] | None\n``` default = None Server URLs for the OpenAPI schema.🔗 ```\ndependencies: Any\n``` default = None Global dependencies applied to all routes.🔗 ```\ndefault_response_class: Any\n``` default = None The default response class for routes.🔗 ```\nredirect_slashes: bool\n``` default = True Whether to redirect trailing slashes.🔗 ```\ndocs_url: str | None\n``` default = \"/docs\" The URL path for the Swagger UI docs. Set to None to disable.🔗 ```\nredoc_url: str | None\n``` default = \"/redoc\" The URL path for the ReDoc docs. Set to None to disable.🔗 ```\nmiddleware: Any\n``` default = None List of middleware to add to the server.🔗 ```\nexception_handlers: Any\n``` default = None Custom exception handlers.🔗 ```\non_startup: Any\n``` default = None List of startup event handlers. Prefer lifespan instead.🔗 ```\non_shutdown: Any\n``` default = None List of shutdown event handlers. Prefer lifespan instead.🔗 ```\nlifespan: Any\n``` default = None An async context manager for startup/shutdown lifecycle.🔗 ```\nterms_of_service: str | None\n``` default = None URL to the terms of service.🔗 ```\ncontact: dict[str, Any] | None\n``` default = None Contact information dict for the API.🔗 ```\nlicense_info: dict[str, Any] | None\n``` default = None License information dict for the API.🔗 ```\nroot_path: str\n``` default = \"\" A path prefix for the app when behind a proxy.🔗 ```\nroot_path_in_servers: bool\n``` default = True Whether to include root_path in the OpenAPI servers field.🔗 ```\nresponses: dict[int | str, dict[str, Any]] | None\n``` default = None Additional responses for the OpenAPI schema.🔗 ```\ncallbacks: Any\n``` default = None OpenAPI callback definitions.🔗 ```\nwebhooks: Any\n``` default = None OpenAPI webhook definitions.🔗 ```\ndeprecated: bool | None\n``` default = None Mark all routes as deprecated.🔗 ```\ninclude_in_schema: bool\n``` default = True Whether to include all routes in the OpenAPI schema.🔗 ```\ngenerate_unique_id_function: Any\n``` default = None Custom function to generate unique operation IDs.🔗 ```\nseparate_input_output_schemas: bool\n``` default = True Whether to generate separate input/output schemas.🔗 ```\nextra: Any\n```   Demos server_app  Methods api  ```\ngradio.Server.api(···)\n``` Description  Decorator to register a function as a Gradio API endpoint. &lt;br&gt; Goes through Gradio&#x27;s queue with concurrency control and SSE streaming.  Parameters ▼ 🔗 ```\nfn: Callable | None\n``` default = None 🔗 ```\nname: str | None\n``` default = None 🔗 ```\ndescription: str | None\n``` default = None 🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` default = \"default\" 🔗 ```\nconcurrency_id: str | None\n``` default = None 🔗 ```\nqueue: bool\n``` default = True 🔗 ```\nbatch: bool\n``` default = False 🔗 ```\nmax_batch_size: int\n``` default = 4 🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" 🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 launch  ```\ngradio.Server.launch(···)\n``` Description  Launch the Gradio API server (Server mode). &lt;br&gt; Parameters match ``Blocks.launch()``; see that method for full descriptions. &lt;br&gt;  Parameters ▼ 🔗 ```\ninline: bool | None\n``` default = None 🔗 ```\ninbrowser: bool\n``` default = False 🔗 ```\nshare: bool | None\n``` default = None 🔗 ```\ndebug: bool\n``` default = False 🔗 ```\nmax_threads: int\n``` default = 40 🔗 ```\nauth: Callable[[str, str], bool] | tuple[str, str] | list[tuple[str, str]] | None\n``` default = None 🔗 ```\nauth_message: str | None\n``` default = None 🔗 ```\nprevent_thread_lock: bool\n``` default = False 🔗 ```\nshow_error: bool\n``` default = False 🔗 ```\nserver_name: str | None\n``` default = None 🔗 ```\nserver_port: int | None\n``` default = None 🔗 ```\nheight: int\n``` default = 500 🔗 ```\nwidth: int | str\n``` default = \"100%\" 🔗 ```\nfavicon_path: str | Path | None\n``` default = None 🔗 ```\nssl_keyfile: str | None\n``` default = None 🔗 ```\nssl_certfile: str | None\n``` default = None 🔗 ```\nssl_keyfile_password: str | None\n``` default = None 🔗 ```\nssl_verify: bool\n``` default = True 🔗 ```\nquiet: bool\n``` default = False 🔗 ```\nfooter_links: list[Literal['api', 'gradio', 'settings', 'runs'] | dict[str, str]] | None\n``` default = None 🔗 ```\nrun_history: bool | None\n``` default = None 🔗 ```\nallowed_paths: list[str] | None\n``` default = None 🔗 ```\nblocked_paths: list[str] | None\n``` default = None 🔗 ```\nroot_path: str | None\n``` default = None 🔗 ```\napp_kwargs: dict[str, Any] | None\n``` default = None 🔗 ```\nstate_session_capacity: int\n``` default = 10000 🔗 ```\nshare_server_address: str | None\n``` default = None 🔗 ```\nshare_server_protocol: Literal['http', 'https'] | None\n``` default = None 🔗 ```\nshare_server_tls_certificate: str | None\n``` default = None 🔗 ```\nauth_dependency: Callable[[fastapi.Request], str | None | Awaitable[str | None]] | None\n``` default = None 🔗 ```\nmax_file_size: str | int | None\n``` default = None 🔗 ```\nenable_monitoring: bool | None\n``` default = None 🔗 ```\nstrict_cors: bool\n``` default = True 🔗 ```\nnode_server_name: str | None\n``` default = None 🔗 ```\nnode_port: int | None\n``` default = None 🔗 ```\nssr_mode: bool | None\n``` default = None 🔗 ```\npwa: bool | None\n``` default = None 🔗 ```\nmcp_server: bool | None\n``` default = None 🔗 ```\ni18n: I18n | None\n``` default = None 🔗 ```\ntheme: Theme | str | None\n``` default = None 🔗 ```\ncss: str | None\n``` default = None 🔗 ```\ncss_paths: str | Path | list[str | Path] | None\n``` default = None 🔗 ```\njs: str | Literal[True] | None\n``` default = None 🔗 ```\nhead: str | None\n``` default = None 🔗 ```\nhead_paths: str | Path | list[str | Path] | None\n``` default = None 🔗 ```\nnum_workers: int | None\n``` default = None   Server Mode","type":"DOCS"},{"title":"render","slug":"/main/docs/gradio/render","content":"render ```\n@gr.render(inputs=···)\ndef hello(···):\n   ... \n``` Description The render decorator allows Gradio Blocks apps to have dynamic layouts, so that the components and event listeners in your app can change depending on custom logic. Attaching a @gr.render decorator to a function will cause the function to be re-run whenever the inputs are changed (or specified triggers are activated). The function contains the components and event listeners that will update based on the inputs. With render, you can:  - Show or hide components  - Change text or layout  - Create components based on what users enter  The basic usage of @gr.render is as follows:  1. Create a function and attach the @gr.render decorator to it.  2. Add the input components to the inputs= argument of @gr.render, and create a corresponding argument in your function for each component.  3. Add all components inside the function that you want to update based on the inputs. Any event listeners that use these components should also be inside this function.  Example Usage ```\nimport gradio as gr\n\nwith gr.Blocks() as demo:\n    textbox = gr.Textbox(label=\"Enter text\")\n\n    @gr.render(inputs=textbox)\n    def show_message(text):\n        if not text:\n            gr.Markdown(\"Please enter some text.\")\n        else:\n            gr.Markdown(f\"You entered: {text}\")\n\ndemo.launch()\n``` Initialization Parameters ▼ 🔗 ```\ninputs: list[Component] | Component | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\ntriggers: list[Trigger] | Trigger | None\n``` default = None List of triggers to listen to, e.g. [btn.click, number.change]. If None, will listen to changes to any inputs.🔗 ```\nqueue: bool\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = \"always_last\" If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` default = None 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\"     Dynamic Apps with the Render Decorator","type":"DOCS"},{"title":"Accordion","slug":"/main/docs/gradio/accordion","content":"Accordion ```\ngradio.Accordion(···)\n``` Description Accordion is a layout element which can be toggled to show/hide the contained content. Example Usage ```\nwith gr.Accordion(\"See Details\"):\n    gr.Markdown(\"lorem ipsum\")\n``` Initialization Parameters ▼ 🔗 ```\nlabel: str | I18nData | None\n``` default = None name of accordion section.🔗 ```\nopen: bool\n``` default = True if True, accordion is open by default.🔗 ```\nvisible: bool | Literal['hidden']\n``` default = True 🔗 ```\nelem_id: str | None\n``` 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.🔗 ```\nelem_classes: list[str] | str | None\n``` default = None An optional string or list of strings that are assigned as the class of this component in the HTML DOM. Can be used for targeting CSS styles.🔗 ```\nrender: bool\n``` default = True If False, this layout will not be rendered in the Blocks context. Should be used if the intention is to assign event listeners now but render the component later.🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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 &#039;preserved_by_key&#039; are not reset across a re-render.🔗 ```\npreserved_by_key: list[str] | str | None\n``` default = None A list of parameters from this component&#039;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.  Methods expand  ```\ngradio.Accordion.expand(···)\n``` Description  This listener is triggered when the Accordion is expanded.  Parameters ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.collapse  ```\ngradio.Accordion.collapse(···)\n``` Description  This listener is triggered when the Accordion is collapsed.  Parameters ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.  Controlling Layout","type":"DOCS"},{"title":"Column","slug":"/main/docs/gradio/column","content":"Column ```\ngradio.Column(···)\n``` Description Column is a layout element within Blocks that renders all children vertically. The widths of columns can be set through the scale and min_width parameters. If a certain scale results in a column narrower than min_width, the min_width parameter will win. Example Usage ```\nwith gr.Blocks() as demo:\n    with gr.Row():\n        with gr.Column(scale=1):\n            text1 = gr.Textbox()\n            text2 = gr.Textbox()\n        with gr.Column(scale=4):\n            btn1 = gr.Button(\"Button 1\")\n            btn2 = gr.Button(\"Button 2\")\n``` Initialization Parameters ▼ 🔗 ```\nscale: int\n``` default = 1 relative width compared to adjacent Columns. For example, if Column A has scale=2, and Column B has scale=1, A will be twice as wide as B.🔗 ```\nmin_width: int\n``` default = 320 minimum pixel width of Column, will wrap if not sufficient screen space to satisfy this value. If a certain scale value results in a column narrower than min_width, the min_width parameter will be respected first.🔗 ```\nvariant: Literal['default', 'panel', 'compact']\n``` default = \"default\" column type, &#039;default&#039; (no background), &#039;panel&#039; (gray background color and rounded corners), or &#039;compact&#039; (rounded corners and no internal gap).🔗 ```\nvisible: bool | Literal['hidden']\n``` default = True If False, column will be hidden.🔗 ```\nelem_id: str | None\n``` 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.🔗 ```\nelem_classes: list[str] | str | None\n``` default = None An optional string or list of strings that are assigned as the class of this component in the HTML DOM. Can be used for targeting CSS styles.🔗 ```\nrender: bool\n``` 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.🔗 ```\nshow_progress: bool\n``` default = False If True, shows progress animation when being updated.🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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 &#039;preserved_by_key&#039; are not reset across a re-render.🔗 ```\npreserved_by_key: list[str] | str | None\n``` default = None A list of parameters from this component&#039;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.   Controlling Layout","type":"DOCS"},{"title":"Group","slug":"/main/docs/gradio/group","content":"Group ```\ngradio.Group(···)\n``` Description Group is a layout element within Blocks which groups together children so that they do not have any padding or margin between them. Example Usage ```\nwith gr.Group():\n    gr.Textbox(label=\"First\")\n    gr.Textbox(label=\"Last\")\n``` Initialization Parameters ▼ 🔗 ```\nvisible: bool | Literal['hidden']\n``` default = True If False, group will be hidden.🔗 ```\nelem_id: str | None\n``` 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.🔗 ```\nelem_classes: list[str] | str | None\n``` default = None An optional string or list of strings that are assigned as the class of this component in the HTML DOM. Can be used for targeting CSS styles.🔗 ```\nrender: bool\n``` default = True If False, this layout will not be rendered in the Blocks context. Should be used if the intention is to assign event listeners now but render the component later.🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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 &#039;preserved_by_key&#039; are not reset across a re-render.🔗 ```\npreserved_by_key: list[str] | str | None\n``` default = None A list of parameters from this component&#039;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.   ","type":"DOCS"},{"title":"Row","slug":"/main/docs/gradio/row","content":"Row ```\ngradio.Row(···)\n``` Description Row is a layout element within Blocks that renders all children horizontally. Example Usage ```\nwith gr.Blocks() as demo:\n    with gr.Row():\n        gr.Image(\"lion.jpg\", scale=2)\n        gr.Image(\"tiger.jpg\", scale=1)\ndemo.launch()\n``` Initialization Parameters ▼ 🔗 ```\nvariant: Literal['default', 'panel', 'compact']\n``` default = \"default\" row type, &#039;default&#039; (no background), &#039;panel&#039; (gray background color and rounded corners), or &#039;compact&#039; (rounded corners and no internal gap).🔗 ```\nvisible: bool | Literal['hidden']\n``` default = True If False, row will be hidden.🔗 ```\nelem_id: str | None\n``` 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.🔗 ```\nelem_classes: list[str] | str | None\n``` default = None An optional string or list of strings that are assigned as the class of this component in the HTML DOM. Can be used for targeting CSS styles.🔗 ```\nscale: int | None\n``` default = None relative height compared to adjacent elements. 1 or greater indicates the Row will expand in height, and any child columns will also expand to fill the height.🔗 ```\nrender: bool\n``` default = True If False, this layout will not be rendered in the Blocks context. Should be used if the intention is to assign event listeners now but render the component later.🔗 ```\nheight: int | str | None\n``` default = None The height of the row, specified in pixels if a number is passed, or in CSS units if a string is passed. If content exceeds the height, the row will scroll vertically. If not set, the row will expand to fit the content.🔗 ```\nmax_height: int | str | None\n``` default = None The maximum height of the row, specified in pixels if a number is passed, or in CSS units if a string is passed. If content exceeds the height, the row will scroll vertically. If content is shorter than the height, the row will shrink to fit the content. Will not have any effect if `height` is set and is smaller than `max_height`.🔗 ```\nmin_height: int | str | None\n``` default = None The minimum height of the row, specified in pixels if a number is passed, or in CSS units if a string is passed. If content exceeds the height, the row will expand to fit the content. Will not have any effect if `height` is set and is larger than `min_height`.🔗 ```\nequal_height: bool\n``` default = False If True, makes every child element have equal height🔗 ```\nshow_progress: bool\n``` default = False If True, shows progress animation when being updated.🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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 &#039;preserved_by_key&#039; are not reset across a re-render.🔗 ```\npreserved_by_key: list[str] | str | None\n``` default = None A list of parameters from this component&#039;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. Controlling Width The widths of elements in a Row can be controlled via a combination of scale and min_width arguments that are present in every component. scale is an integer that defines how an element will take up space in a Row. If scale is set to 0, the element will not expand to take up space. If scale is set to 1 or greater, the element will expand. Multiple elements in a row will expand proportional to their scale. Below, btn2 will expand twice as much as btn1, while btn0 will not expand at all: ```\nwith gr.Blocks() as demo:\n    with gr.Row():\n        btn0 = gr.Button(\"Button 0\", scale=0)\n        btn1 = gr.Button(\"Button 1\", scale=1)\n        btn2 = gr.Button(\"Button 2\", scale=2)\n``` min_width will set the minimum width the element will take. The Row will wrap if there isn’t sufficient space to satisfy all min_width values.   Controlling Layout","type":"DOCS"},{"title":"Tab","slug":"/main/docs/gradio/tab","content":"Tab ```\ngradio.Tab(···)\n``` Description Tab (or its alias TabItem) is a layout element. Components defined within the Tab will be visible when this tab is selected tab. Example Usage ```\nwith gr.Blocks() as demo:\n    with gr.Tab(\"Lion\"):\n        gr.Image(\"lion.jpg\")\n        gr.Button(\"New Lion\")\n    with gr.Tab(\"Tiger\"):\n        gr.Image(\"tiger.jpg\")\n        gr.Button(\"New Tiger\")\n``` Initialization Parameters ▼ 🔗 ```\nlabel: str | I18nData | None\n``` default = None The visual label for the tab🔗 ```\nvisible: bool | Literal['hidden']\n``` default = True If False, Tab will be hidden.🔗 ```\ninteractive: bool\n``` default = True If False, Tab will not be clickable.🔗 ```\nid: int | str | None\n``` default = None An optional identifier for the tab, required if you wish to control the selected tab from a predict function.🔗 ```\nalignment: Literal['left', 'right']\n``` default = \"left\" The side of the tab bar where the tab is placed. Right-aligned tabs are grouped together while preserving their relative order.🔗 ```\nelem_id: str | None\n``` default = None An optional string that is assigned as the id of the &lt;div&gt; containing the contents of the Tab layout. The same string followed by &quot;-button&quot; is attached to the Tab button. Can be used for targeting CSS styles.🔗 ```\nelem_classes: list[str] | str | None\n``` default = None An optional string or list of strings that are assigned as the class of this component in the HTML DOM. Can be used for targeting CSS styles.🔗 ```\nscale: int | None\n``` default = None relative size compared to adjacent elements. 1 or greater indicates the Tab will expand in size.🔗 ```\nrender: bool\n``` default = True If False, this layout will not be rendered in the Blocks context. Should be used if the intention is to assign event listeners now but render the component later.🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` default = None 🔗 ```\npreserved_by_key: list[str] | str | None\n``` default = None 🔗 ```\nrender_children: bool\n``` default = False If True, the children of this Tab will be rendered on the page (but hidden) when the Tab is visible but inactive. This can be useful if you want to ensure that any components (e.g. videos or audio) within the Tab are pre-loaded before the user clicks on the Tab.  Methods select  ```\ngradio.Tab.select(···)\n``` Description  Event listener for when the user selects the Tab. Uses event data gradio.SelectData to carry `value` referring to the label of the Tab, and `selected` to refer to state of the Tab. See https://www.gradio.app/main/docs/gradio/eventdata documentation for more details.  Parameters ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.  Controlling Layout","type":"DOCS"},{"title":"Walkthrough","slug":"/main/docs/gradio/walkthrough","content":"Walkthrough ```\ngradio.Walkthrough(···)\n``` Description Walkthrough is a layout element within Blocks that can contain multiple \"Step\" Components, which can be used to create a step-by-step workflow. Example Usage ```\nwith gr.Walkthrough(selected=1) as walkthrough:\n    with gr.Step(\"Step 1\", id=1):\n        btn = gr.Button(\"go to Step 2\")\n        btn.click(lambda: gr.Walkthrough(selected=2), outputs=walkthrough)\n    with gr.Step(\"Step 2\", id=2):\n        txt = gr.Textbox(\"Welcome to Step 2\")\n``` Initialization Parameters ▼ 🔗 ```\nselected: int | None\n``` default = None The currently selected step. Must be a number corresponding to the step number. Defaults to the first step.🔗 ```\nvisible: bool\n``` default = True If False, Walkthrough will be hidden.🔗 ```\nelem_id: str | None\n``` 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.🔗 ```\nelem_classes: list[str] | str | None\n``` default = None An optional string or list of strings that are assigned as the class of this component in the HTML DOM. Can be used for targeting CSS styles.🔗 ```\nrender: bool\n``` default = True If False, this layout will not be rendered in the Blocks context. Should be used if the intention is to assign event listeners now but render the component later.🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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 &#039;preserved_by_key&#039; are not reset across a re-render.🔗 ```\npreserved_by_key: list[str] | str | None\n``` default = None A list of parameters from this component&#039;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. Demos walkthrough  Methods change  ```\ngradio.Walkthrough.change(···)\n``` Description  Triggered when the value of the Walkthrough 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.  Parameters ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.select  ```\ngradio.Walkthrough.select(···)\n``` Description  Event listener for when the user selects or deselects the Walkthrough. Uses event data gradio.SelectData to carry `value` referring to the label of the Walkthrough, and `selected` to refer to state of the Walkthrough. See https://www.gradio.app/main/docs/gradio/eventdata for more details.  Parameters ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.  Controlling Layout Step ```\ngradio.Step(···)\n``` Description Step is a layout element. A step is a single step in a step-by-step workflow. Initialization Parameters ▼ 🔗 ```\nlabel: str | I18nData | None\n``` default = None The visual label for the step🔗 ```\nvisible: bool\n``` default = True If False, Step will be hidden.🔗 ```\ninteractive: bool\n``` default = True If False, Step will not be clickable.🔗 ```\nid: int | None\n``` default = None An optional numeric identifier for the step, required if you wish to control the selected step from a predict function. Must be a number.🔗 ```\nelem_id: str | None\n``` default = None An optional string that is assigned as the id of the &lt;div&gt; containing the contents of the Step layout. The same string followed by &quot;-button&quot; is attached to the Step button. Can be used for targeting CSS styles.🔗 ```\nelem_classes: list[str] | str | None\n``` default = None An optional string or list of strings that are assigned as the class of this component in the HTML DOM. Can be used for targeting CSS styles.🔗 ```\nscale: int | None\n``` default = None relative size compared to adjacent elements. 1 or greater indicates the Step will expand in size.🔗 ```\nrender: bool\n``` default = True If False, this layout will not be rendered in the Blocks context. Should be used if the intention is to assign event listeners now but render the component later.🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` default = None 🔗 ```\npreserved_by_key: list[str] | str | None\n``` default = None  Methods select  ```\ngradio.Step.select(···)\n``` Description  Event listener for when the user selects or deselects the Step. Uses event data gradio.SelectData to carry `value` referring to the label of the Step, and `selected` to refer to state of the Step. See https://www.gradio.app/main/docs/gradio/eventdata for more details.  Parameters ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.  ","type":"DOCS"},{"title":"Components","slug":"/main/docs/gradio/introduction","content":"Components Introduction Gradio includes pre-built components that can be used as inputs or outputs in your Interface or Blocks with a single line of code. Components include preprocessing steps that convert user data submitted through browser to something that be can used by a Python function, and postprocessing steps to convert values returned by a Python function into something that can be displayed in a browser. Consider an example with three inputs (Textbox, Number, and Image) and two outputs (Number and Gallery), below is a diagram of what our preprocessing will send to the function and what our postprocessing will require from it.  Events Components also come with certain events that they support. These are methods that are triggered with user actions. Below is a table showing which events are supported for each component. All events are also listed (with parameters) in the component’s docs. editchangelikedeletestart_recordingpausekey_upapplyloaduploaddouble_clickstopsubmitblurinputpreview_openexample_selectundopreview_closeoption_selectexpandtickretryreleasestop_recordingdownloadendcollapsestreamselectplaycopypause_recordingclickclearfocusButton✕✓✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✓✕✕AnnotatedImage✕✓✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✓✕✕✕✕✕✕Audio✕✓✕✕✓✓✕✕✕✓✕✓✕✕✓✕✕✕✕✕✕✕✕✕✓✕✕✕✓✕✓✕✓✕✓✕BrowserState✕✓✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕Chatbot✓✓✓✕✕✕✕✕✕✕✕✕✕✕✕✕✓✓✕✓✕✕✓✕✕✕✕✕✕✓✕✓✕✕✓✕Checkbox✕✓✕✕✕✕✕✕✕✕✕✕✕✕✓✕✕✕✕✕✕✕✕✕✕✕✕✕✕✓✕✕✕✕✕✕CheckboxGroup✕✓✕✕✕✕✕✕✕✕✕✕✕✕✓✕✕✕✕✕✕✕✕✕✕✕✕✕✕✓✕✕✕✕✕✕ClearButton✕✓✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✓✕✕Code✕✓✕✕✕✕✕✕✕✕✕✕✕✓✓✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✓ColorPicker✕✓✕✕✕✕✕✕✕✕✕✕✓✓✓✕✕✕✕✕✕✕✕✓✕✕✕✕✕✕✕✕✕✕✕✓Dataframe✓✓✕✕✕✕✕✕✕✕✕✕✕✕✓✕✕✕✕✕✕✕✕✕✕✕✕✕✕✓✕✕✕✕✕✕Dataset✕✓✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✓✕✕✕✓✕✕DateTime✕✓✕✕✕✕✕✕✕✕✕✕✓✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕DeepLinkButton✕✓✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✓✕✕Dialogue✕✓✕✕✕✕✕✕✕✕✕✕✓✕✓✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕DownloadButton✕✓✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✓✕✕Dropdown✕✓✕✕✕✕✓✕✕✕✕✕✕✓✓✕✕✕✕✕✕✕✕✕✕✕✕✕✕✓✕✕✕✕✕✓DuplicateButton✕✓✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✓✕✕File✕✓✕✓✕✕✕✕✕✓✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✓✕✕✕✓✕✕✕✕✓✕FileExplorer✕✓✕✕✕✕✕✕✕✕✕✕✕✕✓✕✕✕✕✕✕✕✕✕✕✕✕✕✕✓✕✕✕✕✕✕ImageEditor✕✓✕✕✕✕✕✓✕✓✕✕✕✕✓✕✕✕✕✕✕✕✕✕✕✕✕✕✕✓✕✕✕✕✓✕Gallery✕✓✕✓✕✕✕✕✕✓✕✕✕✕✕✓✕✕✓✕✕✕✕✕✕✕✕✕✕✓✕✕✕✕✕✕HighlightedText✕✓✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✓✕✕✕✕✕✕HTML✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✕✓✓✕✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓Image✕✓✕✕✕✕✕✕✕✓✕✕✕✕✓✕✕✕✕✕✕✕✕✕✕✕✕✕✓✓✕✕✕✕✓✕ImageSlider✕✓✕✕✕✕✕✕✕✓✕✕✕✕✓✕✕✕✕✕✕✕✕✕✕✕✕✕✓✓✕✕✕✕✓✕JSON✕✓✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕Label✕✓✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✓✕✕✕✕✕✕LoginButton✕✓✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✓✕✕Markdown✕✓✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✓✕✕✕✕Model3D✓✓✕✕✕✕✕✕✕✓✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✓✕Textbox✕✓✕✕✕✕✕✕✕✕✕✓✓✓✓✕✕✕✕✕✕✕✕✕✕✕✕✕✕✓✕✓✕✕✕✓MultimodalTextbox✕✓✕✕✕✕✕✕✕✕✕✓✓✓✓✕✕✕✕✕✕✕✕✕✕✕✕✕✕✓✕✕✕✕✕✓BarPlot✕✓✕✕✕✕✕✕✕✕✓✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✓✕✕✕✕✕✕LinePlot✕✓✕✕✕✕✕✕✕✕✓✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✓✕✕✕✕✕✕ScatterPlot✕✓✕✕✕✕✕✕✕✕✓✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✓✕✕✕✕✕✕Navbar✕✓✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕Number✕✓✕✕✕✕✕✕✕✕✕✕✓✓✓✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✓ParamViewer✕✓✕✕✕✕✕✕✕✓✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕Plot✕✓✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕Radio✕✓✕✕✕✕✕✕✕✕✕✕✕✕✓✕✕✕✕✕✕✕✕✕✕✕✕✕✕✓✕✕✕✕✕✕Slider✕✓✕✕✕✕✕✕✕✕✕✕✕✕✓✕✕✕✕✕✕✕✕✓✕✕✕✕✕✕✕✕✕✕✕✕State✕✓✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕Timer✕✓✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✓✕✕✕✕✕✕✕✕✕✕✕✕✕✕UploadButton✕✓✕✕✕✕✕✕✕✓✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✓✕✕Video✕✓✕✕✓✓✕✕✕✓✕✓✕✕✓✕✕✕✕✕✕✕✕✕✓✕✓✕✕✕✓✕✕✕✓✕WorkflowCanvas✕✓✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕SimpleImage✕✓✕✕✕✕✕✕✕✓✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✕✓✕","type":"DOCS"},{"title":"AnnotatedImage","slug":"/main/docs/gradio/annotatedimage","content":"AnnotatedImage ```\ngradio.AnnotatedImage(···)\n``` Description 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.  Behavior Using AnnotatedImage as an input component. How AnnotatedImage will pass its value to your function: Type: tuple[str, list[tuple[str, str]]] | None Passes its value as a tuple consisting of:\nstr filepath to a base image\nlist of annotations.\nEach annotation itself is a tuple of a mask (as a str filepath to image) and a str label. Example Code \n    \n    import gradio as gr\n\n    def predict(\n        value: tuple[str, list[tuple[str, str]]] | None\n    ):\n        # process value from the AnnotatedImage component\n        return \"prediction\"\n\n    interface = gr.Interface(predict, gr.AnnotatedImage(), gr.Textbox())\n    interface.launch()\n\n  Using AnnotatedImage as an output component How AnnotatedImage expects you to return a value: Type: tuple[np.ndarray | PIL.Image.Image | str, Sequence[tuple[np.ndarray | tuple[int, int, int, int], str]]] | None Expects a tuple consisting of a base image and list of annotations: a tuple[Image, list[Annotation]].\nThe Image itself can be str filepath, numpy.ndarray, or PIL.Image.\nEach Annotation is a tuple[Mask, str].\nThe 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.\nThe second element of the Annotation tuple is a str label. Example Code \n    \n    import gradio as gr\n\n    def predict(text) -> tuple[np.ndarray | PIL.Image.Image | str, Sequence[tuple[np.ndarray | tuple[int, int, int, int], str]]] | None\n        # process value to return to the AnnotatedImage component\n        return value\n\n    interface = gr.Interface(predict, gr.Textbox(), gr.AnnotatedImage())\n    interface.launch()\n\n Initialization Parameters ▼ 🔗 ```\nvalue: tuple[np.ndarray | PIL.Image.Image | str, list[tuple[np.ndarray | tuple[int, int, int, int], str]]] | None\n``` default = None Tuple of base image and list of (annotation, label) pairs.🔗 ```\nformat: str\n``` default = \"webp\" Format used to save images before it is returned to the front end, such as &#039;jpeg&#039; or &#039;png&#039;. 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.🔗 ```\nshow_legend: bool\n``` default = True If True, will show a legend of the annotations.🔗 ```\nheight: int | str | None\n``` 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.🔗 ```\nwidth: int | str | None\n``` 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.🔗 ```\ncolor_map: dict[str, str] | None\n``` default = None A dictionary mapping labels to colors. The colors must be specified as hex codes.🔗 ```\nlabel: str | I18nData | None\n``` 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.🔗 ```\nevery: Timer | float | None\n``` default = None Continuously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.🔗 ```\ninputs: Component | list[Component] | set[Component] | None\n``` 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.🔗 ```\nshow_label: bool | None\n``` default = None if True, will display label.🔗 ```\ncontainer: bool\n``` default = True If True, will place the component in a container - providing some extra padding around the border.🔗 ```\nscale: int | None\n``` 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.🔗 ```\nmin_width: int\n``` 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.🔗 ```\nvisible: bool | Literal['hidden']\n``` default = True If False, component will be hidden. If &quot;hidden&quot;, component will be visually hidden and not take up space in the layout but still exist in the DOM🔗 ```\nelem_id: str | None\n``` 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.🔗 ```\nelem_classes: list[str] | str | None\n``` 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.🔗 ```\nrender: bool\n``` 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.🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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 &#039;preserved_by_key&#039; are not reset across a re-render.🔗 ```\npreserved_by_key: list[str] | str | None\n``` default = \"value\" A list of parameters from this component&#039;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.🔗 ```\nbuttons: list[Literal['fullscreen'] | Button] | None\n``` default = None A list of buttons to show for the component. Valid options in the list are &quot;fullscreen&quot; or a gr.Button() instance. The &quot;fullscreen&quot; button allows the user to view the image in fullscreen mode. Custom gr.Button() instances will appear in the toolbar with their configured icon and/or label, and clicking them will trigger any .click() events registered on the button. By default, the fullscreen button is shown, and this can hidden by providing an empty list. Shortcuts Shortcuts ```\ngradio.AnnotatedImage\n``` Interface String Shortcut \"annotatedimage\" Initialization Uses default values Demos image_segmentation  Event Listeners Description Event listeners allow you to respond to user interactions with the UI\n\t\tcomponents you've defined in a Gradio Blocks app. When a user interacts with\n\t\tan element, such as changing a slider value or uploading an image, a\n\t\tfunction is called. Supported Event Listeners The AnnotatedImage component supports the following event listeners. Each event listener takes the\n\t\tsame parameters, which are listed in the Event Parameters table below. Listeners ```\nAnnotatedImage.change(fn, ···)\n``` Triggered when the value of the AnnotatedImage 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.```\nAnnotatedImage.select(fn, ···)\n``` 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 https://www.gradio.app/main/docs/gradio/eventdata for more details. Event Parameters Parameters ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.  ","type":"DOCS"},{"title":"Audio","slug":"/main/docs/gradio/audio","content":"Audio ```\ngradio.Audio(···)\n``` Description Creates an audio component that can be used to upload/record audio (as an input) or display audio (as an output). Behavior Using Audio as an input component. How Audio will pass its value to your function: Type: str | tuple[int, np.ndarray] | None Passes audio as one of these formats (depending on type):\nstr filepath\ntuple of (sample rate in Hz, audio data as numpy array).\nThe audio data is a 16-bit int array whose values range from -32768 to 32767 and shape of the audio data array is (samples,) for mono audio or (samples, channels) for multi-channel audio. Example Code \n    \n    import gradio as gr\n\n    def predict(\n        value: str | tuple[int, np.ndarray] | None\n    ):\n        # process value from the Audio component\n        return \"prediction\"\n\n    interface = gr.Interface(predict, gr.Audio(), gr.Textbox())\n    interface.launch()\n\n  Using Audio as an output component How Audio expects you to return a value: Type: str | Path | bytes | tuple[int, np.ndarray] | None Expects audio data in any of these formats:\nstr\npathlib.Path filepath\nURL to an audio file\nbytes object (recommended for streaming)\ntuple of (sample rate in Hz, audio data as numpy array).\nNote: if audio is supplied as a numpy array, the audio will be normalized by its peak value to avoid distortion or clipping in the resulting audio. Example Code \n    \n    import gradio as gr\n\n    def predict(text) -> str | Path | bytes | tuple[int, np.ndarray] | None\n        # process value to return to the Audio component\n        return value\n\n    interface = gr.Interface(predict, gr.Textbox(), gr.Audio())\n    interface.launch()\n\n Initialization Parameters ▼ 🔗 ```\nvalue: str | Path | tuple[int, np.ndarray] | Callable | None\n``` default = None A path, URL, or [sample_rate, numpy array] tuple (sample rate in Hz, audio data as a float or int numpy array) for the default value that Audio component is going to take. If a function is provided, the function will be called each time the app loads to set the initial value of this component.🔗 ```\nsources: list[Literal['upload', 'microphone']] | Literal['upload', 'microphone'] | None\n``` default = None A list of sources permitted for audio. &quot;upload&quot; creates a box where user can drop an audio file, &quot;microphone&quot; creates a microphone input. The first element in the list will be used as the default source. If None, defaults to [&quot;upload&quot;, &quot;microphone&quot;], or [&quot;microphone&quot;] if `streaming` is True.🔗 ```\ntype: Literal['numpy', 'filepath']\n``` default = \"numpy\" The format the audio file is converted to before being passed into the prediction function. &quot;numpy&quot; converts the audio to a tuple consisting of: (int sample rate, numpy.array for the data), &quot;filepath&quot; passes a str path to a temporary file containing the audio.🔗 ```\nlabel: str | I18nData | None\n``` 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.🔗 ```\nevery: Timer | float | None\n``` default = None Continuously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.🔗 ```\ninputs: Component | list[Component] | set[Component] | None\n``` 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.🔗 ```\nshow_label: bool | None\n``` default = None if True, will display label.🔗 ```\ncontainer: bool\n``` default = True If True, will place the component in a container - providing some extra padding around the border.🔗 ```\nscale: int | None\n``` 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.🔗 ```\nmin_width: int\n``` 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.🔗 ```\ninteractive: bool | None\n``` default = None If True, will allow users to upload and edit an audio file. If False, can only be used to play audio. If not provided, this is inferred based on whether the component is used as an input or output.🔗 ```\nvisible: bool | Literal['hidden']\n``` default = True If False, component will be hidden. If &quot;hidden&quot;, component will be visually hidden and not take up space in the layout but still exist in the DOM If &quot;hidden&quot;, component will be visually hidden and not take up space in the layout but still exist in the DOM.🔗 ```\nstreaming: bool\n``` default = False If set to True when used in a `live` interface as an input, will automatically stream webcam feed. When used set as an output, takes audio chunks yield from the backend and combines them into one streaming audio output.🔗 ```\nelem_id: str | None\n``` 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.🔗 ```\nelem_classes: list[str] | str | None\n``` 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.🔗 ```\nrender: bool\n``` default = True if False, component will not be rendered in the Blocks context. Should be used if the intention is to assign event listeners now but render the component later.🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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 &#039;preserved_by_key&#039; are not reset across a re-render.🔗 ```\npreserved_by_key: list[str] | str | None\n``` default = \"value\" A list of parameters from this component&#039;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.🔗 ```\nformat: Literal['wav', 'mp3'] | None\n``` default = None the file extension with which to save audio files. Either &#039;wav&#039; or &#039;mp3&#039;. wav files are lossless but will tend to be larger files. mp3 files tend to be smaller. This parameter applies both when this component is used as an input (and `type` is &quot;filepath&quot;) to determine which file format to convert user-provided audio to, and when this component is used as an output to determine the format of audio returned to the user. If None, no file format conversion is done and the audio is kept as is. In the case where output audio is returned from the prediction function as numpy array and no `format` is provided, it will be returned as a &quot;wav&quot; file.🔗 ```\nautoplay: bool\n``` default = False Whether to automatically play the audio when the component is used as an output. Note: browsers will not autoplay audio files if the user has not interacted with the page yet.🔗 ```\neditable: bool\n``` default = True If True, allows users to manipulate the audio file if the component is interactive. Defaults to True.🔗 ```\nbuttons: list[Literal['download', 'share'] | Button] | None\n``` default = None A list of buttons to show in the top right corner of the component. Valid options are &quot;download&quot;, &quot;share&quot;, or a gr.Button() instance. The &quot;download&quot; button allows the user to save the audio to their device. The &quot;share&quot; button allows the user to share the audio via Hugging Face Spaces Discussions. Custom gr.Button() instances will appear in the toolbar with their configured icon and/or label, and clicking them will trigger any .click() events registered on the button. By default, only the &quot;download&quot; and &quot;share&quot; buttons are shown.🔗 ```\nwaveform_options: WaveformOptions | dict | None\n``` default = None A dictionary of options for the waveform display. Options include: waveform_color (str), waveform_progress_color (str), skip_length (int), trim_region_color (str). Default is None, which uses the default values for these options. See `gr.WaveformOptions` docs.🔗 ```\nloop: bool\n``` default = False If True, the audio will loop when it reaches the end and continue playing from the beginning.🔗 ```\nrecording: bool\n``` default = False If True, the audio component will be set to record audio from the microphone if the source is set to &quot;microphone&quot;. Defaults to False.🔗 ```\nsubtitles: str | Path | list[dict[str, Any]] | None\n``` default = None A subtitle file (srt, vtt, or json) for the audio, or a list of subtitle dictionaries in the format [{&quot;text&quot;: str, &quot;timestamp&quot;: [start, end]}] where timestamps are in seconds. JSON files should contain an array of subtitle objects.🔗 ```\nplayback_position: float\n``` default = 0 The starting playback position in seconds. This value is also updated as the audio plays, reflecting the current playback position. Shortcuts Shortcuts ```\ngradio.Audio\n``` Interface String Shortcut \"audio\" Initialization Uses default values```\ngradio.Microphone\n``` Interface String Shortcut \"microphone\" Initialization Uses sources=[\"microphone\"] Demos generate_tonereverse_audio  Event Listeners Description Event listeners allow you to respond to user interactions with the UI\n\t\tcomponents you've defined in a Gradio Blocks app. When a user interacts with\n\t\tan element, such as changing a slider value or uploading an image, a\n\t\tfunction is called. Supported Event Listeners The Audio component supports the following event listeners. Each event listener takes the\n\t\tsame parameters, which are listed in the Event Parameters table below. Listeners ```\nAudio.stream(fn, ···)\n``` This listener is triggered when the user streams the Audio.```\nAudio.change(fn, ···)\n``` Triggered when the value of the Audio 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.```\nAudio.clear(fn, ···)\n``` This listener is triggered when the user clears the Audio using the clear button for the component.```\nAudio.play(fn, ···)\n``` This listener is triggered when the user plays the media in the Audio.```\nAudio.pause(fn, ···)\n``` This listener is triggered when the media in the Audio stops for any reason.```\nAudio.stop(fn, ···)\n``` This listener is triggered when the user reaches the end of the media playing in the Audio.```\nAudio.pause(fn, ···)\n``` This listener is triggered when the media in the Audio stops for any reason.```\nAudio.start_recording(fn, ···)\n``` This listener is triggered when the user starts recording with the Audio.```\nAudio.pause_recording(fn, ···)\n``` This listener is triggered when the user pauses recording with the Audio.```\nAudio.stop_recording(fn, ···)\n``` This listener is triggered when the user stops recording with the Audio.```\nAudio.upload(fn, ···)\n``` This listener is triggered when the user uploads a file into the Audio.```\nAudio.input(fn, ···)\n``` This listener is triggered when the user changes the value of the Audio. Event Parameters Parameters ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"minimal\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.  Helper Classes WaveformOptions ```\ngradio.WaveformOptions(···)\n``` Description A dataclass for specifying options for the waveform display in the Audio component. An instance of this class can be passed into the waveform_options parameter of gr.Audio. Initialization Parameters ▼ 🔗 ```\nwaveform_color: str | None\n``` default = None The color (as a hex string or valid CSS color) of the full waveform representing the amplitude of the audio. Defaults to a light gray color.🔗 ```\nwaveform_progress_color: str | None\n``` default = None The color (as a hex string or valid CSS color) that the waveform fills with to as the audio plays. Defaults to the accent color.🔗 ```\ntrim_region_color: str | None\n``` default = None The color (as a hex string or valid CSS color) of the trim region. Defaults to the accent color.🔗 ```\nshow_recording_waveform: bool\n``` default = True If True, shows a waveform when recording audio or playing audio. If False, uses the default browser audio players. For streamed audio, the default browser audio player is always used.🔗 ```\nskip_length: int | float\n``` default = 5 The percentage (between 0 and 100) of the audio to skip when clicking on the skip forward / skip backward buttons.🔗 ```\nsample_rate: int\n``` default = 44100 The output sample rate (in Hz) of the audio after editing. is_audio_correct_length Validates that the audio length is within the specified min and max length (in seconds).\nYou can use this to construct a validator that will check if the user-provided audio is either too short or too long. ```\nimport gradio as gr\ndemo = gr.Interface(\n    lambda x: x,\n    inputs=\"audio\",\n    outputs=\"audio\",\n    validator=lambda audio: gr.validators.is_audio_correct_length(audio, min_length=1, max_length=5)\n)\ndemo.launch()\n``` Initialization Parameters ▼ 🔗 ```\naudio: tuple[int, 'np.ndarray']\n```  A tuple of (sample rate in Hz, audio data as numpy array).🔗 ```\nmin_length: float | None\n```  Minimum length of audio in seconds. If None, no minimum length check is performed.🔗 ```\nmax_length: float | None\n```  Maximum length of audio in seconds. If None, no maximum length check is performed. Streaming InputsStreaming OutputsAutomatic Voice DetectionReal Time Speech Recognition","type":"DOCS"},{"title":"BarPlot","slug":"/main/docs/gradio/barplot","content":"BarPlot ```\ngradio.BarPlot(···)\n``` Description Creates a bar plot component to display data from a pandas DataFrame.  Behavior Using BarPlot as an input component. How BarPlot will pass its value to your function: Type: PlotData | None The data to display in a line plot. Example Code \n    \n    import gradio as gr\n\n    def predict(\n        value: PlotData | None\n    ):\n        # process value from the BarPlot component\n        return \"prediction\"\n\n    interface = gr.Interface(predict, gr.BarPlot(), gr.Textbox())\n    interface.launch()\n\n  Using BarPlot as an output component How BarPlot expects you to return a value: Type: pd.DataFrame | dict | None Expects a pandas DataFrame containing the data to display in the line plot. The DataFrame should contain at least two columns:\none for the x-axis (corresponding to this component's x argument)\none for the y-axis (corresponding to y). Example Code \n    \n    import gradio as gr\n\n    def predict(text) -> pd.DataFrame | dict | None\n        # process value to return to the BarPlot component\n        return value\n\n    interface = gr.Interface(predict, gr.Textbox(), gr.BarPlot())\n    interface.launch()\n\n Initialization Parameters ▼ 🔗 ```\nvalue: pd.DataFrame | Callable | None\n``` default = None The pandas dataframe containing the data to display in the plot.🔗 ```\nx: str | None\n``` default = None Column corresponding to the x axis. Column can be numeric, datetime, or string/category.🔗 ```\ny: str | None\n``` default = None Column corresponding to the y axis. Column must be numeric.🔗 ```\ncolor: str | None\n``` default = None Column corresponding to series, visualized by color. Column must be string/category.🔗 ```\ntitle: str | None\n``` default = None The title to display on top of the chart.🔗 ```\nx_title: str | None\n``` default = None The title given to the x axis. By default, uses the value of the x parameter.🔗 ```\ny_title: str | None\n``` default = None The title given to the y axis. By default, uses the value of the y parameter.🔗 ```\ncolor_title: str | None\n``` default = None The title given to the color legend. By default, uses the value of color parameter.🔗 ```\nx_bin: str | float | None\n``` default = None Grouping used to cluster x values. If x column is numeric, should be number to bin the x values. If x column is datetime, should be string such as &quot;1h&quot;, &quot;15m&quot;, &quot;10s&quot;, using &quot;s&quot;, &quot;m&quot;, &quot;h&quot;, &quot;d&quot; suffixes.🔗 ```\ny_aggregate: Literal['sum', 'mean', 'median', 'min', 'max', 'count'] | None\n``` default = None Aggregation function used to aggregate y values, used if x_bin is provided or x is a string/category. Must be one of &quot;sum&quot;, &quot;mean&quot;, &quot;median&quot;, &quot;min&quot;, &quot;max&quot;.🔗 ```\ncolor_map: dict[str, str] | None\n``` default = None Mapping of series to color names or codes. For example, {&quot;success&quot;: &quot;green&quot;, &quot;fail&quot;: &quot;#FF8888&quot;}.🔗 ```\ncolors_in_legend: list[str] | None\n``` default = None List containing column names of the series to show in the legend. By default, all series are shown.🔗 ```\nx_lim: list[float | None] | None\n``` default = None A tuple or list containing the limits for the x-axis, specified as [x_min, x_max]. To fix only one of these values, set the other to None, e.g. [0, None] to scale from 0 to the maximum value. If x column is datetime type, x_lim should be timestamps.🔗 ```\ny_lim: list[float | None]\n``` default = None A tuple of list containing the limits for the y-axis, specified as [y_min, y_max]. To fix only one of these values, set the other to None, e.g. [0, None] to scale from 0 to the maximum to value.🔗 ```\nx_label_angle: float\n``` default = 0 The angle of the x-axis labels in degrees offset clockwise.🔗 ```\ny_label_angle: float\n``` default = 0 The angle of the y-axis labels in degrees offset clockwise.🔗 ```\nx_axis_format: str | None\n``` default = None A d3 format string for the x-axis labels (e.g., &quot;.2e&quot; for scientific notation, &quot;~g&quot; for general format). If None, uses Vega-Lite&#039;s default formatting.🔗 ```\ny_axis_format: str | None\n``` default = None A d3 format string for the y-axis labels (e.g., &quot;.2e&quot; for scientific notation, &quot;~g&quot; for general format). If None, uses Vega-Lite&#039;s default formatting.🔗 ```\nx_axis_labels_visible: bool | Literal['hidden']\n``` default = True Whether the x-axis labels should be visible. Can be hidden when many x-axis labels are present.🔗 ```\ncaption: str | I18nData | None\n``` default = None The (optional) caption to display below the plot.🔗 ```\nsort: Literal['x', 'y', '-x', '-y'] | list[str] | None\n``` default = None The sorting order of the x values, if x column is type string/category. Can be &quot;x&quot;, &quot;y&quot;, &quot;-x&quot;, &quot;-y&quot;, or list of strings that represent the order of the categories.🔗 ```\ntooltip: Literal['axis', 'none', 'all'] | list[str]\n``` default = \"axis\" The tooltip to display when hovering on a point. &quot;axis&quot; shows the values for the axis columns, &quot;all&quot; shows all column values, and &quot;none&quot; shows no tooltips. Can also provide a list of strings representing columns to show in the tooltip, which will be displayed along with axis values.🔗 ```\nheight: int | None\n``` default = None The height of the plot in pixels.🔗 ```\nlabel: str | I18nData | None\n``` default = None The (optional) label to display on the top left corner of the plot.🔗 ```\nshow_label: bool | None\n``` default = None Whether the label should be displayed.🔗 ```\ncontainer: bool\n``` default = True If True, will place the component in a container - providing some extra padding around the border.🔗 ```\nscale: int | None\n``` 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.🔗 ```\nmin_width: int\n``` 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.🔗 ```\nevery: Timer | float | None\n``` default = None Continuously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.🔗 ```\ninputs: Component | list[Component] | Set[Component] | None\n``` 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.🔗 ```\nvisible: bool | Literal['hidden']\n``` default = True Whether the plot should be visible.🔗 ```\nelem_id: str | None\n``` 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.🔗 ```\nelem_classes: list[str] | str | None\n``` 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.🔗 ```\nrender: bool\n``` 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.🔗 ```\nbuttons: list[Literal['fullscreen', 'export'] | Button] | None\n``` default = None A list of buttons to show for the component. Valid options are &quot;fullscreen&quot;, &quot;export&quot;, or a gr.Button() instance. The &quot;fullscreen&quot; button allows the user to view the plot in fullscreen mode. The &quot;export&quot; button allows the user to export and download the current view of the plot as a PNG image. Custom gr.Button() instances will appear in the toolbar with their configured icon and/or label, and clicking them will trigger any .click() events registered on the button. By default, no buttons are shown.🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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 &#039;preserved_by_key&#039; are not reset across a re-render.🔗 ```\npreserved_by_key: list[str] | str | None\n``` default = \"value\" A list of parameters from this component&#039;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. Key Concepts gr.LinePlot, gr.ScatterPlot, and gr.BarPlot all share the same API. Here is a summary of the most important features. For full details and live demos, see the Creating Plots and Time Plots guides. Basic Usage with a DataFrame Pass a pd.DataFrame as the value, and specify x and y column names. The y-axis must be numeric; the x-axis can be strings, numbers, categories, or datetimes. ```\nimport gradio as gr\nimport pandas as pd\n\ndf = pd.DataFrame({\"origin\": [\"US\", \"EU\", \"Asia\"], \"sales\": [120, 95, 180]})\n\nwith gr.Blocks() as demo:\n    gr.BarPlot(df, x=\"origin\", y=\"sales\")\n``` Breaking Out Series by Color Use the color argument to group bars by a categorical column. Use color_map to assign specific colors: ```\ngr.BarPlot(df, x=\"origin\", y=\"sales\", color=\"year\",\n           color_map={\"2023\": \"#4488FF\", \"2024\": \"#FF8844\"})\n``` Aggregating Values Use x_bin and y_aggregate to group and summarize data. For string x-axes, the string values act as category bins automatically. For numeric x-axes, x_bin sets the bin size: ```\ngr.BarPlot(df, x=\"origin\", y=\"sales\", y_aggregate=\"sum\")\ngr.BarPlot(df, x=\"year\", y=\"sales\", x_bin=1, y_aggregate=\"mean\")\n``` For time-series data, pass a string suffix (\"s\", \"m\", \"h\", or \"d\") to x_bin: ```\ngr.BarPlot(df, x=\"timestamp\", y=\"sales\", x_bin=\"1d\", y_aggregate=\"sum\")\n``` Interactive Selection and Zoom Use the .select event listener to respond to region selections (click and drag). Combine with .double_click and x_lim to implement zoom in/out: ```\nwith gr.Blocks() as demo:\n    plot = gr.BarPlot(df, x=\"timestamp\", y=\"sales\")\n\n    @plot.select\n    def zoom(selection: gr.SelectData):\n        return gr.BarPlot(x_lim=[selection.index[0], selection.index[1]])\n\n    plot.double_click(lambda: gr.BarPlot(x_lim=None), outputs=plot)\n``` Realtime Data Use gr.Timer to keep plots updated with live data. You can attach the timer via every, or wire it up manually: ```\ndef get_data():\n    return pd.DataFrame(...)  # fetch latest data\n\nwith gr.Blocks() as demo:\n    timer = gr.Timer(5)\n    plot = gr.BarPlot(get_data, x=\"time\", y=\"sales\", every=timer)\n``` Interactive Dashboards Plots can be driven by other components (dropdowns, sliders, etc.) to create fully interactive dashboards: ```\nwith gr.Blocks() as demo:\n    year = gr.Dropdown(choices=[2022, 2023, 2024], value=2024)\n    plot = gr.BarPlot(x=\"origin\", y=\"sales\")\n\n    def update(yr):\n        filtered = df[df[\"year\"] == yr]\n        return gr.BarPlot(filtered)\n\n    year.change(update, inputs=year, outputs=plot)\n``` Shortcuts Shortcuts ```\ngradio.BarPlot\n``` Interface String Shortcut \"barplot\" Initialization Uses default values Demos bar_plot_demo  Event Listeners Description Event listeners allow you to respond to user interactions with the UI\n\t\tcomponents you've defined in a Gradio Blocks app. When a user interacts with\n\t\tan element, such as changing a slider value or uploading an image, a\n\t\tfunction is called. Supported Event Listeners The BarPlot component supports the following event listeners. Each event listener takes the\n\t\tsame parameters, which are listed in the Event Parameters table below. Listeners ```\nBarPlot.change(fn, ···)\n``` Triggered when the value of the NativePlot 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.```\nBarPlot.select(fn, ···)\n``` Event listener for when the user selects or deselects the NativePlot. Uses event data gradio.SelectData to carry value referring to the label of the NativePlot, and selected to refer to state of the NativePlot. See https://www.gradio.app/main/docs/gradio/eventdata for more details.```\nBarPlot.double_click(fn, ···)\n``` Triggered when the NativePlot is double clicked. Event Parameters Parameters ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.  Creating PlotsTime Plots","type":"DOCS"},{"title":"Button","slug":"/main/docs/gradio/button","content":"Button ```\ngradio.Button(···)\n``` Description Creates a button that can be assigned arbitrary .click() events. The value (label) of the button can be used as an input to the function (rarely used) or set via the output of a function. Behavior Using Button as an input component. How Button will pass its value to your function: Type: str | None (Rarely used) the str corresponding to the button label when the button is clicked Example Code \n    \n    import gradio as gr\n\n    def predict(\n        value: str | None\n    ):\n        # process value from the Button component\n        return \"prediction\"\n\n    interface = gr.Interface(predict, gr.Button(), gr.Textbox())\n    interface.launch()\n\n  Using Button as an output component How Button expects you to return a value: Type: str | None string corresponding to the button label Example Code \n    \n    import gradio as gr\n\n    def predict(text) -> str | None\n        # process value to return to the Button component\n        return value\n\n    interface = gr.Interface(predict, gr.Textbox(), gr.Button())\n    interface.launch()\n\n Initialization Parameters ▼ 🔗 ```\nvalue: str | I18nData | Callable\n``` default = \"Run\" default text for the button to display. If a function is provided, the function will be called each time the app loads to set the initial value of this component.🔗 ```\nevery: Timer | float | None\n``` default = None continuously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.🔗 ```\ninputs: Component | list[Component] | set[Component] | None\n``` 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.🔗 ```\nvariant: Literal['primary', 'secondary', 'stop', 'huggingface']\n``` default = \"secondary\" sets the background and text color of the button. Use &#039;primary&#039; for main call-to-action buttons, &#039;secondary&#039; for a more subdued style, &#039;stop&#039; for a stop button, &#039;huggingface&#039; for a black background with white text, consistent with Hugging Face&#039;s button styles.🔗 ```\nsize: Literal['sm', 'md', 'lg']\n``` default = \"lg\" size of the button. Can be &quot;sm&quot;, &quot;md&quot;, or &quot;lg&quot;.🔗 ```\nicon: str | Path | None\n``` default = None URL or path to the icon file to display within the button. If None, no icon will be displayed.🔗 ```\nlink: str | None\n``` default = None URL to open when the button is clicked. If None, no link will be used.🔗 ```\nlink_target: Literal['_self', '_blank', '_parent', '_top']\n``` default = \"_self\" determines where to open the linked URL. &quot;_self&quot; (default, same tab), &quot;_blank&quot; (new tab), &quot;_parent&quot; (parent frame), &quot;_top&quot; (top frame).🔗 ```\nvisible: bool | Literal['hidden']\n``` default = True If False, component will be hidden. If &quot;hidden&quot;, component will be visually hidden and not take up space in the layout but still exist in the DOM🔗 ```\ninteractive: bool\n``` default = True if False, the Button will be in a disabled state.🔗 ```\nelem_id: str | None\n``` 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.🔗 ```\nelem_classes: list[str] | str | None\n``` 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.🔗 ```\nrender: bool\n``` 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.🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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 &#039;preserved_by_key&#039; are not reset across a re-render.🔗 ```\npreserved_by_key: list[str] | str | None\n``` default = \"value\" A list of parameters from this component&#039;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.🔗 ```\nscale: int | None\n``` 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.🔗 ```\nmin_width: int | None\n``` default = None minimum pixel width, will wrap if not sufficient screen space to satisfy this value. If a certain scale value results in this Component being narrower than min_width, the min_width parameter will be respected first. Shortcuts Shortcuts ```\ngradio.Button\n``` Interface String Shortcut \"button\" Initialization Uses default values```\ngradio.ClearButton\n``` Interface String Shortcut \"clearbutton\" Initialization Uses default values```\ngradio.DeepLinkButton\n``` Interface String Shortcut \"deeplinkbutton\" Initialization Uses default values```\ngradio.DuplicateButton\n``` Interface String Shortcut \"duplicatebutton\" Initialization Uses default values```\ngradio.LoginButton\n``` Interface String Shortcut \"loginbutton\" Initialization Uses default values  Event Listeners Description Event listeners allow you to respond to user interactions with the UI\n\t\tcomponents you've defined in a Gradio Blocks app. When a user interacts with\n\t\tan element, such as changing a slider value or uploading an image, a\n\t\tfunction is called. Supported Event Listeners The Button component supports the following event listeners. Each event listener takes the\n\t\tsame parameters, which are listed in the Event Parameters table below. Listeners ```\nButton.change(fn, ···)\n``` Triggered when the value of the Button 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.```\nButton.click(fn, ···)\n``` Triggered when the Button is clicked. Event Parameters Parameters ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.  ","type":"DOCS"},{"title":"Chatbot","slug":"/main/docs/gradio/chatbot","content":"Chatbot ```\ngradio.Chatbot(···)\n``` Description Creates a chatbot that displays user-submitted messages and responses. Supports a subset of Markdown including bold, italics, code, tables. Also supports audio/video/image files, which are displayed in the Chatbot, and other kinds of files which are displayed as links. This component is usually used as an output component.  Behavior The Chatbot component accepts a list of messages, where each message is a dictionary with role and content keys. This format is compatible with the message format expected by most LLM APIs (OpenAI, Claude, HuggingChat, etc.), making it easy to pipe model outputs directly into the component. The role key should be either 'user' or 'assistant', and the content key can be a string (rendered as markdown/HTML) or a Gradio component (useful for displaying files, images, plots, and other media). As an example: ```\nimport gradio as gr\n\nhistory = [\n    {\"role\": \"assistant\", \"content\": \"I am happy to provide you that report and plot.\"},\n    {\"role\": \"assistant\", \"content\": gr.Plot(value=make_plot_from_file('quaterly_sales.txt'))}\n]\n\nwith gr.Blocks() as demo:\n    gr.Chatbot(history)\n\ndemo.launch()\n``` For convenience, you can use the ChatMessage dataclass so that your text editor can give you autocomplete hints and typechecks. ```\nimport gradio as gr\n\nhistory = [\n    gr.ChatMessage(role=\"assistant\", content=\"How can I help you?\"),\n    gr.ChatMessage(role=\"user\", content=\"Can you make me a plot of quarterly sales?\"),\n    gr.ChatMessage(role=\"assistant\", content=\"I am happy to provide you that report and plot.\")\n]\n\nwith gr.Blocks() as demo:\n    gr.Chatbot(history)\n\ndemo.launch()\n``` Initialization Parameters ▼ 🔗 ```\nvalue: list[MessageDict | Message] | Callable | None\n``` default = None Default list of messages to show in chatbot, where each message is of the format {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Help me.&quot;}. Role can be one of &quot;user&quot;, &quot;assistant&quot;, or &quot;system&quot;. Content should be either text, or media passed as a Gradio component, e.g. {&quot;content&quot;: gr.Image(&quot;lion.jpg&quot;)}. If a function is provided, the function will be called each time the app loads to set the initial value of this component.🔗 ```\nlabel: str | I18nData | None\n``` 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.🔗 ```\nevery: Timer | float | None\n``` default = None Continuously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.🔗 ```\ninputs: Component | list[Component] | set[Component] | None\n``` 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.🔗 ```\nshow_label: bool | None\n``` default = None if True, will display label.🔗 ```\ncontainer: bool\n``` default = True If True, will place the component in a container - providing some extra padding around the border.🔗 ```\nscale: int | None\n``` 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.🔗 ```\nmin_width: int\n``` 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.🔗 ```\nvisible: bool | Literal['hidden']\n``` default = True If False, component will be hidden. If &quot;hidden&quot;, component will be visually hidden and not take up space in the layout but still exist in the DOM🔗 ```\nelem_id: str | None\n``` 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.🔗 ```\nelem_classes: list[str] | str | None\n``` 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.🔗 ```\nautoscroll: bool\n``` default = True If True, will automatically scroll to the bottom of the textbox when the value changes, unless the user scrolls up. If False, will not scroll to the bottom of the textbox when the value changes.🔗 ```\nrender: bool\n``` 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.🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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 &#039;preserved_by_key&#039; are not reset across a re-render.🔗 ```\npreserved_by_key: list[str] | str | None\n``` default = \"value\" A list of parameters from this component&#039;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.🔗 ```\nheight: int | str | None\n``` default = 400 The height of the component, specified in pixels if a number is passed, or in CSS units if a string is passed. If messages exceed the height, the component will scroll.🔗 ```\nresizable: bool\n``` default = False If True, the user of the Gradio app can resize the chatbot by dragging the bottom right corner.🔗 ```\nmax_height: int | str | None\n``` 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 messages exceed the height, the component will scroll. If messages are 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`.🔗 ```\nmin_height: int | str | None\n``` 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 messages exceed 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`.🔗 ```\neditable: Literal['user', 'all'] | None\n``` default = None Allows user to edit messages in the chatbot. If set to &quot;user&quot;, allows editing of user messages. If set to &quot;all&quot;, allows editing of assistant messages as well.🔗 ```\nlatex_delimiters: list[dict[str, str | bool]] | None\n``` default = None A list of dicts of the form {&quot;left&quot;: open delimiter (str), &quot;right&quot;: close delimiter (str), &quot;display&quot;: whether to display in newline (bool)} that will be used to render LaTeX expressions. If not provided, `latex_delimiters` is set to `[{ &quot;left&quot;: &quot;$$&quot;, &quot;right&quot;: &quot;$$&quot;, &quot;display&quot;: 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.🔗 ```\nrtl: bool\n``` default = False If True, sets the direction of the rendered text to right-to-left. Default is False, which renders text left-to-right.🔗 ```\nbuttons: list[Literal['share', 'copy', 'copy_all'] | Button] | None\n``` default = None A list of buttons to show in the top right corner of the component. Valid options are &quot;share&quot;, &quot;copy&quot;, &quot;copy_all&quot;, or a gr.Button() instance. The &quot;share&quot; button allows the user to share outputs to Hugging Face Spaces Discussions. The &quot;copy&quot; button makes a copy button appear next to each individual chatbot message. The &quot;copy_all&quot; button appears at the component level and allows the user to copy all chatbot messages. Custom gr.Button() instances will appear in the toolbar with their configured icon and/or label, and clicking them will trigger any .click() events registered on the button. By default, &quot;share&quot; and &quot;copy_all&quot; buttons are shown.🔗 ```\nwatermark: str | None\n``` default = None If provided, this text will be appended to the end of messages copied from the chatbot, after a blank line. Useful for indicating that the message is generated by an AI model.🔗 ```\navatar_images: tuple[str | Path | None, str | Path | None] | None\n``` default = None Tuple of two avatar image paths or URLs for user and bot (in that order). Pass None for either the user or bot image to skip. Must be within the working directory of the Gradio app or an external URL.🔗 ```\nsanitize_html: bool\n``` default = True If False, will disable HTML sanitization for chatbot messages. This is not recommended, as it can lead to security vulnerabilities.🔗 ```\nrender_markdown: bool\n``` default = True If False, will disable Markdown rendering for chatbot messages.🔗 ```\nfeedback_options: list[str] | tuple[str, ...] | None\n``` default = ('Like', 'Dislike') A list of strings representing the feedback options that will be displayed to the user. The exact case-sensitive strings &quot;Like&quot; and &quot;Dislike&quot; will render as thumb icons, but any other choices will appear under a separate flag icon.🔗 ```\nfeedback_value: list[str | None] | None\n``` default = None A list of strings representing the feedback state for entire chat. Only works when type=&quot;messages&quot;. Each entry in the list corresponds to that assistant message, in order, and the value is the feedback given (e.g. &quot;Like&quot;, &quot;Dislike&quot;, or any custom feedback option) or None if no feedback was given for that message.🔗 ```\nline_breaks: bool\n``` default = True If True (default), will enable Github-flavored Markdown line breaks in chatbot messages. If False, single new lines will be ignored. Only applies if `render_markdown` is True.🔗 ```\nlayout: Literal['panel', 'bubble'] | None\n``` default = None If &quot;panel&quot;, will display the chatbot in a llm style layout. If &quot;bubble&quot;, will display the chatbot with message bubbles, with the user and bot messages on alterating sides. Will default to &quot;bubble&quot;.🔗 ```\nplaceholder: str | None\n``` default = None a placeholder message to display in the chatbot when it is empty. Centered vertically and horizontally in the Chatbot. Supports Markdown and HTML. If None, no placeholder is displayed.🔗 ```\nexamples: list[ExampleMessage] | None\n``` default = None A list of example messages to display in the chatbot before any user/assistant messages are shown. Each example should be a dictionary with an optional &quot;text&quot; key representing the message that should be populated in the Chatbot when clicked, an optional &quot;files&quot; key, whose value should be a list of files to populate in the Chatbot, an optional &quot;icon&quot; key, whose value should be a filepath or URL to an image to display in the example box, and an optional &quot;display_text&quot; key, whose value should be the text to display in the example box. If &quot;display_text&quot; is not provided, the value of &quot;text&quot; will be displayed.🔗 ```\nallow_file_downloads: bool\n``` default = True If True, will show a download button for chatbot messages that contain media. Defaults to True.🔗 ```\ngroup_consecutive_messages: bool\n``` default = True If True, will display consecutive messages from the same role in the same bubble. If False, will display each message in a separate bubble. Defaults to True.🔗 ```\nallow_tags: list[str] | bool\n``` default = True If a list of tags is provided, these tags will be preserved in the output chatbot messages, even if `sanitize_html` is `True`. For example, if this list is [&quot;thinking&quot;], the tags `&lt;thinking&gt;` and `&lt;/thinking&gt;` will not be removed. If True, all custom tags (non-standard HTML tags) will be preserved. If False, no tags will be preserved. Default value is &#039;True&#039;.🔗 ```\nreasoning_tags: list[tuple[str, str]] | None\n``` default = None If provided, a list of tuples of (open_tag, close_tag) strings. Any text between these tags will be extracted and displayed in a separate collapsible message with metadata={&quot;title&quot;: &quot;Reasoning&quot;}. For example, [(&quot;&lt;thinking&gt;&quot;, &quot;&lt;/thinking&gt;&quot;)] will extract content between &lt;thinking&gt; and &lt;/thinking&gt; tags. Each thinking block will be displayed as a separate collapsible message before the main response. If None (default), no automatic extraction is performed.🔗 ```\nlike_user_message: bool\n``` default = False If True, will show like/dislike buttons for user messages as well. Defaults to False. Shortcuts Shortcuts ```\ngradio.Chatbot\n``` Interface String Shortcut \"chatbot\" Initialization Uses default values Examples Displaying Thoughts/Tool Usage You can provide additional metadata regarding any tools used to generate the response.\nThis is useful for displaying the thought process of LLM agents. For example, ```\ndef generate_response(history):\n    history.append(\n        ChatMessage(role=\"assistant\",\n                    content=\"The weather API says it is 20 degrees Celcius in New York.\",\n                    metadata={\"title\": \"🛠️ Used tool Weather API\"})\n        )\n    return history\n``` Would be displayed as following:  You can also specify metadata with a plain python dictionary, ```\ndef generate_response(history):\n    history.append(\n        dict(role=\"assistant\",\n             content=\"The weather API says it is 20 degrees Celcius in New York.\",\n             metadata={\"title\": \"🛠️ Used tool Weather API\"})\n        )\n    return history\n``` Using Gradio Components Inside gr.Chatbot The Chatbot component supports using many of the core Gradio components (such as gr.Image, gr.Plot, gr.Audio, and gr.HTML) inside of the chatbot. Simply include one of these components as the content of a message. Here’s an example: ```\nimport gradio as gr\n\ndef load():\n    return [\n        {\"role\": \"user\", \"content\": \"Can you show me some media?\"},\n        {\"role\": \"assistant\", \"content\": \"Here's an audio clip:\"},\n        {\"role\": \"assistant\", \"content\": gr.Audio(\"https://github.com/gradio-app/gradio/raw/main/gradio/media_assets/audio/audio_sample.wav\")},\n        {\"role\": \"assistant\", \"content\": \"And here's a video:\"},\n        {\"role\": \"assistant\", \"content\": gr.Video(\"https://github.com/gradio-app/gradio/raw/main/gradio/media_assets/videos/world.mp4\")}\n    ]\n\nwith gr.Blocks() as demo:\n    chatbot = gr.Chatbot()\n    button = gr.Button(\"Load audio and video\")\n    button.click(load, None, chatbot)\n\ndemo.launch()\n``` Demos chatbot_simplechatbot_streamingchatbot_with_toolschatbot_core_components  Event Listeners Description Event listeners allow you to respond to user interactions with the UI\n\t\tcomponents you've defined in a Gradio Blocks app. When a user interacts with\n\t\tan element, such as changing a slider value or uploading an image, a\n\t\tfunction is called. Supported Event Listeners The Chatbot component supports the following event listeners. Each event listener takes the\n\t\tsame parameters, which are listed in the Event Parameters table below. Listeners ```\nChatbot.change(fn, ···)\n``` Triggered when the value of the Chatbot 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.```\nChatbot.select(fn, ···)\n``` Event listener for when the user selects or deselects the Chatbot. Uses event data gradio.SelectData to carry value referring to the label of the Chatbot, and selected to refer to state of the Chatbot. See https://www.gradio.app/main/docs/gradio/eventdata for more details.```\nChatbot.like(fn, ···)\n``` This listener is triggered when the user likes/dislikes from within the Chatbot. This event has EventData of type gradio.LikeData that carries information, accessible through LikeData.index and LikeData.value. See EventData documentation on how to use this event data.```\nChatbot.retry(fn, ···)\n``` This listener is triggered when the user clicks the retry button in the chatbot message.```\nChatbot.undo(fn, ···)\n``` This listener is triggered when the user clicks the undo button in the chatbot message.```\nChatbot.example_select(fn, ···)\n``` This listener is triggered when the user clicks on an example from within the Chatbot. This event has SelectData of type gradio.SelectData that carries information, accessible through SelectData.index and SelectData.value. See SelectData documentation on how to use this event data.```\nChatbot.option_select(fn, ···)\n``` This listener is triggered when the user clicks on an option from within the Chatbot. This event has SelectData of type gradio.SelectData that carries information, accessible through SelectData.index and SelectData.value. See SelectData documentation on how to use this event data.```\nChatbot.clear(fn, ···)\n``` This listener is triggered when the user clears the Chatbot using the clear button for the component.```\nChatbot.copy(fn, ···)\n``` This listener is triggered when the user copies content from the Chatbot. Uses event data gradio.CopyData to carry information about the copied content. See EventData documentation on how to use this event data```\nChatbot.edit(fn, ···)\n``` This listener is triggered when the user edits the Chatbot (e.g. image) using the built-in editor. Event Parameters Parameters ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.  Helper Classes ChatMessage ```\ngradio.ChatMessage(···)\n``` Description A dataclass that represents a message in the Chatbot component (with type=\"messages\"). The only required field is content. The value of gr.Chatbot is a list of these dataclasses. Parameters ▼ 🔗 ```\ncontent: MessageContent | list[MessageContent]\n```  The content of the message. Can be a string, a file dict, a gradio component, or a list of these types to group these messages together.🔗 ```\nrole: Literal['user', 'assistant', 'system']\n``` default = \"assistant\" The role of the message, which determines the alignment of the message in the chatbot. Can be &quot;user&quot;, &quot;assistant&quot;, or &quot;system&quot;. Defaults to &quot;assistant&quot;.🔗 ```\nmetadata: MetadataDict\n``` default = _HAS_DEFAULT_FACTORY_CLASS() The metadata of the message, which is used to display intermediate thoughts / tool usage. Should be a dictionary with the following keys: &quot;title&quot; (required to display the thought), and optionally: &quot;id&quot; and &quot;parent_id&quot; (to nest thoughts), &quot;duration&quot; (to display the duration of the thought), &quot;status&quot; (to display the status of the thought).🔗 ```\noptions: list[OptionDict]\n``` default = _HAS_DEFAULT_FACTORY_CLASS() The options of the message. A list of Option objects, which are dictionaries with the following keys: &quot;label&quot; (the text to display in the option), and optionally &quot;value&quot; (the value to return when the option is selected if different from the label). MetadataDict A typed dictionary to represent metadata for a message in the Chatbot component. An instance of this dictionary is used for the metadata field in a ChatMessage when the chat message should be displayed as a thought. Keys ▼ 🔗 ```\ntitle: str\n```  The title of the &#039;thought&#039; message. Only required field.🔗 ```\nid: int | str\n```  The ID of the message. Only used for nested thoughts. Nested thoughts can be nested by setting the parent_id to the id of the parent thought.🔗 ```\nparent_id: int | str\n```  The ID of the parent message. Only used for nested thoughts.🔗 ```\nlog: str\n```  A string message to display next to the thought title in a subdued font.🔗 ```\nduration: float\n```  The duration of the message in seconds. Appears next to the thought title in a subdued font inside a parentheses.🔗 ```\nstatus: Literal['pending', 'done']\n```  if set to `&#039;pending&#039;`, a spinner appears next to the thought title and the accordion is initialized open.  If `status` is `&#039;done&#039;`, the thought accordion is initialized closed. If `status` is not provided, the thought accordion is initialized open and no spinner is displayed. OptionDict A typed dictionary to represent an option in a ChatMessage. A list of these dictionaries is used for the options field in a ChatMessage. Keys ▼ 🔗 ```\nvalue: str\n```  The value to return when the option is selected.🔗 ```\nlabel: str\n```  The text to display in the option, if different from the value. Chatbot Specific EventsConversational ChatbotCreating A Chatbot FastCreating A Custom Chatbot With BlocksAgents And Tool Usage","type":"DOCS"},{"title":"Checkbox","slug":"/main/docs/gradio/checkbox","content":"Checkbox ```\ngradio.Checkbox(···)\n``` Description Creates a checkbox that can be set to True or False. Can be used as an input to pass a boolean value to a function or as an output to display a boolean value.  Behavior Using Checkbox as an input component. How Checkbox will pass its value to your function: Type: bool | None Passes the status of the checkbox as a bool. Example Code \n    \n    import gradio as gr\n\n    def predict(\n        value: bool | None\n    ):\n        # process value from the Checkbox component\n        return \"prediction\"\n\n    interface = gr.Interface(predict, gr.Checkbox(), gr.Textbox())\n    interface.launch()\n\n  Using Checkbox as an output component How Checkbox expects you to return a value: Type: bool | None Expects a bool value that is set as the status of the checkbox Example Code \n    \n    import gradio as gr\n\n    def predict(text) -> bool | None\n        # process value to return to the Checkbox component\n        return value\n\n    interface = gr.Interface(predict, gr.Textbox(), gr.Checkbox())\n    interface.launch()\n\n Initialization Parameters ▼ 🔗 ```\nvalue: bool | Callable\n``` default = False if True, checked by default. If a function is provided, the function will be called each time the app loads to set the initial value of this component.🔗 ```\nlabel: str | I18nData | None\n``` default = None the label for this checkbox, displayed to the right of the checkbox if `show_label` is `True`.🔗 ```\ninfo: str | I18nData | None\n``` default = None additional component description, appears below the label in smaller font. Supports markdown / HTML syntax.🔗 ```\nevery: Timer | float | None\n``` default = None Continuously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.🔗 ```\ninputs: Component | list[Component] | set[Component] | None\n``` 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.🔗 ```\nshow_label: bool | None\n``` default = None if True, will display label.🔗 ```\ncontainer: bool\n``` default = True If True, will place the component in a container - providing some extra padding around the border.🔗 ```\nscale: int | None\n``` 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.🔗 ```\nmin_width: int\n``` 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.🔗 ```\ninteractive: bool | None\n``` default = None if True, this checkbox can be checked; if False, checking will be disabled. If not provided, this is inferred based on whether the component is used as an input or output.🔗 ```\nvisible: bool | Literal['hidden']\n``` default = True If False, component will be hidden. If &quot;hidden&quot;, component will be visually hidden and not take up space in the layout but still exist in the DOM🔗 ```\nelem_id: str | None\n``` 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.🔗 ```\nelem_classes: list[str] | str | None\n``` 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.🔗 ```\nrender: bool\n``` 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.🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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 &#039;preserved_by_key&#039; are not reset across a re-render.🔗 ```\npreserved_by_key: list[str] | str | None\n``` default = \"value\" A list of parameters from this component&#039;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.🔗 ```\nbuttons: list[Button] | None\n``` default = None A list of gr.Button() instances to show in the top right corner of the component. Custom buttons will appear in the toolbar with their configured icon and/or label, and clicking them will trigger any .click() events registered on the button. Shortcuts Shortcuts ```\ngradio.Checkbox\n``` Interface String Shortcut \"checkbox\" Initialization Uses default values Demos sentence_builderhello_world_3  Event Listeners Description Event listeners allow you to respond to user interactions with the UI\n\t\tcomponents you've defined in a Gradio Blocks app. When a user interacts with\n\t\tan element, such as changing a slider value or uploading an image, a\n\t\tfunction is called. Supported Event Listeners The Checkbox component supports the following event listeners. Each event listener takes the\n\t\tsame parameters, which are listed in the Event Parameters table below. Listeners ```\nCheckbox.change(fn, ···)\n``` 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.```\nCheckbox.input(fn, ···)\n``` This listener is triggered when the user changes the value of the Checkbox.```\nCheckbox.select(fn, ···)\n``` 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 https://www.gradio.app/main/docs/gradio/eventdata for more details. Event Parameters Parameters ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.  ","type":"DOCS"},{"title":"CheckboxGroup","slug":"/main/docs/gradio/checkboxgroup","content":"CheckboxGroup ```\ngradio.CheckboxGroup(···)\n``` Description 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. Behavior Using CheckboxGroup as an input component. How CheckboxGroup will pass its value to your function: Type: list[str | int | float] | list[int | None] 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. Example Code \n    \n    import gradio as gr\n\n    def predict(\n        value: list[str | int | float] | list[int | None]\n    ):\n        # process value from the CheckboxGroup component\n        return \"prediction\"\n\n    interface = gr.Interface(predict, gr.CheckboxGroup(), gr.Textbox())\n    interface.launch()\n\n  Using CheckboxGroup as an output component How CheckboxGroup expects you to return a value: Type: list[str | int | float] | str | int | float | None Expects a list[str | int | float] of values or a single str | int | float value, the checkboxes with these values are checked. Example Code \n    \n    import gradio as gr\n\n    def predict(text) -> list[str | int | float] | str | int | float | None\n        # process value to return to the CheckboxGroup component\n        return value\n\n    interface = gr.Interface(predict, gr.Textbox(), gr.CheckboxGroup())\n    interface.launch()\n\n Initialization Parameters ▼ 🔗 ```\nchoices: list[str | int | float | tuple[str | I18nData, str | int | float]] | None\n``` 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.🔗 ```\nvalue: list[str | float | int] | str | float | int | Callable | None\n``` 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.🔗 ```\ntype: Literal['value', 'index']\n``` default = \"value\" Type of value to be returned by component. &quot;value&quot; returns the list of strings of the choices selected, &quot;index&quot; returns the list of indices of the choices selected.🔗 ```\nlabel: str | I18nData | None\n``` 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.🔗 ```\ninfo: str | I18nData | None\n``` default = None additional component description, appears below the label in smaller font. Supports markdown / HTML syntax.🔗 ```\nevery: Timer | float | None\n``` default = None Continuously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.🔗 ```\ninputs: Component | list[Component] | set[Component] | None\n``` 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.🔗 ```\nshow_label: bool | None\n``` default = None If True, will display label.🔗 ```\nshow_select_all: bool\n``` default = False If True, will display a select/deselect all checkbox next to the label. Only available when show_label is True.🔗 ```\ncontainer: bool\n``` default = True If True, will place the component in a container - providing some extra padding around the border.🔗 ```\nscale: int | None\n``` 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.🔗 ```\nmin_width: int\n``` 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.🔗 ```\ninteractive: bool | None\n``` 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.🔗 ```\nvisible: bool | Literal['hidden']\n``` default = True If False, component will be hidden. If &quot;hidden&quot;, component will be visually hidden and not take up space in the layout but still exist in the DOM🔗 ```\nelem_id: str | None\n``` 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.🔗 ```\nelem_classes: list[str] | str | None\n``` 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.🔗 ```\nrender: bool\n``` 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.🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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 &#039;preserved_by_key&#039; are not reset across a re-render.🔗 ```\npreserved_by_key: list[str] | str | None\n``` default = \"value\" A list of parameters from this component&#039;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.🔗 ```\nbuttons: list[Button] | None\n``` default = None A list of gr.Button() instances to show in the top right corner of the component. Custom buttons will appear in the toolbar with their configured icon and/or label, and clicking them will trigger any .click() events registered on the button. Shortcuts Shortcuts ```\ngradio.CheckboxGroup\n``` Interface String Shortcut \"checkboxgroup\" Initialization Uses default values Demos sentence_builder  Event Listeners Description Event listeners allow you to respond to user interactions with the UI\n\t\tcomponents you've defined in a Gradio Blocks app. When a user interacts with\n\t\tan element, such as changing a slider value or uploading an image, a\n\t\tfunction is called. Supported Event Listeners The CheckboxGroup component supports the following event listeners. Each event listener takes the\n\t\tsame parameters, which are listed in the Event Parameters table below. Listeners ```\nCheckboxGroup.change(fn, ···)\n``` 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.```\nCheckboxGroup.input(fn, ···)\n``` This listener is triggered when the user changes the value of the CheckboxGroup.```\nCheckboxGroup.select(fn, ···)\n``` 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 https://www.gradio.app/main/docs/gradio/eventdata for more details. Event Parameters Parameters ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.  ","type":"DOCS"},{"title":"ClearButton","slug":"/main/docs/gradio/clearbutton","content":"ClearButton ```\ngradio.ClearButton(···)\n``` Description Button that clears the value of a component or a list of components when clicked. It is instantiated with the list of components to clear. Behavior Using ClearButton as an input component. How ClearButton will pass its value to your function: Type: str | None (Rarely used) the str corresponding to the button label when the button is clicked Example Code \n    \n    import gradio as gr\n\n    def predict(\n        value: str | None\n    ):\n        # process value from the ClearButton component\n        return \"prediction\"\n\n    interface = gr.Interface(predict, gr.ClearButton(), gr.Textbox())\n    interface.launch()\n\n  Using ClearButton as an output component How ClearButton expects you to return a value: Type: str | None string corresponding to the button label Example Code \n    \n    import gradio as gr\n\n    def predict(text) -> str | None\n        # process value to return to the ClearButton component\n        return value\n\n    interface = gr.Interface(predict, gr.Textbox(), gr.ClearButton())\n    interface.launch()\n\n Initialization Parameters ▼ 🔗 ```\ncomponents: None | list[Component] | Component\n``` default = None 🔗 ```\nvalue: str\n``` default = \"Clear\" default text for the button to display. If a function is provided, the function will be called each time the app loads to set the initial value of this component.🔗 ```\nevery: Timer | float | None\n``` default = None continuously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.🔗 ```\ninputs: Component | list[Component] | set[Component] | None\n``` 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.🔗 ```\nvariant: Literal['primary', 'secondary', 'stop']\n``` default = \"secondary\" sets the background and text color of the button. Use &#039;primary&#039; for main call-to-action buttons, &#039;secondary&#039; for a more subdued style, &#039;stop&#039; for a stop button, &#039;huggingface&#039; for a black background with white text, consistent with Hugging Face&#039;s button styles.🔗 ```\nsize: Literal['sm', 'md', 'lg']\n``` default = \"lg\" size of the button. Can be &quot;sm&quot;, &quot;md&quot;, or &quot;lg&quot;.🔗 ```\nicon: str | Path | None\n``` default = None URL or path to the icon file to display within the button. If None, no icon will be displayed.🔗 ```\nlink: str | None\n``` default = None URL to open when the button is clicked. If None, no link will be used.🔗 ```\nlink_target: Literal['_self', '_blank', '_parent', '_top']\n``` default = \"_self\" 🔗 ```\nvisible: bool | Literal['hidden']\n``` default = True If False, component will be hidden. If &quot;hidden&quot;, component will be visually hidden and not take up space in the layout but still exist in the DOM🔗 ```\ninteractive: bool\n``` default = True if False, the Button will be in a disabled state.🔗 ```\nelem_id: str | None\n``` 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.🔗 ```\nelem_classes: list[str] | str | None\n``` 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.🔗 ```\nrender: bool\n``` 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.🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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 &#039;preserved_by_key&#039; are not reset across a re-render.🔗 ```\npreserved_by_key: list[str] | str | None\n``` default = \"value\" A list of parameters from this component&#039;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.🔗 ```\nscale: int | None\n``` 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.🔗 ```\nmin_width: int | None\n``` default = None minimum pixel width, will wrap if not sufficient screen space to satisfy this value. If a certain scale value results in this Component being narrower than min_width, the min_width parameter will be respected first.🔗 ```\napi_name: str | None\n``` default = None 🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"undocumented\"  Shortcuts Shortcuts ```\ngradio.ClearButton\n``` Interface String Shortcut \"clearbutton\" Initialization Uses default values  Event Listeners Description Event listeners allow you to respond to user interactions with the UI\n\t\tcomponents you've defined in a Gradio Blocks app. When a user interacts with\n\t\tan element, such as changing a slider value or uploading an image, a\n\t\tfunction is called. Supported Event Listeners The ClearButton component supports the following event listeners. Each event listener takes the\n\t\tsame parameters, which are listed in the Event Parameters table below. Listeners ```\nClearButton.add(fn, ···)\n``` Adds a component or list of components to the list of components that will be cleared when the button is clicked.```\nClearButton.change(fn, ···)\n``` Triggered when the value of the Button 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.```\nClearButton.click(fn, ···)\n``` Triggered when the Button is clicked. Event Parameters Parameters ▼ 🔗 ```\ncomponents: None | Component | list[Component]\n```    ","type":"DOCS"},{"title":"Code","slug":"/main/docs/gradio/code","content":"Code ```\ngradio.Code(···)\n``` Description Creates a code editor for viewing code (as an output component), or for entering and editing code (as an input component). Behavior Using Code as an input component. How Code will pass its value to your function: Type: str | None Passes the code entered as a str. Example Code \n    \n    import gradio as gr\n\n    def predict(\n        value: str | None\n    ):\n        # process value from the Code component\n        return \"prediction\"\n\n    interface = gr.Interface(predict, gr.Code(), gr.Textbox())\n    interface.launch()\n\n  Using Code as an output component How Code expects you to return a value: Type: str | None Expects a str of code. Example Code \n    \n    import gradio as gr\n\n    def predict(text) -> str | None\n        # process value to return to the Code component\n        return value\n\n    interface = gr.Interface(predict, gr.Textbox(), gr.Code())\n    interface.launch()\n\n Initialization Parameters ▼ 🔗 ```\nvalue: str | Callable | None\n``` default = None Default value to show in the code editor. If a function is provided, the function will be called each time the app loads to set the initial value of this component.🔗 ```\nlanguage: Literal['python', 'c', 'cpp', 'markdown', 'latex', 'json', 'html', 'css', 'javascript', 'jinja2', 'typescript', 'yaml', 'dockerfile', 'shell', 'r', 'sql', 'sql-msSQL', 'sql-mySQL', 'sql-mariaDB', 'sql-sqlite', 'sql-cassandra', 'sql-plSQL', 'sql-hive', 'sql-pgSQL', 'sql-gql', 'sql-gpSQL', 'sql-sparkSQL', 'sql-esper'] | None\n``` default = None The language to display the code as. Supported languages listed in `gr.Code.languages`.🔗 ```\nevery: Timer | float | None\n``` default = None Continuously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.🔗 ```\ninputs: Component | list[Component] | set[Component] | None\n``` 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.🔗 ```\nlines: int\n``` default = 5 Minimum number of visible lines to show in the code editor.🔗 ```\nmax_lines: int | None\n``` default = None Maximum number of visible lines to show in the code editor. Defaults to None and will fill the height of the container.🔗 ```\nlabel: str | I18nData | None\n``` 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.🔗 ```\ninteractive: bool | None\n``` default = None Whether user should be able to enter code or only view it.🔗 ```\nshow_label: bool | None\n``` default = None if True, will display label.🔗 ```\ncontainer: bool\n``` default = True If True, will place the component in a container - providing some extra padding around the border.🔗 ```\nscale: int | None\n``` 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.🔗 ```\nmin_width: int\n``` 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.🔗 ```\nvisible: bool | Literal['hidden']\n``` default = True If False, component will be hidden. If &quot;hidden&quot;, component will be visually hidden and not take up space in the layout but still exist in the DOM🔗 ```\nelem_id: str | None\n``` 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.🔗 ```\nelem_classes: list[str] | str | None\n``` 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.🔗 ```\nrender: bool\n``` 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.🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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 &#039;preserved_by_key&#039; are not reset across a re-render.🔗 ```\npreserved_by_key: list[str] | str | None\n``` default = \"value\" A list of parameters from this component&#039;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.🔗 ```\nwrap_lines: bool\n``` default = False If True, will wrap lines to the width of the container when overflow occurs. Defaults to False.🔗 ```\nshow_line_numbers: bool\n``` default = True  If True, displays line numbers, and if False, hides line numbers.🔗 ```\nautocomplete: bool\n``` default = False If True, will show autocomplete suggestions for supported languages. Defaults to False.🔗 ```\nbuttons: list[Literal['copy', 'download'] | Button] | None\n``` default = None A list of buttons to show in the top right corner of the component. Valid options are &quot;copy&quot;, &quot;download&quot;, or a gr.Button() instance. The &quot;copy&quot; button allows the user to copy the code to their clipboard. The &quot;download&quot; button allows the user to download the code as a file. Custom gr.Button() instances will appear in the toolbar with their configured icon and/or label, and clicking them will trigger any .click() events registered on the button. By default, both the &quot;copy&quot; and &quot;download&quot; buttons are shown. Shortcuts Shortcuts ```\ngradio.Code\n``` Interface String Shortcut \"code\" Initialization Uses default values  Event Listeners Description Event listeners allow you to respond to user interactions with the UI\n\t\tcomponents you've defined in a Gradio Blocks app. When a user interacts with\n\t\tan element, such as changing a slider value or uploading an image, a\n\t\tfunction is called. Supported Event Listeners The Code component supports the following event listeners. Each event listener takes the\n\t\tsame parameters, which are listed in the Event Parameters table below. Listeners ```\nCode.languages(fn, ···)\n``` [&#x27;python&#x27;, &#x27;c&#x27;, &#x27;cpp&#x27;, &#x27;markdown&#x27;, &#x27;latex&#x27;, &#x27;json&#x27;, &#x27;html&#x27;, &#x27;css&#x27;, &#x27;javascript&#x27;, &#x27;jinja2&#x27;, &#x27;typescript&#x27;, &#x27;yaml&#x27;, &#x27;dockerfile&#x27;, &#x27;shell&#x27;, &#x27;r&#x27;, &#x27;sql&#x27;, &#x27;sql-msSQL&#x27;, &#x27;sql-mySQL&#x27;, &#x27;sql-mariaDB&#x27;, &#x27;sql-sqlite&#x27;, &#x27;sql-cassandra&#x27;, &#x27;sql-plSQL&#x27;, &#x27;sql-hive&#x27;, &#x27;sql-pgSQL&#x27;, &#x27;sql-gql&#x27;, &#x27;sql-gpSQL&#x27;, &#x27;sql-sparkSQL&#x27;, &#x27;sql-esper&#x27;, None]```\nCode.change(fn, ···)\n``` Triggered when the value of the Code 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.```\nCode.input(fn, ···)\n``` This listener is triggered when the user changes the value of the Code.```\nCode.focus(fn, ···)\n``` This listener is triggered when the Code is focused.```\nCode.blur(fn, ···)\n``` This listener is triggered when the Code is unfocused/blurred. Event Parameters Parameters ▼   ","type":"DOCS"},{"title":"ColorPicker","slug":"/main/docs/gradio/colorpicker","content":"ColorPicker ```\ngradio.ColorPicker(···)\n``` Description Creates a color picker for user to select a color as string input. Can be used as an input to pass a color value to a function or as an output to display a color value. Behavior Using ColorPicker as an input component. How ColorPicker will pass its value to your function: Type: str | None Passes selected color value as a hex str into the function. Example Code \n    \n    import gradio as gr\n\n    def predict(\n        value: str | None\n    ):\n        # process value from the ColorPicker component\n        return \"prediction\"\n\n    interface = gr.Interface(predict, gr.ColorPicker(), gr.Textbox())\n    interface.launch()\n\n  Using ColorPicker as an output component How ColorPicker expects you to return a value: Type: str | None Expects a hex str returned from function and sets color picker value to it. Example Code \n    \n    import gradio as gr\n\n    def predict(text) -> str | None\n        # process value to return to the ColorPicker component\n        return value\n\n    interface = gr.Interface(predict, gr.Textbox(), gr.ColorPicker())\n    interface.launch()\n\n Initialization Parameters ▼ 🔗 ```\nvalue: str | Callable | None\n``` default = None default color hex code to provide in color picker. If a function is provided, the function will be called each time the app loads to set the initial value of this component.🔗 ```\nlabel: str | I18nData | None\n``` 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.🔗 ```\ninfo: str | I18nData | None\n``` default = None additional component description, appears below the label in smaller font. Supports markdown / HTML syntax.🔗 ```\nevery: Timer | float | None\n``` default = None Continuously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.🔗 ```\ninputs: Component | list[Component] | set[Component] | None\n``` 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.🔗 ```\nshow_label: bool | None\n``` default = None if True, will display label.🔗 ```\ncontainer: bool\n``` default = True If True, will place the component in a container - providing some extra padding around the border.🔗 ```\nscale: int | None\n``` 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.🔗 ```\nmin_width: int\n``` 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.🔗 ```\ninteractive: bool | None\n``` default = None if True, will be rendered as an editable color picker; if False, editing will be disabled. If not provided, this is inferred based on whether the component is used as an input or output.🔗 ```\nvisible: bool | Literal['hidden']\n``` default = True If False, component will be hidden. If &quot;hidden&quot;, component will be visually hidden and not take up space in the layout but still exist in the DOM🔗 ```\nelem_id: str | None\n``` 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.🔗 ```\nelem_classes: list[str] | str | None\n``` 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.🔗 ```\nrender: bool\n``` 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.🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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 &#039;preserved_by_key&#039; are not reset across a re-render.🔗 ```\npreserved_by_key: list[str] | str | None\n``` default = \"value\" A list of parameters from this component&#039;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. Shortcuts Shortcuts ```\ngradio.ColorPicker\n``` Interface String Shortcut \"colorpicker\" Initialization Uses default values Demos color_picker  Event Listeners Description Event listeners allow you to respond to user interactions with the UI\n\t\tcomponents you've defined in a Gradio Blocks app. When a user interacts with\n\t\tan element, such as changing a slider value or uploading an image, a\n\t\tfunction is called. Supported Event Listeners The ColorPicker component supports the following event listeners. Each event listener takes the\n\t\tsame parameters, which are listed in the Event Parameters table below. Listeners ```\nColorPicker.change(fn, ···)\n``` Triggered when the value of the ColorPicker 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.```\nColorPicker.input(fn, ···)\n``` This listener is triggered when the user changes the value of the ColorPicker.```\nColorPicker.release(fn, ···)\n``` This listener is triggered when the user releases the mouse on this ColorPicker.```\nColorPicker.submit(fn, ···)\n``` This listener is triggered when the user presses the Enter key while the ColorPicker is focused.```\nColorPicker.focus(fn, ···)\n``` This listener is triggered when the ColorPicker is focused.```\nColorPicker.blur(fn, ···)\n``` This listener is triggered when the ColorPicker is unfocused/blurred. Event Parameters Parameters ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.  ","type":"DOCS"},{"title":"Dataframe","slug":"/main/docs/gradio/dataframe","content":"Dataframe ```\ngradio.Dataframe(···)\n``` Description This component displays a table of value spreadsheet-like component. Can be used to display data as an output component, or as an input to collect data from the user. Behavior Using Dataframe as an input component. How Dataframe will pass its value to your function: Type: pd.DataFrame | np.ndarray | pl.DataFrame | list[list] Passes the uploaded spreadsheet data as a pandas.DataFrame, numpy.array, polars.DataFrame, or native 2D Python list[list] depending on type. Example Code \n    \n    import gradio as gr\n\n    def predict(\n        value: pd.DataFrame | np.ndarray | pl.DataFrame | list[list]\n    ):\n        # process value from the Dataframe component\n        return \"prediction\"\n\n    interface = gr.Interface(predict, gr.Dataframe(), gr.Textbox())\n    interface.launch()\n\n  Using Dataframe as an output component How Dataframe expects you to return a value: Type: pd.DataFrame | Styler | np.ndarray | pl.DataFrame | list | list[list] | dict | str | None Expects data in any of these formats:\npandas.DataFrame\npandas.Styler\nnumpy.array\npolars.DataFrame\nlist[list]\nlist\ndict with keys 'data' (and optionally 'headers')\nstr path to a csv, which is rendered as the spreadsheet. Example Code \n    \n    import gradio as gr\n\n    def predict(text) -> pd.DataFrame | Styler | np.ndarray | pl.DataFrame | list | list[list] | dict | str | None\n        # process value to return to the Dataframe component\n        return value\n\n    interface = gr.Interface(predict, gr.Textbox(), gr.Dataframe())\n    interface.launch()\n\n Initialization Parameters ▼ 🔗 ```\nvalue: pd.DataFrame | Styler | np.ndarray | pl.DataFrame | list | list[list] | dict | str | Callable | None\n``` default = None Default value to display in the DataFrame. Supports pandas, numpy, polars, and list of lists. If a Styler is provided, it will be used to set the displayed value in the DataFrame (e.g. to set precision of numbers) if the `interactive` is False. If a Callable function is provided, the function will be called whenever the app loads to set the initial value of the component.🔗 ```\nheaders: list[str] | None\n``` default = None List of str header names. These are used to set the column headers of the dataframe if the value does not have headers. If None, no headers are shown.🔗 ```\nrow_count: int | None\n``` default = None The number of rows to initially display in the dataframe. If None, the number of rows is determined automatically based on the `value`.🔗 ```\nrow_limits: tuple[int | None, int | None] | None\n``` default = None A tuple of two integers specifying the minimum and maximum number of rows that can be created in the dataframe via the UI. If the first element is None, there is no minimum number of rows. If the second element is None, there is no maximum number of rows. Only applies if `interactive` is True.🔗 ```\ncol_count: None\n``` default = None This parameter is deprecated. Please use `column_count` instead.🔗 ```\ncolumn_count: int | None\n``` default = None The number of columns to initially display in the dataframe. If None, the number of columns is determined automatically based on the `value`.🔗 ```\ncolumn_limits: tuple[int | None, int | None] | None\n``` default = None A tuple of two integers specifying the minimum and maximum number of columns that can be created in the dataframe via the UI. If the first element is None, there is no minimum number of columns. If the second element is None, there is no maximum number of columns. Only applies if `interactive` is True.🔗 ```\ndatatype: Literal['str', 'number', 'bool', 'date', 'markdown', 'html', 'image', 'auto'] | list[Literal['str', 'number', 'bool', 'date', 'markdown', 'html']]\n``` default = \"str\" Datatype of values in sheet. Can be provided per column as a list of strings, or for the entire sheet as a single string. Valid datatypes are &quot;str&quot;, &quot;number&quot;, &quot;bool&quot;, &quot;date&quot;, and &quot;markdown&quot;. Boolean columns will display as checkboxes. If the datatype &quot;auto&quot; is used, the column datatypes are automatically selected based on the value input if possible.🔗 ```\ntype: Literal['pandas', 'numpy', 'array', 'polars']\n``` default = \"pandas\" Type of value to be returned by component. &quot;pandas&quot; for pandas dataframe, &quot;numpy&quot; for numpy array, &quot;polars&quot; for polars dataframe, or &quot;array&quot; for a Python list of lists.🔗 ```\nlatex_delimiters: list[dict[str, str | bool]] | None\n``` default = None A list of dicts of the form {&quot;left&quot;: open delimiter (str), &quot;right&quot;: close delimiter (str), &quot;display&quot;: whether to display in newline (bool)} that will be used to render LaTeX expressions. If not provided, `latex_delimiters` is set to `[{ &quot;left&quot;: &quot;$$&quot;, &quot;right&quot;: &quot;$$&quot;, &quot;display&quot;: 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. Only applies to columns whose datatype is &quot;markdown&quot;.🔗 ```\nlabel: str | I18nData | None\n``` 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.🔗 ```\nshow_label: bool | None\n``` default = None if True, will display label.🔗 ```\nevery: Timer | float | None\n``` default = None Continuously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.🔗 ```\ninputs: Component | list[Component] | set[Component] | None\n``` 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.🔗 ```\nmax_height: int | str\n``` default = 500 The maximum height of the dataframe, specified in pixels if a number is passed, or in CSS units if a string is passed. If more rows are created than can fit in the height, a scrollbar will appear.🔗 ```\nscale: int | None\n``` 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.🔗 ```\nmin_width: int\n``` 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.🔗 ```\ninteractive: bool | None\n``` default = None if True, will allow users to edit the dataframe; if False, can only be used to display data. If not provided, this is inferred based on whether the component is used as an input or output.🔗 ```\nvisible: bool | Literal['hidden']\n``` default = True If False, component will be hidden. If &quot;hidden&quot;, component will be visually hidden and not take up space in the layout but still exist in the DOM🔗 ```\nelem_id: str | None\n``` 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.🔗 ```\nelem_classes: list[str] | str | None\n``` 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.🔗 ```\nrender: bool\n``` 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.🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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 &#039;preserved_by_key&#039; are not reset across a re-render.🔗 ```\npreserved_by_key: list[str] | str | None\n``` default = \"value\" A list of parameters from this component&#039;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.🔗 ```\nwrap: bool\n``` default = False If True, the text in table cells will wrap when appropriate. If False and the `column_width` parameter is not set, the column widths will expand based on the cell contents and the table may need to be horizontally scrolled. If `column_width` is set, then any overflow text will be hidden.🔗 ```\nline_breaks: bool\n``` default = True If True (default), will enable Github-flavored Markdown line breaks in chatbot messages. If False, single new lines will be ignored. Only applies for columns of type &quot;markdown.&quot;🔗 ```\ncolumn_widths: list[str | int] | None\n``` default = None An optional list representing the width of each column. The elements of the list should be in the format &quot;100px&quot; (ints are also accepted and converted to pixel values) or &quot;10%&quot;. The percentage width is calculated based on the viewport width of the table. If not provided, the column widths will be automatically determined based on the content of the cells.🔗 ```\nbuttons: list[Literal['fullscreen', 'copy']] | None\n``` default = None A list of buttons to show in the top right corner of the component. Valid options are &quot;fullscreen&quot; and &quot;copy&quot;. The &quot;fullscreen&quot; button allows the user to view the table in fullscreen mode. The &quot;copy&quot; button allows the user to copy the table data to the clipboard. By default, all buttons are shown.🔗 ```\nshow_row_numbers: bool\n``` default = False If True, will display row numbers in a separate column.🔗 ```\nmax_chars: int | None\n``` default = None Maximum number of characters to display in each cell before truncating (single-clicking a cell value will still reveal the full content). If None, no truncation is applied.🔗 ```\nshow_search: Literal['none', 'search', 'filter']\n``` default = \"none\" Show a search input in the toolbar. If &quot;search&quot;, a search input is shown. If &quot;filter&quot;, a search input and filter buttons are shown. If &quot;none&quot;, no search input is shown.🔗 ```\npinned_columns: int | None\n``` default = None If provided, will pin the specified number of columns from the left.🔗 ```\nstatic_columns: list[int] | None\n``` default = None List of column indices (int) that should not be editable. Only applies when interactive=True. When specified, col_count is automatically set to &quot;fixed&quot; and columns cannot be inserted or deleted. Shortcuts Shortcuts ```\ngradio.Dataframe\n``` Interface String Shortcut \"dataframe\" Initialization Uses default values```\ngradio.Numpy\n``` Interface String Shortcut \"numpy\" Initialization Uses type=\"numpy\"```\ngradio.Matrix\n``` Interface String Shortcut \"matrix\" Initialization Uses type=\"array\"```\ngradio.List\n``` Interface String Shortcut \"list\" Initialization Uses type=\"array\", col_count=1 Demos filter_recordsmatrix_transposetax_calculatorsort_records  Event Listeners Description Event listeners allow you to respond to user interactions with the UI\n\t\tcomponents you've defined in a Gradio Blocks app. When a user interacts with\n\t\tan element, such as changing a slider value or uploading an image, a\n\t\tfunction is called. Supported Event Listeners The Dataframe component supports the following event listeners. Each event listener takes the\n\t\tsame parameters, which are listed in the Event Parameters table below. Listeners ```\nDataframe.change(fn, ···)\n``` Triggered when the value of the Dataframe 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.```\nDataframe.input(fn, ···)\n``` This listener is triggered when the user changes the value of the Dataframe.```\nDataframe.select(fn, ···)\n``` Event listener for when the user selects or deselects the Dataframe. Uses event data gradio.SelectData to carry value referring to the label of the Dataframe, and selected to refer to state of the Dataframe. See https://www.gradio.app/main/docs/gradio/eventdata for more details.```\nDataframe.edit(fn, ···)\n``` This listener is triggered when the user edits the Dataframe (e.g. image) using the built-in editor. Event Parameters Parameters ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.  Styling The Gradio DataframeFilters Tables And Stats","type":"DOCS"},{"title":"Dataset","slug":"/main/docs/gradio/dataset","content":"Dataset ```\ngradio.Dataset(···)\n``` Description Creates a gallery or table to display data samples. This component is primarily designed for internal use to display examples. However, it can also be used directly to display a dataset and let users select examples. Behavior Using Dataset as an input component. How Dataset will pass its value to your function: Type: int | list | tuple[int, list] | None Passes the selected sample either as a list of data corresponding to each input component (if type is \"value\") or as an int index (if type is \"index\"), or as a tuple of the index and the data (if type is \"tuple\"). Example Code \n    \n    import gradio as gr\n\n    def predict(\n        value: int | list | tuple[int, list] | None\n    ):\n        # process value from the Dataset component\n        return \"prediction\"\n\n    interface = gr.Interface(predict, gr.Dataset(), gr.Textbox())\n    interface.launch()\n\n  Using Dataset as an output component How Dataset expects you to return a value: Type: int | list | None Expects an int index or list of sample data. Returns the index of the sample in the dataset or None if the sample is not found. Example Code \n    \n    import gradio as gr\n\n    def predict(text) -> int | list | None\n        # process value to return to the Dataset component\n        return value\n\n    interface = gr.Interface(predict, gr.Textbox(), gr.Dataset())\n    interface.launch()\n\n Initialization Parameters ▼ 🔗 ```\nlabel: str | I18nData | None\n``` default = None the label for this component, appears above the component.🔗 ```\nshow_label: bool\n``` default = True If True, the label will be shown above the component.🔗 ```\ncomponents: list[Component] | list[str] | None\n``` default = None Which component types to show in this dataset widget, can be passed in as a list of string names or Components instances. The following components are supported in a Dataset: Audio, Checkbox, CheckboxGroup, ColorPicker, Dataframe, Dropdown, File, HTML, Image, Markdown, Model3D, Number, Radio, Slider, Textbox, TimeSeries, Video🔗 ```\ncomponent_props: list[dict[str, Any]] | None\n``` default = None 🔗 ```\nsamples: list[list[Any]] | None\n``` default = None a nested list of samples. Each sublist within the outer list represents a data sample, and each element within the sublist represents an value for each component🔗 ```\nheaders: list[str] | None\n``` default = None Column headers in the Dataset widget, should be the same len as components. If not provided, inferred from component labels🔗 ```\ntype: Literal['values', 'index', 'tuple']\n``` default = \"values\" &quot;values&quot; if clicking on a sample should pass the value of the sample, &quot;index&quot; if it should pass the index of the sample, or &quot;tuple&quot; if it should pass both the index and the value of the sample.🔗 ```\nlayout: Literal['gallery', 'table'] | None\n``` default = None &quot;gallery&quot; if the dataset should be displayed as a gallery with each sample in a clickable card, or &quot;table&quot; if it should be displayed as a table with each sample in a row. By default, &quot;gallery&quot; is used if there is a single component, and &quot;table&quot; is used if there are more than one component. If there are more than one component, the layout can only be &quot;table&quot;.🔗 ```\nsamples_per_page: int\n``` default = 10 how many examples to show per page.🔗 ```\nvisible: bool | Literal['hidden']\n``` default = True If False, component will be hidden. If &quot;hidden&quot;, component will be visually hidden and not take up space in the layout but still exist in the DOM🔗 ```\nelem_id: str | None\n``` 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.🔗 ```\nelem_classes: list[str] | str | None\n``` 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.🔗 ```\nrender: bool\n``` 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.🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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 &#039;preserved_by_key&#039; are not reset across a re-render.🔗 ```\npreserved_by_key: list[str] | str | None\n``` default = \"value\" A list of parameters from this component&#039;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.🔗 ```\ncontainer: bool\n``` default = True If True, will place the component in a container - providing some extra padding around the border.🔗 ```\nscale: int | None\n``` 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.🔗 ```\nmin_width: int\n``` 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.🔗 ```\nproxy_url: str | None\n``` default = None The URL of the external Space used to load this component. Set automatically when using `gr.load()`. This should not be set manually.🔗 ```\nsample_labels: list[str] | None\n``` default = None A list of labels for each sample. If provided, the length of this list should be the same as the number of samples, and these labels will be used in the UI instead of rendering the sample values. Shortcuts Shortcuts ```\ngradio.Dataset\n``` Interface String Shortcut \"dataset\" Initialization Uses default values  Examples Updating a Dataset In this example, we display a text dataset using gr.Dataset and then update it when the user clicks a button: ```\nimport gradio as gr\n\nphilosophy_quotes = [\n    [\"I think therefore I am.\"],\n    [\"The unexamined life is not worth living.\"]\n]\n\nstartup_quotes = [\n    [\"Ideas are easy. Implementation is hard\"],\n    [\"Make mistakes faster.\"]\n]\n\ndef show_startup_quotes():\n    return gr.Dataset(samples=startup_quotes)\n\nwith gr.Blocks() as demo:\n    textbox = gr.Textbox()\n    dataset = gr.Dataset(components=[textbox], samples=philosophy_quotes)\n    button = gr.Button()\n\n    button.click(show_startup_quotes, None, dataset)\n\ndemo.launch()\n``` Event Listeners Description Event listeners allow you to respond to user interactions with the UI\n\t\tcomponents you've defined in a Gradio Blocks app. When a user interacts with\n\t\tan element, such as changing a slider value or uploading an image, a\n\t\tfunction is called. Supported Event Listeners The Dataset component supports the following event listeners. Each event listener takes the\n\t\tsame parameters, which are listed in the Event Parameters table below. Listeners ```\nDataset.change(fn, ···)\n``` Triggered when the value of the Dataset 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.```\nDataset.click(fn, ···)\n``` Triggered when the Dataset is clicked.```\nDataset.select(fn, ···)\n``` Event listener for when the user selects or deselects the Dataset. Uses event data gradio.SelectData to carry value referring to the label of the Dataset, and selected to refer to state of the Dataset. See https://www.gradio.app/main/docs/gradio/eventdata for more details. Event Parameters Parameters ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.  ","type":"DOCS"},{"title":"DateTime","slug":"/main/docs/gradio/datetime","content":"DateTime ```\ngradio.DateTime(···)\n``` Description Component to select a date and (optionally) a time.  Behavior Using DateTime as an input component. How DateTime will pass its value to your function: Type: str | float | datetime | None Passes text value as a str into the function. Example Code \n    \n    import gradio as gr\n\n    def predict(\n        value: str | float | datetime | None\n    ):\n        # process value from the DateTime component\n        return \"prediction\"\n\n    interface = gr.Interface(predict, gr.DateTime(), gr.Textbox())\n    interface.launch()\n\n  Using DateTime as an output component How DateTime expects you to return a value: Type: float | datetime | str | None Expects a tuple pair of datetimes. Example Code \n    \n    import gradio as gr\n\n    def predict(text) -> float | datetime | str | None\n        # process value to return to the DateTime component\n        return value\n\n    interface = gr.Interface(predict, gr.Textbox(), gr.DateTime())\n    interface.launch()\n\n Initialization Parameters ▼ 🔗 ```\nvalue: float | str | datetime | None\n``` default = None default value for datetime.🔗 ```\ninclude_time: bool\n``` default = True If True, the component will include time selection. If False, only date selection will be available.🔗 ```\ntype: Literal['timestamp', 'datetime', 'string']\n``` default = \"timestamp\" The type of the value. Can be &quot;timestamp&quot;, &quot;datetime&quot;, or &quot;string&quot;. If &quot;timestamp&quot;, the value will be a number representing the start and end date in seconds since epoch. If &quot;datetime&quot;, the value will be a datetime object. If &quot;string&quot;, the value will be the date entered by the user.🔗 ```\ntimezone: str | None\n``` default = None The timezone to use for timestamps, such as &quot;US/Pacific&quot; or &quot;Europe/Paris&quot;. If None, the timezone will be the local timezone.🔗 ```\nlabel: str | I18nData | None\n``` 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.🔗 ```\nshow_label: bool | None\n``` default = None if True, will display label.🔗 ```\ninfo: str | I18nData | None\n``` default = None additional component description, appears below the label in smaller font. Supports markdown / HTML syntax.🔗 ```\nevery: float | None\n``` default = None If `value` is a callable, run the function &#039;every&#039; number of seconds while the client connection is open. Has no effect otherwise. The event can be accessed (e.g. to cancel it) via this component&#039;s .load_event attribute.🔗 ```\nscale: int | None\n``` 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.🔗 ```\nmin_width: int\n``` 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.🔗 ```\nvisible: bool | Literal['hidden']\n``` default = True If False, component will be hidden. If &quot;hidden&quot;, component will be visually hidden and not take up space in the layout but still exist in the DOM🔗 ```\ninteractive: bool | None\n``` default = None 🔗 ```\nelem_id: str | None\n``` default = None 🔗 ```\nelem_classes: list[str] | str | None\n``` 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.🔗 ```\nrender: bool\n``` 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.🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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 &#039;preserved_by_key&#039; are not reset across a re-render.🔗 ```\npreserved_by_key: list[str] | str | None\n``` default = \"value\" A list of parameters from this component&#039;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.🔗 ```\nbuttons: list[Button] | None\n``` default = None A list of gr.Button() instances to show in the top right corner of the component. Custom buttons will appear in the toolbar with their configured icon and/or label, and clicking them will trigger any .click() events registered on the button. Shortcuts Shortcuts ```\ngradio.DateTime\n``` Interface String Shortcut \"datetime\" Initialization Uses default values  Event Listeners Description Event listeners allow you to respond to user interactions with the UI\n\t\tcomponents you've defined in a Gradio Blocks app. When a user interacts with\n\t\tan element, such as changing a slider value or uploading an image, a\n\t\tfunction is called. Supported Event Listeners The DateTime component supports the following event listeners. Each event listener takes the\n\t\tsame parameters, which are listed in the Event Parameters table below. Listeners ```\nDateTime.change(fn, ···)\n``` Triggered when the value of the DateTime changes either because of user input (e.g. a user types in a textbox) OR because of a function update (e.g. an image receives a value from the output of an event trigger). See .input() for a listener that is only triggered by user input.```\nDateTime.submit(fn, ···)\n``` This listener is triggered when the user presses the Enter key while the DateTime is focused. Event Parameters Parameters ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.  Time Plots","type":"DOCS"},{"title":"Dialogue","slug":"/main/docs/gradio/dialogue","content":"Dialogue ```\ngradio.Dialogue(···)\n``` Description Creates a Dialogue component for displaying or collecting multi-speaker conversations. This component can be used as input to allow users to enter dialogue involving multiple speakers, or as output to display diarized speech, such as the result of a transcription or speaker identification model. Each message can be associated with a specific speaker, making it suitable for use cases like conversations, interviews, or meetings.  Behavior Using Dialogue as an input component. How Dialogue will pass its value to your function: Type: str | list[dict[str, str]] Returns the dialogue as a string or list of dictionaries. Example Code \n    \n    import gradio as gr\n\n    def predict(\n        value: str | list[dict[str, str]]\n    ):\n        # process value from the Dialogue component\n        return \"prediction\"\n\n    interface = gr.Interface(predict, gr.Dialogue(), gr.Textbox())\n    interface.launch()\n\n  Using Dialogue as an output component How Dialogue expects you to return a value: Type: list[dict[str, str]] | str | None Expects a string or a list of dictionaries of dialogue lines, where each dictionary contains 'speaker' and 'text' keys, or a string. Example Code \n    \n    import gradio as gr\n\n    def predict(text) -> list[dict[str, str]] | str | None\n        # process value to return to the Dialogue component\n        return value\n\n    interface = gr.Interface(predict, gr.Textbox(), gr.Dialogue())\n    interface.launch()\n\n Initialization Parameters ▼ 🔗 ```\nvalue: list[dict[str, str]] | Callable | None\n``` default = None Value of the dialogue. It is a list of dictionaries, each containing a &#039;speaker&#039; key and a &#039;text&#039; key. If a function is provided, the function will be called each time the app loads to set the initial value of this component.🔗 ```\ntype: Literal['list', 'text']\n``` default = \"text\" The type of the component, either &quot;list&quot; for a multi-speaker dialogue consisting of dictionaries with &#039;speaker&#039; and &#039;text&#039; keys or &quot;text&quot; for a single text input. Defaults to &quot;text&quot;.🔗 ```\nspeakers: list[str] | None\n``` default = None The different speakers allowed in the dialogue. If `None` or an empty list, no speakers will be displayed. Instead, the component will be a standard textarea that optionally supports `tags` autocompletion.🔗 ```\nformatter: Callable | None\n``` default = None A function that formats the dialogue line dictionary, e.g. {&quot;speaker&quot;: &quot;Speaker 1&quot;, &quot;text&quot;: &quot;Hello, how are you?&quot;} into a string, e.g. &quot;Speaker 1: Hello, how are you?&quot;. This function is run on user input and the resulting string is passed into the prediction function.🔗 ```\nunformatter: Callable | None\n``` default = None A function that parses a formatted dialogue string back into a dialogue line dictionary. Should take a single string line and return a dictionary with &#039;speaker&#039; and &#039;text&#039; keys. If not provided, the default unformatter will attempt to parse the default formatter pattern.🔗 ```\ntags: list[str] | None\n``` default = None The different tags allowed in the dialogue. Tags are displayed in an autocomplete menu below the input textbox when the user starts typing `:`. Use the exact tag name expected by the AI model or inference function.🔗 ```\nseparator: str\n``` default = \"\n\" The separator between the different dialogue lines used to join the formatted dialogue lines into a single string. It should be unambiguous. For example, a newline character or tab character.🔗 ```\ncolor_map: dict[str, str] | None\n``` default = None A dictionary mapping speaker names to colors. The colors may be specified as hex codes or by their names. For example: {&quot;Speaker 1&quot;: &quot;red&quot;, &quot;Speaker 2&quot;: &quot;#FFEE22&quot;}. If not provided, default colors will be assigned to speakers. This is only used if `interactive` is False.🔗 ```\nlabel: str | None\n``` default = \"Dialogue\" 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.🔗 ```\ninfo: str | None\n``` default = \"Type colon (:) in the dialogue line to see the available tags\" 🔗 ```\nplaceholder: str | None\n``` default = None placeholder hint to provide behind textarea.🔗 ```\nshow_label: bool | None\n``` default = None if True, will display the label. If False, the copy button is hidden as well as well as the label.🔗 ```\ncontainer: bool\n``` default = True if True, will place the component in a container - providing some extra padding around the border.🔗 ```\nscale: int | None\n``` 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.🔗 ```\nmin_width: int\n``` 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.🔗 ```\ninteractive: bool | None\n``` default = None if True, will be rendered as an editable textbox; if False, editing will be disabled. If not provided, this is inferred based on whether the component is used as an input or output.🔗 ```\nvisible: bool | Literal['hidden']\n``` default = True If False, component will be hidden. If &quot;hidden&quot;, component will be visually hidden and not take up space in the layout but still exist in the DOM🔗 ```\nelem_id: str | None\n``` 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.🔗 ```\nautofocus: bool\n``` default = False If True, will focus on the textbox when the page loads. Use this carefully, as it can cause usability issues for sighted and non-sighted users.🔗 ```\nautoscroll: bool\n``` default = True If True, will automatically scroll to the bottom of the textbox when the value changes, unless the user scrolls up. If False, will not scroll to the bottom of the textbox when the value changes.🔗 ```\nelem_classes: list[str] | str | None\n``` 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.🔗 ```\nrender: bool\n``` 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.🔗 ```\nkey: int | str | None\n``` default = None if assigned, will be used to assume identity across a re-render. Components that have the same key across a re-render will have their value preserved.🔗 ```\nmax_lines: int | None\n``` default = None maximum number of lines allowed in the dialogue.🔗 ```\nbuttons: list[Literal['copy'] | Button] | None\n``` default = None A list of buttons to show for the component. Valid options are &quot;copy&quot; or a gr.Button() instance. The &quot;copy&quot; button allows the user to copy the text in the textbox. Custom gr.Button() instances will appear in the toolbar with their configured icon and/or label, and clicking them will trigger any .click() events registered on the button. By default, no buttons are shown.🔗 ```\nsubmit_btn: str | bool | None\n``` default = False If False, will not show a submit button. If True, will show a submit button with an icon. If a string, will use that string as the submit button text.🔗 ```\nui_mode: Literal['dialogue', 'text', 'both']\n``` default = \"both\" Determines the user interface mode of the component. Can be &quot;dialogue&quot; (displays dialogue lines), &quot;text&quot; (displays a single text input), or &quot;both&quot; (displays both dialogue lines and a text input). Defaults to &quot;both&quot;. Shortcuts Shortcuts ```\ngradio.Dialogue\n``` Interface String Shortcut \"dialogue\" Initialization Uses default values Demos dia_dialogue_demo  Event Listeners Description Event listeners allow you to respond to user interactions with the UI\n\t\tcomponents you've defined in a Gradio Blocks app. When a user interacts with\n\t\tan element, such as changing a slider value or uploading an image, a\n\t\tfunction is called. Supported Event Listeners The Dialogue component supports the following event listeners. Each event listener takes the\n\t\tsame parameters, which are listed in the Event Parameters table below. Listeners ```\nDialogue.change(fn, ···)\n``` Triggered when the value of the Dialogue 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.```\nDialogue.input(fn, ···)\n``` This listener is triggered when the user changes the value of the Dialogue.```\nDialogue.submit(fn, ···)\n``` This listener is triggered when the user presses the Enter key while the Dialogue is focused. Event Parameters Parameters ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.  ","type":"DOCS"},{"title":"DownloadButton","slug":"/main/docs/gradio/downloadbutton","content":"DownloadButton ```\ngradio.DownloadButton(···)\n``` Description Creates a button, that when clicked, allows a user to download a single file of arbitrary type.  Behavior Using DownloadButton as an input component. How DownloadButton will pass its value to your function: Type: str | None (Rarely used) passes the file as a str into the function. Example Code \n    \n    import gradio as gr\n\n    def predict(\n        value: str | None\n    ):\n        # process value from the DownloadButton component\n        return \"prediction\"\n\n    interface = gr.Interface(predict, gr.DownloadButton(), gr.Textbox())\n    interface.launch()\n\n  Using DownloadButton as an output component How DownloadButton expects you to return a value: Type: str | Path | None Expects a str or pathlib.Path filepath Example Code \n    \n    import gradio as gr\n\n    def predict(text) -> str | Path | None\n        # process value to return to the DownloadButton component\n        return value\n\n    interface = gr.Interface(predict, gr.Textbox(), gr.DownloadButton())\n    interface.launch()\n\n Initialization Parameters ▼ 🔗 ```\nlabel: str\n``` default = \"Download\" Text to display on the button. Defaults to &quot;Download&quot;.🔗 ```\nvalue: str | Path | Callable | None\n``` default = None A str or pathlib.Path filepath or URL to download, or a Callable that returns a str or pathlib.Path filepath or URL to download.🔗 ```\nevery: Timer | float | None\n``` default = None Continuously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.🔗 ```\ninputs: Component | list[Component] | set[Component] | None\n``` 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.🔗 ```\nvariant: Literal['primary', 'secondary', 'stop']\n``` default = \"secondary\" &#039;primary&#039; for main call-to-action, &#039;secondary&#039; for a more subdued style, &#039;stop&#039; for a stop button.🔗 ```\nvisible: bool | Literal['hidden']\n``` default = True If False, component will be hidden. If &quot;hidden&quot;, component will be visually hidden and not take up space in the layout but still exist in the DOM🔗 ```\nsize: Literal['sm', 'md', 'lg']\n``` default = \"lg\" size of the button. Can be &quot;sm&quot;, &quot;md&quot;, or &quot;lg&quot;.🔗 ```\nicon: str | None\n``` default = None URL or path to the icon file to display within the button. If None, no icon will be displayed.🔗 ```\nscale: int | None\n``` 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.🔗 ```\nmin_width: int | None\n``` default = None minimum pixel width, will wrap if not sufficient screen space to satisfy this value. If a certain scale value results in this Component being narrower than min_width, the min_width parameter will be respected first.🔗 ```\ninteractive: bool\n``` default = True If False, the UploadButton will be in a disabled state.🔗 ```\nelem_id: str | None\n``` 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.🔗 ```\nelem_classes: list[str] | str | None\n``` 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.🔗 ```\nrender: bool\n``` 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.🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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 &#039;preserved_by_key&#039; are not reset across a re-render.🔗 ```\npreserved_by_key: list[str] | str | None\n``` default = \"value\" A list of parameters from this component&#039;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. Shortcuts Shortcuts ```\ngradio.DownloadButton\n``` Interface String Shortcut \"downloadbutton\" Initialization Uses default values Demos upload_and_download  Event Listeners Description Event listeners allow you to respond to user interactions with the UI\n\t\tcomponents you've defined in a Gradio Blocks app. When a user interacts with\n\t\tan element, such as changing a slider value or uploading an image, a\n\t\tfunction is called. Supported Event Listeners The DownloadButton component supports the following event listeners. Each event listener takes the\n\t\tsame parameters, which are listed in the Event Parameters table below. Listeners ```\nDownloadButton.change(fn, ···)\n``` Triggered when the value of the DownloadButton 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.```\nDownloadButton.click(fn, ···)\n``` Triggered when the DownloadButton is clicked. Event Parameters Parameters ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.  ","type":"DOCS"},{"title":"Dropdown","slug":"/main/docs/gradio/dropdown","content":"Dropdown ```\ngradio.Dropdown(···)\n``` Description Creates a dropdown of choices from which a single entry or multiple entries can be selected (as an input component) or displayed (as an output component).  Behavior Using Dropdown as an input component. How Dropdown will pass its value to your function: Type: str | int | float | list[str | int | float] | list[int | None] | None Passes the value of the selected dropdown choice as a str | int | float or its index as an int into the function, depending on type. Or, if multiselect is True, passes the values of the selected dropdown choices as a list of corresponding values/indices instead. Example Code \n    \n    import gradio as gr\n\n    def predict(\n        value: str | int | float | list[str | int | float] | list[int | None] | None\n    ):\n        # process value from the Dropdown component\n        return \"prediction\"\n\n    interface = gr.Interface(predict, gr.Dropdown(), gr.Textbox())\n    interface.launch()\n\n  Using Dropdown as an output component How Dropdown expects you to return a value: Type: str | int | float | list[str | int | float] | None Expects a str | int | float corresponding to the value of the dropdown entry to be selected. Or, if multiselect is True, expects a list of values corresponding to the selected dropdown entries. Example Code \n    \n    import gradio as gr\n\n    def predict(text) -> str | int | float | list[str | int | float] | None\n        # process value to return to the Dropdown component\n        return value\n\n    interface = gr.Interface(predict, gr.Textbox(), gr.Dropdown())\n    interface.launch()\n\n Initialization Parameters ▼ 🔗 ```\nchoices: list[str | int | float | tuple[str | I18nData, str | int | float]] | None\n``` default = None a list of string or numeric options to choose from. An option can also be a tuple of the form (name, value), where name is the displayed name of the dropdown choice and value is the value to be passed to the function, or returned by the function.🔗 ```\nvalue: str | int | float | list[str | int | float] | Callable | DefaultValue | None\n``` default = DefaultValue() the value selected in dropdown. If `multiselect` is true, this should be list, otherwise a single string or number from among `choices`. By default, the first choice in `choices` is initially selected. If set explicitly to None, no value is initially selected. If a function is provided, the function will be called each time the app loads to set the initial value of this component.🔗 ```\ntype: Literal['value', 'index']\n``` default = \"value\" type of value to be returned by component. &quot;value&quot; returns the string of the choice selected, &quot;index&quot; returns the index of the choice selected.🔗 ```\nmultiselect: bool | None\n``` default = None if True, multiple choices can be selected.🔗 ```\nallow_custom_value: bool\n``` default = False if True, allows user to enter a custom value that is not in the list of choices.🔗 ```\nmax_choices: int | None\n``` default = None maximum number of choices that can be selected. If None, no limit is enforced.🔗 ```\nnum_choices_shown: int | None\n``` default = 100 number of matching choices to show initially. More choices are loaded automatically as the user scrolls. If None, all matching choices are shown immediately.🔗 ```\nfilterable: bool\n``` default = True if True, user will be able to type into the dropdown and filter the choices by typing. Can only be set to False if `allow_custom_value` is False.🔗 ```\nlabel: str | I18nData | None\n``` 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.🔗 ```\ninfo: str | I18nData | None\n``` default = None additional component description, appears below the label in smaller font. Supports markdown / HTML syntax.🔗 ```\nevery: Timer | float | None\n``` default = None continuously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.🔗 ```\ninputs: Component | list[Component] | set[Component] | None\n``` 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.🔗 ```\nshow_label: bool | None\n``` default = None if True, will display label.🔗 ```\ncontainer: bool\n``` default = True if True, will place the component in a container - providing some extra padding around the border.🔗 ```\nscale: int | None\n``` 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.🔗 ```\nmin_width: int\n``` 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.🔗 ```\ninteractive: bool | None\n``` default = None if True, choices in this dropdown will be selectable; if False, selection will be disabled. If not provided, this is inferred based on whether the component is used as an input or output.🔗 ```\nvisible: bool | Literal['hidden']\n``` default = True If False, component will be hidden. If &quot;hidden&quot;, component will be visually hidden and not take up space in the layout but still exist in the DOM🔗 ```\nelem_id: str | None\n``` 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.🔗 ```\nelem_classes: list[str] | str | None\n``` 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.🔗 ```\nrender: bool\n``` default = True if False, component will not be rendered in the Blocks context. Should be used if the intention is to assign event listeners now but render the component later.🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` default = None 🔗 ```\npreserved_by_key: list[str] | str | None\n``` default = \"value\" 🔗 ```\nbuttons: list[Button] | None\n``` default = None A list of gr.Button() instances to show in the top right corner of the component. Custom buttons will appear in the toolbar with their configured icon and/or label, and clicking them will trigger any .click() events registered on the button. Shortcuts Shortcuts ```\ngradio.Dropdown\n``` Interface String Shortcut \"dropdown\" Initialization Uses default values Demos sentence_builder  Event Listeners Description Event listeners allow you to respond to user interactions with the UI\n\t\tcomponents you've defined in a Gradio Blocks app. When a user interacts with\n\t\tan element, such as changing a slider value or uploading an image, a\n\t\tfunction is called. Supported Event Listeners The Dropdown component supports the following event listeners. Each event listener takes the\n\t\tsame parameters, which are listed in the Event Parameters table below. Listeners ```\nDropdown.change(fn, ···)\n``` Triggered when the value of the Dropdown 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.```\nDropdown.input(fn, ···)\n``` This listener is triggered when the user changes the value of the Dropdown.```\nDropdown.select(fn, ···)\n``` Event listener for when the user selects or deselects the Dropdown. Uses event data gradio.SelectData to carry value referring to the label of the Dropdown, and selected to refer to state of the Dropdown. See https://www.gradio.app/main/docs/gradio/eventdata for more details.```\nDropdown.focus(fn, ···)\n``` This listener is triggered when the Dropdown is focused.```\nDropdown.blur(fn, ···)\n``` This listener is triggered when the Dropdown is unfocused/blurred.```\nDropdown.key_up(fn, ···)\n``` This listener is triggered when the user presses a key while the Dropdown is focused. Event Parameters Parameters ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.  ","type":"DOCS"},{"title":"DuplicateButton","slug":"/main/docs/gradio/duplicatebutton","content":"DuplicateButton ```\ngradio.DuplicateButton(···)\n``` Description Button that triggers a Spaces Duplication, when the demo is on Hugging Face Spaces. Does nothing locally. Behavior Using DuplicateButton as an input component. How DuplicateButton will pass its value to your function: Type: str | None (Rarely used) the str corresponding to the button label when the button is clicked Example Code \n    \n    import gradio as gr\n\n    def predict(\n        value: str | None\n    ):\n        # process value from the DuplicateButton component\n        return \"prediction\"\n\n    interface = gr.Interface(predict, gr.DuplicateButton(), gr.Textbox())\n    interface.launch()\n\n  Using DuplicateButton as an output component How DuplicateButton expects you to return a value: Type: str | None string corresponding to the button label Example Code \n    \n    import gradio as gr\n\n    def predict(text) -> str | None\n        # process value to return to the DuplicateButton component\n        return value\n\n    interface = gr.Interface(predict, gr.Textbox(), gr.DuplicateButton())\n    interface.launch()\n\n Initialization Parameters ▼ 🔗 ```\nvalue: str\n``` default = \"Duplicate Space\" default text for the button to display. If a function is provided, the function will be called each time the app loads to set the initial value of this component.🔗 ```\nevery: Timer | float | None\n``` default = None continuously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.🔗 ```\ninputs: Component | list[Component] | set[Component] | None\n``` 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.🔗 ```\nvariant: Literal['primary', 'secondary', 'stop', 'huggingface']\n``` default = \"huggingface\" sets the background and text color of the button. Use &#039;primary&#039; for main call-to-action buttons, &#039;secondary&#039; for a more subdued style, &#039;stop&#039; for a stop button, &#039;huggingface&#039; for a black background with white text, consistent with Hugging Face&#039;s button styles.🔗 ```\nsize: Literal['sm', 'md', 'lg']\n``` default = \"sm\" size of the button. Can be &quot;sm&quot;, &quot;md&quot;, or &quot;lg&quot;.🔗 ```\nicon: str | Path | None\n``` default = None URL or path to the icon file to display within the button. If None, no icon will be displayed.🔗 ```\nlink: str | None\n``` default = None URL to open when the button is clicked. If None, no link will be used.🔗 ```\nlink_target: Literal['_self', '_blank', '_parent', '_top']\n``` default = \"_self\" 🔗 ```\nvisible: bool | Literal['hidden']\n``` default = True If False, component will be hidden. If &quot;hidden&quot;, component will be visually hidden and not take up space in the layout but still exist in the DOM🔗 ```\ninteractive: bool\n``` default = True if False, the Button will be in a disabled state.🔗 ```\nelem_id: str | None\n``` 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.🔗 ```\nelem_classes: list[str] | str | None\n``` 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.🔗 ```\nrender: bool\n``` 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.🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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 &#039;preserved_by_key&#039; are not reset across a re-render.🔗 ```\npreserved_by_key: list[str] | str | None\n``` default = \"value\" A list of parameters from this component&#039;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.🔗 ```\nscale: int | None\n``` default = 0 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.🔗 ```\nmin_width: int | None\n``` default = None minimum pixel width, will wrap if not sufficient screen space to satisfy this value. If a certain scale value results in this Component being narrower than min_width, the min_width parameter will be respected first. Shortcuts Shortcuts ```\ngradio.DuplicateButton\n``` Interface String Shortcut \"duplicatebutton\" Initialization Uses default values  Event Listeners Description Event listeners allow you to respond to user interactions with the UI\n\t\tcomponents you've defined in a Gradio Blocks app. When a user interacts with\n\t\tan element, such as changing a slider value or uploading an image, a\n\t\tfunction is called. Supported Event Listeners The DuplicateButton component supports the following event listeners. Each event listener takes the\n\t\tsame parameters, which are listed in the Event Parameters table below. Listeners ```\nDuplicateButton.change(fn, ···)\n``` Triggered when the value of the Button 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.```\nDuplicateButton.click(fn, ···)\n``` Triggered when the Button is clicked. Event Parameters Parameters ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.  ","type":"DOCS"},{"title":"File","slug":"/main/docs/gradio/file","content":"File ```\ngradio.File(···)\n``` Description Creates a file component that allows uploading one or more generic files (when used as an input) or displaying generic files or URLs for download (as output).      Demo: zip_files, zip_to_json Behavior Using File as an input component. How File will pass its value to your function: Type: bytes | str | list[bytes] | list[str] | None Passes the file as a str or bytes object, or a list of str or list of bytes objects, depending on type and file_count. Example Code \n    \n    import gradio as gr\n\n    def predict(\n        value: bytes | str | list[bytes] | list[str] | None\n    ):\n        # process value from the File component\n        return \"prediction\"\n\n    interface = gr.Interface(predict, gr.File(), gr.Textbox())\n    interface.launch()\n\n  Using File as an output component How File expects you to return a value: Type: str | list[str] | None Expects a str filepath or URL, or a list[str] of filepaths/URLs. Example Code \n    \n    import gradio as gr\n\n    def predict(text) -> str | list[str] | None\n        # process value to return to the File component\n        return value\n\n    interface = gr.Interface(predict, gr.Textbox(), gr.File())\n    interface.launch()\n\n Initialization Parameters ▼ 🔗 ```\nvalue: str | list[str] | Callable | None\n``` default = None Default file(s) to display, given as a str file path or URL, or a list of str file paths / URLs. If a function is provided, the function will be called each time the app loads to set the initial value of this component.🔗 ```\nfile_count: Literal['single', 'multiple', 'directory']\n``` default = \"single\" if single, allows user to upload one file. If &quot;multiple&quot;, user uploads multiple files. If &quot;directory&quot;, user uploads all files in selected directory. Return type will be list for each file in case of &quot;multiple&quot; or &quot;directory&quot;.🔗 ```\nfile_types: list[str] | None\n``` default = None List of file extensions or types of files to be uploaded (e.g. [&#039;image&#039;, &#039;.json&#039;, &#039;.mp4&#039;]). &quot;file&quot; allows any file to be uploaded, &quot;image&quot; allows only image files to be uploaded, &quot;audio&quot; allows only audio files to be uploaded, &quot;video&quot; allows only video files to be uploaded, &quot;text&quot; allows only text files to be uploaded.🔗 ```\ntype: Literal['filepath', 'binary']\n``` default = \"filepath\" Type of value to be returned by component. &quot;file&quot; returns a temporary file object with the same base name as the uploaded file, whose full path can be retrieved by file_obj.name, &quot;binary&quot; returns an bytes object.🔗 ```\nlabel: str | I18nData | None\n``` 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.🔗 ```\nevery: Timer | float | None\n``` default = None Continuously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.🔗 ```\ninputs: Component | list[Component] | set[Component] | None\n``` 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.🔗 ```\nshow_label: bool | None\n``` default = None if True, will display label.🔗 ```\ncontainer: bool\n``` default = True If True, will place the component in a container - providing some extra padding around the border.🔗 ```\nscale: int | None\n``` 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.🔗 ```\nmin_width: int\n``` 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.🔗 ```\nheight: int | str | float | None\n``` default = None The default height of the file component when no files have been uploaded, or the maximum height of the file component when files are present. Specified in pixels if a number is passed, or in CSS units if a string is passed. If more files are uploaded than can fit in the height, a scrollbar will appear.🔗 ```\ninteractive: bool | None\n``` default = None if True, will allow users to upload a file; if False, can only be used to display files. If not provided, this is inferred based on whether the component is used as an input or output.🔗 ```\nvisible: bool | Literal['hidden']\n``` default = True If False, component will be hidden. If &quot;hidden&quot;, component will be visually hidden and not take up space in the layout but still exist in the DOM🔗 ```\nelem_id: str | None\n``` 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.🔗 ```\nelem_classes: list[str] | str | None\n``` 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.🔗 ```\nrender: bool\n``` 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.🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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 &#039;preserved_by_key&#039; are not reset across a re-render.🔗 ```\npreserved_by_key: list[str] | str | None\n``` default = \"value\" A list of parameters from this component&#039;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.🔗 ```\nallow_reordering: bool\n``` default = False if True, will allow users to reorder uploaded files by dragging and dropping.🔗 ```\nbuttons: list[Button] | None\n``` default = None  Shortcuts Shortcuts ```\ngradio.File\n``` Interface String Shortcut \"file\" Initialization Uses default values```\ngradio.Files\n``` Interface String Shortcut \"files\" Initialization Uses file_count=\"multiple\"  Event Listeners Description Event listeners allow you to respond to user interactions with the UI\n\t\tcomponents you've defined in a Gradio Blocks app. When a user interacts with\n\t\tan element, such as changing a slider value or uploading an image, a\n\t\tfunction is called. Supported Event Listeners The File component supports the following event listeners. Each event listener takes the\n\t\tsame parameters, which are listed in the Event Parameters table below. Listeners ```\nFile.change(fn, ···)\n``` Triggered when the value of the File 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.```\nFile.select(fn, ···)\n``` Event listener for when the user selects or deselects the File. Uses event data gradio.SelectData to carry value referring to the label of the File, and selected to refer to state of the File. See https://www.gradio.app/main/docs/gradio/eventdata for more details.```\nFile.clear(fn, ···)\n``` This listener is triggered when the user clears the File using the clear button for the component.```\nFile.upload(fn, ···)\n``` This listener is triggered when the user uploads a file into the File.```\nFile.delete(fn, ···)\n``` This listener is triggered when the user deletes and item from the File. Uses event data gradio.DeletedFileData to carry value referring to the file that was deleted as an instance of FileData. See EventData documentation on how to use this event data```\nFile.download(fn, ···)\n``` This listener is triggered when the user downloads a file from the File. Uses event data gradio.DownloadData to carry information about the downloaded file as a FileData object. See EventData documentation on how to use this event data Event Parameters Parameters ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.  ","type":"DOCS"},{"title":"FileExplorer","slug":"/main/docs/gradio/fileexplorer","content":"FileExplorer ```\ngradio.FileExplorer(···)\n``` Description Creates a file explorer component that allows users to browse files on the machine hosting the Gradio app. As an input component, it also allows users to select files to be used as input to a function, while as an output component, it displays selected files. Behavior Using FileExplorer as an input component. How FileExplorer will pass its value to your function: Type: list[str] | str | None Passes the selected file or directory as a str path (relative to root) or list[str} depending on file_count Example Code \n    \n    import gradio as gr\n\n    def predict(\n        value: list[str] | str | None\n    ):\n        # process value from the FileExplorer component\n        return \"prediction\"\n\n    interface = gr.Interface(predict, gr.FileExplorer(), gr.Textbox())\n    interface.launch()\n\n  Using FileExplorer as an output component How FileExplorer expects you to return a value: Type: str | list[str] | None Expects function to return a str path to a file, or list[str] consisting of paths to files. Example Code \n    \n    import gradio as gr\n\n    def predict(text) -> str | list[str] | None\n        # process value to return to the FileExplorer component\n        return value\n\n    interface = gr.Interface(predict, gr.Textbox(), gr.FileExplorer())\n    interface.launch()\n\n Initialization Parameters ▼ 🔗 ```\nglob: str\n``` default = \"**/*\" The glob-style pattern used to select which files to display, e.g. &quot;*&quot; to match all files, &quot;*.png&quot; to match all .png files, &quot;**/*.txt&quot; to match any .txt file in any subdirectory, etc. The default value matches all files and folders recursively. See the Python glob documentation at https://docs.python.org/3/library/glob.html for more information.🔗 ```\nvalue: str | list[str] | Callable | None\n``` default = None The file (or list of files, depending on the `file_count` parameter) to show as &quot;selected&quot; when the component is first loaded. If a callable is provided, it will be called when the app loads to set the initial value of the component. If not provided, no files are shown as selected.🔗 ```\nfile_count: Literal['single', 'multiple']\n``` default = \"multiple\" Whether to allow single or multiple files to be selected. If &quot;single&quot;, the component will return a single absolute file path as a string. If &quot;multiple&quot;, the component will return a list of absolute file paths as a list of strings.🔗 ```\nroot_dir: str | Path\n``` default = \".\" Path to root directory to select files from. If not provided, defaults to current working directory. Raises ValueError if the directory does not exist.🔗 ```\nignore_glob: str | None\n``` default = None The glob-style, case-sensitive pattern that will be used to exclude files from the list. For example, &quot;*.py&quot; will exclude all .py files from the list. See the Python glob documentation at https://docs.python.org/3/library/glob.html for more information.🔗 ```\nlabel: str | I18nData | None\n``` 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.🔗 ```\nevery: Timer | float | None\n``` default = None Continuously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.🔗 ```\ninputs: Component | list[Component] | set[Component] | None\n``` 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.🔗 ```\nshow_label: bool | None\n``` default = None if True, will display label.🔗 ```\ncontainer: bool\n``` default = True If True, will place the component in a container - providing some extra padding around the border.🔗 ```\nscale: int | None\n``` 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.🔗 ```\nmin_width: int\n``` 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.🔗 ```\nheight: int | str | None\n``` default = None The maximum height of the file component, specified in pixels if a number is passed, or in CSS units if a string is passed. If more files are uploaded than can fit in the height, a scrollbar will appear.🔗 ```\nmax_height: int | str | None\n``` default = 500 🔗 ```\nmin_height: int | str | None\n``` default = None 🔗 ```\ninteractive: bool | None\n``` default = None if True, will allow users to select file(s); if False, will only display files. If not provided, this is inferred based on whether the component is used as an input or output.🔗 ```\nvisible: bool | Literal['hidden']\n``` default = True If False, component will be hidden. If &quot;hidden&quot;, component will be visually hidden and not take up space in the layout but still exist in the DOM🔗 ```\nelem_id: str | None\n``` 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.🔗 ```\nelem_classes: list[str] | str | None\n``` 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.🔗 ```\nrender: bool\n``` 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.🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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 &#039;preserved_by_key&#039; are not reset across a re-render.🔗 ```\npreserved_by_key: list[str] | str | None\n``` default = \"value\" A list of parameters from this component&#039;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.🔗 ```\nbuttons: list[Button] | None\n``` default = None A list of gr.Button() instances to show in the top right corner of the component. Custom buttons will appear in the toolbar with their configured icon and/or label, and clicking them will trigger any .click() events registered on the button. Shortcuts Shortcuts ```\ngradio.FileExplorer\n``` Interface String Shortcut \"fileexplorer\" Initialization Uses default values  Event Listeners Description Event listeners allow you to respond to user interactions with the UI\n\t\tcomponents you've defined in a Gradio Blocks app. When a user interacts with\n\t\tan element, such as changing a slider value or uploading an image, a\n\t\tfunction is called. Supported Event Listeners The FileExplorer component supports the following event listeners. Each event listener takes the\n\t\tsame parameters, which are listed in the Event Parameters table below. Listeners ```\nFileExplorer.change(fn, ···)\n``` Triggered when the value of the FileExplorer 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.```\nFileExplorer.input(fn, ···)\n``` This listener is triggered when the user changes the value of the FileExplorer.```\nFileExplorer.select(fn, ···)\n``` Event listener for when the user selects or deselects the FileExplorer. Uses event data gradio.SelectData to carry value referring to the label of the FileExplorer, and selected to refer to state of the FileExplorer. See https://www.gradio.app/main/docs/gradio/eventdata for more details. Event Parameters Parameters ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.  ","type":"DOCS"},{"title":"Gallery","slug":"/main/docs/gradio/gallery","content":"Gallery ```\ngradio.Gallery(···)\n``` Description Creates a gallery component that allows displaying a grid of images or videos, and optionally captions. If used as an input, the user can upload images or videos to the gallery. If used as an output, the user can click on individual images or videos to view them at a higher resolution.  Behavior Using Gallery as an input component. How Gallery will pass its value to your function: Type: list[tuple[str, str | None]] | list[tuple[PIL.Image.Image, str | None]] | list[tuple[np.ndarray, str | None]] | None Passes the list of images or videos as:\na list of (media, caption) tuples\na list of (media, None) tuples if no captions are provided (which is usually the case).\nDepending on type, images can be a:\nstr file path\nnumpy array\nPIL.Image object\nVideos are always str file path. Example Code \n    \n    import gradio as gr\n\n    def predict(\n        value: list[tuple[str, str | None]] | list[tuple[PIL.Image.Image, str | None]] | list[tuple[np.ndarray, str | None]] | None\n    ):\n        # process value from the Gallery component\n        return \"prediction\"\n\n    interface = gr.Interface(predict, gr.Gallery(), gr.Textbox())\n    interface.launch()\n\n  Using Gallery as an output component How Gallery expects you to return a value: Type: list[GalleryMediaType | CaptionedGalleryMediaType] | None Expects the function to return a:\nlist of images or videos\nlist of (media, str caption) tuples.\nEach image can be a:\nstr file path\nnumpy array\nPIL.Image object\nEach video can be a str file path. Example Code \n    \n    import gradio as gr\n\n    def predict(text) -> list[GalleryMediaType | CaptionedGalleryMediaType] | None\n        # process value to return to the Gallery component\n        return value\n\n    interface = gr.Interface(predict, gr.Textbox(), gr.Gallery())\n    interface.launch()\n\n Initialization Parameters ▼ 🔗 ```\nvalue: list[np.ndarray | PIL.Image.Image | str | Path | tuple] | Callable | None\n``` default = None List of images or videos to display in the gallery by default. If a function is provided, the function will be called each time the app loads to set the initial value of this component.🔗 ```\nformat: str\n``` default = \"webp\" Format to save images before they are returned to the frontend, such as &#039;jpeg&#039; or &#039;png&#039;. This parameter only applies to images that are returned from the prediction function as numpy arrays or PIL Images. The format should be supported by the PIL library.🔗 ```\nfile_types: list[str] | None\n``` default = None List of file extensions or types of files to be uploaded (e.g. [&#039;image&#039;, &#039;.mp4&#039;]), when this is used as an input component. &quot;image&quot; allows only image files to be uploaded, &quot;video&quot; allows only video files to be uploaded, &quot;.mp4&quot; allows only mp4 files to be uploaded, etc. If None, any image and video files types are allowed.🔗 ```\nlabel: str | I18nData | None\n``` 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.🔗 ```\nevery: Timer | float | None\n``` default = None Continuously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.🔗 ```\ninputs: Component | list[Component] | set[Component] | None\n``` 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.🔗 ```\nshow_label: bool | None\n``` default = None if True, will display label.🔗 ```\ncontainer: bool\n``` default = True If True, will place the component in a container - providing some extra padding around the border.🔗 ```\nscale: int | None\n``` 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.🔗 ```\nmin_width: int\n``` 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.🔗 ```\nvisible: bool | Literal['hidden']\n``` default = True If False, component will be hidden. If &quot;hidden&quot;, component will be visually hidden and not take up space in the layout but still exist in the DOM🔗 ```\nelem_id: str | None\n``` 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.🔗 ```\nelem_classes: list[str] | str | None\n``` 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.🔗 ```\nrender: bool\n``` 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.🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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 &#039;preserved_by_key&#039; are not reset across a re-render.🔗 ```\npreserved_by_key: list[str] | str | None\n``` default = \"value\" A list of parameters from this component&#039;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.🔗 ```\ncolumns: int | None\n``` default = 2 Represents the number of images that should be shown in one row.🔗 ```\nrows: int | None\n``` default = None Represents the number of rows in the image grid.🔗 ```\nheight: int | float | str | None\n``` default = None The height of the gallery component, specified in pixels if a number is passed, or in CSS units if a string is passed. If more images are displayed than can fit in the height, a scrollbar will appear.🔗 ```\nallow_preview: bool\n``` default = True If True, images in the gallery will be enlarged when they are clicked. Default is True.🔗 ```\npreview: bool | None\n``` default = None If True, Gallery will start in preview mode, which shows all of the images as thumbnails and allows the user to click on them to view them in full size. Only works if allow_preview is True.🔗 ```\nselected_index: int | None\n``` default = None The index of the image that should be initially selected. If None, no image will be selected at start. If provided, will set Gallery to preview mode unless allow_preview is set to False.🔗 ```\nobject_fit: Literal['contain', 'cover', 'fill', 'none', 'scale-down'] | None\n``` default = None CSS object-fit property for the thumbnail images in the gallery. Can be &quot;contain&quot;, &quot;cover&quot;, &quot;fill&quot;, &quot;none&quot;, or &quot;scale-down&quot;.🔗 ```\nbuttons: list[Literal['share', 'download', 'download_all', 'fullscreen'] | Button] | None\n``` default = None A list of buttons to show in the top right corner of the component. Valid options are &quot;share&quot;, &quot;download&quot;, &quot;download_all&quot;, &quot;fullscreen&quot;, or a gr.Button() instance. The &quot;share&quot; button allows the user to share outputs to Hugging Face Spaces Discussions. The &quot;download&quot; button allows the user to download the selected image. The &quot;download_all&quot; button allows the user to download all gallery images and videos. The &quot;fullscreen&quot; button allows the user to view the gallery in fullscreen mode. Custom gr.Button() instances will appear in the toolbar with their configured icon and/or label, and clicking them will trigger any .click() events registered on the button. by default, all of the built-in buttons are shown.🔗 ```\ninteractive: bool | None\n``` default = None If True, the gallery will be interactive, allowing the user to upload images. If False, the gallery will be static. Default is True.🔗 ```\ntype: Literal['numpy', 'pil', 'filepath']\n``` default = \"filepath\" The format the image is converted to before being passed into the prediction function. &quot;numpy&quot; converts the image to a numpy array with shape (height, width, 3) and values from 0 to 255, &quot;pil&quot; converts the image to a PIL image object, &quot;filepath&quot; passes a str path to a temporary file containing the image. If the image is SVG, the `type` is ignored and the filepath of the SVG is returned.🔗 ```\nfit_columns: bool\n``` default = True Expand columns to fit the full width when there are fewer images than the columns parameter.🔗 ```\nsources: list[Literal['upload', 'webcam', 'clipboard']] | None\n``` default = None A list of sources that the user can upload images from when this component is used as an input. Valid options are &quot;upload&quot;, &quot;webcam&quot;, and &quot;clipboard&quot;. &quot;upload&quot; allows the user to upload files from their computer, &quot;webcam&quot; allows the user to take a photo or video using their webcam, and &quot;clipboard&quot; allows the user to paste an image or video from their clipboard. By default, only &quot;upload&quot; is allowed. Shortcuts Shortcuts ```\ngradio.Gallery\n``` Interface String Shortcut \"gallery\" Initialization Uses default values Demos fake_gangif_maker  Event Listeners Description Event listeners allow you to respond to user interactions with the UI\n\t\tcomponents you've defined in a Gradio Blocks app. When a user interacts with\n\t\tan element, such as changing a slider value or uploading an image, a\n\t\tfunction is called. Supported Event Listeners The Gallery component supports the following event listeners. Each event listener takes the\n\t\tsame parameters, which are listed in the Event Parameters table below. Listeners ```\nGallery.select(fn, ···)\n``` Event listener for when the user selects or deselects the Gallery. Uses event data gradio.SelectData to carry value referring to the label of the Gallery, and selected to refer to state of the Gallery. See https://www.gradio.app/main/docs/gradio/eventdata for more details.```\nGallery.upload(fn, ···)\n``` This listener is triggered when the user uploads a file into the Gallery.```\nGallery.change(fn, ···)\n``` Triggered when the value of the Gallery 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.```\nGallery.delete(fn, ···)\n``` This listener is triggered when the user deletes and item from the Gallery. Uses event data gradio.DeletedFileData to carry value referring to the file that was deleted as an instance of FileData. See EventData documentation on how to use this event data```\nGallery.preview_close(fn, ···)\n``` This event is triggered when the Gallery preview is closed by the user```\nGallery.preview_open(fn, ···)\n``` This event is triggered when the Gallery preview is opened by the user Event Parameters Parameters ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.  ","type":"DOCS"},{"title":"HighlightedText","slug":"/main/docs/gradio/highlightedtext","content":"HighlightedText ```\ngradio.HighlightedText(···)\n``` Description Displays text that contains spans that are highlighted by category or numerical value.  Behavior Using HighlightedText as an input component. How HighlightedText will pass its value to your function: Type: list[tuple[str, str | float | None]] | None Passes the value as a list of tuples: list[tuple]. Each tuple consists of:\na str substring of the text (so the entire text is included)\na str | float | None label, which is the category or confidence of that substring. Example Code \n    \n    import gradio as gr\n\n    def predict(\n        value: list[tuple[str, str | float | None]] | None\n    ):\n        # process value from the HighlightedText component\n        return \"prediction\"\n\n    interface = gr.Interface(predict, gr.HighlightedText(), gr.Textbox())\n    interface.launch()\n\n  Using HighlightedText as an output component How HighlightedText expects you to return a value: Type: list[tuple[str, str | float | None]] | dict | None Expects either of:\na list of (word, category) tuples\na dictionary of two keys: \"text\", and \"entities\".\n\"entities\" itself is a list of dictionaries, each of which have the keys: \"entity\" (or \"entity_group\"), \"start\", and \"end\" Example Code \n    \n    import gradio as gr\n\n    def predict(text) -> list[tuple[str, str | float | None]] | dict | None\n        # process value to return to the HighlightedText component\n        return value\n\n    interface = gr.Interface(predict, gr.Textbox(), gr.HighlightedText())\n    interface.launch()\n\n Initialization Parameters ▼ 🔗 ```\nvalue: list[tuple[str, str | float | None]] | dict | Callable | None\n``` 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.🔗 ```\ncolor_map: dict[str, str] | None\n``` default = None A dictionary mapping labels to colors. The colors may be specified as hex codes or by their names. For example: {&quot;person&quot;: &quot;red&quot;, &quot;location&quot;: &quot;#FFEE22&quot;}🔗 ```\nshow_legend: bool\n``` default = False whether to show span categories in a separate legend or inline.🔗 ```\nshow_inline_category: bool\n``` default = True If False, will not display span category label. Only applies if show_legend=False and interactive=False.🔗 ```\ncombine_adjacent: bool\n``` default = False If True, will merge the labels of adjacent tokens belonging to the same category.🔗 ```\nadjacent_separator: str\n``` default = \"\" Specifies the separator to be used between tokens if combine_adjacent is True.🔗 ```\nshow_whitespaces: bool\n``` default = True If False, leading and trailing whitespace of each token will be stripped before display.🔗 ```\nlabel: str | I18nData | None\n``` 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.🔗 ```\nevery: Timer | float | None\n``` default = None Continuously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.🔗 ```\ninputs: Component | list[Component] | set[Component] | None\n``` 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.🔗 ```\nshow_label: bool | None\n``` default = None if True, will display label.🔗 ```\ncontainer: bool\n``` default = True If True, will place the component in a container - providing some extra padding around the border.🔗 ```\nscale: int | None\n``` 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.🔗 ```\nmin_width: int\n``` 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.🔗 ```\nvisible: bool | Literal['hidden']\n``` default = True If False, component will be hidden. If &quot;hidden&quot;, component will be visually hidden and not take up space in the layout but still exist in the DOM🔗 ```\nelem_id: str | None\n``` 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.🔗 ```\nelem_classes: list[str] | str | None\n``` 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.🔗 ```\nrender: bool\n``` 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.🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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 &#039;preserved_by_key&#039; are not reset across a re-render.🔗 ```\npreserved_by_key: list[str] | str | None\n``` default = \"value\" A list of parameters from this component&#039;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.🔗 ```\ninteractive: bool | None\n``` default = None If True, the component will be editable, and allow user to select spans of text and label them.🔗 ```\nrtl: bool\n``` 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.🔗 ```\nbuttons: list[Button] | None\n``` default = None A list of gr.Button() instances to show in the top right corner of the component. Custom buttons will appear in the toolbar with their configured icon and/or label, and clicking them will trigger any .click() events registered on the button. Shortcuts Shortcuts ```\ngradio.HighlightedText\n``` Interface String Shortcut \"highlightedtext\" Initialization Uses default values Demos diff_texts  Event Listeners Description Event listeners allow you to respond to user interactions with the UI\n\t\tcomponents you've defined in a Gradio Blocks app. When a user interacts with\n\t\tan element, such as changing a slider value or uploading an image, a\n\t\tfunction is called. Supported Event Listeners The HighlightedText component supports the following event listeners. Each event listener takes the\n\t\tsame parameters, which are listed in the Event Parameters table below. Listeners ```\nHighlightedText.change(fn, ···)\n``` 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.```\nHighlightedText.select(fn, ···)\n``` 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 https://www.gradio.app/main/docs/gradio/eventdata for more details. Event Parameters Parameters ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.  Named Entity Recognition","type":"DOCS"},{"title":"HTML","slug":"/main/docs/gradio/html","content":"HTML ```\ngradio.HTML(···)\n``` Description Creates a component with arbitrary HTML. Can include CSS and JavaScript to create highly customized and interactive components. Behavior Using HTML as an input component. How HTML will pass its value to your function: Type: str | None (Rarely used) passes the HTML as a str. Example Code \n    \n    import gradio as gr\n\n    def predict(\n        value: str | None\n    ):\n        # process value from the HTML component\n        return \"prediction\"\n\n    interface = gr.Interface(predict, gr.HTML(), gr.Textbox())\n    interface.launch()\n\n  Using HTML as an output component How HTML expects you to return a value: Type: str | None Expects a str consisting of valid HTML. Example Code \n    \n    import gradio as gr\n\n    def predict(text) -> str | None\n        # process value to return to the HTML component\n        return value\n\n    interface = gr.Interface(predict, gr.Textbox(), gr.HTML())\n    interface.launch()\n\n Initialization Parameters ▼ 🔗 ```\nvalue: Any | Callable | None\n``` default = None The HTML content in the ${value} tag in the html_template. For example, if html_template=&quot;&lt;p&gt;${value}&lt;/p&gt;&quot; and value=&quot;Hello, world!&quot;, the component will render as `&quot;&lt;p&gt;Hello, world!&lt;/p&gt;&quot;`.🔗 ```\nlabel: str | I18nData | None\n``` default = None The label for this component. Is 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.🔗 ```\nhtml_template: str\n``` default = \"${value}\" A string representing the HTML template for this component as a JS template string and Handlebars template. The `${value}` tag will be replaced with the `value` parameter, and all other tags will be filled in with the values from `props`. This element can have children when used in a `with gr.HTML(...):` context, and the children will be rendered to replace `@children` substring, which cannot be nested inside any HTML tags.🔗 ```\ncss_template: str\n``` default = \"\" A string representing the CSS template for this component as a JS template string and Handlebars template. The CSS will be automatically scoped to this component, and rules outside a block will target the component&#039;s root element. The `${value}` tag will be replaced with the `value` parameter, and all other tags will be filled in with the values from `props`.🔗 ```\njs_on_load: str | None\n``` default = \"element.addEventListener('click', function() { trigger('click') });\" A string representing the JavaScript code that will be executed when the component is loaded. The `element` variable refers to the HTML element of this component, and can be used to access children such as `element.querySelector()`. The `trigger` function can be used to trigger events, such as `trigger(&#039;click&#039;)`. The value and other props can be edited through `props`, e.g. `props.value = &quot;new value&quot;` which will re-render the HTML template. If `server_functions` is provided, a `server` object is also available in `js_on_load`, where each function is accessible as an async method, e.g. `server.list_files(path).then(files =&gt; ...)` or `const files = await server.list_files(path)`. The `upload` async function can be used to upload a JavaScript `File` object to the Gradio server, returning a dictionary with `path` (the server-side file path) and `url` (the public URL to access the file), e.g. `const { path, url } = await upload(file)`. The `watch` function can be used to observe prop changes when the component is an output to a Python event listener: `watch(&#039;value&#039;, () =&gt; { ... })` runs the callback after the template re-renders whenever `value` changes, or `watch([&#039;value&#039;, &#039;color&#039;], () =&gt; { ... })` to watch multiple props.`.🔗 ```\napply_default_css: bool\n``` default = True If True, default Gradio CSS styles will be applied to the HTML component.🔗 ```\nevery: Timer | float | None\n``` default = None Continuously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.🔗 ```\ninputs: Component | list[Component] | set[Component] | None\n``` 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.🔗 ```\nshow_label: bool\n``` default = False If True, the label will be displayed. If False, the label will be hidden.🔗 ```\nscale: int | None\n``` 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.🔗 ```\nmin_width: int | None\n``` default = None minimum pixel width, will wrap if not sufficient screen space to satisfy this value. If a certain scale value results in this Component being narrower than min_width, the min_width parameter will be respected first.🔗 ```\nvisible: bool | Literal['hidden']\n``` default = True If False, component will be hidden. If &quot;hidden&quot;, component will be visually hidden and not take up space in the layout but still exist in the DOM🔗 ```\nelem_id: str | None\n``` 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.🔗 ```\nelem_classes: list[str] | str | None\n``` 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.🔗 ```\nrender: bool\n``` 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.🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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 &#039;preserved_by_key&#039; are not reset across a re-render.🔗 ```\npreserved_by_key: list[str] | str | None\n``` default = \"value\" A list of parameters from this component&#039;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.🔗 ```\nmin_height: int | None\n``` 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 HTML content exceeds the height, the component will expand to fit the content.🔗 ```\nmax_height: int | None\n``` 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 content exceeds the height, the component will scroll.🔗 ```\ncontainer: bool\n``` default = False If True, the HTML component will be displayed in a container. Default is False.🔗 ```\npadding: bool\n``` default = False If True, the HTML component will have a certain padding (set by the `--block-padding` CSS variable) in all directions. Default is False.🔗 ```\nautoscroll: bool\n``` default = False If True, will automatically scroll to the bottom of the component when the content changes, unless the user has scrolled up. If False, will not scroll to the bottom when the content changes.🔗 ```\nbuttons: list[Button] | None\n``` default = None A list of gr.Button() instances to show in the top right corner of the component. Custom buttons will appear in the toolbar with their configured icon and/or label, and clicking them will trigger any .click() events registered on the button.🔗 ```\nhead: str | None\n``` default = None A raw HTML string to inject into the document `&lt;head&gt;` before `js_on_load` runs. Typically used for `&lt;script&gt;` and `&lt;link&gt;` tags to load third-party libraries. Scripts are deduplicated by `src` and links by `href`, so multiple components requiring the same library won&#039;t load it twice.🔗 ```\nserver_functions: list[Callable] | None\n``` default = None A list of Python functions that can be called from `js_on_load` via the `server` object. For example, if you pass `server_functions=[my_func]`, you can call `server.my_func(arg1, arg2)` in your `js_on_load` code. Each function becomes an async method that sends the call to the Python backend and returns the result.🔗 ```\nprops: Any\n```  Additional keyword arguments to pass into the HTML and CSS templates for rendering. Shortcuts Shortcuts ```\ngradio.HTML\n``` Interface String Shortcut \"html\" Initialization Uses default values Demos super_html  Event Listeners Description Event listeners allow you to respond to user interactions with the UI\n\t\tcomponents you've defined in a Gradio Blocks app. When a user interacts with\n\t\tan element, such as changing a slider value or uploading an image, a\n\t\tfunction is called. Supported Event Listeners The HTML component supports the following event listeners. Each event listener takes the\n\t\tsame parameters, which are listed in the Event Parameters table below. Listeners ```\nHTML.change(fn, ···)\n``` Triggered when the value of the HTML 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.```\nHTML.input(fn, ···)\n``` This listener is triggered when the user changes the value of the HTML.```\nHTML.click(fn, ···)\n``` Triggered when the HTML is clicked.```\nHTML.double_click(fn, ···)\n``` Triggered when the HTML is double clicked.```\nHTML.submit(fn, ···)\n``` This listener is triggered when the user presses the Enter key while the HTML is focused.```\nHTML.stop(fn, ···)\n``` This listener is triggered when the user reaches the end of the media playing in the HTML.```\nHTML.edit(fn, ···)\n``` This listener is triggered when the user edits the HTML (e.g. image) using the built-in editor.```\nHTML.clear(fn, ···)\n``` This listener is triggered when the user clears the HTML using the clear button for the component.```\nHTML.play(fn, ···)\n``` This listener is triggered when the user plays the media in the HTML.```\nHTML.pause(fn, ···)\n``` This listener is triggered when the media in the HTML stops for any reason.```\nHTML.end(fn, ···)\n``` This listener is triggered when the user reaches the end of the media playing in the HTML.```\nHTML.start_recording(fn, ···)\n``` This listener is triggered when the user starts recording with the HTML.```\nHTML.pause_recording(fn, ···)\n``` This listener is triggered when the user pauses recording with the HTML.```\nHTML.stop_recording(fn, ···)\n``` This listener is triggered when the user stops recording with the HTML.```\nHTML.focus(fn, ···)\n``` This listener is triggered when the HTML is focused.```\nHTML.blur(fn, ···)\n``` This listener is triggered when the HTML is unfocused/blurred.```\nHTML.upload(fn, ···)\n``` This listener is triggered when the user uploads a file into the HTML.```\nHTML.release(fn, ···)\n``` This listener is triggered when the user releases the mouse on this HTML.```\nHTML.select(fn, ···)\n``` Event listener for when the user selects or deselects the HTML. Uses event data gradio.SelectData to carry value referring to the label of the HTML, and selected to refer to state of the HTML. See https://www.gradio.app/main/docs/gradio/eventdata for more details.```\nHTML.stream(fn, ···)\n``` This listener is triggered when the user streams the HTML.```\nHTML.like(fn, ···)\n``` This listener is triggered when the user likes/dislikes from within the HTML. This event has EventData of type gradio.LikeData that carries information, accessible through LikeData.index and LikeData.value. See EventData documentation on how to use this event data.```\nHTML.example_select(fn, ···)\n``` This listener is triggered when the user clicks on an example from within the HTML. This event has SelectData of type gradio.SelectData that carries information, accessible through SelectData.index and SelectData.value. See SelectData documentation on how to use this event data.```\nHTML.option_select(fn, ···)\n``` This listener is triggered when the user clicks on an option from within the HTML. This event has SelectData of type gradio.SelectData that carries information, accessible through SelectData.index and SelectData.value. See SelectData documentation on how to use this event data.```\nHTML.load(fn, ···)\n``` This listener is triggered when the HTML initially loads in the browser.```\nHTML.key_up(fn, ···)\n``` This listener is triggered when the user presses a key while the HTML is focused.```\nHTML.apply(fn, ···)\n``` This listener is triggered when the user applies changes to the HTML through an integrated UI action.```\nHTML.delete(fn, ···)\n``` This listener is triggered when the user deletes and item from the HTML. Uses event data gradio.DeletedFileData to carry value referring to the file that was deleted as an instance of FileData. See EventData documentation on how to use this event data```\nHTML.tick(fn, ···)\n``` This listener is triggered at regular intervals defined by the HTML.```\nHTML.undo(fn, ···)\n``` This listener is triggered when the user clicks the undo button in the chatbot message.```\nHTML.retry(fn, ···)\n``` This listener is triggered when the user clicks the retry button in the chatbot message.```\nHTML.expand(fn, ···)\n``` This listener is triggered when the HTML is expanded.```\nHTML.collapse(fn, ···)\n``` This listener is triggered when the HTML is collapsed.```\nHTML.download(fn, ···)\n``` This listener is triggered when the user downloads a file from the HTML. Uses event data gradio.DownloadData to carry information about the downloaded file as a FileData object. See EventData documentation on how to use this event data```\nHTML.copy(fn, ···)\n``` This listener is triggered when the user copies content from the HTML. 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 ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.  Custom HTML ComponentsCustom CSS And JS","type":"DOCS"},{"title":"Image","slug":"/main/docs/gradio/image","content":"Image ```\ngradio.Image(···)\n``` Description Creates an image component that can be used to upload images (as an input) or display images (as an output).  Behavior Using Image as an input component. How Image will pass its value to your function: Type: np.ndarray | PIL.Image.Image | str | None Passes the uploaded image as a numpy.array, PIL.Image or str filepath depending on type. Example Code \n    \n    import gradio as gr\n\n    def predict(\n        value: np.ndarray | PIL.Image.Image | str | None\n    ):\n        # process value from the Image component\n        return \"prediction\"\n\n    interface = gr.Interface(predict, gr.Image(), gr.Textbox())\n    interface.launch()\n\n  Using Image as an output component How Image expects you to return a value: Type: np.ndarray | PIL.Image.Image | str | Path | None Expects a numpy.array, PIL.Image, or str or pathlib.Path filepath to an image which is displayed. Example Code \n    \n    import gradio as gr\n\n    def predict(text) -> np.ndarray | PIL.Image.Image | str | Path | None\n        # process value to return to the Image component\n        return value\n\n    interface = gr.Interface(predict, gr.Textbox(), gr.Image())\n    interface.launch()\n\n Initialization Parameters ▼ 🔗 ```\nvalue: str | PIL.Image.Image | np.ndarray | Callable | None\n``` default = None A `PIL.Image`, `numpy.array`, `pathlib.Path`, or `str` filepath or URL for the default value that Image component is going to take. If a function is provided, the function will be called each time the app loads to set the initial value of this component.🔗 ```\nformat: str\n``` default = \"webp\" File format (e.g. &quot;png&quot; or &quot;gif&quot;). Used to save image if it does not already have a valid format (e.g. if the image is being returned to the frontend as a numpy array or PIL Image). The format should be supported by the PIL library. Applies both when this component is used as an input or output. This parameter has no effect on SVG files.🔗 ```\nheight: int | str | None\n``` 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.🔗 ```\nwidth: int | str | None\n``` 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.🔗 ```\nimage_mode: Literal['1', 'L', 'P', 'RGB', 'RGBA', 'CMYK', 'YCbCr', 'LAB', 'HSV', 'I', 'F'] | None\n``` default = \"RGB\" The pixel format and color depth that the image should be loaded and preprocessed as. &quot;RGB&quot; will load the image as a color image, or &quot;L&quot; as black-and-white. See https://pillow.readthedocs.io/en/stable/handbook/concepts.html for other supported image modes and their meaning. This parameter has no effect on SVG or GIF files. If set to None, the image_mode will be inferred from the image file type (e.g. &quot;RGBA&quot; for a .png image, &quot;RGB&quot; in most other cases).🔗 ```\nsources: list[Literal['upload', 'webcam', 'clipboard']] | Literal['upload', 'webcam', 'clipboard'] | None\n``` default = None List of sources for the image. &quot;upload&quot; creates a box where user can drop an image file, &quot;webcam&quot; allows user to take snapshot from their webcam, &quot;clipboard&quot; allows users to paste an image from the clipboard. If None, defaults to [&quot;upload&quot;, &quot;webcam&quot;, &quot;clipboard&quot;] if streaming is False, otherwise defaults to [&quot;webcam&quot;].🔗 ```\ntype: Literal['numpy', 'pil', 'filepath']\n``` default = \"numpy\" The format the image is converted before being passed into the prediction function. &quot;numpy&quot; converts the image to a numpy array with shape (height, width, 3) and values from 0 to 255, &quot;pil&quot; converts the image to a PIL image object, &quot;filepath&quot; passes a str path to a temporary file containing the image. To support animated GIFs in input, the `type` should be set to &quot;filepath&quot; or &quot;pil&quot;. To support SVGs, the `type` should be set to &quot;filepath&quot;.🔗 ```\nlabel: str | I18nData | None\n``` 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.🔗 ```\nevery: Timer | float | None\n``` default = None Continuously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.🔗 ```\ninputs: Component | list[Component] | set[Component] | None\n``` 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.🔗 ```\nshow_label: bool | None\n``` default = None if True, will display label.🔗 ```\nbuttons: list[Literal['download', 'share', 'fullscreen'] | Button] | None\n``` default = None A list of buttons to show in the corner of the component. Valid options are &quot;download&quot;, &quot;share&quot;, &quot;fullscreen&quot;, or a gr.Button() instance. The &quot;download&quot; button allows the user to download the image. The &quot;share&quot; button allows the user to share to Hugging Face Spaces Discussions. The &quot;fullscreen&quot; button allows the user to view in fullscreen mode. Custom gr.Button() instances will appear in the toolbar with their configured icon and/or label, and clicking them will trigger any .click() events registered on the button. by default, all of the built-in buttons are shown.🔗 ```\ncontainer: bool\n``` default = True If True, will place the component in a container - providing some extra padding around the border.🔗 ```\nscale: int | None\n``` 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.🔗 ```\nmin_width: int\n``` 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.🔗 ```\ninteractive: bool | None\n``` default = None if True, will allow users to upload and edit an image; if False, can only be used to display images. If not provided, this is inferred based on whether the component is used as an input or output.🔗 ```\nvisible: bool | Literal['hidden']\n``` default = True If False, component will be hidden. If &quot;hidden&quot;, component will be visually hidden and not take up space in the layout but still exist in the DOM🔗 ```\nstreaming: bool\n``` default = False If True when used in a `live` interface, will automatically stream webcam feed. Only valid is source is &#039;webcam&#039;. If the component is an output component, will automatically convert images to base64.🔗 ```\nelem_id: str | None\n``` 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.🔗 ```\nelem_classes: list[str] | str | None\n``` 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.🔗 ```\nrender: bool\n``` 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.🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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 &#039;preserved_by_key&#039; are not reset across a re-render.🔗 ```\npreserved_by_key: list[str] | str | None\n``` default = \"value\" A list of parameters from this component&#039;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.🔗 ```\nwebcam_options: WebcamOptions | None\n``` default = None 🔗 ```\nplaceholder: str | None\n``` default = None Custom text for the upload area. Overrides default upload messages when provided. Accepts new lines and `#` to designate a heading.🔗 ```\nwatermark: WatermarkOptions | None\n``` default = None If provided and this component is used to display a `value` image, the `watermark` image will be displayed on the bottom right of the `value` image, 10 pixels from the bottom and 10 pixels from the right. The watermark image will not be resized. Supports `PIL.Image`, `numpy.array`, `pathlib.Path`, and `str` filepaths. SVGs and GIFs are not supported as `watermark` images nor can they be watermarked.🔗 ```\nalt_text: str | None\n``` default = None Alternative text for the image, used by screen readers. If not provided, the image is treated as decorative. Shortcuts Shortcuts ```\ngradio.Image\n``` Interface String Shortcut \"image\" Initialization Uses default values Understanding Image Types The type parameter controls the format of the data passed to your Python function. Choosing the right type avoids unnecessary conversions in your code: typeYour function receivesShape / FormatBest for\"numpy\" (default)numpy.ndarray(height, width, 3), dtype uint8, values 0–255ML models (PyTorch, TensorFlow, scikit-learn)\"pil\"PIL.Image.ImagePIL Image objectImage processing with Pillow\"filepath\"strPath to a temporary file on diskLarge images, GIFs, SVGs, or when you need to read the file yourself ```\nimport gradio as gr\n\n# For a model that expects a numpy array:\ndef predict(img):\n    # img is a numpy array with shape (H, W, 3)\n    return model(img)\n\ndemo = gr.Interface(fn=predict, inputs=gr.Image(type=\"numpy\"), outputs=\"label\")\n\n# For a pipeline that works with file paths:\ndef process(path):\n    # path is a string like \"/tmp/gradio/abcdef.webp\"\n    return my_pipeline(path)\n\ndemo = gr.Interface(fn=process, inputs=gr.Image(type=\"filepath\"), outputs=\"image\")\n``` If you need grayscale input, set image_mode=\"L\" — the array shape becomes (height, width) instead of (height, width, 3). GIF and SVG Image Formats The gr.Image component can process or display any image format that is supported by the PIL library, including animated GIFs. In addition, it also supports the SVG image format. When the gr.Image component is used as an input component, the image is converted into a str filepath, a PIL.Image object, or a numpy.array, depending on the type parameter. However, animated GIF and SVG images are treated differently: Animated GIF images can only be converted to str filepaths or PIL.Image objects. If they are converted to a numpy.array (which is the default behavior), only the first frame will be used. So if your demo expects an input GIF image, make sure to set the type parameter accordingly, e.g. ```\nimport gradio as gr\n\ndemo = gr.Interface(\n    fn=lambda x:x, \n    inputs=gr.Image(type=\"filepath\"), \n    outputs=gr.Image()\n)\n    \ndemo.launch()\n``` For SVG images, the type parameter is ignored altogether and the image is always returned as an image filepath. This is because SVG images cannot be processed as PIL.Image or numpy.array objects. Demos sepia_filterfake_diffusion  Event Listeners Description Event listeners allow you to respond to user interactions with the UI\n\t\tcomponents you've defined in a Gradio Blocks app. When a user interacts with\n\t\tan element, such as changing a slider value or uploading an image, a\n\t\tfunction is called. Supported Event Listeners The Image component supports the following event listeners. Each event listener takes the\n\t\tsame parameters, which are listed in the Event Parameters table below. Listeners ```\nImage.clear(fn, ···)\n``` This listener is triggered when the user clears the Image using the clear button for the component.```\nImage.change(fn, ···)\n``` Triggered when the value of the Image changes either because of user input (e.g. a user types in a textbox) OR because of a function update (e.g. an image receives a value from the output of an event trigger). See .input() for a listener that is only triggered by user input.```\nImage.stream(fn, ···)\n``` This listener is triggered when the user streams the Image.```\nImage.select(fn, ···)\n``` Event listener for when the user selects or deselects the Image. Uses event data gradio.SelectData to carry value referring to the label of the Image, and selected to refer to state of the Image. See https://www.gradio.app/main/docs/gradio/eventdata for more details.```\nImage.upload(fn, ···)\n``` This listener is triggered when the user uploads a file into the Image.```\nImage.input(fn, ···)\n``` This listener is triggered when the user changes the value of the Image. Event Parameters Parameters ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.  Helper Classes Webcam Options ```\ngradio.WebcamOptions(···)\n``` Description A dataclass for specifying options for the webcam tool in the ImageEditor component. An instance of this class can be passed to the webcam_options parameter of gr.ImageEditor. Initialization Parameters ▼ 🔗 ```\nmirror: bool\n``` default = True If True, the webcam will be mirrored.🔗 ```\nconstraints: dict[str, Any] | None\n``` default = None A dictionary of constraints for the webcam. Streaming InputsStreaming Outputs","type":"DOCS"},{"title":"ImageEditor","slug":"/main/docs/gradio/imageeditor","content":"ImageEditor ```\ngradio.ImageEditor(···)\n``` Description Creates an image component that, as an input, can be used to upload and edit images using simple editing tools such as brushes, strokes, cropping, and layers. Or, as an output, this component can be used to display images.  Behavior Using ImageEditor as an input component. How ImageEditor will pass its value to your function: Type: EditorValue | None Passes the uploaded images as an instance of EditorValue, which is just a dict with keys: 'background', 'layers', and 'composite'.\nThe values corresponding to 'background' and 'composite' are images\nthe value corresponding to  'layers' is a list of images.\nDepending on the type parameter, the images are of type:\nPIL.Image\nnp.array\nstr filepath. Example Code \n    \n    import gradio as gr\n\n    def predict(\n        value: EditorValue | None\n    ):\n        # process value from the ImageEditor component\n        return \"prediction\"\n\n    interface = gr.Interface(predict, gr.ImageEditor(), gr.Textbox())\n    interface.launch()\n\n  Using ImageEditor as an output component How ImageEditor expects you to return a value: Type: EditorValue | ImageType | None Expects a EditorValue, which is just a dictionary with keys: 'background', 'layers', and 'composite'.\nThe values corresponding to 'background' and 'composite' should be images or None\nthe value corresponding to layers should be a list of images.\nImages can be of type:\nPIL.Image\nnp.array\nstr filepath/URL\nOr, the value can be simply a single image (ImageType), in which case it will be used as the background. Example Code \n    \n    import gradio as gr\n\n    def predict(text) -> EditorValue | ImageType | None\n        # process value to return to the ImageEditor component\n        return value\n\n    interface = gr.Interface(predict, gr.Textbox(), gr.ImageEditor())\n    interface.launch()\n\n Initialization Parameters ▼ 🔗 ```\nvalue: EditorValue | ImageType | None\n``` default = None Optional initial image(s) to populate the image editor. Should be a dictionary with keys: `background`, `layers`, and `composite`. The values corresponding to `background` and `composite` should be images or None, while `layers` should be a list of images. Images can be of type PIL.Image, np.array, or str filepath/URL. Or, the value can be a callable, in which case the function will be called whenever the app loads to set the initial value of the component.🔗 ```\nheight: int | str | None\n``` 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 files or numpy arrays, but will affect the displayed images. Beware of conflicting values with the canvas_size parameter. If the canvas_size is larger than the height, the editing canvas will not fit in the component.🔗 ```\nwidth: int | str | None\n``` 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 files or numpy arrays, but will affect the displayed images. Beware of conflicting values with the canvas_size parameter. If the canvas_size is larger than the height, the editing canvas will not fit in the component.🔗 ```\nimage_mode: Literal['1', 'L', 'P', 'RGB', 'RGBA', 'CMYK', 'YCbCr', 'LAB', 'HSV', 'I', 'F']\n``` default = \"RGBA\" &quot;RGB&quot; if color, or &quot;L&quot; if black and white. See https://pillow.readthedocs.io/en/stable/handbook/concepts.html for other supported image modes and their meaning.🔗 ```\nsources: Iterable[Literal['upload', 'webcam', 'clipboard']] | Literal['upload', 'webcam', 'clipboard'] | None\n``` default = ('upload', 'webcam', 'clipboard') List of sources that can be used to set the background image. &quot;upload&quot; creates a box where user can drop an image file, &quot;webcam&quot; allows user to take snapshot from their webcam, &quot;clipboard&quot; allows users to paste an image from the clipboard.🔗 ```\ntype: Literal['numpy', 'pil', 'filepath']\n``` default = \"numpy\" The format the images are converted to before being passed into the prediction function. &quot;numpy&quot; converts the images to numpy arrays with shape (height, width, 3) and values from 0 to 255, &quot;pil&quot; converts the images to PIL image objects, &quot;filepath&quot; passes images as str filepaths to temporary copies of the images.🔗 ```\nlabel: str | I18nData | None\n``` 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.🔗 ```\nevery: Timer | float | None\n``` default = None Continuously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.🔗 ```\ninputs: Component | list[Component] | set[Component] | None\n``` 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.🔗 ```\nshow_label: bool | None\n``` default = None if True, will display label.🔗 ```\nbuttons: list[Literal['download', 'share', 'fullscreen']] | None\n``` default = None A list of buttons to show in the corner of the component. Valid options are &quot;download&quot; to download the image, &quot;share&quot; to share to Hugging Face Spaces Discussions, and &quot;fullscreen&quot; to view in fullscreen mode. By default, all buttons are shown.🔗 ```\ncontainer: bool\n``` default = True If True, will place the component in a container - providing some extra padding around the border.🔗 ```\nscale: int | None\n``` 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.🔗 ```\nmin_width: int\n``` 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.🔗 ```\ninteractive: bool | None\n``` default = None if True, will allow users to upload and edit an image; if False, can only be used to display images. If not provided, this is inferred based on whether the component is used as an input or output.🔗 ```\nvisible: bool | Literal['hidden']\n``` default = True If False, component will be hidden. If &quot;hidden&quot;, component will be visually hidden and not take up space in the layout but still exist in the DOM🔗 ```\nelem_id: str | None\n``` 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.🔗 ```\nelem_classes: list[str] | str | None\n``` 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.🔗 ```\nrender: bool\n``` 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.🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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 &#039;preserved_by_key&#039; are not reset across a re-render.🔗 ```\npreserved_by_key: list[str] | str | None\n``` default = \"value\" A list of parameters from this component&#039;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.🔗 ```\nplaceholder: str | None\n``` default = None Custom text for the upload area. Overrides default upload messages when provided. Accepts new lines and `#` to designate a heading.🔗 ```\ntransforms: Iterable[Literal['crop', 'resize']] | None\n``` default = ('crop', 'resize') The transforms tools to make available to users. &quot;crop&quot; allows the user to crop the image.🔗 ```\neraser: Eraser | None | Literal[False]\n``` default = None The options for the eraser tool in the image editor. Should be an instance of the `gr.Eraser` class, or None to use the default settings. Can also be False to hide the eraser tool. See `gr.Eraser` docs.🔗 ```\nbrush: Brush | None | Literal[False]\n``` default = None The options for the brush tool in the image editor. Should be an instance of the `gr.Brush` class, or None to use the default settings. Can also be False to hide the brush tool, which will also hide the eraser tool. See `gr.Brush` docs.🔗 ```\nformat: str\n``` default = \"webp\" Format to save image if it does not already have a valid format (e.g. if the image is being returned to the frontend as a numpy array or PIL Image).  The format should be supported by the PIL library. This parameter has no effect on SVG files.🔗 ```\nlayers: bool | LayerOptions\n``` default = True The options for the layer tool in the image editor. Can be a boolean     or an instance of the `gr.LayerOptions` class. If True, will allow users to add layers to the image. If False, the layers option will be hidden. If an instance of `gr.LayerOptions`, it will be used to configure the layer tool. See `gr.LayerOptions` docs.🔗 ```\ncanvas_size: tuple[int, int]\n``` default = (800, 800) The initial size of the canvas in pixels. The first value is the width and the second value is the height. If `fixed_canvas` is `True`, uploaded images will be rescaled to fit the canvas size while preserving the aspect ratio. Otherwise, the canvas size will change to match the size of an uploaded image.🔗 ```\nfixed_canvas: bool\n``` default = False If True, the canvas size will not change based on the size of the background image and the image will be rescaled to fit (while preserving the aspect ratio) and placed in the center of the canvas.🔗 ```\nwebcam_options: WebcamOptions | None\n``` default = None The options for the webcam tool in the image editor. Can be an instance of the `gr.WebcamOptions` class, or None to use the default settings. See `gr.WebcamOptions` docs. Shortcuts Shortcuts ```\ngradio.ImageEditor\n``` Interface String Shortcut \"imageeditor\" Initialization Uses default values```\ngradio.Sketchpad\n``` Interface String Shortcut \"sketchpad\" Initialization Uses sources=(), brush=Brush(colors=[\"#000000\"], color_mode=\"fixed\")```\ngradio.Paint\n``` Interface String Shortcut \"paint\" Initialization Uses sources=()```\ngradio.ImageMask\n``` Interface String Shortcut \"imagemask\" Initialization Uses brush=Brush(colors=[\"#000000\"], color_mode=\"fixed\") Demos image_editor  Event Listeners Description Event listeners allow you to respond to user interactions with the UI\n\t\tcomponents you've defined in a Gradio Blocks app. When a user interacts with\n\t\tan element, such as changing a slider value or uploading an image, a\n\t\tfunction is called. Supported Event Listeners The ImageEditor component supports the following event listeners. Each event listener takes the\n\t\tsame parameters, which are listed in the Event Parameters table below. Listeners ```\nImageEditor.clear(fn, ···)\n``` This listener is triggered when the user clears the ImageEditor using the clear button for the component.```\nImageEditor.change(fn, ···)\n``` Triggered when the value of the ImageEditor 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.```\nImageEditor.input(fn, ···)\n``` This listener is triggered when the user changes the value of the ImageEditor.```\nImageEditor.select(fn, ···)\n``` Event listener for when the user selects or deselects the ImageEditor. Uses event data gradio.SelectData to carry value referring to the label of the ImageEditor, and selected to refer to state of the ImageEditor. See https://www.gradio.app/main/docs/gradio/eventdata for more details.```\nImageEditor.upload(fn, ···)\n``` This listener is triggered when the user uploads a file into the ImageEditor.```\nImageEditor.apply(fn, ···)\n``` This listener is triggered when the user applies changes to the ImageEditor through an integrated UI action. Event Parameters Parameters ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.  Helper Classes Brush ```\ngradio.Brush(···)\n``` Description A dataclass for specifying options for the brush tool in the ImageEditor component. An instance of this class can be passed to the brush parameter of gr.ImageEditor. Initialization Parameters ▼ 🔗 ```\ndefault_size: int | Literal['auto']\n``` default = \"auto\" The default radius, in pixels, of the brush tool. Defaults to &quot;auto&quot; in which case the radius is automatically determined based on the size of the image (generally 1/50th of smaller dimension).🔗 ```\ncolors: list[str | tuple[str, float]] | str | tuple[str, float] | None\n``` default = None A list of colors to make available to the user when using the brush. Defaults to a list of 5 colors.🔗 ```\ndefault_color: str | tuple[str, float] | None\n``` default = None The default color of the brush. Defaults to the first color in the `colors` list.🔗 ```\ncolor_mode: Literal['fixed', 'defaults']\n``` default = \"defaults\" If set to &quot;fixed&quot;, user can only select from among the colors in `colors`. If &quot;defaults&quot;, the colors in `colors` are provided as a default palette, but the user can also select any color using a color picker.  Eraser ```\ngradio.Eraser(···)\n``` Description A dataclass for specifying options for the eraser tool in the ImageEditor component. An instance of this class can be passed to the eraser parameter of gr.ImageEditor. Initialization Parameters ▼ 🔗 ```\ndefault_size: int | Literal['auto']\n``` default = \"auto\" The default radius, in pixels, of the eraser tool. Defaults to &quot;auto&quot; in which case the radius is automatically determined based on the size of the image (generally 1/50th of smaller dimension).  Layer Options ```\ngradio.LayerOptions(···)\n``` Description A dataclass for specifying options for the layer tool in the ImageEditor component. An instance of this class can be passed to the layers parameter of gr.ImageEditor. Initialization Parameters ▼ 🔗 ```\nallow_additional_layers: bool\n``` default = True If True, users can add additional layers to the image. If False, the add layer button will not be shown.🔗 ```\nlayers: list[str] | None\n``` default = None A list of layers to make available to the user when using the layer tool. One layer must be provided, if the length of the list is 0 then a layer will be generated automatically.🔗 ```\ndisabled: bool\n``` default = False   Webcam Options ```\ngradio.WebcamOptions(···)\n``` Description A dataclass for specifying options for the webcam tool in the ImageEditor component. An instance of this class can be passed to the webcam_options parameter of gr.ImageEditor. Initialization Parameters ▼ 🔗 ```\nmirror: bool\n``` default = True If True, the webcam will be mirrored.🔗 ```\nconstraints: dict[str, Any] | None\n``` default = None A dictionary of constraints for the webcam. ","type":"DOCS"},{"title":"ImageSlider","slug":"/main/docs/gradio/imageslider","content":"ImageSlider ```\ngradio.ImageSlider(···)\n``` Description Creates an image component that can be used to upload images (as an input) or display images (as an output).  Behavior Using ImageSlider as an input component. How ImageSlider will pass its value to your function: Type: image_tuple | None Passes the uploaded image as a tuple of numpy.array, PIL.Image or str filepath depending on type. Example Code \n    \n    import gradio as gr\n\n    def predict(\n        value: image_tuple | None\n    ):\n        # process value from the ImageSlider component\n        return \"prediction\"\n\n    interface = gr.Interface(predict, gr.ImageSlider(), gr.Textbox())\n    interface.launch()\n\n  Using ImageSlider as an output component How ImageSlider expects you to return a value: Type: tuple[np.ndarray | PIL.Image.Image | str | Path | None, np.ndarray | PIL.Image.Image | str | Path | None] | None Expects a tuple of numpy.array, PIL.Image, or str or pathlib.Path filepath to an image which is displayed. Example Code \n    \n    import gradio as gr\n\n    def predict(text) -> tuple[np.ndarray | PIL.Image.Image | str | Path | None, np.ndarray | PIL.Image.Image | str | Path | None] | None\n        # process value to return to the ImageSlider component\n        return value\n\n    interface = gr.Interface(predict, gr.Textbox(), gr.ImageSlider())\n    interface.launch()\n\n Initialization Parameters ▼ 🔗 ```\nvalue: image_tuple | Callable | None\n``` default = None A tuple of PIL Image, numpy array, path or URL for the default value that ImageSlider component is going to take, this pair of images should be of equal size. If a function is provided, the function will be called each time the app loads to set the initial value of this component.🔗 ```\nformat: str\n``` default = \"webp\" File format (e.g. &quot;png&quot; or &quot;gif&quot;). Used to save image if it does not already have a valid format (e.g. if the image is being returned to the frontend as a numpy array or PIL Image). The format should be supported by the PIL library. Applies both when this component is used as an input or output. This parameter has no effect on SVG files.🔗 ```\nheight: int | str | None\n``` default = None The height of the component, specified in pixels if a number is passed, or in CSS units if a string is passed. This has no effect on the preprocessed tuple of image file or numpy array, but will affect the displayed image.🔗 ```\nwidth: int | str | None\n``` default = None The width of the component, specified in pixels if a number is passed, or in CSS units if a string is passed. This has no effect on the preprocessed tuple of image file or numpy array, but will affect the displayed image.🔗 ```\nimage_mode: Literal['1', 'L', 'P', 'RGB', 'RGBA', 'CMYK', 'YCbCr', 'LAB', 'HSV', 'I', 'F'] | None\n``` default = \"RGB\" The pixel format and color depth that the image should be loaded and preprocessed as. &quot;RGB&quot; will load the image as a color image, or &quot;L&quot; as black-and-white. See https://pillow.readthedocs.io/en/stable/handbook/concepts.html for other supported image modes and their meaning. This parameter has no effect on SVG or GIF files. If set to None, the image_mode will be inferred from the image file types (e.g. &quot;RGBA&quot; for a .png image, &quot;RGB&quot; in most other cases).🔗 ```\ntype: Literal['numpy', 'pil', 'filepath']\n``` default = \"numpy\" The format the images are converted to before being passed into the prediction function. &quot;numpy&quot; converts the images to numpy arrays with shape (height, width, 3) and values from 0 to 255, &quot;pil&quot; converts the images to PIL image objects, &quot;filepath&quot; passes str paths to temporary files containing the images. To support animated GIFs in input, the `type` should be set to &quot;filepath&quot; or &quot;pil&quot;. To support SVGs, the `type` should be set to &quot;filepath&quot;.🔗 ```\nlabel: str | None\n``` 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.🔗 ```\nevery: Timer | float | None\n``` default = None Continuously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.🔗 ```\ninputs: Component | list[Component] | set[Component] | None\n``` 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.🔗 ```\nshow_label: bool | None\n``` default = None if True, will display label.🔗 ```\nbuttons: list[Literal['download', 'fullscreen'] | Button] | None\n``` default = None A list of buttons to show in the top right corner of the component. Valid options are &quot;download&quot;, &quot;fullscreen&quot;, or a gr.Button() instance. The &quot;download&quot; button allows the user to download the image. The &quot;fullscreen&quot; button allows the user to view the image in fullscreen mode. Custom gr.Button() instances will appear in the toolbar with their configured icon and/or label, and clicking them will trigger any .click() events registered on the button. by default, all of the built-in buttons are shown.🔗 ```\ncontainer: bool\n``` default = True If True, will place the component in a container - providing some extra padding around the border.🔗 ```\nscale: int | None\n``` 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.🔗 ```\nmin_width: int\n``` 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.🔗 ```\ninteractive: bool | None\n``` default = None if True, will allow users to upload and edit an image; if False, can only be used to display images. If not provided, this is inferred based on whether the component is used as an input or output.🔗 ```\nvisible: bool | Literal['hidden']\n``` default = True If False, component will be hidden. If &quot;hidden&quot;, component will be visually hidden and not take up space in the layout but still exist in the DOM🔗 ```\nelem_id: str | None\n``` 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.🔗 ```\nelem_classes: list[str] | str | None\n``` 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.🔗 ```\nrender: bool\n``` 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.🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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 &#039;preserved_by_key&#039; are not reset across a re-render.🔗 ```\npreserved_by_key: list[str] | str | None\n``` default = \"value\" A list of parameters from this component&#039;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.🔗 ```\nslider_position: float\n``` default = 50 The position of the slider as a percentage of the width of the image, between 0 and 100.🔗 ```\nmax_height: int\n``` default = 500 The maximum height of the image. Shortcuts Shortcuts ```\ngradio.ImageSlider\n``` Interface String Shortcut \"imageslider\" Initialization Uses default values Demos imageslider  Event Listeners Description Event listeners allow you to respond to user interactions with the UI\n\t\tcomponents you've defined in a Gradio Blocks app. When a user interacts with\n\t\tan element, such as changing a slider value or uploading an image, a\n\t\tfunction is called. Supported Event Listeners The ImageSlider component supports the following event listeners. Each event listener takes the\n\t\tsame parameters, which are listed in the Event Parameters table below. Listeners ```\nImageSlider.clear(fn, ···)\n``` This listener is triggered when the user clears the ImageSlider using the clear button for the component.```\nImageSlider.change(fn, ···)\n``` Triggered when the value of the ImageSlider changes either because of user input (e.g. a user types in a textbox) OR because of a function update (e.g. an image receives a value from the output of an event trigger). See .input() for a listener that is only triggered by user input.```\nImageSlider.stream(fn, ···)\n``` This listener is triggered when the user streams the ImageSlider.```\nImageSlider.select(fn, ···)\n``` Event listener for when the user selects or deselects the ImageSlider. Uses event data gradio.SelectData to carry value referring to the label of the ImageSlider, and selected to refer to state of the ImageSlider. See https://www.gradio.app/main/docs/gradio/eventdata for more details.```\nImageSlider.upload(fn, ···)\n``` This listener is triggered when the user uploads a file into the ImageSlider.```\nImageSlider.input(fn, ···)\n``` This listener is triggered when the user changes the value of the ImageSlider. Event Parameters Parameters ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.  ","type":"DOCS"},{"title":"JSON","slug":"/main/docs/gradio/json","content":"JSON ```\ngradio.JSON(···)\n``` Description Used to display arbitrary JSON output prettily. As this component does not accept user input, it is rarely used as an input component.  Behavior Using JSON as an input component. How JSON will pass its value to your function: Type: dict | list | None Passes the JSON value as a dict or list depending on the value. Example Code \n    \n    import gradio as gr\n\n    def predict(\n        value: dict | list | None\n    ):\n        # process value from the JSON component\n        return \"prediction\"\n\n    interface = gr.Interface(predict, gr.JSON(), gr.Textbox())\n    interface.launch()\n\n  Using JSON as an output component How JSON expects you to return a value: Type: dict | list | str | None Expects a valid JSON str -- or a list or dict that can be serialized to a JSON string. The list or dict value can contain numpy arrays. Example Code \n    \n    import gradio as gr\n\n    def predict(text) -> dict | list | str | None\n        # process value to return to the JSON component\n        return value\n\n    interface = gr.Interface(predict, gr.Textbox(), gr.JSON())\n    interface.launch()\n\n Initialization Parameters ▼ 🔗 ```\nvalue: str | dict | list | Callable | None\n``` default = None Default value as a valid JSON `str` -- or a `list` or `dict` that can be serialized to a JSON string. If a function is provided, the function will be called each time the app loads to set the initial value of this component.🔗 ```\nlabel: str | I18nData | None\n``` 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.🔗 ```\nevery: Timer | float | None\n``` default = None Continuously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.🔗 ```\ninputs: Component | list[Component] | set[Component] | None\n``` 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.🔗 ```\nshow_label: bool | None\n``` default = None if True, will display label.🔗 ```\ncontainer: bool\n``` default = True If True, will place the component in a container - providing some extra padding around the border.🔗 ```\nscale: int | None\n``` 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.🔗 ```\nmin_width: int\n``` 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.🔗 ```\nvisible: bool | Literal['hidden']\n``` default = True If False, component will be hidden. If &quot;hidden&quot;, component will be visually hidden and not take up space in the layout but still exist in the DOM🔗 ```\nelem_id: str | None\n``` 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.🔗 ```\nelem_classes: list[str] | str | None\n``` 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.🔗 ```\nrender: bool\n``` 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.🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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 &#039;preserved_by_key&#039; are not reset across a re-render.🔗 ```\npreserved_by_key: list[str] | str | None\n``` default = \"value\" A list of parameters from this component&#039;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.🔗 ```\nopen: bool\n``` default = False If True, all JSON nodes will be expanded when rendered. By default, node levels deeper than 3 are collapsed.🔗 ```\nshow_indices: bool\n``` default = False Whether to show numerical indices when displaying the elements of a list within the JSON object.🔗 ```\nheight: int | str | None\n``` default = None Height of the JSON component in pixels if a number is passed, or in CSS units if a string is passed. Overflow will be scrollable. If None, the height will be automatically adjusted to fit the content.🔗 ```\nmax_height: int | str | None\n``` default = 500 🔗 ```\nmin_height: int | str | None\n``` default = None 🔗 ```\nbuttons: list[Literal['copy'] | Button] | None\n``` default = None A list of buttons to show for the component. Valid options are &quot;copy&quot; or a gr.Button() instance. The &quot;copy&quot; button allows users to copy the JSON to the clipboard. Custom gr.Button() instances will appear in the toolbar with their configured icon and/or label, and clicking them will trigger any .click() events registered on the button. By default, the copy button is shown. Shortcuts Shortcuts ```\ngradio.JSON\n``` Interface String Shortcut \"json\" Initialization Uses default values Demos zip_to_jsonblocks_xray  Event Listeners Description Event listeners allow you to respond to user interactions with the UI\n\t\tcomponents you've defined in a Gradio Blocks app. When a user interacts with\n\t\tan element, such as changing a slider value or uploading an image, a\n\t\tfunction is called. Supported Event Listeners The JSON component supports the following event listeners. Each event listener takes the\n\t\tsame parameters, which are listed in the Event Parameters table below. Listeners ```\nJSON.change(fn, ···)\n``` Triggered when the value of the JSON changes either because of user input (e.g. a user types in a textbox) OR because of a function update (e.g. an image receives a value from the output of an event trigger). See .input() for a listener that is only triggered by user input. Event Parameters Parameters ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.  ","type":"DOCS"},{"title":"Label","slug":"/main/docs/gradio/label","content":"Label ```\ngradio.Label(···)\n``` Description Displays a classification label, along with confidence scores of top categories, if provided. As this component does not accept user input, it is rarely used as an input component.  Behavior Using Label as an input component. How Label will pass its value to your function: Type: dict[str, float] | str | int | float | None Depending on the value, passes the label as a str | int | float, or the labels and confidences as a dict[str, float]. Example Code \n    \n    import gradio as gr\n\n    def predict(\n        value: dict[str, float] | str | int | float | None\n    ):\n        # process value from the Label component\n        return \"prediction\"\n\n    interface = gr.Interface(predict, gr.Label(), gr.Textbox())\n    interface.launch()\n\n  Using Label as an output component How Label expects you to return a value: Type: dict[str | float, float] | str | int | float | None Expects a dict[str, float] of classes and confidences, or str with just the class or an int | float for regression outputs, or a str path to a .json file containing a json dictionary in one of the preceding formats. Example Code \n    \n    import gradio as gr\n\n    def predict(text) -> dict[str | float, float] | str | int | float | None\n        # process value to return to the Label component\n        return value\n\n    interface = gr.Interface(predict, gr.Textbox(), gr.Label())\n    interface.launch()\n\n Initialization Parameters ▼ 🔗 ```\nvalue: dict[str, float] | str | float | Callable | None\n``` default = None Default value to show in the component. If a str or number is provided, simply displays the string or number. If a {Dict[str, float]} of classes and confidences is provided, displays the top class on top and the `num_top_classes` below, along with their confidence bars. If a function is provided, the function will be called each time the app loads to set the initial value of this component.🔗 ```\nnum_top_classes: int | None\n``` default = None number of most confident classes to show.🔗 ```\nlabel: str | I18nData | None\n``` 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.🔗 ```\nevery: Timer | float | None\n``` default = None Continuously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.🔗 ```\ninputs: Component | list[Component] | set[Component] | None\n``` 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.🔗 ```\nshow_label: bool | None\n``` default = None if True, will display label.🔗 ```\ncontainer: bool\n``` default = True If True, will place the component in a container - providing some extra padding around the border.🔗 ```\nscale: int | None\n``` 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.🔗 ```\nmin_width: int\n``` 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.🔗 ```\nvisible: bool | Literal['hidden']\n``` default = True If False, component will be hidden. If &quot;hidden&quot;, component will be visually hidden and not take up space in the layout but still exist in the DOM🔗 ```\nelem_id: str | None\n``` 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.🔗 ```\nelem_classes: list[str] | str | None\n``` 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.🔗 ```\nrender: bool\n``` 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.🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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 &#039;preserved_by_key&#039; are not reset across a re-render.🔗 ```\npreserved_by_key: list[str] | str | None\n``` default = \"value\" A list of parameters from this component&#039;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.🔗 ```\ncolor: str | None\n``` default = None The background color of the label (either a valid css color name or hexadecimal string).🔗 ```\nshow_heading: bool\n``` default = True If False, the heading will not be displayed if a dictionary of labels and confidences is provided. The heading will still be visible if the value is a string or number.🔗 ```\nbuttons: list[Button] | None\n``` default = None A list of gr.Button() instances to show in the top right corner of the component. Custom buttons will appear in the toolbar with their configured icon and/or label, and clicking them will trigger any .click() events registered on the button. Shortcuts Shortcuts ```\ngradio.Label\n``` Interface String Shortcut \"label\" Initialization Uses default values  Event Listeners Description Event listeners allow you to respond to user interactions with the UI\n\t\tcomponents you've defined in a Gradio Blocks app. When a user interacts with\n\t\tan element, such as changing a slider value or uploading an image, a\n\t\tfunction is called. Supported Event Listeners The Label component supports the following event listeners. Each event listener takes the\n\t\tsame parameters, which are listed in the Event Parameters table below. Listeners ```\nLabel.change(fn, ···)\n``` Triggered when the value of the Label 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.```\nLabel.select(fn, ···)\n``` Event listener for when the user selects or deselects the Label. Uses event data gradio.SelectData to carry value referring to the label of the Label, and selected to refer to state of the Label. See https://www.gradio.app/main/docs/gradio/eventdata for more details. Event Parameters Parameters ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.  Image Classification In PytorchImage Classification With Vision Transformers","type":"DOCS"},{"title":"LinePlot","slug":"/main/docs/gradio/lineplot","content":"LinePlot ```\ngradio.LinePlot(···)\n``` Description Creates a line plot component to display data from a pandas DataFrame.  Behavior Using LinePlot as an input component. How LinePlot will pass its value to your function: Type: PlotData | None The data to display in a line plot. Example Code \n    \n    import gradio as gr\n\n    def predict(\n        value: PlotData | None\n    ):\n        # process value from the LinePlot component\n        return \"prediction\"\n\n    interface = gr.Interface(predict, gr.LinePlot(), gr.Textbox())\n    interface.launch()\n\n  Using LinePlot as an output component How LinePlot expects you to return a value: Type: pd.DataFrame | dict | None Expects a pandas DataFrame containing the data to display in the line plot. The DataFrame should contain at least two columns:\none for the x-axis (corresponding to this component's x argument)\none for the y-axis (corresponding to y). Example Code \n    \n    import gradio as gr\n\n    def predict(text) -> pd.DataFrame | dict | None\n        # process value to return to the LinePlot component\n        return value\n\n    interface = gr.Interface(predict, gr.Textbox(), gr.LinePlot())\n    interface.launch()\n\n Initialization Parameters ▼ 🔗 ```\nvalue: pd.DataFrame | Callable | None\n``` default = None The pandas dataframe containing the data to display in the plot.🔗 ```\nx: str | None\n``` default = None Column corresponding to the x axis. Column can be numeric, datetime, or string/category.🔗 ```\ny: str | None\n``` default = None Column corresponding to the y axis. Column must be numeric.🔗 ```\ncolor: str | None\n``` default = None Column corresponding to series, visualized by color. Column must be string/category.🔗 ```\ntitle: str | None\n``` default = None The title to display on top of the chart.🔗 ```\nx_title: str | None\n``` default = None The title given to the x axis. By default, uses the value of the x parameter.🔗 ```\ny_title: str | None\n``` default = None The title given to the y axis. By default, uses the value of the y parameter.🔗 ```\ncolor_title: str | None\n``` default = None The title given to the color legend. By default, uses the value of color parameter.🔗 ```\nx_bin: str | float | None\n``` default = None Grouping used to cluster x values. If x column is numeric, should be number to bin the x values. If x column is datetime, should be string such as &quot;1h&quot;, &quot;15m&quot;, &quot;10s&quot;, using &quot;s&quot;, &quot;m&quot;, &quot;h&quot;, &quot;d&quot; suffixes.🔗 ```\ny_aggregate: Literal['sum', 'mean', 'median', 'min', 'max', 'count'] | None\n``` default = None Aggregation function used to aggregate y values, used if x_bin is provided or x is a string/category. Must be one of &quot;sum&quot;, &quot;mean&quot;, &quot;median&quot;, &quot;min&quot;, &quot;max&quot;.🔗 ```\ncolor_map: dict[str, str] | None\n``` default = None Mapping of series to color names or codes. For example, {&quot;success&quot;: &quot;green&quot;, &quot;fail&quot;: &quot;#FF8888&quot;}.🔗 ```\ncolors_in_legend: list[str] | None\n``` default = None List containing column names of the series to show in the legend. By default, all series are shown.🔗 ```\nx_lim: list[float | None] | None\n``` default = None A tuple or list containing the limits for the x-axis, specified as [x_min, x_max]. To fix only one of these values, set the other to None, e.g. [0, None] to scale from 0 to the maximum value. If x column is datetime type, x_lim should be timestamps.🔗 ```\ny_lim: list[float | None]\n``` default = None A tuple of list containing the limits for the y-axis, specified as [y_min, y_max]. To fix only one of these values, set the other to None, e.g. [0, None] to scale from 0 to the maximum to value.🔗 ```\nx_label_angle: float\n``` default = 0 The angle of the x-axis labels in degrees offset clockwise.🔗 ```\ny_label_angle: float\n``` default = 0 The angle of the y-axis labels in degrees offset clockwise.🔗 ```\nx_axis_format: str | None\n``` default = None A d3 format string for the x-axis labels (e.g., &quot;.2e&quot; for scientific notation, &quot;~g&quot; for general format). If None, uses Vega-Lite&#039;s default formatting.🔗 ```\ny_axis_format: str | None\n``` default = None A d3 format string for the y-axis labels (e.g., &quot;.2e&quot; for scientific notation, &quot;~g&quot; for general format). If None, uses Vega-Lite&#039;s default formatting.🔗 ```\nx_axis_labels_visible: bool | Literal['hidden']\n``` default = True Whether the x-axis labels should be visible. Can be hidden when many x-axis labels are present.🔗 ```\ncaption: str | I18nData | None\n``` default = None The (optional) caption to display below the plot.🔗 ```\nsort: Literal['x', 'y', '-x', '-y'] | list[str] | None\n``` default = None The sorting order of the x values, if x column is type string/category. Can be &quot;x&quot;, &quot;y&quot;, &quot;-x&quot;, &quot;-y&quot;, or list of strings that represent the order of the categories.🔗 ```\ntooltip: Literal['axis', 'none', 'all'] | list[str]\n``` default = \"axis\" The tooltip to display when hovering on a point. &quot;axis&quot; shows the values for the axis columns, &quot;all&quot; shows all column values, and &quot;none&quot; shows no tooltips. Can also provide a list of strings representing columns to show in the tooltip, which will be displayed along with axis values.🔗 ```\nheight: int | None\n``` default = None The height of the plot in pixels.🔗 ```\nlabel: str | I18nData | None\n``` default = None The (optional) label to display on the top left corner of the plot.🔗 ```\nshow_label: bool | None\n``` default = None Whether the label should be displayed.🔗 ```\ncontainer: bool\n``` default = True If True, will place the component in a container - providing some extra padding around the border.🔗 ```\nscale: int | None\n``` 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.🔗 ```\nmin_width: int\n``` 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.🔗 ```\nevery: Timer | float | None\n``` default = None Continuously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.🔗 ```\ninputs: Component | list[Component] | Set[Component] | None\n``` 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.🔗 ```\nvisible: bool | Literal['hidden']\n``` default = True Whether the plot should be visible.🔗 ```\nelem_id: str | None\n``` 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.🔗 ```\nelem_classes: list[str] | str | None\n``` 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.🔗 ```\nrender: bool\n``` 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.🔗 ```\nbuttons: list[Literal['fullscreen', 'export'] | Button] | None\n``` default = None A list of buttons to show for the component. Valid options are &quot;fullscreen&quot;, &quot;export&quot;, or a gr.Button() instance. The &quot;fullscreen&quot; button allows the user to view the plot in fullscreen mode. The &quot;export&quot; button allows the user to export and download the current view of the plot as a PNG image. Custom gr.Button() instances will appear in the toolbar with their configured icon and/or label, and clicking them will trigger any .click() events registered on the button. By default, no buttons are shown.🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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 &#039;preserved_by_key&#039; are not reset across a re-render.🔗 ```\npreserved_by_key: list[str] | str | None\n``` default = \"value\" A list of parameters from this component&#039;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. Key Concepts gr.LinePlot, gr.ScatterPlot, and gr.BarPlot all share the same API. Here is a summary of the most important features. For full details and live demos, see the Creating Plots and Time Plots guides. Basic Usage with a DataFrame Pass a pd.DataFrame as the value, and specify x and y column names. The y-axis must be numeric; the x-axis can be strings, numbers, categories, or datetimes. ```\nimport gradio as gr\nimport pandas as pd\n\ndf = pd.DataFrame({\"week\": [1, 2, 3, 4], \"price\": [10, 25, 18, 30]})\n\nwith gr.Blocks() as demo:\n    gr.LinePlot(df, x=\"week\", y=\"price\")\n``` Breaking Out Series by Color Use the color argument to split data into multiple series. Use color_map to assign specific colors: ```\ngr.LinePlot(df, x=\"week\", y=\"price\", color=\"origin\",\n            color_map={\"US\": \"#FF9988\", \"EU\": \"#88EEAA\"})\n``` Aggregating Values Use x_bin and y_aggregate to group and summarize data. For numeric x-axes, x_bin creates histogram-style bins. For string x-axes, strings act as category bins automatically: ```\ngr.LinePlot(df, x=\"week\", y=\"price\", x_bin=2, y_aggregate=\"mean\")\n``` For time-series data, pass a string suffix (\"s\", \"m\", \"h\", or \"d\") to x_bin: ```\ngr.LinePlot(df, x=\"timestamp\", y=\"price\", x_bin=\"1d\", y_aggregate=\"mean\")\n``` Interactive Selection and Zoom Use the .select event listener to respond to region selections (click and drag). Combine with .double_click and x_lim to implement zoom in/out: ```\nwith gr.Blocks() as demo:\n    plot = gr.LinePlot(df, x=\"week\", y=\"price\")\n\n    @plot.select\n    def zoom(selection: gr.SelectData):\n        return gr.LinePlot(x_lim=[selection.index[0], selection.index[1]])\n\n    plot.double_click(lambda: gr.LinePlot(x_lim=None), outputs=plot)\n``` Realtime Data Use gr.Timer to keep plots updated with live data. You can attach the timer via every, or wire it up manually: ```\ndef get_data():\n    return pd.DataFrame(...)  # fetch latest data\n\nwith gr.Blocks() as demo:\n    timer = gr.Timer(5)\n    plot = gr.LinePlot(get_data, x=\"time\", y=\"price\", every=timer)\n``` Interactive Dashboards Plots can be driven by other components (dropdowns, sliders, etc.) to create fully interactive dashboards: ```\nwith gr.Blocks() as demo:\n    origin = gr.Dropdown(choices=[\"US\", \"EU\", \"Asia\"], value=\"US\")\n    plot = gr.LinePlot(x=\"week\", y=\"price\")\n\n    def update(origin):\n        filtered = df[df[\"origin\"] == origin]\n        return gr.LinePlot(filtered)\n\n    origin.change(update, inputs=origin, outputs=plot)\n``` Shortcuts Shortcuts ```\ngradio.LinePlot\n``` Interface String Shortcut \"lineplot\" Initialization Uses default values Demos line_plot_demo  Event Listeners Description Event listeners allow you to respond to user interactions with the UI\n\t\tcomponents you've defined in a Gradio Blocks app. When a user interacts with\n\t\tan element, such as changing a slider value or uploading an image, a\n\t\tfunction is called. Supported Event Listeners The LinePlot component supports the following event listeners. Each event listener takes the\n\t\tsame parameters, which are listed in the Event Parameters table below. Listeners ```\nLinePlot.change(fn, ···)\n``` Triggered when the value of the NativePlot 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.```\nLinePlot.select(fn, ···)\n``` Event listener for when the user selects or deselects the NativePlot. Uses event data gradio.SelectData to carry value referring to the label of the NativePlot, and selected to refer to state of the NativePlot. See https://www.gradio.app/main/docs/gradio/eventdata for more details.```\nLinePlot.double_click(fn, ···)\n``` Triggered when the NativePlot is double clicked. Event Parameters Parameters ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.  Creating PlotsConnecting To A Database","type":"DOCS"},{"title":"LoginButton","slug":"/main/docs/gradio/loginbutton","content":"LoginButton ```\ngradio.LoginButton(···)\n``` Description Creates a \"Sign In\" button that redirects the user to sign in with Hugging Face OAuth. Once the user is signed in, the button will act as a logout button, and you can retrieve a signed-in user's profile by adding a parameter of type gr.OAuthProfile to any Gradio function. This will only work if this Gradio app is running in a Hugging Face Space. Permissions for the OAuth app can be configured in the Spaces README file, as described here: https://huggingface.co/docs/hub/en/spaces-oauth. For local development, instead of OAuth, the local Hugging Face account that is logged in (via hf auth login) will be available through the gr.OAuthProfile object.  Behavior Using LoginButton as an input component. How LoginButton will pass its value to your function: Type: str | None (Rarely used) the str corresponding to the button label when the button is clicked Example Code \n    \n    import gradio as gr\n\n    def predict(\n        value: str | None\n    ):\n        # process value from the LoginButton component\n        return \"prediction\"\n\n    interface = gr.Interface(predict, gr.LoginButton(), gr.Textbox())\n    interface.launch()\n\n  Using LoginButton as an output component How LoginButton expects you to return a value: Type: str | None string corresponding to the button label Example Code \n    \n    import gradio as gr\n\n    def predict(text) -> str | None\n        # process value to return to the LoginButton component\n        return value\n\n    interface = gr.Interface(predict, gr.Textbox(), gr.LoginButton())\n    interface.launch()\n\n Initialization Parameters ▼ 🔗 ```\nvalue: str\n``` default = \"Sign in with Hugging Face\" 🔗 ```\nlogout_value: str\n``` default = \"Logout ({})\" The text to display when the user is signed in. The string should contain a placeholder for the username with a call-to-action to logout, e.g. &quot;Logout ({})&quot;.🔗 ```\nevery: Timer | float | None\n``` default = None 🔗 ```\ninputs: Component | list[Component] | set[Component] | None\n``` default = None 🔗 ```\nvariant: Literal['primary', 'secondary', 'stop', 'huggingface']\n``` default = \"huggingface\" 🔗 ```\nsize: Literal['sm', 'md', 'lg']\n``` default = \"lg\" 🔗 ```\nicon: str | Path | None\n``` default = \"/home/runner/work/gradio/gradio/gradio/icons/huggingface-logo.svg\" 🔗 ```\nlink: str | None\n``` default = None 🔗 ```\nlink_target: Literal['_self', '_blank', '_parent', '_top']\n``` default = \"_self\" 🔗 ```\nvisible: bool | Literal['hidden']\n``` default = True 🔗 ```\ninteractive: bool\n``` default = True 🔗 ```\nelem_id: str | None\n``` default = None 🔗 ```\nelem_classes: list[str] | str | None\n``` default = None 🔗 ```\nrender: bool\n``` default = True 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` default = None 🔗 ```\npreserved_by_key: list[str] | str | None\n``` default = \"value\" 🔗 ```\nscale: int | None\n``` default = None 🔗 ```\nmin_width: int | None\n``` default = None  Shortcuts Shortcuts ```\ngradio.LoginButton\n``` Interface String Shortcut \"loginbutton\" Initialization Uses default values Demos login_with_huggingface  Event Listeners Description Event listeners allow you to respond to user interactions with the UI\n\t\tcomponents you've defined in a Gradio Blocks app. When a user interacts with\n\t\tan element, such as changing a slider value or uploading an image, a\n\t\tfunction is called. Supported Event Listeners The LoginButton component supports the following event listeners. Each event listener takes the\n\t\tsame parameters, which are listed in the Event Parameters table below. Listeners ```\nLoginButton.change(fn, ···)\n``` Triggered when the value of the Button 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.```\nLoginButton.click(fn, ···)\n``` Triggered when the Button is clicked. Event Parameters Parameters ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.  Sharing Your App","type":"DOCS"},{"title":"Markdown","slug":"/main/docs/gradio/markdown","content":"Markdown ```\ngradio.Markdown(···)\n``` Description Used to render arbitrary Markdown output. Can also render latex enclosed by dollar signs as well as code blocks with syntax highlighting. Supported languages are bash, c, cpp, go, java, javascript, json, php, python, rust, sql, and yaml. As this component does not accept user input, it is rarely used as an input component.  Behavior Using Markdown as an input component. How Markdown will pass its value to your function: Type: str | None Passes the str of Markdown corresponding to the displayed value. Example Code \n    \n    import gradio as gr\n\n    def predict(\n        value: str | None\n    ):\n        # process value from the Markdown component\n        return \"prediction\"\n\n    interface = gr.Interface(predict, gr.Markdown(), gr.Textbox())\n    interface.launch()\n\n  Using Markdown as an output component How Markdown expects you to return a value: Type: str | I18nData | None Expects a valid str that can be rendered as Markdown. Example Code \n    \n    import gradio as gr\n\n    def predict(text) -> str | I18nData | None\n        # process value to return to the Markdown component\n        return value\n\n    interface = gr.Interface(predict, gr.Textbox(), gr.Markdown())\n    interface.launch()\n\n Initialization Parameters ▼ 🔗 ```\nvalue: str | I18nData | Callable | None\n``` 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.🔗 ```\nlabel: str | I18nData | None\n``` default = None This parameter has no effect🔗 ```\nevery: Timer | float | None\n``` default = None Continuously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.🔗 ```\ninputs: Component | list[Component] | set[Component] | None\n``` 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.🔗 ```\nshow_label: bool | None\n``` default = None This parameter has no effect.🔗 ```\nscale: int | None\n``` 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.🔗 ```\nmin_width: int | None\n``` default = None minimum pixel width, will wrap if not sufficient screen space to satisfy this value. If a certain scale value results in this Component being narrower than min_width, the min_width parameter will be respected first.🔗 ```\nrtl: bool\n``` default = False If True, sets the direction of the rendered text to right-to-left. Default is False, which renders text left-to-right.🔗 ```\nlatex_delimiters: list[dict[str, str | bool]] | None\n``` default = None A list of dicts of the form {&quot;left&quot;: open delimiter (str), &quot;right&quot;: close delimiter (str), &quot;display&quot;: whether to display in newline (bool)} that will be used to render LaTeX expressions. If not provided, `latex_delimiters` is set to `[{ &quot;left&quot;: &quot;$$&quot;, &quot;right&quot;: &quot;$$&quot;, &quot;display&quot;: 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.🔗 ```\nvisible: bool | Literal['hidden']\n``` default = True If False, component will be hidden. If &quot;hidden&quot;, component will be visually hidden and not take up space in the layout but still exist in the DOM🔗 ```\nelem_id: str | None\n``` 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.🔗 ```\nelem_classes: list[str] | str | None\n``` 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.🔗 ```\nrender: bool\n``` 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.🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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 &#039;preserved_by_key&#039; are not reset across a re-render.🔗 ```\npreserved_by_key: list[str] | str | None\n``` default = \"value\" A list of parameters from this component&#039;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.🔗 ```\nsanitize_html: bool\n``` default = True If False, will disable HTML sanitization when converted from markdown. This is not recommended, as it can lead to security vulnerabilities.🔗 ```\nline_breaks: bool\n``` default = False If True, will enable Github-flavored Markdown line breaks in chatbot messages. If False (default), single new lines will be ignored.🔗 ```\nheader_links: bool\n``` default = False If True, will automatically create anchors for headings, displaying a link icon on hover.🔗 ```\nheight: int | str | None\n``` 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.🔗 ```\nmax_height: int | str | None\n``` 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`.🔗 ```\nmin_height: int | str | None\n``` 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`.🔗 ```\nbuttons: list[Literal['copy']] | None\n``` default = None A list of buttons to show for the component. Currently, the only valid option is &quot;copy&quot;. The &quot;copy&quot; button allows the user to copy the text in the Markdown component. By default, no buttons are shown.🔗 ```\ncontainer: bool\n``` default = False If True, the Markdown component will be displayed in a container. Default is False.🔗 ```\npadding: bool\n``` 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. Shortcuts Shortcuts ```\ngradio.Markdown\n``` Interface String Shortcut \"markdown\" Initialization Uses default values Demos blocks_helloblocks_kinematics  Event Listeners Description Event listeners allow you to respond to user interactions with the UI\n\t\tcomponents you've defined in a Gradio Blocks app. When a user interacts with\n\t\tan element, such as changing a slider value or uploading an image, a\n\t\tfunction is called. Supported Event Listeners The Markdown component supports the following event listeners. Each event listener takes the\n\t\tsame parameters, which are listed in the Event Parameters table below. Listeners ```\nMarkdown.change(fn, ···)\n``` 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.```\nMarkdown.copy(fn, ···)\n``` 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 ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.  ","type":"DOCS"},{"title":"Model3D","slug":"/main/docs/gradio/model3d","content":"Model3D ```\ngradio.Model3D(···)\n``` Description Creates a component allows users to upload or view 3D Model files (.obj, .glb, .stl, .gltf, .splat, or .ply).  Behavior Using Model3D as an input component. How Model3D will pass its value to your function: Type: str | None Passes the uploaded file as a str filepath to the function. Example Code \n    \n    import gradio as gr\n\n    def predict(\n        value: str | None\n    ):\n        # process value from the Model3D component\n        return \"prediction\"\n\n    interface = gr.Interface(predict, gr.Model3D(), gr.Textbox())\n    interface.launch()\n\n  Using Model3D as an output component How Model3D expects you to return a value: Type: str | Path | None Expects function to return a str or pathlib.Path filepath of type (.obj, .glb, .stl, or .gltf) Example Code \n    \n    import gradio as gr\n\n    def predict(text) -> str | Path | None\n        # process value to return to the Model3D component\n        return value\n\n    interface = gr.Interface(predict, gr.Textbox(), gr.Model3D())\n    interface.launch()\n\n Initialization Parameters ▼ 🔗 ```\nvalue: str | Callable | None\n``` default = None path to (.obj, .glb, .stl, .gltf, .splat, or .ply) file to show in model3D viewer. If a function is provided, the function will be called each time the app loads to set the initial value of this component.🔗 ```\ndisplay_mode: Literal['solid', 'point_cloud', 'wireframe'] | None\n``` default = None the display mode of the 3D model in the scene. Can be &quot;solid&quot; (which renders the model as a solid object), &quot;point_cloud&quot;, or &quot;wireframe&quot;. For .splat files, and for .ply files holding a Gaussian splat, this parameter is ignored, as those can only be rendered as solid objects.🔗 ```\nclear_color: tuple[float, float, float, float] | None\n``` default = None background color of scene, should be a tuple of 4 floats between 0 and 1 representing RGBA values.🔗 ```\ncamera_position: tuple[int | float | None, int | float | None, int | float | None]\n``` default = (None, None, None) initial camera position of scene, provided as a tuple of `(alpha, beta, radius)`. Each value is optional. If provided, `alpha` and `beta` should be in degrees reflecting the angular position along the longitudinal and latitudinal axes, respectively. Radius corresponds to the distance from the center of the object to the camera.🔗 ```\nzoom_speed: float\n``` default = 1 the speed of zooming in and out of the scene when the cursor wheel is rotated or when screen is pinched on a mobile device. Should be a positive float, increase this value to make zooming faster, decrease to make it slower. Affects the wheelPrecision property of the camera.🔗 ```\npan_speed: float\n``` default = 1 the speed of panning the scene when the cursor is dragged or when the screen is dragged on a mobile device. Should be a positive float, increase this value to make panning faster, decrease to make it slower. Affects the panSensibility property of the camera.🔗 ```\nheight: int | str | None\n``` default = None The height of the model3D component, specified in pixels if a number is passed, or in CSS units if a string is passed.🔗 ```\nlabel: str | I18nData | None\n``` 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.🔗 ```\nshow_label: bool | None\n``` default = None if True, will display label.🔗 ```\nevery: Timer | float | None\n``` default = None Continuously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.🔗 ```\ninputs: Component | list[Component] | set[Component] | None\n``` 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.🔗 ```\ncontainer: bool\n``` default = True If True, will place the component in a container - providing some extra padding around the border.🔗 ```\nscale: int | None\n``` 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.🔗 ```\nmin_width: int\n``` 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.🔗 ```\ninteractive: bool | None\n``` default = None if True, will allow users to upload a file; if False, can only be used to display files. If not provided, this is inferred based on whether the component is used as an input or output.🔗 ```\nvisible: bool | Literal['hidden']\n``` default = True If False, component will be hidden. If &quot;hidden&quot;, component will be visually hidden and not take up space in the layout but still exist in the DOM🔗 ```\nelem_id: str | None\n``` 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.🔗 ```\nelem_classes: list[str] | str | None\n``` 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.🔗 ```\nrender: bool\n``` 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.🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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 &#039;preserved_by_key&#039; are not reset across a re-render.🔗 ```\npreserved_by_key: list[str] | str | None\n``` default = \"value\" A list of parameters from this component&#039;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.🔗 ```\nbuttons: list[Button] | None\n``` default = None A list of gr.Button() instances to show in the top right corner of the component. Custom buttons will appear in the toolbar with their configured icon and/or label, and clicking them will trigger any .click() events registered on the button. Shortcuts Shortcuts ```\ngradio.Model3D\n``` Interface String Shortcut \"model3d\" Initialization Uses default values  Event Listeners Description Event listeners allow you to respond to user interactions with the UI\n\t\tcomponents you've defined in a Gradio Blocks app. When a user interacts with\n\t\tan element, such as changing a slider value or uploading an image, a\n\t\tfunction is called. Supported Event Listeners The Model3D component supports the following event listeners. Each event listener takes the\n\t\tsame parameters, which are listed in the Event Parameters table below. Listeners ```\nModel3D.change(fn, ···)\n``` Triggered when the value of the Model3D 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.```\nModel3D.upload(fn, ···)\n``` This listener is triggered when the user uploads a file into the Model3D.```\nModel3D.edit(fn, ···)\n``` This listener is triggered when the user edits the Model3D (e.g. image) using the built-in editor.```\nModel3D.clear(fn, ···)\n``` This listener is triggered when the user clears the Model3D using the clear button for the component. Event Parameters Parameters ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.  How To Use 3D Model Component","type":"DOCS"},{"title":"MultimodalTextbox","slug":"/main/docs/gradio/multimodaltextbox","content":"MultimodalTextbox ```\ngradio.MultimodalTextbox(···)\n``` Description Creates a textarea for users to enter string input or display string output and also allows for the uploading of multimedia files.  Behavior Using MultimodalTextbox as an input component. How MultimodalTextbox will pass its value to your function: Type: MultimodalValue | None Passes text value and list of file(s) as a dict into the function. Example Code \n    \n    import gradio as gr\n\n    def predict(\n        value: MultimodalValue | None\n    ):\n        # process value from the MultimodalTextbox component\n        return \"prediction\"\n\n    interface = gr.Interface(predict, gr.MultimodalTextbox(), gr.Textbox())\n    interface.launch()\n\n  Using MultimodalTextbox as an output component How MultimodalTextbox expects you to return a value: Type: MultimodalValue | str | None Expects a dict with \"text\" and \"files\", both optional. The files array is a list of file paths or URLs. Example Code \n    \n    import gradio as gr\n\n    def predict(text) -> MultimodalValue | str | None\n        # process value to return to the MultimodalTextbox component\n        return value\n\n    interface = gr.Interface(predict, gr.Textbox(), gr.MultimodalTextbox())\n    interface.launch()\n\n Initialization Parameters ▼ 🔗 ```\nvalue: str | dict[str, str | list] | Callable | None\n``` default = None Default value to show in MultimodalTextbox. A string value, or a dictionary of the form {&quot;text&quot;: &quot;sample text&quot;, &quot;files&quot;: [{path: &quot;files/file.jpg&quot;, orig_name: &quot;file.jpg&quot;, url: &quot;http://image_url.jpg&quot;, size: 100}]}. If a function is provided, the function will be called each time the app loads to set the initial value of this component.🔗 ```\nsources: list[Literal['upload', 'microphone']] | Literal['upload', 'microphone'] | None\n``` default = None A list of sources permitted. &quot;upload&quot; creates a button where users can click to upload or drop files, &quot;microphone&quot; creates a microphone input. If None, defaults to [&quot;upload&quot;].🔗 ```\nfile_types: list[str] | None\n``` default = None List of file extensions or types of files to be uploaded (e.g. [&#039;image&#039;, &#039;.json&#039;, &#039;.mp4&#039;]). &quot;file&quot; allows any file to be uploaded, &quot;image&quot; allows only image files to be uploaded, &quot;audio&quot; allows only audio files to be uploaded, &quot;video&quot; allows only video files to be uploaded, &quot;text&quot; allows only text files to be uploaded.🔗 ```\nfile_count: Literal['single', 'multiple', 'directory']\n``` default = \"single\" if single, allows user to upload one file. If &quot;multiple&quot;, user uploads multiple files. If &quot;directory&quot;, user uploads all files in selected directory. Return type will be list for each file in case of &quot;multiple&quot; or &quot;directory&quot;.🔗 ```\nlines: int\n``` default = 1 minimum number of line rows to provide in textarea.🔗 ```\nmax_lines: int\n``` default = 20 maximum number of line rows to provide in textarea.🔗 ```\nplaceholder: str | None\n``` default = None placeholder hint to provide behind textarea.🔗 ```\nlabel: str | I18nData | None\n``` 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.🔗 ```\ninfo: str | I18nData | None\n``` default = None additional component description, appears below the label in smaller font. Supports markdown / HTML syntax.🔗 ```\nevery: Timer | float | None\n``` default = None Continuously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.🔗 ```\ninputs: Component | list[Component] | set[Component] | None\n``` 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.🔗 ```\nshow_label: bool | None\n``` default = None if True, will display label.🔗 ```\ncontainer: bool\n``` default = True If True, will place the component in a container - providing some extra padding around the border.🔗 ```\nscale: int | None\n``` 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.🔗 ```\nmin_width: int\n``` 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.🔗 ```\ninteractive: bool | None\n``` default = None if True, will be rendered as an editable textbox; if False, editing will be disabled. If not provided, this is inferred based on whether the component is used as an input or output.🔗 ```\nvisible: bool | Literal['hidden']\n``` default = True If False, component will be hidden. If &quot;hidden&quot;, component will be visually hidden and not take up space in the layout but still exist in the DOM🔗 ```\nelem_id: str | None\n``` 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.🔗 ```\nautofocus: bool\n``` default = False If True, will focus on the textbox when the page loads. Use this carefully, as it can cause usability issues for sighted and non-sighted users.🔗 ```\nautoscroll: bool\n``` default = True If True, will automatically scroll to the bottom of the textbox when the value changes, unless the user scrolls up. If False, will not scroll to the bottom of the textbox when the value changes.🔗 ```\nelem_classes: list[str] | str | None\n``` 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.🔗 ```\nrender: bool\n``` 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.🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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 &#039;preserved_by_key&#039; are not reset across a re-render.🔗 ```\npreserved_by_key: list[str] | str | None\n``` default = \"value\" A list of parameters from this component&#039;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.🔗 ```\ntext_align: Literal['left', 'right'] | None\n``` default = None How to align the text in the textbox, can be: &quot;left&quot;, &quot;right&quot;, or None (default). If None, the alignment is left if `rtl` is False, or right if `rtl` is True. Can only be changed if `type` is &quot;text&quot;.🔗 ```\nrtl: bool\n``` default = False If True and `type` is &quot;text&quot;, sets the direction of the text to right-to-left (cursor appears on the left of the text). Default is False, which renders cursor on the right.🔗 ```\nsubmit_btn: str | bool | None\n``` default = True If False, will not show a submit button. If a string, will use that string as the submit button text.🔗 ```\nstop_btn: str | bool | None\n``` default = False If True, will show a stop button (useful for streaming demos). If a string, will use that string as the stop button text.🔗 ```\nmax_plain_text_length: int\n``` default = 1000 Maximum length of plain text in the textbox. If the text exceeds this length, the text will be pasted as a file. Default is 1000.🔗 ```\nhtml_attributes: InputHTMLAttributes | None\n``` default = None An instance of gr.InputHTMLAttributes, which can be used to set HTML attributes for the input/textarea elements. Example: InputHTMLAttributes(autocorrect=&quot;off&quot;, spellcheck=False) to disable autocorrect and spellcheck. Shortcuts Shortcuts ```\ngradio.MultimodalTextbox\n``` Interface String Shortcut \"multimodaltextbox\" Initialization Uses default values Demos chatbot_multimodal  Event Listeners Description Event listeners allow you to respond to user interactions with the UI\n\t\tcomponents you've defined in a Gradio Blocks app. When a user interacts with\n\t\tan element, such as changing a slider value or uploading an image, a\n\t\tfunction is called. Supported Event Listeners The MultimodalTextbox component supports the following event listeners. Each event listener takes the\n\t\tsame parameters, which are listed in the Event Parameters table below. Listeners ```\nMultimodalTextbox.change(fn, ···)\n``` Triggered when the value of the MultimodalTextbox 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.```\nMultimodalTextbox.input(fn, ···)\n``` This listener is triggered when the user changes the value of the MultimodalTextbox.```\nMultimodalTextbox.select(fn, ···)\n``` Event listener for when the user selects or deselects the MultimodalTextbox. Uses event data gradio.SelectData to carry value referring to the label of the MultimodalTextbox, and selected to refer to state of the MultimodalTextbox. See https://www.gradio.app/main/docs/gradio/eventdata for more details.```\nMultimodalTextbox.submit(fn, ···)\n``` This listener is triggered when the user presses the Enter key while the MultimodalTextbox is focused.```\nMultimodalTextbox.focus(fn, ···)\n``` This listener is triggered when the MultimodalTextbox is focused.```\nMultimodalTextbox.blur(fn, ···)\n``` This listener is triggered when the MultimodalTextbox is unfocused/blurred.```\nMultimodalTextbox.stop(fn, ···)\n``` This listener is triggered when the user reaches the end of the media playing in the MultimodalTextbox. Event Parameters Parameters ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.  Creating A Custom Chatbot With Blocks","type":"DOCS"},{"title":"Navbar","slug":"/main/docs/gradio/navbar","content":"Navbar ```\ngradio.Navbar(···)\n``` Description Creates a navigation bar component for multipage Gradio apps. The navbar component allows customizing the appearance of the navbar for that page. Only one Navbar component can exist per page in a Blocks app, and it can be placed anywhere within the page.  The Navbar component is designed to control the appearance of the navigation bar in multipage applications. When present in a Blocks app, its properties override the default navbar behavior.  Behavior Using Navbar as an input component. How Navbar will pass its value to your function: Type: list[tuple[str, str]] | None The preprocessed input data sent to the user's function in the backend. Example Code \n    \n    import gradio as gr\n\n    def predict(\n        value: list[tuple[str, str]] | None\n    ):\n        # process value from the Navbar component\n        return \"prediction\"\n\n    interface = gr.Interface(predict, gr.Navbar(), gr.Textbox())\n    interface.launch()\n\n  Using Navbar as an output component How Navbar expects you to return a value: Type: list[tuple[str, str]] | None The output data received by the component from the user's function in the backend. Example Code \n    \n    import gradio as gr\n\n    def predict(text) -> list[tuple[str, str]] | None\n        # process value to return to the Navbar component\n        return value\n\n    interface = gr.Interface(predict, gr.Textbox(), gr.Navbar())\n    interface.launch()\n\n Initialization Parameters ▼ 🔗 ```\nvalue: list[tuple[str, str]] | None\n``` default = None If a list of tuples of (page_name, page_path) are provided, these additional pages will be added to the navbar alongside the existing pages defined in the Blocks app. The page_path can be either a relative path for internal Gradio app pages (e.g., &quot;analytics&quot;) or an absolute URL for external links (e.g., &quot;https://twitter.com/username&quot;). Otherwise, only the pages defined using the `Blocks.route` method will be displayed. Example: [(&quot;Dashboard&quot;, &quot;dashboard&quot;), (&quot;About&quot;, &quot;https://twitter.com/abidlabs&quot;)]🔗 ```\nvisible: bool\n``` default = True If True, the navbar will be visible. If False, the navbar will be hidden.🔗 ```\nmain_page_name: str | Literal[False]\n``` default = \"Home\" The title to display in the navbar for the main page of the Gradio. If False, the main page will not be displayed in the navbar.🔗 ```\nelem_id: str | None\n``` 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.🔗 ```\nelem_classes: list[str] | str | None\n``` 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.🔗 ```\nrender: bool\n``` 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.🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` default = None in a gr.render, Components with the same key across re-renders are treated as the same component, not a new component. Shortcuts Shortcuts ```\ngradio.Navbar\n``` Interface String Shortcut \"navbar\" Initialization Uses default values  Event Listeners Description Event listeners allow you to respond to user interactions with the UI\n\t\tcomponents you've defined in a Gradio Blocks app. When a user interacts with\n\t\tan element, such as changing a slider value or uploading an image, a\n\t\tfunction is called. Supported Event Listeners The Navbar component supports the following event listeners. Each event listener takes the\n\t\tsame parameters, which are listed in the Event Parameters table below. Listeners ```\nNavbar.change(fn, ···)\n``` Triggered when the value of the Navbar changes either because of user input (e.g. a user types in a textbox) OR because of a function update (e.g. an image receives a value from the output of an event trigger). See .input() for a listener that is only triggered by user input. Event Parameters Parameters ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.  Multipage Apps","type":"DOCS"},{"title":"Number","slug":"/main/docs/gradio/number","content":"Number ```\ngradio.Number(···)\n``` Description Creates a numeric field for user to enter numbers as input or display numeric output.  Behavior Using Number as an input component. How Number will pass its value to your function: Type: float | int | None Passes field value as a float or int into the function, depending on precision. Example Code \n    \n    import gradio as gr\n\n    def predict(\n        value: float | int | None\n    ):\n        # process value from the Number component\n        return \"prediction\"\n\n    interface = gr.Interface(predict, gr.Number(), gr.Textbox())\n    interface.launch()\n\n  Using Number as an output component How Number expects you to return a value: Type: float | int | None Expects an int or float returned from the function and sets field value to it. Example Code \n    \n    import gradio as gr\n\n    def predict(text) -> float | int | None\n        # process value to return to the Number component\n        return value\n\n    interface = gr.Interface(predict, gr.Textbox(), gr.Number())\n    interface.launch()\n\n Initialization Parameters ▼ 🔗 ```\nvalue: float | Callable | None\n``` default = None default value. If None, the component will be empty and show the `placeholder` if is set. If no `placeholder` is set, the component will show 0. If a function is provided, the function will be called each time the app loads to set the initial value of this component.🔗 ```\nlabel: str | I18nData | None\n``` 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.🔗 ```\nplaceholder: str | I18nData | None\n``` default = None placeholder hint to provide behind number input.🔗 ```\ninfo: str | I18nData | None\n``` default = None additional component description, appears below the label in smaller font. Supports markdown / HTML syntax.🔗 ```\nevery: Timer | float | None\n``` default = None Continuously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.🔗 ```\ninputs: Component | list[Component] | set[Component] | None\n``` 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.🔗 ```\nshow_label: bool | None\n``` default = None if True, will display label.🔗 ```\ncontainer: bool\n``` default = True If True, will place the component in a container - providing some extra padding around the border.🔗 ```\nscale: int | None\n``` 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.🔗 ```\nmin_width: int\n``` 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.🔗 ```\ninteractive: bool | None\n``` default = None if True, will be editable; if False, editing will be disabled. If not provided, this is inferred based on whether the component is used as an input or output.🔗 ```\nvisible: bool | Literal['hidden']\n``` default = True If False, component will be hidden. If &quot;hidden&quot;, component will be visually hidden and not take up space in the layout but still exist in the DOM🔗 ```\nelem_id: str | None\n``` 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.🔗 ```\nelem_classes: list[str] | str | None\n``` 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.🔗 ```\nrender: bool\n``` 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.🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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 &#039;preserved_by_key&#039; are not reset across a re-render.🔗 ```\npreserved_by_key: list[str] | str | None\n``` default = \"value\" A list of parameters from this component&#039;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.🔗 ```\nbuttons: list[Button] | None\n``` default = None A list of gr.Button() instances to show in the top right corner of the component. Custom buttons will appear in the toolbar with their configured icon and/or label, and clicking them will trigger any .click() events registered on the button.🔗 ```\nprecision: int | None\n``` default = None Precision to round input/output to. If set to 0, will round to nearest integer and convert type to int. If None, no rounding happens.🔗 ```\nminimum: float | None\n``` default = None Minimum value. Only applied when component is used as an input. If a user provides a smaller value, a gr.Error exception is raised by the backend.🔗 ```\nmaximum: float | None\n``` default = None Maximum value. Only applied when component is used as an input. If a user provides a larger value, a gr.Error exception is raised by the backend.🔗 ```\nstep: float\n``` default = 1 The interval between allowed numbers in the component. Can be used along with optional parameters `minimum` and `maximum` to create a range of legal values starting from `minimum` and incrementing according to this parameter. Shortcuts Shortcuts ```\ngradio.Number\n``` Interface String Shortcut \"number\" Initialization Uses default values Demos tax_calculatorblocks_simple_squares  Event Listeners Description Event listeners allow you to respond to user interactions with the UI\n\t\tcomponents you've defined in a Gradio Blocks app. When a user interacts with\n\t\tan element, such as changing a slider value or uploading an image, a\n\t\tfunction is called. Supported Event Listeners The Number component supports the following event listeners. Each event listener takes the\n\t\tsame parameters, which are listed in the Event Parameters table below. Listeners ```\nNumber.change(fn, ···)\n``` Triggered when the value of the Number 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.```\nNumber.input(fn, ···)\n``` This listener is triggered when the user changes the value of the Number.```\nNumber.submit(fn, ···)\n``` This listener is triggered when the user presses the Enter key while the Number is focused.```\nNumber.focus(fn, ···)\n``` This listener is triggered when the Number is focused.```\nNumber.blur(fn, ···)\n``` This listener is triggered when the Number is unfocused/blurred. Event Parameters Parameters ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.  ","type":"DOCS"},{"title":"ParamViewer","slug":"/main/docs/gradio/paramviewer","content":"ParamViewer ```\ngradio.ParamViewer(···)\n``` Description Displays an interactive table of parameters and their descriptions and default values with syntax highlighting. For each parameter, the user should provide a type (e.g. a str), a human-readable description, and a default value. As this component does not accept user input, it is rarely used as an input component. Internally, this component is used to display the parameters of components in the Custom Component Gallery (https://www.gradio.app/custom-components/gallery).  Behavior Using ParamViewer as an input component. How ParamViewer will pass its value to your function: Type: dict[str, Parameter] (Rarely used) passes value as a dict[str, dict]. The key in the outer dictionary is the parameter name, while the inner dictionary has keys \"type\", \"description\", and \"default\" for each parameter. Example Code \n    \n    import gradio as gr\n\n    def predict(\n        value: dict[str, Parameter]\n    ):\n        # process value from the ParamViewer component\n        return \"prediction\"\n\n    interface = gr.Interface(predict, gr.ParamViewer(), gr.Textbox())\n    interface.launch()\n\n  Using ParamViewer as an output component How ParamViewer expects you to return a value: Type: dict[str, Parameter] Expects value as a dict[str, dict]. The key in the outer dictionary is the parameter name, while the inner dictionary has keys \"type\", \"description\", and \"default\" for each parameter. Example Code \n    \n    import gradio as gr\n\n    def predict(text) -> dict[str, Parameter]\n        # process value to return to the ParamViewer component\n        return value\n\n    interface = gr.Interface(predict, gr.Textbox(), gr.ParamViewer())\n    interface.launch()\n\n Initialization Parameters ▼ 🔗 ```\nvalue: dict[str, Parameter] | None\n``` default = None A dictionary of dictionaries. The key in the outer dictionary is the parameter name, while the inner dictionary has keys &quot;type&quot;, &quot;description&quot;, and &quot;default&quot; for each parameter. Markdown links are supported in &quot;description&quot;.🔗 ```\nlanguage: Literal['python', 'typescript']\n``` default = \"python\" The language to display the code in. One of &quot;python&quot; or &quot;typescript&quot;.🔗 ```\nlinkify: list[str] | None\n``` default = None A list of strings to linkify. If any of these strings is found in the description, it will be rendered as a link.🔗 ```\nevery: Timer | float | None\n``` default = None Continuously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.🔗 ```\ninputs: Component | list[Component] | set[Component] | None\n``` 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.🔗 ```\nrender: bool\n``` 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.🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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 &#039;preserved_by_key&#039; are not reset across a re-render.🔗 ```\npreserved_by_key: list[str] | str | None\n``` default = \"value\" A list of parameters from this component&#039;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.🔗 ```\nheader: str | None\n``` default = \"Parameters\" The header to display above the table of parameters, also includes a toggle button that closes/opens all details at once. If None, no header will be displayed.🔗 ```\nanchor_links: bool | str\n``` default = False If True, creates anchor links for each parameter that can be used to link directly to that parameter. If a string, creates anchor links with the given string as the prefix to prevent conflicts with other ParamViewer components.🔗 ```\nmax_height: int | str | None\n``` 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 content exceeds the height, the parameter table will scroll vertically while the header remains fixed in place. If content is shorter than the height, the component will shrink to fit the content. Shortcuts Shortcuts ```\ngradio.ParamViewer\n``` Interface String Shortcut \"paramviewer\" Initialization Uses default values  Event Listeners Description Event listeners allow you to respond to user interactions with the UI\n\t\tcomponents you've defined in a Gradio Blocks app. When a user interacts with\n\t\tan element, such as changing a slider value or uploading an image, a\n\t\tfunction is called. Supported Event Listeners The ParamViewer component supports the following event listeners. Each event listener takes the\n\t\tsame parameters, which are listed in the Event Parameters table below. Listeners ```\nParamViewer.change(fn, ···)\n``` Triggered when the value of the ParamViewer 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.```\nParamViewer.upload(fn, ···)\n``` This listener is triggered when the user uploads a file into the ParamViewer. Event Parameters Parameters ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.  Documenting Custom Components","type":"DOCS"},{"title":"Plot","slug":"/main/docs/gradio/plot","content":"Plot ```\ngradio.Plot(···)\n``` Description Creates a plot component to display various kinds of plots (matplotlib, plotly, altair, or bokeh plots are supported). As this component does not accept user input, it is rarely used as an input component.  Behavior Using Plot as an input component. How Plot will pass its value to your function: Type: PlotData | None (Rarely used) passes the data displayed in the plot as an PlotData dataclass, which includes the plot information as a JSON string, as well as the type of chart and the plotting library. Example Code \n    \n    import gradio as gr\n\n    def predict(\n        value: PlotData | None\n    ):\n        # process value from the Plot component\n        return \"prediction\"\n\n    interface = gr.Interface(predict, gr.Plot(), gr.Textbox())\n    interface.launch()\n\n  Using Plot as an output component How Plot expects you to return a value: Type: Any Expects plot data in one of these formats: a matplotlib.Figure, bokeh.Model, plotly.Figure, or altair.Chart object. Example Code \n    \n    import gradio as gr\n\n    def predict(text) -> Any\n        # process value to return to the Plot component\n        return value\n\n    interface = gr.Interface(predict, gr.Textbox(), gr.Plot())\n    interface.launch()\n\n Initialization Parameters ▼ 🔗 ```\nvalue: Any | None\n``` default = None Optionally, supply a default plot object to display, must be a matplotlib, plotly, altair, or bokeh figure, or a callable. If a function is provided, the function will be called each time the app loads to set the initial value of this component.🔗 ```\nformat: str\n``` default = \"webp\" File format in which to send matplotlib plots to the front end, such as &#039;jpg&#039; or &#039;png&#039;.🔗 ```\nlabel: str | I18nData | None\n``` 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.🔗 ```\nevery: Timer | float | None\n``` default = None Continuously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.🔗 ```\ninputs: Component | list[Component] | set[Component] | None\n``` 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.🔗 ```\nshow_label: bool | None\n``` default = None if True, will display label.🔗 ```\ncontainer: bool\n``` default = True If True, will place the component in a container - providing some extra padding around the border.🔗 ```\nscale: int | None\n``` 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.🔗 ```\nmin_width: int\n``` 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.🔗 ```\nvisible: bool | Literal['hidden']\n``` default = True If False, component will be hidden. If &quot;hidden&quot;, component will be visually hidden and not take up space in the layout but still exist in the DOM🔗 ```\nelem_id: str | None\n``` 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.🔗 ```\nelem_classes: list[str] | str | None\n``` 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.🔗 ```\nrender: bool\n``` 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.🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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 &#039;preserved_by_key&#039; are not reset across a re-render.🔗 ```\npreserved_by_key: list[str] | str | None\n``` default = \"value\" A list of parameters from this component&#039;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.🔗 ```\nbuttons: list[Button] | None\n``` default = None A list of gr.Button() instances to show in the top right corner of the component. Custom buttons will appear in the toolbar with their configured icon and/or label, and clicking them will trigger any .click() events registered on the button. Shortcuts Shortcuts ```\ngradio.Plot\n``` Interface String Shortcut \"plot\" Initialization Uses default values Demos blocks_kinematicsstock_forecast  Event Listeners Description Event listeners allow you to respond to user interactions with the UI\n\t\tcomponents you've defined in a Gradio Blocks app. When a user interacts with\n\t\tan element, such as changing a slider value or uploading an image, a\n\t\tfunction is called. Supported Event Listeners The Plot component supports the following event listeners. Each event listener takes the\n\t\tsame parameters, which are listed in the Event Parameters table below. Listeners ```\nPlot.change(fn, ···)\n``` Triggered when the value of the Plot changes either because of user input (e.g. a user types in a textbox) OR because of a function update (e.g. an image receives a value from the output of an event trigger). See .input() for a listener that is only triggered by user input. Event Parameters Parameters ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.  Plot Component For Maps","type":"DOCS"},{"title":"Radio","slug":"/main/docs/gradio/radio","content":"Radio ```\ngradio.Radio(···)\n``` Description Creates a set of (string or numeric type) radio buttons of which only one can be selected.  Behavior Using Radio as an input component. How Radio will pass its value to your function: Type: str | int | float | None Passes the value of the selected radio button as a str | int | float, or its index as an int into the function, depending on type. Example Code \n    \n    import gradio as gr\n\n    def predict(\n        value: str | int | float | None\n    ):\n        # process value from the Radio component\n        return \"prediction\"\n\n    interface = gr.Interface(predict, gr.Radio(), gr.Textbox())\n    interface.launch()\n\n  Using Radio as an output component How Radio expects you to return a value: Type: str | int | float | None Expects a str | int | float corresponding to the value of the radio button to be selected Example Code \n    \n    import gradio as gr\n\n    def predict(text) -> str | int | float | None\n        # process value to return to the Radio component\n        return value\n\n    interface = gr.Interface(predict, gr.Textbox(), gr.Radio())\n    interface.launch()\n\n Initialization Parameters ▼ 🔗 ```\nchoices: list[str | int | float | tuple[str | I18nData, str | int | float]] | None\n``` default = None A list of string or numeric options to select from. An option can also be a tuple of the form (name, value), where name is the displayed name of the radio button and value is the value to be passed to the function, or returned by the function.🔗 ```\nvalue: str | int | float | Callable | None\n``` default = None The option selected by default. If None, no option is selected by default. If a function is provided, the function will be called each time the app loads to set the initial value of this component.🔗 ```\ntype: Literal['value', 'index']\n``` default = \"value\" Type of value to be returned by component. &quot;value&quot; returns the string of the choice selected, &quot;index&quot; returns the index of the choice selected.🔗 ```\nlabel: str | I18nData | None\n``` 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.🔗 ```\ninfo: str | I18nData | None\n``` default = None additional component description, appears below the label in smaller font. Supports markdown / HTML syntax.🔗 ```\nevery: Timer | float | None\n``` default = None Continuously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.🔗 ```\ninputs: Component | list[Component] | set[Component] | None\n``` 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.🔗 ```\nshow_label: bool | None\n``` default = None if True, will display label.🔗 ```\ncontainer: bool\n``` default = True If True, will place the component in a container - providing some extra padding around the border.🔗 ```\nscale: int | None\n``` 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.🔗 ```\nmin_width: int\n``` 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.🔗 ```\ninteractive: bool | None\n``` default = None If True, choices in this radio group will be selectable; if False, selection will be disabled. If not provided, this is inferred based on whether the component is used as an input or output.🔗 ```\nvisible: bool | Literal['hidden']\n``` default = True If False, component will be hidden. If &quot;hidden&quot;, component will be visually hidden and not take up space in the layout but still exist in the DOM🔗 ```\nelem_id: str | None\n``` 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.🔗 ```\nelem_classes: list[str] | str | None\n``` 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.🔗 ```\nrender: bool\n``` 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.🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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 &#039;preserved_by_key&#039; are not reset across a re-render.🔗 ```\npreserved_by_key: list[str] | str | None\n``` default = \"value\" A list of parameters from this component&#039;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.🔗 ```\nrtl: bool\n``` default = False If True, the radio buttons will be displayed in right-to-left order. Default is False.🔗 ```\nbuttons: list[Button] | None\n``` default = None A list of gr.Button() instances to show in the top right corner of the component. Custom buttons will appear in the toolbar with their configured icon and/or label, and clicking them will trigger any .click() events registered on the button. Shortcuts Shortcuts ```\ngradio.Radio\n``` Interface String Shortcut \"radio\" Initialization Uses default values Demos sentence_builderblocks_essay  Event Listeners Description Event listeners allow you to respond to user interactions with the UI\n\t\tcomponents you've defined in a Gradio Blocks app. When a user interacts with\n\t\tan element, such as changing a slider value or uploading an image, a\n\t\tfunction is called. Supported Event Listeners The Radio component supports the following event listeners. Each event listener takes the\n\t\tsame parameters, which are listed in the Event Parameters table below. Listeners ```\nRadio.select(fn, ···)\n``` Event listener for when the user selects or deselects the Radio. Uses event data gradio.SelectData to carry value referring to the label of the Radio, and selected to refer to state of the Radio. See https://www.gradio.app/main/docs/gradio/eventdata for more details.```\nRadio.change(fn, ···)\n``` Triggered when the value of the Radio changes either because of user input (e.g. a user types in a textbox) OR because of a function update (e.g. an image receives a value from the output of an event trigger). See .input() for a listener that is only triggered by user input.```\nRadio.input(fn, ···)\n``` This listener is triggered when the user changes the value of the Radio. Event Parameters Parameters ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.  ","type":"DOCS"},{"title":"ScatterPlot","slug":"/main/docs/gradio/scatterplot","content":"ScatterPlot ```\ngradio.ScatterPlot(···)\n``` Description Creates a scatter plot component to display data from a pandas DataFrame.  Behavior Using ScatterPlot as an input component. How ScatterPlot will pass its value to your function: Type: PlotData | None The data to display in a line plot. Example Code \n    \n    import gradio as gr\n\n    def predict(\n        value: PlotData | None\n    ):\n        # process value from the ScatterPlot component\n        return \"prediction\"\n\n    interface = gr.Interface(predict, gr.ScatterPlot(), gr.Textbox())\n    interface.launch()\n\n  Using ScatterPlot as an output component How ScatterPlot expects you to return a value: Type: pd.DataFrame | dict | None Expects a pandas DataFrame containing the data to display in the line plot. The DataFrame should contain at least two columns:\none for the x-axis (corresponding to this component's x argument)\none for the y-axis (corresponding to y). Example Code \n    \n    import gradio as gr\n\n    def predict(text) -> pd.DataFrame | dict | None\n        # process value to return to the ScatterPlot component\n        return value\n\n    interface = gr.Interface(predict, gr.Textbox(), gr.ScatterPlot())\n    interface.launch()\n\n Initialization Parameters ▼ 🔗 ```\nvalue: pd.DataFrame | Callable | None\n``` default = None The pandas dataframe containing the data to display in the plot.🔗 ```\nx: str | None\n``` default = None Column corresponding to the x axis. Column can be numeric, datetime, or string/category.🔗 ```\ny: str | None\n``` default = None Column corresponding to the y axis. Column must be numeric.🔗 ```\ncolor: str | None\n``` default = None Column corresponding to series, visualized by color. Column must be string/category.🔗 ```\ntitle: str | None\n``` default = None The title to display on top of the chart.🔗 ```\nx_title: str | None\n``` default = None The title given to the x axis. By default, uses the value of the x parameter.🔗 ```\ny_title: str | None\n``` default = None The title given to the y axis. By default, uses the value of the y parameter.🔗 ```\ncolor_title: str | None\n``` default = None The title given to the color legend. By default, uses the value of color parameter.🔗 ```\nx_bin: str | float | None\n``` default = None Grouping used to cluster x values. If x column is numeric, should be number to bin the x values. If x column is datetime, should be string such as &quot;1h&quot;, &quot;15m&quot;, &quot;10s&quot;, using &quot;s&quot;, &quot;m&quot;, &quot;h&quot;, &quot;d&quot; suffixes.🔗 ```\ny_aggregate: Literal['sum', 'mean', 'median', 'min', 'max', 'count'] | None\n``` default = None Aggregation function used to aggregate y values, used if x_bin is provided or x is a string/category. Must be one of &quot;sum&quot;, &quot;mean&quot;, &quot;median&quot;, &quot;min&quot;, &quot;max&quot;.🔗 ```\ncolor_map: dict[str, str] | None\n``` default = None Mapping of series to color names or codes. For example, {&quot;success&quot;: &quot;green&quot;, &quot;fail&quot;: &quot;#FF8888&quot;}.🔗 ```\ncolors_in_legend: list[str] | None\n``` default = None List containing column names of the series to show in the legend. By default, all series are shown.🔗 ```\nx_lim: list[float | None] | None\n``` default = None A tuple or list containing the limits for the x-axis, specified as [x_min, x_max]. To fix only one of these values, set the other to None, e.g. [0, None] to scale from 0 to the maximum value. If x column is datetime type, x_lim should be timestamps.🔗 ```\ny_lim: list[float | None]\n``` default = None A tuple of list containing the limits for the y-axis, specified as [y_min, y_max]. To fix only one of these values, set the other to None, e.g. [0, None] to scale from 0 to the maximum to value.🔗 ```\nx_label_angle: float\n``` default = 0 The angle of the x-axis labels in degrees offset clockwise.🔗 ```\ny_label_angle: float\n``` default = 0 The angle of the y-axis labels in degrees offset clockwise.🔗 ```\nx_axis_format: str | None\n``` default = None A d3 format string for the x-axis labels (e.g., &quot;.2e&quot; for scientific notation, &quot;~g&quot; for general format). If None, uses Vega-Lite&#039;s default formatting.🔗 ```\ny_axis_format: str | None\n``` default = None A d3 format string for the y-axis labels (e.g., &quot;.2e&quot; for scientific notation, &quot;~g&quot; for general format). If None, uses Vega-Lite&#039;s default formatting.🔗 ```\nx_axis_labels_visible: bool | Literal['hidden']\n``` default = True Whether the x-axis labels should be visible. Can be hidden when many x-axis labels are present.🔗 ```\ncaption: str | I18nData | None\n``` default = None The (optional) caption to display below the plot.🔗 ```\nsort: Literal['x', 'y', '-x', '-y'] | list[str] | None\n``` default = None The sorting order of the x values, if x column is type string/category. Can be &quot;x&quot;, &quot;y&quot;, &quot;-x&quot;, &quot;-y&quot;, or list of strings that represent the order of the categories.🔗 ```\ntooltip: Literal['axis', 'none', 'all'] | list[str]\n``` default = \"axis\" The tooltip to display when hovering on a point. &quot;axis&quot; shows the values for the axis columns, &quot;all&quot; shows all column values, and &quot;none&quot; shows no tooltips. Can also provide a list of strings representing columns to show in the tooltip, which will be displayed along with axis values.🔗 ```\nheight: int | None\n``` default = None The height of the plot in pixels.🔗 ```\nlabel: str | I18nData | None\n``` default = None The (optional) label to display on the top left corner of the plot.🔗 ```\nshow_label: bool | None\n``` default = None Whether the label should be displayed.🔗 ```\ncontainer: bool\n``` default = True If True, will place the component in a container - providing some extra padding around the border.🔗 ```\nscale: int | None\n``` 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.🔗 ```\nmin_width: int\n``` 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.🔗 ```\nevery: Timer | float | None\n``` default = None Continuously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.🔗 ```\ninputs: Component | list[Component] | Set[Component] | None\n``` 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.🔗 ```\nvisible: bool | Literal['hidden']\n``` default = True Whether the plot should be visible.🔗 ```\nelem_id: str | None\n``` 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.🔗 ```\nelem_classes: list[str] | str | None\n``` 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.🔗 ```\nrender: bool\n``` 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.🔗 ```\nbuttons: list[Literal['fullscreen', 'export'] | Button] | None\n``` default = None A list of buttons to show for the component. Valid options are &quot;fullscreen&quot;, &quot;export&quot;, or a gr.Button() instance. The &quot;fullscreen&quot; button allows the user to view the plot in fullscreen mode. The &quot;export&quot; button allows the user to export and download the current view of the plot as a PNG image. Custom gr.Button() instances will appear in the toolbar with their configured icon and/or label, and clicking them will trigger any .click() events registered on the button. By default, no buttons are shown.🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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 &#039;preserved_by_key&#039; are not reset across a re-render.🔗 ```\npreserved_by_key: list[str] | str | None\n``` default = \"value\" A list of parameters from this component&#039;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. Key Concepts gr.LinePlot, gr.ScatterPlot, and gr.BarPlot all share the same API. Here is a summary of the most important features. For full details and live demos, see the Creating Plots and Time Plots guides. Basic Usage with a DataFrame Pass a pd.DataFrame as the value, and specify x and y column names. The y-axis must be numeric; the x-axis can be strings, numbers, categories, or datetimes. ```\nimport gradio as gr\nimport pandas as pd\n\ndf = pd.DataFrame({\"weight\": [50, 70, 90, 60], \"height\": [160, 175, 180, 165]})\n\nwith gr.Blocks() as demo:\n    gr.ScatterPlot(df, x=\"weight\", y=\"height\")\n``` Breaking Out Series by Color Use the color argument to split data into multiple series. The color column can be string/categorical or numeric. Use color_map to assign specific colors: ```\ngr.ScatterPlot(df, x=\"weight\", y=\"height\", color=\"gender\",\n               color_map={\"M\": \"#4488FF\", \"F\": \"#FF8844\"})\n``` Aggregating Values Use x_bin and y_aggregate to group and summarize data. For numeric x-axes, x_bin creates histogram-style bins. For string x-axes, strings act as category bins automatically: ```\ngr.ScatterPlot(df, x=\"age_group\", y=\"height\", y_aggregate=\"mean\")\ngr.ScatterPlot(df, x=\"weight\", y=\"height\", x_bin=10, y_aggregate=\"mean\")\n``` For time-series data, pass a string suffix (\"s\", \"m\", \"h\", or \"d\") to x_bin: ```\ngr.ScatterPlot(df, x=\"timestamp\", y=\"value\", x_bin=\"1h\", y_aggregate=\"mean\")\n``` Interactive Selection and Zoom Use the .select event listener to respond to region selections (click and drag). Combine with .double_click and x_lim to implement zoom in/out: ```\nwith gr.Blocks() as demo:\n    plot = gr.ScatterPlot(df, x=\"weight\", y=\"height\")\n\n    @plot.select\n    def zoom(selection: gr.SelectData):\n        return gr.ScatterPlot(x_lim=[selection.index[0], selection.index[1]])\n\n    plot.double_click(lambda: gr.ScatterPlot(x_lim=None), outputs=plot)\n``` Realtime Data Use gr.Timer to keep plots updated with live data. You can attach the timer via every, or wire it up manually: ```\ndef get_data():\n    return pd.DataFrame(...)  # fetch latest data\n\nwith gr.Blocks() as demo:\n    timer = gr.Timer(5)\n    plot = gr.ScatterPlot(get_data, x=\"weight\", y=\"height\", every=timer)\n``` Interactive Dashboards Plots can be driven by other components (dropdowns, sliders, etc.) to create fully interactive dashboards: ```\nwith gr.Blocks() as demo:\n    category = gr.Dropdown(choices=[\"A\", \"B\", \"C\"], value=\"A\")\n    plot = gr.ScatterPlot(x=\"weight\", y=\"height\")\n\n    def update(cat):\n        filtered = df[df[\"category\"] == cat]\n        return gr.ScatterPlot(filtered)\n\n    category.change(update, inputs=category, outputs=plot)\n``` Shortcuts Shortcuts ```\ngradio.ScatterPlot\n``` Interface String Shortcut \"scatterplot\" Initialization Uses default values Demos scatter_plot_demo  Event Listeners Description Event listeners allow you to respond to user interactions with the UI\n\t\tcomponents you've defined in a Gradio Blocks app. When a user interacts with\n\t\tan element, such as changing a slider value or uploading an image, a\n\t\tfunction is called. Supported Event Listeners The ScatterPlot component supports the following event listeners. Each event listener takes the\n\t\tsame parameters, which are listed in the Event Parameters table below. Listeners ```\nScatterPlot.change(fn, ···)\n``` Triggered when the value of the NativePlot 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.```\nScatterPlot.select(fn, ···)\n``` Event listener for when the user selects or deselects the NativePlot. Uses event data gradio.SelectData to carry value referring to the label of the NativePlot, and selected to refer to state of the NativePlot. See https://www.gradio.app/main/docs/gradio/eventdata for more details.```\nScatterPlot.double_click(fn, ···)\n``` Triggered when the NativePlot is double clicked. Event Parameters Parameters ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.  Creating Plots","type":"DOCS"},{"title":"Sidebar","slug":"/main/docs/gradio/sidebar","content":"Sidebar ```\ngradio.Sidebar(···)\n``` Description Sidebar is a collapsible panel that renders child components on the left side of the screen within a Blocks layout. Example Usage ```\nwith gr.Blocks() as demo:\n    with gr.Sidebar():\n        gr.Textbox()\n        gr.Button()\n``` Initialization Parameters ▼ 🔗 ```\nlabel: str | I18nData | None\n``` default = None name of the sidebar. Not displayed to the user.🔗 ```\nopen: bool\n``` default = True if True, sidebar is open by default.🔗 ```\nvisible: bool | Literal['hidden']\n``` default = True 🔗 ```\nelem_id: str | None\n``` 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.🔗 ```\nelem_classes: list[str] | str | None\n``` default = None An optional string or list of strings that are assigned as the class of this component in the HTML DOM. Can be used for targeting CSS styles.🔗 ```\nrender: bool\n``` default = True If False, this layout will not be rendered in the Blocks context. Should be used if the intention is to assign event listeners now but render the component later.🔗 ```\nwidth: int | str\n``` default = 320 The width of the sidebar, specified in pixels if a number is passed, or in CSS units if a string is passed.🔗 ```\nposition: Literal['left', 'right']\n``` default = \"left\" The position of the sidebar in the layout, either &quot;left&quot; or &quot;right&quot;. Defaults to &quot;left&quot;.🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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 &#039;preserved_by_key&#039; are not reset across a re-render.🔗 ```\npreserved_by_key: list[str] | str | None\n``` default = None A list of parameters from this component&#039;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.  Methods expand  ```\ngradio.Sidebar.expand(···)\n``` Description  This listener is triggered when the Sidebar is expanded.  Parameters ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.collapse  ```\ngradio.Sidebar.collapse(···)\n``` Description  This listener is triggered when the Sidebar is collapsed.  Parameters ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.  Controlling Layout","type":"DOCS"},{"title":"SimpleImage","slug":"/main/docs/gradio/simpleimage","content":"SimpleImage ```\ngradio.SimpleImage(···)\n``` Description Creates an image component that can be used to upload images (as an input) or display images (as an output). Behavior Using SimpleImage as an input component. How SimpleImage will pass its value to your function: Type: str | None A str containing the path to the image. Example Code \n    \n    import gradio as gr\n\n    def predict(\n        value: str | None\n    ):\n        # process value from the SimpleImage component\n        return \"prediction\"\n\n    interface = gr.Interface(predict, gr.SimpleImage(), gr.Textbox())\n    interface.launch()\n\n  Using SimpleImage as an output component How SimpleImage expects you to return a value: Type: str | Path | None Expects a str or pathlib.Path object containing the path to the image. Example Code \n    \n    import gradio as gr\n\n    def predict(text) -> str | Path | None\n        # process value to return to the SimpleImage component\n        return value\n\n    interface = gr.Interface(predict, gr.Textbox(), gr.SimpleImage())\n    interface.launch()\n\n Initialization Parameters ▼ 🔗 ```\nvalue: str | None\n``` default = None A path or URL for the default value that SimpleImage component is going to take. If a function is provided, the function will be called each time the app loads to set the initial value of this component.🔗 ```\nlabel: str | I18nData | None\n``` 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.🔗 ```\nevery: Timer | float | None\n``` default = None Continuously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.🔗 ```\ninputs: Component | list[Component] | set[Component] | None\n``` 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.🔗 ```\nshow_label: bool | None\n``` default = None if True, will display label.🔗 ```\nshow_download_button: bool\n``` default = True If True, will display button to download image.🔗 ```\ncontainer: bool\n``` default = True If True, will place the component in a container - providing some extra padding around the border.🔗 ```\nscale: int | None\n``` 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.🔗 ```\nmin_width: int\n``` 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.🔗 ```\ninteractive: bool | None\n``` default = None if True, will allow users to upload and edit an image; if False, can only be used to display images. If not provided, this is inferred based on whether the component is used as an input or output.🔗 ```\nvisible: bool | Literal['hidden']\n``` default = True If False, component will be hidden. If &quot;hidden&quot;, component will be visually hidden and not take up space in the layout but still exist in the DOM🔗 ```\nelem_id: str | None\n``` 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.🔗 ```\nelem_classes: list[str] | str | None\n``` 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.🔗 ```\nrender: bool\n``` 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.🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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 &#039;preserved_by_key&#039; are not reset across a re-render.🔗 ```\npreserved_by_key: list[str] | str | None\n``` default = \"value\" A list of parameters from this component&#039;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. Shortcuts Shortcuts ```\ngradio.SimpleImage\n``` Interface String Shortcut \"simpleimage\" Initialization Uses default values  Event Listeners Description Event listeners allow you to respond to user interactions with the UI\n\t\tcomponents you've defined in a Gradio Blocks app. When a user interacts with\n\t\tan element, such as changing a slider value or uploading an image, a\n\t\tfunction is called. Supported Event Listeners The SimpleImage component supports the following event listeners. Each event listener takes the\n\t\tsame parameters, which are listed in the Event Parameters table below. Listeners ```\nSimpleImage.clear(fn, ···)\n``` This listener is triggered when the user clears the SimpleImage using the clear button for the component.```\nSimpleImage.change(fn, ···)\n``` Triggered when the value of the SimpleImage 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.```\nSimpleImage.upload(fn, ···)\n``` This listener is triggered when the user uploads a file into the SimpleImage. Event Parameters Parameters ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.  ","type":"DOCS"},{"title":"Slider","slug":"/main/docs/gradio/slider","content":"Slider ```\ngradio.Slider(···)\n``` Description Creates a slider that ranges from minimum to maximum with a step size of step.  Behavior Using Slider as an input component. How Slider will pass its value to your function: Type: float Passes slider value as a float into the function. Example Code \n    \n    import gradio as gr\n\n    def predict(\n        value: float\n    ):\n        # process value from the Slider component\n        return \"prediction\"\n\n    interface = gr.Interface(predict, gr.Slider(), gr.Textbox())\n    interface.launch()\n\n  Using Slider as an output component How Slider expects you to return a value: Type: float | None Expects an int or float returned from function and sets slider value to it as long as it is within range (otherwise, sets to minimum value). Example Code \n    \n    import gradio as gr\n\n    def predict(text) -> float | None\n        # process value to return to the Slider component\n        return value\n\n    interface = gr.Interface(predict, gr.Textbox(), gr.Slider())\n    interface.launch()\n\n Initialization Parameters ▼ 🔗 ```\nminimum: float\n``` default = 0 minimum value for slider. When used as an input, if a user provides a smaller value, a gr.Error exception is raised by the backend.🔗 ```\nmaximum: float\n``` default = 100 maximum value for slider. When used as an input, if a user provides a larger value, a gr.Error exception is raised by the backend.🔗 ```\nvalue: float | Callable | None\n``` default = None default value for slider. If a function is provided, the function will be called each time the app loads to set the initial value of this component. Ignored if randomized=True.🔗 ```\nstep: float | None\n``` default = None increment between slider values.🔗 ```\nprecision: int | None\n``` default = None Precision to round input/output to. If set to 0, will round to nearest integer and convert type to int. If None, no rounding happens.🔗 ```\nlabel: str | I18nData | None\n``` 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.🔗 ```\ninfo: str | I18nData | None\n``` default = None additional component description, appears below the label in smaller font. Supports markdown / HTML syntax.🔗 ```\nevery: Timer | float | None\n``` default = None Continuously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.🔗 ```\ninputs: Component | list[Component] | set[Component] | None\n``` 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.🔗 ```\nshow_label: bool | None\n``` default = None if True, will display label.🔗 ```\ncontainer: bool\n``` default = True If True, will place the component in a container - providing some extra padding around the border.🔗 ```\nscale: int | None\n``` 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.🔗 ```\nmin_width: int\n``` 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.🔗 ```\ninteractive: bool | None\n``` default = None if True, slider will be adjustable; if False, adjusting will be disabled. If not provided, this is inferred based on whether the component is used as an input or output.🔗 ```\nvisible: bool | Literal['hidden']\n``` default = True If False, component will be hidden. If &quot;hidden&quot;, component will be visually hidden and not take up space in the layout but still exist in the DOM🔗 ```\nelem_id: str | None\n``` 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.🔗 ```\nelem_classes: list[str] | str | None\n``` 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.🔗 ```\nrender: bool\n``` 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.🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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 &#039;preserved_by_key&#039; are not reset across a re-render.🔗 ```\npreserved_by_key: list[str] | str | None\n``` default = \"value\" A list of parameters from this component&#039;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.🔗 ```\nrandomize: bool\n``` default = False If True, the value of the slider when the app loads is taken uniformly at random from the range given by the minimum and maximum.🔗 ```\nbuttons: list[Literal['reset']] | None\n``` default = None A list of buttons to show for the component. Currently, the only valid option is &quot;reset&quot;. The &quot;reset&quot; button allows the user to reset the slider to its default value. By default, no buttons are shown. Shortcuts Shortcuts ```\ngradio.Slider\n``` Interface String Shortcut \"slider\" Initialization Uses default values Common Patterns Logarithmic scale Sliders are linear by default. For parameters that vary over several orders of magnitude (e.g. learning rate), map the slider value inside your function: ```\nimport gradio as gr\n\ndef train(lr_exp):\n    lr = 10 ** lr_exp  # slider value -5 → lr 0.00001\n    return f\"Training with lr={lr}\"\n\ndemo = gr.Interface(\n    fn=train,\n    inputs=gr.Slider(-5, 0, value=-3, step=0.5, label=\"Learning rate (log₁₀)\"),\n    outputs=\"text\",\n)\n``` Reacting on release only By default, the slider triggers a change event on every movement. For expensive operations, listen to release instead so the function only runs when the user lets go: ```\nimport gradio as gr\n\nwith gr.Blocks() as demo:\n    slider = gr.Slider(0, 100, label=\"Epochs\")\n    output = gr.Textbox()\n    slider.release(fn=lambda v: f\"Will train for {int(v)} epochs\", inputs=slider, outputs=output)\n``` Demos sentence_builderslider_releaseinterface_random_sliderblocks_random_slider  Event Listeners Description Event listeners allow you to respond to user interactions with the UI\n\t\tcomponents you've defined in a Gradio Blocks app. When a user interacts with\n\t\tan element, such as changing a slider value or uploading an image, a\n\t\tfunction is called. Supported Event Listeners The Slider component supports the following event listeners. Each event listener takes the\n\t\tsame parameters, which are listed in the Event Parameters table below. Listeners ```\nSlider.change(fn, ···)\n``` Triggered when the value of the Slider 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.```\nSlider.input(fn, ···)\n``` This listener is triggered when the user changes the value of the Slider.```\nSlider.release(fn, ···)\n``` This listener is triggered when the user releases the mouse on this Slider. Event Parameters Parameters ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.  ","type":"DOCS"},{"title":"State","slug":"/main/docs/gradio/state","content":"State ```\ngradio.State(···)\n``` Description A base class for defining methods that all input/output components should have. Behavior Using State as an input component. How State will pass its value to your function: Type: Any Passes a value of arbitrary type through. Example Code \n    \n    import gradio as gr\n\n    def predict(\n        value: Any\n    ):\n        # process value from the State component\n        return \"prediction\"\n\n    interface = gr.Interface(predict, gr.State(), gr.Textbox())\n    interface.launch()\n\n  Using State as an output component How State expects you to return a value: Type: Any Expects a value of arbitrary type, as long as it can be deepcopied. Example Code \n    \n    import gradio as gr\n\n    def predict(text) -> Any\n        # process value to return to the State component\n        return value\n\n    interface = gr.Interface(predict, gr.Textbox(), gr.State())\n    interface.launch()\n\n Initialization Parameters ▼ 🔗 ```\nvalue: Any\n``` default = None the initial value (of arbitrary type) of the state. The provided argument is deepcopied. If a callable is provided, the function will be called whenever the app loads to set the initial value of the state.🔗 ```\nrender: bool\n``` default = True should always be True, is included for consistency with other components.🔗 ```\ntime_to_live: int | float | None\n``` default = None the number of seconds the state should be stored for after it is created or updated. If None, the state will be stored indefinitely. Gradio automatically deletes state variables after a user closes the browser tab or refreshes the page, so this is useful for clearing state for potentially long running sessions.🔗 ```\ndelete_callback: Callable[[Any], None] | None\n``` default = None a function that is called when the state is deleted. The function should take the state value as an argument.   Event Listeners Description Event listeners allow you to respond to user interactions with the UI\n\t\tcomponents you've defined in a Gradio Blocks app. When a user interacts with\n\t\tan element, such as changing a slider value or uploading an image, a\n\t\tfunction is called. Supported Event Listeners The State component supports the following event listeners. Each event listener takes the\n\t\tsame parameters, which are listed in the Event Parameters table below. Listeners ```\nState.change(fn, ···)\n``` Triggered when the value of the State changes either because of user input (e.g. a user types in a textbox) OR because of a function update (e.g. an image receives a value from the output of an event trigger). See .input() for a listener that is only triggered by user input. Event Parameters Parameters ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.  ","type":"DOCS"},{"title":"Textbox","slug":"/main/docs/gradio/textbox","content":"Textbox ```\ngradio.Textbox(···)\n``` Description Creates a textarea for user to enter string input or display string output.  Behavior Using Textbox as an input component. How Textbox will pass its value to your function: Type: str | None Passes text value as a str into the function. Example Code \n    \n    import gradio as gr\n\n    def predict(\n        value: str | None\n    ):\n        # process value from the Textbox component\n        return \"prediction\"\n\n    interface = gr.Interface(predict, gr.Textbox(), gr.Textbox())\n    interface.launch()\n\n  Using Textbox as an output component How Textbox expects you to return a value: Type: str | None Expects a str returned from function and sets textarea value to it. Example Code \n    \n    import gradio as gr\n\n    def predict(text) -> str | None\n        # process value to return to the Textbox component\n        return value\n\n    interface = gr.Interface(predict, gr.Textbox(), gr.Textbox())\n    interface.launch()\n\n Initialization Parameters ▼ 🔗 ```\nvalue: str | I18nData | Callable | None\n``` default = None text to show in textbox. If a function is provided, the function will be called each time the app loads to set the initial value of this component.🔗 ```\ntype: Literal['text', 'password', 'email']\n``` default = \"text\" The type of textbox. One of: &#039;text&#039; (which allows users to enter any text), &#039;password&#039; (which masks text entered by the user), &#039;email&#039; (which suggests email input to the browser). For &quot;password&quot; and &quot;email&quot; types, `lines` must be 1 and `max_lines` must be None or 1.🔗 ```\nlines: int\n``` default = 1 minimum number of line rows to provide in textarea.🔗 ```\nmax_lines: int | None\n``` default = None maximum number of line rows to provide in textarea. Must be at least `lines`. If not provided, the maximum number of lines is max(lines, 20) for &quot;text&quot; type, and 1 for &quot;password&quot; and &quot;email&quot; types.🔗 ```\nplaceholder: str | I18nData | None\n``` default = None placeholder hint to provide behind textarea.🔗 ```\nlabel: str | I18nData | None\n``` 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.🔗 ```\ninfo: str | I18nData | None\n``` default = None additional component description, appears below the label in smaller font. Supports markdown / HTML syntax.🔗 ```\nevery: Timer | float | None\n``` default = None continuously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.🔗 ```\ninputs: Component | list[Component] | set[Component] | None\n``` 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.🔗 ```\nshow_label: bool | None\n``` default = None if True, will display the label. If False, the copy button is hidden as well as well as the label.🔗 ```\ncontainer: bool\n``` default = True if True, will place the component in a container - providing some extra padding around the border.🔗 ```\nscale: int | None\n``` 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.🔗 ```\nmin_width: int\n``` 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.🔗 ```\ninteractive: bool | None\n``` default = None if True, will be rendered as an editable textbox; if False, editing will be disabled. If not provided, this is inferred based on whether the component is used as an input or output.🔗 ```\nvisible: bool | Literal['hidden']\n``` default = True If False, component will be hidden. If &quot;hidden&quot;, component will be visually hidden and not take up space in the layout but still exist in the DOM🔗 ```\nelem_id: str | None\n``` 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.🔗 ```\nautofocus: bool\n``` default = False If True, will focus on the textbox when the page loads. Use this carefully, as it can cause usability issues for sighted and non-sighted users.🔗 ```\nautoscroll: bool\n``` default = True If True, will automatically scroll to the bottom of the textbox when the value changes, unless the user scrolls up. If False, will not scroll to the bottom of the textbox when the value changes.🔗 ```\nelem_classes: list[str] | str | None\n``` 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.🔗 ```\nrender: bool\n``` 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.🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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 &#039;preserved_by_key&#039; are not reset across a re-render.🔗 ```\npreserved_by_key: list[str] | str | None\n``` default = \"value\" A list of parameters from this component&#039;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.🔗 ```\ntext_align: Literal['left', 'right'] | None\n``` default = None How to align the text in the textbox, can be: &quot;left&quot;, &quot;right&quot;, or None (default). If None, the alignment is left if `rtl` is False, or right if `rtl` is True. Can only be changed if `type` is &quot;text&quot;.🔗 ```\nrtl: bool\n``` default = False If True and `type` is &quot;text&quot;, sets the direction of the text to right-to-left (cursor appears on the left of the text). Default is False, which renders cursor on the right.🔗 ```\nbuttons: list[Literal['copy'] | Button] | None\n``` default = None A list of buttons to show for the component. The only built-in button for this component is &quot;copy&quot;, which allows the user to copy the text in the textbox. Custom gr.Button() can also provided, they will appear in the toolbar with their configured icon and/or label, and clicking them will trigger any .click() events registered on the button. Only applies if show_label is True. By default, no buttons are shown.🔗 ```\nmax_length: int | None\n``` default = None maximum number of characters (including newlines) allowed in the textbox. If None, there is no maximum length.🔗 ```\nsubmit_btn: str | bool | None\n``` default = False If False, will not show a submit button. If True, will show a submit button with an icon. If a string, will use that string as the submit button text. When the submit button is shown, the border of the textbox will be removed, which is useful for creating a chat interface.🔗 ```\nstop_btn: str | bool | None\n``` default = False If False, will not show a stop button. If True, will show a stop button with an icon. If a string, will use that string as the stop button text. When the stop button is shown, the border of the textbox will be removed, which is useful for creating a chat interface.🔗 ```\nhtml_attributes: InputHTMLAttributes | None\n``` default = None An instance of gr.InputHTMLAttributes, which can be used to set HTML attributes for the input/textarea elements. Example: InputHTMLAttributes(autocorrect=&quot;off&quot;, spellcheck=False) to disable autocorrect and spellcheck. Shortcuts Shortcuts ```\ngradio.Textbox\n``` Interface String Shortcut \"textbox\" Initialization Uses default values```\ngradio.TextArea\n``` Interface String Shortcut \"textarea\" Initialization Uses lines=7 ### Common Patterns Multi-line text input By default, gr.Textbox renders as a single-line input. For longer text such as paragraphs or code, set lines to show multiple rows and optionally max_lines to cap the height: ```\nimport gradio as gr\n\ndef summarize(text):\n    return f\"Received {len(text.split())} words.\"\n\ndemo = gr.Interface(\n    fn=summarize,\n    inputs=gr.Textbox(lines=5, max_lines=10, label=\"Paste your text here\"),\n    outputs=\"text\",\n)\n``` Password and sensitive input Set type=\"password\" to mask characters as the user types. The value is passed as plain text to your function — masking is display-only: ```\nimport gradio as gr\n\ndef check(password):\n    return \"Access granted\" if password == \"secret\" else \"Wrong password\"\n\ndemo = gr.Interface(\n    fn=check,\n    inputs=gr.Textbox(type=\"password\", label=\"Enter password\"),\n    outputs=\"text\",\n)\n``` Demos hello_worlddiff_textssentence_builder  Event Listeners Description Event listeners allow you to respond to user interactions with the UI\n\t\tcomponents you've defined in a Gradio Blocks app. When a user interacts with\n\t\tan element, such as changing a slider value or uploading an image, a\n\t\tfunction is called. Supported Event Listeners The Textbox component supports the following event listeners. Each event listener takes the\n\t\tsame parameters, which are listed in the Event Parameters table below. Listeners ```\nTextbox.change(fn, ···)\n``` Triggered when the value of the Textbox 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.```\nTextbox.input(fn, ···)\n``` This listener is triggered when the user changes the value of the Textbox.```\nTextbox.select(fn, ···)\n``` Event listener for when the user selects or deselects the Textbox. Uses event data gradio.SelectData to carry value referring to the label of the Textbox, and selected to refer to state of the Textbox. See https://www.gradio.app/main/docs/gradio/eventdata for more details.```\nTextbox.submit(fn, ···)\n``` This listener is triggered when the user presses the Enter key while the Textbox is focused.```\nTextbox.focus(fn, ···)\n``` This listener is triggered when the Textbox is focused.```\nTextbox.blur(fn, ···)\n``` This listener is triggered when the Textbox is unfocused/blurred.```\nTextbox.stop(fn, ···)\n``` This listener is triggered when the user reaches the end of the media playing in the Textbox.```\nTextbox.copy(fn, ···)\n``` This listener is triggered when the user copies content from the Textbox. 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 ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.  Quickstart","type":"DOCS"},{"title":"Timer","slug":"/main/docs/gradio/timer","content":"Timer ```\ngradio.Timer(···)\n``` Description Special component that ticks at regular intervals when active. It is not visible, and only used to trigger events at a regular interval through the tick event listener.  Behavior Using Timer as an input component. How Timer will pass its value to your function: Type: float | None The interval of the timer as a float. Example Code \n    \n    import gradio as gr\n\n    def predict(\n        value: float | None\n    ):\n        # process value from the Timer component\n        return \"prediction\"\n\n    interface = gr.Interface(predict, gr.Timer(), gr.Textbox())\n    interface.launch()\n\n  Using Timer as an output component How Timer expects you to return a value: Type: float | None The interval of the timer as a float or None. Example Code \n    \n    import gradio as gr\n\n    def predict(text) -> float | None\n        # process value to return to the Timer component\n        return value\n\n    interface = gr.Interface(predict, gr.Textbox(), gr.Timer())\n    interface.launch()\n\n Initialization Parameters ▼ 🔗 ```\nvalue: float\n``` default = 1 Interval in seconds between each tick.🔗 ```\nactive: bool\n``` default = True Whether the timer is active.🔗 ```\nrender: bool\n``` 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. Shortcuts Shortcuts ```\ngradio.Timer\n``` Interface String Shortcut \"timer\" Initialization Uses default values  Event Listeners Description Event listeners allow you to respond to user interactions with the UI\n\t\tcomponents you've defined in a Gradio Blocks app. When a user interacts with\n\t\tan element, such as changing a slider value or uploading an image, a\n\t\tfunction is called. Supported Event Listeners The Timer component supports the following event listeners. Each event listener takes the\n\t\tsame parameters, which are listed in the Event Parameters table below. Listeners ```\nTimer.change(fn, ···)\n``` Triggered when the value of the Timer 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.```\nTimer.tick(fn, ···)\n``` This listener is triggered at regular intervals defined by the Timer. Event Parameters Parameters ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.  More Blocks FeaturesTime Plots","type":"DOCS"},{"title":"UploadButton","slug":"/main/docs/gradio/uploadbutton","content":"UploadButton ```\ngradio.UploadButton(···)\n``` Description Used to create an upload button, when clicked allows a user to upload files that satisfy the specified file type or generic files (if file_type not set).  Behavior Using UploadButton as an input component. How UploadButton will pass its value to your function: Type: bytes | str | list[bytes] | list[str] | None Passes the file as a str or bytes object, or a list of str or list of bytes objects, depending on type and file_count. Example Code \n    \n    import gradio as gr\n\n    def predict(\n        value: bytes | str | list[bytes] | list[str] | None\n    ):\n        # process value from the UploadButton component\n        return \"prediction\"\n\n    interface = gr.Interface(predict, gr.UploadButton(), gr.Textbox())\n    interface.launch()\n\n  Using UploadButton as an output component How UploadButton expects you to return a value: Type: str | list[str] | None Expects a str filepath or URL, or a list[str] of filepaths/URLs. Example Code \n    \n    import gradio as gr\n\n    def predict(text) -> str | list[str] | None\n        # process value to return to the UploadButton component\n        return value\n\n    interface = gr.Interface(predict, gr.Textbox(), gr.UploadButton())\n    interface.launch()\n\n Initialization Parameters ▼ 🔗 ```\nlabel: str\n``` default = \"Upload a File\" Text to display on the button. Defaults to &quot;Upload a File&quot;.🔗 ```\nvalue: str | I18nData | list[str] | Callable | None\n``` default = None File or list of files to upload by default.🔗 ```\nevery: Timer | float | None\n``` default = None Continuously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.🔗 ```\ninputs: Component | list[Component] | set[Component] | None\n``` 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.🔗 ```\nvariant: Literal['primary', 'secondary', 'stop']\n``` default = \"secondary\" &#039;primary&#039; for main call-to-action, &#039;secondary&#039; for a more subdued style, &#039;stop&#039; for a stop button.🔗 ```\nvisible: bool | Literal['hidden']\n``` default = True If False, component will be hidden. If &quot;hidden&quot;, component will be visually hidden and not take up space in the layout but still exist in the DOM🔗 ```\nsize: Literal['sm', 'md', 'lg']\n``` default = \"lg\" size of the button. Can be &quot;sm&quot;, &quot;md&quot;, or &quot;lg&quot;.🔗 ```\nicon: str | None\n``` default = None URL or path to the icon file to display within the button. If None, no icon will be displayed.🔗 ```\nscale: int | None\n``` 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.🔗 ```\nmin_width: int | None\n``` default = None minimum pixel width, will wrap if not sufficient screen space to satisfy this value. If a certain scale value results in this Component being narrower than min_width, the min_width parameter will be respected first.🔗 ```\ninteractive: bool\n``` default = True If False, the UploadButton will be in a disabled state.🔗 ```\nelem_id: str | None\n``` 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.🔗 ```\nelem_classes: list[str] | str | None\n``` 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.🔗 ```\nrender: bool\n``` 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.🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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 &#039;preserved_by_key&#039; are not reset across a re-render.🔗 ```\npreserved_by_key: list[str] | str | None\n``` default = \"value\" A list of parameters from this component&#039;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.🔗 ```\ntype: Literal['filepath', 'binary']\n``` default = \"filepath\" Type of value to be returned by component. &quot;file&quot; returns a temporary file object with the same base name as the uploaded file, whose full path can be retrieved by file_obj.name, &quot;binary&quot; returns an bytes object.🔗 ```\nfile_count: Literal['single', 'multiple', 'directory']\n``` default = \"single\" if single, allows user to upload one file. If &quot;multiple&quot;, user uploads multiple files. If &quot;directory&quot;, user uploads all files in selected directory. Return type will be list for each file in case of &quot;multiple&quot; or &quot;directory&quot;.🔗 ```\nfile_types: list[str] | None\n``` default = None List of type of files to be uploaded. &quot;file&quot; allows any file to be uploaded, &quot;image&quot; allows only image files to be uploaded, &quot;audio&quot; allows only audio files to be uploaded, &quot;video&quot; allows only video files to be uploaded, &quot;text&quot; allows only text files to be uploaded. Shortcuts Shortcuts ```\ngradio.UploadButton\n``` Interface String Shortcut \"uploadbutton\" Initialization Uses default values Demos upload_and_downloadupload_button  Event Listeners Description Event listeners allow you to respond to user interactions with the UI\n\t\tcomponents you've defined in a Gradio Blocks app. When a user interacts with\n\t\tan element, such as changing a slider value or uploading an image, a\n\t\tfunction is called. Supported Event Listeners The UploadButton component supports the following event listeners. Each event listener takes the\n\t\tsame parameters, which are listed in the Event Parameters table below. Listeners ```\nUploadButton.change(fn, ···)\n``` Triggered when the value of the UploadButton 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.```\nUploadButton.click(fn, ···)\n``` Triggered when the UploadButton is clicked.```\nUploadButton.upload(fn, ···)\n``` This listener is triggered when the user uploads a file into the UploadButton. Event Parameters Parameters ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.  ","type":"DOCS"},{"title":"Video","slug":"/main/docs/gradio/video","content":"Video ```\ngradio.Video(···)\n``` Description Creates a video component that can be used to upload/record videos (as an input) or display videos (as an output). For the video to be playable in the browser it must have a compatible container and codec combination. Allowed combinations are .mp4 with h264 codec, .ogg with theora codec, and .webm with vp9 codec. If the component detects that the output video would not be playable in the browser it will attempt to convert it to a playable mp4 video. If the conversion fails, the original video is returned.  Behavior Using Video as an input component. How Video will pass its value to your function: Type: str | None Passes the uploaded video as a str filepath or URL whose extension can be modified by format. Example Code \n    \n    import gradio as gr\n\n    def predict(\n        value: str | None\n    ):\n        # process value from the Video component\n        return \"prediction\"\n\n    interface = gr.Interface(predict, gr.Video(), gr.Textbox())\n    interface.launch()\n\n  Using Video as an output component How Video expects you to return a value: Type: str | Path | None Expects one of either:\na str or pathlib.Path filepath to a video which is displayed\na Tuple[str | pathlib.Path, str | pathlib.Path | None] where the first element is a filepath to a video and the second element is an optional filepath to a subtitle file. Example Code \n    \n    import gradio as gr\n\n    def predict(text) -> str | Path | None\n        # process value to return to the Video component\n        return value\n\n    interface = gr.Interface(predict, gr.Textbox(), gr.Video())\n    interface.launch()\n\n Initialization Parameters ▼ 🔗 ```\nvalue: str | Path | Callable | None\n``` default = None path or URL for the default value that Video component is going to take. Or can be callable, in which case the function will be called whenever the app loads to set the initial value of the component.🔗 ```\nformat: str | None\n``` default = None the file extension with which to save video, such as &#039;avi&#039; or &#039;mp4&#039;. This parameter applies both when this component is used as an input to determine which file format to convert user-provided video to, and when this component is used as an output to determine the format of video returned to the user. If None, no file format conversion is done and the video is kept as is. Use &#039;mp4&#039; to ensure browser playability.🔗 ```\nsources: list[Literal['upload', 'webcam']] | Literal['upload', 'webcam'] | None\n``` default = None list of sources permitted for video. &quot;upload&quot; creates a box where user can drop a video file, &quot;webcam&quot; allows user to record a video from their webcam. If None, defaults to both [&quot;upload, &quot;webcam&quot;].🔗 ```\nheight: int | str | None\n``` 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 video file, but will affect the displayed video.🔗 ```\nwidth: int | str | None\n``` 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 video file, but will affect the displayed video.🔗 ```\nlabel: str | I18nData | None\n``` 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.🔗 ```\nevery: Timer | float | None\n``` default = None continuously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.🔗 ```\ninputs: Component | list[Component] | set[Component] | None\n``` 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.🔗 ```\nshow_label: bool | None\n``` default = None if True, will display label.🔗 ```\ncontainer: bool\n``` default = True if True, will place the component in a container - providing some extra padding around the border.🔗 ```\nscale: int | None\n``` 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.🔗 ```\nmin_width: int\n``` 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.🔗 ```\ninteractive: bool | None\n``` default = None if True, will allow users to upload a video; if False, can only be used to display videos. If not provided, this is inferred based on whether the component is used as an input or output.🔗 ```\nvisible: bool | Literal['hidden']\n``` default = True If False, component will be hidden. If &quot;hidden&quot;, component will be visually hidden and not take up space in the layout but still exist in the DOM🔗 ```\nelem_id: str | None\n``` 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.🔗 ```\nelem_classes: list[str] | str | None\n``` 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.🔗 ```\nrender: bool\n``` 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.🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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 &#039;preserved_by_key&#039; are not reset across a re-render.🔗 ```\npreserved_by_key: list[str] | str | None\n``` default = \"value\" A list of parameters from this component&#039;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.🔗 ```\nwebcam_options: WebcamOptions | None\n``` default = None A `gr.WebcamOptions` instance that allows developers to specify custom media constraints for the webcam stream. This parameter provides flexibility to control the video stream&#039;s properties, such as resolution and front or rear camera on mobile devices. See $demo/webcam_constraints🔗 ```\ninclude_audio: bool | None\n``` default = None whether the component should record/retain the audio track for a video. By default, audio is excluded for webcam videos and included for uploaded videos.🔗 ```\nautoplay: bool\n``` default = False whether to automatically play the video when the component is used as an output. Note: browsers will not autoplay video files if the user has not interacted with the page yet.🔗 ```\nbuttons: list[Literal['download', 'share'] | Button] | None\n``` default = None A list of buttons to show in the top right corner of the component. Valid options are &quot;download&quot;, &quot;share&quot;, or a gr.Button() instance. The &quot;download&quot; button allows the user to save the video to their device. The &quot;share&quot; button allows the user to share the video via Hugging Face Spaces Discussions. Custom gr.Button() instances will appear in the toolbar with their configured icon and/or label, and clicking them will trigger any .click() events registered on the button. By default, no buttons are shown if the component is interactive and both buttons are shown if the component is not interactive.🔗 ```\nloop: bool\n``` default = False if True, the video will loop when it reaches the end and continue playing from the beginning.🔗 ```\nstreaming: bool\n``` default = False when used set as an output, takes video chunks yielded from the backend and combines them into one streaming video output. Each chunk should be a video file with a .ts extension using an h.264 encoding. Mp4 files are also accepted but they will be converted to h.264 encoding.🔗 ```\nwatermark: WatermarkOptions | None\n``` default = None A `gr.WatermarkOptions` instance that includes an image file and position to be used as a watermark on the video. The image is not scaled and is displayed on the provided position on the video. Valid formats for the image are: jpeg, png.🔗 ```\nsubtitles: str | Path | list[dict[str, Any]] | None\n``` default = None A subtitle file (srt, vtt, or json) for the video, or a list of subtitle dictionaries in the format [{&quot;text&quot;: str, &quot;timestamp&quot;: [start, end]}] where timestamps are in seconds. JSON files should contain an array of subtitle objects.🔗 ```\nplayback_position: float\n``` default = 0 The starting playback position in seconds. This value is also updated as the video plays, reflecting the current playback position. Shortcuts Shortcuts ```\ngradio.Video\n``` Interface String Shortcut \"video\" Initialization Uses default values```\ngradio.PlayableVideo\n``` Interface String Shortcut \"playablevideo\" Initialization Uses format=\"mp4\" Demos video_identity_2  Event Listeners Description Event listeners allow you to respond to user interactions with the UI\n\t\tcomponents you've defined in a Gradio Blocks app. When a user interacts with\n\t\tan element, such as changing a slider value or uploading an image, a\n\t\tfunction is called. Supported Event Listeners The Video component supports the following event listeners. Each event listener takes the\n\t\tsame parameters, which are listed in the Event Parameters table below. Listeners ```\nVideo.change(fn, ···)\n``` Triggered when the value of the Video 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.```\nVideo.clear(fn, ···)\n``` This listener is triggered when the user clears the Video using the clear button for the component.```\nVideo.start_recording(fn, ···)\n``` This listener is triggered when the user starts recording with the Video.```\nVideo.stop_recording(fn, ···)\n``` This listener is triggered when the user stops recording with the Video.```\nVideo.stop(fn, ···)\n``` This listener is triggered when the user reaches the end of the media playing in the Video.```\nVideo.play(fn, ···)\n``` This listener is triggered when the user plays the media in the Video.```\nVideo.pause(fn, ···)\n``` This listener is triggered when the media in the Video stops for any reason.```\nVideo.end(fn, ···)\n``` This listener is triggered when the user reaches the end of the media playing in the Video.```\nVideo.upload(fn, ···)\n``` This listener is triggered when the user uploads a file into the Video.```\nVideo.input(fn, ···)\n``` This listener is triggered when the user changes the value of the Video. Event Parameters Parameters ▼ 🔗 ```\nfn: Callable | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; and &#039;outputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None 🔗 ```\nstream_every: float\n``` default = 0.5 🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` 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.🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.  Helper Classes Webcam Options ```\ngradio.WebcamOptions(···)\n``` Description A dataclass for specifying options for the webcam tool in the ImageEditor component. An instance of this class can be passed to the webcam_options parameter of gr.ImageEditor. Initialization Parameters ▼ 🔗 ```\nmirror: bool\n``` default = True If True, the webcam will be mirrored.🔗 ```\nconstraints: dict[str, Any] | None\n``` default = None A dictionary of constraints for the webcam. is_video_correct_length Validates that the audio length is within the specified min and max length (in seconds).\nYou can use this to construct a validator that will check if the user-provided audio is either too short or too long. ```\nimport gradio as gr\ndemo = gr.Interface(\n    lambda x: x,\n    inputs=\"video\",\n    outputs=\"video\",\n    validator=lambda video: gr.validators.is_video_correct_length(video, min_length=1, max_length=5)\n)\ndemo.launch()\n``` Initialization Parameters ▼ 🔗 ```\nvideo: \n```  The path to the video file.🔗 ```\nmin_length: float | None\n```  Minimum length of video in seconds. If None, no minimum length check is performed.🔗 ```\nmax_length: float | None\n```  Maximum length of video in seconds. If None, no maximum length check is performed. Streaming InputsStreaming OutputsObject Detection From Video","type":"DOCS"},{"title":"EventData","slug":"/main/docs/gradio/eventdata","content":"EventData ```\ngradio.EventData(···)\n``` Description When gr.EventData or one of its subclasses is added as a type hint to an argument of a prediction function, a gr.EventData 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. The gr.EventData object itself contains a .target attribute that refers to the component that triggered the event, while subclasses of gr.EventData contains additional attributes that are different for each class.  Example Usage ```\nimport gradio as gr\n\nwith gr.Blocks() as demo:\n    table = gr.Dataframe([[1, 2, 3], [4, 5, 6]])\n    gallery = gr.Gallery([(\"cat.jpg\", \"Cat\"), (\"dog.jpg\", \"Dog\")])\n    textbox = gr.Textbox(\"Hello World!\")\n    statement = gr.Textbox()\n\n    def on_select(value, evt: gr.EventData):\n        return f\"The {evt.target} component was selected, and its value was {value}.\"\n\n    table.select(on_select, table, statement)\n    gallery.select(on_select, gallery, statement)\n    textbox.select(on_select, textbox, statement)\n\ndemo.launch()\n``` Attributes Parameters ▼ 🔗 ```\ntarget: Block | None\n```  The component object that triggered the event. Can be used to distinguish multiple components bound to the same listener. Demos gallery_selectionstictactoe   Blocks And Event Listeners","type":"DOCS"},{"title":"DeletedFileData","slug":"/main/docs/gradio/deletedfiledata","content":"DeletedFileData ```\ngradio.DeletedFileData(···)\n``` Description The gr.DeletedFileData class is a subclass of gr.EventData that specifically carries information about the .delete() event. When gr.DeletedFileData is added as a type hint to an argument of an event listener method, a gr.DeletedFileData 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. Example Usage ```\nimport gradio as gr\n\ndef test(delete_data: gr.DeletedFileData):\n    return delete_data.file.path\n\nwith gr.Blocks() as demo:\n    files = gr.File(file_count=\"multiple\")\n    deleted_file = gr.File()\n    files.delete(test, None, deleted_file)\n\ndemo.launch()\n``` Attributes Parameters ▼ 🔗 ```\nfile: FileData\n```  The file that was deleted, as a FileData object. The str path to the file can be retrieved with the .path attribute. Demos file_component_events   ","type":"DOCS"},{"title":"KeyUpData","slug":"/main/docs/gradio/keyupdata","content":"KeyUpData ```\ngradio.KeyUpData(···)\n``` Description The gr.KeyUpData class is a subclass of gr.EventData that specifically carries information about the .key_up() event. When gr.KeyUpData is added as a type hint to an argument of an event listener method, a gr.KeyUpData 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.  Example Usage ```\nimport gradio as gr\n\ndef test(value, key_up_data: gr.KeyUpData):\n    return {\n        \"component value\": value,\n        \"input value\": key_up_data.input_value,\n        \"key\": key_up_data.key\n    }\n\nwith gr.Blocks() as demo:\n    d = gr.Dropdown([\"abc\", \"def\"], allow_custom_value=True)\n    t = gr.JSON()\n    d.key_up(test, d, t)\ndemo.launch()\n``` Attributes Parameters ▼ 🔗 ```\nkey: str\n```  The key that was pressed.🔗 ```\ninput_value: str\n```  The displayed value in the input textbox after the key was pressed. This may be different than the `value` attribute of the component itself, as the `value` attribute of some components (e.g. Dropdown) are not updated until the user presses Enter. Demos dropdown_key_up   ","type":"DOCS"},{"title":"LikeData","slug":"/main/docs/gradio/likedata","content":"LikeData ```\ngradio.LikeData(···)\n``` Description The gr.LikeData class is a subclass of gr.EventData that specifically carries information about the .like() event. When gr.LikeData is added as a type hint to an argument of an event listener method, a gr.LikeData object will automatically be passed as the value of that argument. The attributes of this object contains information about the event that triggered the listener. Example Usage ```\nimport gradio as gr\n\ndef test(value, like_data: gr.LikeData):\n    return {\n        \"chatbot_value\": value,\n        \"liked_message\": like_data.value,\n        \"liked_index\": like_data.index,\n        \"liked_or_disliked_as_bool\": like_data.liked\n    }\n\nwith gr.Blocks() as demo:\n    c = gr.Chatbot([(\"abc\", \"def\")])\n    t = gr.JSON()\n    c.like(test, c, t)\n\ndemo.launch()\n``` Attributes Parameters ▼ 🔗 ```\nindex: int | tuple[int, int]\n```  The index of the liked/disliked item. Is a tuple if the component is two dimensional.🔗 ```\nvalue: Any\n```  The value of the liked/disliked item.🔗 ```\nliked: bool\n```  True if the item was liked, False if disliked, or string value if any other feedback. Demos chatbot_core_components_simple   Chatbot Specific Events","type":"DOCS"},{"title":"SelectData","slug":"/main/docs/gradio/selectdata","content":"SelectData ```\ngradio.SelectData(···)\n``` Description The gr.SelectData class is a subclass of gr.EventData that specifically carries information about the .select() event. When gr.SelectData is added as a type hint to an argument of an event listener method, a gr.SelectData 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.  Example Usage ```\nimport gradio as gr\n\nwith gr.Blocks() as demo:\n    table = gr.Dataframe([[1, 2, 3], [4, 5, 6]])\n    gallery = gr.Gallery([(\"cat.jpg\", \"Cat\"), (\"dog.jpg\", \"Dog\")])\n    textbox = gr.Textbox(\"Hello World!\")\n    statement = gr.Textbox()\n\n    def on_select(evt: gr.SelectData):\n        return f\"You selected {evt.value} at {evt.index} from {evt.target}\"\n\n    table.select(on_select, None, statement)\n    gallery.select(on_select, None, statement)\n    textbox.select(on_select, None, statement)\n\ndemo.launch()\n``` Attributes Parameters ▼ 🔗 ```\nindex: int | tuple[int, int]\n```  The index of the selected item. Is a tuple if the component is two dimensional or selection is a range.🔗 ```\nvalue: Any\n```  The value of the selected item.🔗 ```\nrow_value: list[float | str]\n```  The value of the entire row that the selected item belongs to, as a 1-D list. Only implemented for the `Dataframe` component, returns None for other components.🔗 ```\ncol_value: list[float | str]\n```  The value of the entire column that the selected item belongs to, as a 1-D list. Only implemented for the `Dataframe` component, returns None for other components.🔗 ```\nselected: bool\n```  True if the item was selected, False if deselected. Demos gallery_selectionstictactoe   ","type":"DOCS"},{"title":"FileData","slug":"/main/docs/gradio/filedata","content":"FileData ```\ngradio.FileData(···)\n``` Description 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.  Example Usage ```\nfrom gradio_client import Client, FileData, handle_file\n\ndef get_url_on_server(data: FileData):\n    print(data['url'])\n\nclient = Client(\"gradio/gif_maker_main\", download_files=False)\njob = client.submit([handle_file(\"./cheetah.jpg\")], api_name=\"/predict\")\ndata = job.result()\nvideo: FileData = data['video']\n\nget_url_on_server(video)\n``` Attributes Parameters ▼ 🔗 ```\npath: str\n```  The server file path where the file is stored.🔗 ```\nurl: Optional[str]\n```  The normalized server URL pointing to the file.🔗 ```\nsize: Optional[int]\n```  The size of the file in bytes.🔗 ```\norig_name: Optional[str]\n```  The original filename before upload.🔗 ```\nmime_type: Optional[str]\n```  The MIME type of the file.🔗 ```\nis_stream: bool\n```  Indicates whether the file is a stream.🔗 ```\nmeta: dict\n```  Additional metadata used internally (should not be changed).   ","type":"DOCS"},{"title":"RetryData","slug":"/main/docs/gradio/retrydata","content":"RetryData ```\ngradio.RetryData(···)\n``` Description The gr.RetryData class is a subclass of gr.Event data that specifically carries information about the .retry() event. When gr.RetryData is added as a type hint to an argument of an event listener method, a gr.RetryData 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. Example Usage ```\nimport gradio as gr\n\ndef retry(retry_data: gr.RetryData, history: list[gr.MessageDict]):\n    history_up_to_retry = history[:retry_data.index]\n    new_response = \"\"\n    for token in api.chat_completion(history):\n        new_response += token\n        yield history + [new_response]\n\nwith gr.Blocks() as demo:\n    chatbot = gr.Chatbot()\n    chatbot.retry(retry, chatbot, chatbot)\ndemo.launch()\n``` Attributes Parameters ▼ 🔗 ```\nindex: int | tuple[int, int]\n```  The index of the user message that should be retried.🔗 ```\nvalue: Any\n```  The value of the user message that should be retried.   Chatbot Specific Events","type":"DOCS"},{"title":"UndoData","slug":"/main/docs/gradio/undodata","content":"UndoData ```\ngradio.UndoData(···)\n``` Description The gr.UndoData class is a subclass of gr.Event data that specifically carries information about the .undo() event. When gr.UndoData is added as a type hint to an argument of an event listener method, a gr.UndoData 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. Example Usage ```\nimport gradio as gr\n\ndef undo(retry_data: gr.UndoData, history: list[gr.MessageDict]):\n    history_up_to_retry = history[:retry_data.index]\n    return history_up_to_retry\n\nwith gr.Blocks() as demo:\n    chatbot = gr.Chatbot()\n    chatbot.undo(undo, chatbot, chatbot)\ndemo.launch()\n``` Attributes Parameters ▼ 🔗 ```\nindex: int | tuple[int, int]\n```  The index of the user message that should be undone.🔗 ```\nvalue: Any\n```  The value of the user message that should be undone.   ","type":"DOCS"},{"title":"EditData","slug":"/main/docs/gradio/editdata","content":"EditData ```\ngradio.EditData(···)\n``` Description The gr.EditData class is a subclass of gr.Event data that specifically carries information about the .edit() event. When gr.EditData is added as a type hint to an argument of an event listener method, a gr.EditData 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. Example Usage ```\nimport gradio as gr\n\ndef edit(edit_data: gr.EditData, history: list[gr.MessageDict]):\n    history_up_to_edit = history[:edit_data.index]\n    history_up_to_edit[-1] = edit_data.value\n    return history_up_to_edit\n\nwith gr.Blocks() as demo:\n    chatbot = gr.Chatbot()\n    chatbot.undo(edit, chatbot, chatbot)\ndemo.launch()\n``` Attributes Parameters ▼ 🔗 ```\nindex: int | tuple[int, int]\n```  The index of the message that was edited.🔗 ```\nprevious_value: Any\n```  The previous content of the message that was edited.🔗 ```\nvalue: Any\n```  The new content of the message that was edited.   Chatbot Specific Events","type":"DOCS"},{"title":"DownloadData","slug":"/main/docs/gradio/downloaddata","content":"DownloadData ```\ngradio.DownloadData(···)\n``` Description The gr.DownloadData class is a subclass of gr.EventData that specifically carries information about the .download() event. When gr.DownloadData is added as a type hint to an argument of an event listener method, a gr.DownloadData object will automatically be passed as the value of that argument. The attributes of this object contains information about the event that triggered the listener. Example Usage ```\nimport gradio as gr\ndef on_download(download_data: gr.DownloadData):\n    return f\"Downloaded file: {download_data.file.path}\"\nwith gr.Blocks() as demo:\n    files = gr.File()\n    textbox = gr.Textbox()\n    files.download(on_download, None, textbox)\ndemo.launch()\n``` Attributes Parameters ▼ 🔗 ```\nfile: FileData\n```  The file that was downloaded, as a FileData object.   ","type":"DOCS"},{"title":"CopyData","slug":"/main/docs/gradio/copydata","content":"CopyData ```\ngradio.CopyData(···)\n``` Description 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. Example Usage ```\nimport gradio as gr\ndef on_copy(copy_data: gr.CopyData):\n    return f\"Copied text: {copy_data.value}\"\nwith gr.Blocks() as demo:\n    textbox = gr.Textbox(\"Hello World!\")\n    copied = gr.Textbox()\n    textbox.copy(on_copy, None, copied)\ndemo.launch()\n``` Attributes Parameters ▼ 🔗 ```\nvalue: Any\n```  The value that was copied.   ","type":"DOCS"},{"title":"Examples","slug":"/main/docs/gradio/examples","content":"Examples ```\ngradio.Examples(···)\n``` Description This class is a wrapper over the Dataset component and can be used to create Examples for Blocks / Interfaces. Populates the Dataset component with examples and assigns event listener so that clicking on an example populates the input/output components. Optionally handles example caching for fast inference.   Initialization Parameters ▼ 🔗 ```\nexamples: list[Any] | list[list[Any]] | str\n```  example inputs that can be clicked to populate specific components. Should be nested list, in which the outer list consists of samples and each inner list consists of an input corresponding to each input component. A string path to a directory of examples can also be provided but it should be within the directory with the python file running the gradio app. If there are multiple input components and a directory is provided, a log.csv file must be present in the directory to link corresponding inputs.🔗 ```\ninputs: Component | list[Component]\n```  the component or list of components corresponding to the examples🔗 ```\noutputs: Component | list[Component] | None\n``` default = None optionally, provide the component or list of components corresponding to the output of the examples. Required if `cache_examples` is not False.🔗 ```\nfn: Callable | None\n``` default = None optionally, provide the function to run to generate the outputs corresponding to the examples. Required if `cache_examples` is not False. Also required if `run_on_click` is True.🔗 ```\ncache_examples: bool | None\n``` default = None If True, caches examples in the server for fast runtime in examples. If &quot;lazy&quot;, then examples are cached (for all users of the app) after their first use (by any user of the app). If None, will use the GRADIO_CACHE_EXAMPLES environment variable, which should be either &quot;true&quot; or &quot;false&quot;. In HuggingFace Spaces, this parameter is True (as long as `fn` and `outputs` are also provided). The default option otherwise is False. Note that examples are cached separately from Gradio&#039;s queue() so certain features, such as gr.Progress(), gr.Info(), gr.Warning(), etc. will not be displayed in Gradio&#039;s UI for cached examples.🔗 ```\ncache_mode: Literal['eager', 'lazy'] | None\n``` default = None if &quot;lazy&quot;, examples are cached after their first use. If &quot;eager&quot;, all examples are cached at app launch. If None, will use the GRADIO_CACHE_MODE environment variable if defined, or default to &quot;eager&quot;.🔗 ```\nexamples_per_page: int\n``` default = 10 how many examples to show per page.🔗 ```\nlabel: str | I18nData | None\n``` default = \"Examples\" the label to use for the examples component (by default, &quot;Examples&quot;)🔗 ```\nelem_id: str | None\n``` default = None an optional string that is assigned as the id of this component in the HTML DOM.🔗 ```\nrun_on_click: bool\n``` default = False if cache_examples is False, clicking on an example does not run the function when an example is clicked. Set this to True to run the function when an example is clicked. Has no effect if cache_examples is True.🔗 ```\npreprocess: bool\n``` default = True if True, preprocesses the example input before running the prediction function and caching the output. Only applies if `cache_examples` is not False.🔗 ```\npostprocess: bool\n``` default = True if True, postprocesses the example output after running the prediction function and before caching. Only applies if `cache_examples` is not False.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"undocumented\" Controls the visibility of the event associated with clicking on the examples. Can be &quot;public&quot; (shown in API docs and callable), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable).🔗 ```\napi_name: str | None\n``` default = \"load_example\" Defines how the event associated with clicking on the examples appears in the API docs. Can be a string or None. If set to a string, the endpoint will be exposed in the API docs with the given name. If None, an auto-generated name will be used.🔗 ```\napi_description: str | None | Literal[False]\n``` default = None Description of the event associated with clicking on the examples 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 description. If None, the function&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nbatch: bool\n``` 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. Used only if cache_examples is not False.🔗 ```\nexample_labels: list[str] | None\n``` default = None A list of labels for each example. If provided, the length of this list should be the same as the number of examples, and these labels will be used in the UI instead of rendering the example values.🔗 ```\nvisible: bool | Literal['hidden']\n``` default = True If False, the examples component will be hidden in the UI.🔗 ```\npreload: int | Literal[False]\n``` default = 0 If an integer is provided (and examples are being cached eagerly and none of the input components have a developer-provided `value`), the example at that index in the examples list will be preloaded when the Gradio app is first loaded. If False, no example will be preloaded. Attributes Parameters ▼ 🔗 ```\ndataset: gradio.Dataset\n```  The `gr.Dataset` component corresponding to this Examples object.🔗 ```\nload_input_event: gradio.events.Dependency\n```  The Gradio event that populates the input values when the examples are clicked. You can attach a `.then()` or a `.success()` to this event to trigger subsequent events to fire after this event.🔗 ```\ncache_event: gradio.events.Dependency | None\n```  The Gradio event that populates the cached output values when the examples are clicked. You can attach a `.then()` or a `.success()` to this event to trigger subsequent events to fire after this event. This event is `None` if `cache_examples` if False, and is the same as `load_input_event` if `cache_examples` is `&#039;lazy&#039;`. Examples Updating Examples In this demo, we show how to update the examples by updating the samples of the underlying dataset. Note that this only works if cache_examples=False as updating the underlying dataset does not update the cache. ```\nimport gradio as gr\n\ndef update_examples(country):\n    if country == \"USA\":\n        return gr.Dataset(samples=[[\"Chicago\"], [\"Little Rock\"], [\"San Francisco\"]])\n    else:\n        return gr.Dataset(samples=[[\"Islamabad\"], [\"Karachi\"], [\"Lahore\"]])\n\nwith gr.Blocks() as demo:\n    dropdown = gr.Dropdown(label=\"Country\", choices=[\"USA\", \"Pakistan\"], value=\"USA\")\n    textbox = gr.Textbox()\n    examples = gr.Examples([[\"Chicago\"], [\"Little Rock\"], [\"San Francisco\"]], textbox)\n    dropdown.change(update_examples, dropdown, examples.dataset)\n    \ndemo.launch()\n``` Demos calculator_blocks   ","type":"DOCS"},{"title":"Progress","slug":"/main/docs/gradio/progress","content":"Progress ```\ngradio.Progress(···)\n``` Description The Progress class provides a custom progress tracker that is used in a function signature. To attach a Progress tracker to a function, simply add a parameter right after the input parameters that has a default value set to a gradio.Progress() instance. The Progress tracker can then be updated in the function by calling the Progress object or using the tqdm method on an Iterable. Example Usage ```\nimport gradio as gr\nimport time\ndef my_function(x, progress=gr.Progress()):\n    progress(0, desc=\"Starting...\")\n    time.sleep(1)\n    for i in progress.tqdm(range(100)):\n        time.sleep(0.1)\n    return x\ngr.Interface(my_function, gr.Textbox(), gr.Textbox()).queue().launch()\n``` Initialization Parameters ▼ 🔗 ```\ntrack_tqdm: bool\n``` default = False If True, the Progress object will track any tqdm.tqdm iterations with the tqdm library in the function.  Methods __call__  ```\ngradio.Progress.__call__(progress, ···)\n``` Description  Updates progress tracker with progress and message text.  Parameters ▼ 🔗 ```\nprogress: float | tuple[int, int | None] | None\n```  If float, should be between 0 and 1 representing completion. If Tuple, first number represents steps completed, and second value represents total steps or None if unknown. If None, hides progress bar.🔗 ```\ndesc: str | None\n``` default = None description to display.🔗 ```\ntotal: int | float | None\n``` default = None estimated total number of steps.🔗 ```\nunit: str\n``` default = \"steps\" unit of iterations.tqdm  ```\ngradio.Progress.tqdm(iterable, ···)\n``` Description  Attaches progress tracker to iterable, like tqdm.  Parameters ▼ 🔗 ```\niterable: Iterable | None\n```  iterable to attach progress tracker to.🔗 ```\ndesc: str | None\n``` default = None description to display.🔗 ```\ntotal: int | float | None\n``` default = None estimated total number of steps.🔗 ```\nunit: str\n``` default = \"steps\" unit of iterations.  Progress Bars","type":"DOCS"},{"title":"Dependency","slug":"/main/docs/gradio/dependency","content":"Dependency Description The Dependency object is usually not created directly but is returned when an event listener is set up. It contains the configuration data for the event listener, and can be used to set up additional event listeners that depend on the completion of the current event listener using .then(), .success(), and .failure().  Example Usage ```\nimport gradio as gr\n\nwith gr.Blocks() as demo: \n    first_textbox = gr.Textbox()\n    second_textbox = gr.Textbox()\n    button = gr.Button(\"Submit\")\n\n    dependency = button.click(lambda x: \"Hello, \" + x, first_textbox, second_textbox)\n    dependency.success(lambda: gr.Info(\"Greeting successful\"), None, None)\n    dependency.failure(lambda: gr.Warning(\"Greeting failed\"), None, None)\n\ndemo.launch()\n``` Demos chatbot_consecutiveblocks_chained_events   ","type":"DOCS"},{"title":"api","slug":"/main/docs/gradio/api","content":"api ```\ngradio.api(···)\n``` Description Sets up an API or MCP endpoint for a generic function without needing define events listeners or components. Derives its typing from type hints in the provided function's signature rather than the components.  Example Usage ```\nimport gradio as gr\nwith gr.Blocks() as demo:\n    with gr.Row():\n        input = gr.Textbox()\n        button = gr.Button(\"Submit\")\n    output = gr.Textbox()\n    def fn(a: int, b: int, c: list[str]) -> tuple[int, str]:\n        return a + b, c[a:b]\n    gr.api(fn, api_name=\"add_and_slice\")\n_, url, _ = demo.launch()\n\nfrom gradio_client import Client\nclient = Client(url)\nresult = client.predict(\n        a=3,\n        b=5,\n        c=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],\n        api_name=\"/add_and_slice\"\n)\nprint(result)\n``` Initialization Parameters ▼ 🔗 ```\nfn: Callable | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;s prediction function. The function should be fully typed, and the type hints will be used to derive the typing information for the API/MCP endpoint.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None\n``` 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&#039;s docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\ntime_limit: int | None\n``` default = None The time limit for the function to run. Parameter only used for the `.stream()` event.🔗 ```\nstream_every: float\n``` default = 0.5 The latency (in seconds) at which stream chunks are sent to the backend. Defaults to 0.5 seconds. Parameter only used for the `.stream()` event.   Building MCP Server With Gradio","type":"DOCS"},{"title":"Cache","slug":"/main/docs/gradio/cache-class","content":"Cache ```\ngradio.Cache(···)\n``` Description Thread-safe cache with manual get/set control, injected as a function parameter (add as a default parameter value and Gradio will inject it automatically). Supports per-session isolation so cached data doesn't leak between users, content-aware hashing for ML types (numpy, PIL, pandas), and LRU eviction with memory limits. Example Usage ```\nimport gradio as gr\n\ndef generate(prompt, c=gr.Cache(per_session=True)):\n    hit = c.get(prompt)\n    if hit is not None:\n        return hit[\"result\"]\n    result = llm(prompt)\n    c.set(prompt, result=result)\n    return result\n``` Initialization Parameters ▼ 🔗 ```\nmax_size: int\n``` default = 128 🔗 ```\nmax_memory: str | int | None\n``` default = None 🔗 ```\nper_session: bool\n``` default = False   Methods get  ```\ngradio.Cache.get(key, ···)\n``` Description  Look up a cache entry by key. Returns a dict of stored data, or None on miss. Keys can be any type supported by gr.cache (strings, numbers, numpy arrays, PIL images, etc.).  Parameters ▼ 🔗 ```\nkey: Any\n```  The cache key to look up.set  ```\ngradio.Cache.set(key, data, ···)\n``` Description  Store arbitrary keyword data under a key.  Parameters ▼ 🔗 ```\nkey: Any\n```  The cache key.🔗 ```\ndata: Any\n```  Arbitrary keyword arguments to store.keys  ```\ngradio.Cache.keys(···)\n``` Description  Return all stored raw keys. Useful for iteration or prefix matching.  clear  ```\ngradio.Cache.clear(···)\n``` Description  Clear all entries from the cache.    Caching","type":"DOCS"},{"title":"cache","slug":"/main/docs/gradio/cache","content":"cache ```\n@gradio.cache(···)\n``` Description Decorator that auto-caches function results based on content-hashed inputs. Works with sync/async functions and sync/async generators. For generators, all yielded values are cached and replayed on hit. Cache hits bypass the Gradio queue. It can also be called at runtime as gr.cache(fn)(*args) to cache intermediate helper calls. Example Usage ```\nimport gradio as gr\n\n@gr.cache\ndef classify(image):\n    return model.predict(image)\n\n@gr.cache(max_size=256, per_session=True)\ndef generate(prompt):\n    return llm(prompt)\n``` Initialization Parameters ▼ 🔗 ```\nfn: Callable | None\n``` default = None The function to cache. When used as @gr.cache without parentheses, this is the decorated function. When used as @gr.cache(...), this is None. When used as `gr.cache(fn)(...)`, this must be a callable.🔗 ```\nkey: Callable | None\n``` default = None Optional function that receives the kwargs dict and returns a hashable cache key, e.g. to only cache based on the prompt, pass in: lambda kw: kw[&quot;prompt&quot;]🔗 ```\nmax_size: int\n``` default = 128 Maximum number of cache entries. Least-recently-used entries are evicted when full. Set to 0 for unlimited. Default: 128.🔗 ```\nmax_memory: str | int | None\n``` default = None Maximum total memory usage before eviction. Accepts strings like &quot;512mb&quot;, &quot;2gb&quot; or integer bytes. When exceeded, least-recently-used entries are evicted. If None, no memory limit is applied. If both max_size and max_memory are set, the cache will evict entries when either limit is reached.🔗 ```\nper_session: bool\n``` default = False When True, each user session gets an isolated cache namespace, preventing cached results from leaking between users. Per-session entries are cleared when the client session disconnects. The max_size and max_memory limits apply to the sum of all entries across all sessions.   Caching","type":"DOCS"},{"title":"load","slug":"/main/docs/gradio/load","content":"load ```\ngradio.load(···)\n``` Description Constructs a Gradio app automatically from a Hugging Face model/Space repo name or a 3rd-party API provider. Note that if a Space repo is loaded, certain high-level attributes of the Blocks (e.g. custom css, js, and head attributes) will not be loaded. Example Usage ```\nimport gradio as gr\ndemo = gr.load(\"gradio/question-answering\", src=\"spaces\")\ndemo.launch()\n``` Initialization Parameters ▼ 🔗 ```\nname: str\n```  the name of the model (e.g. &quot;google/vit-base-patch16-224&quot;) or Space (e.g. &quot;flax-community/spanish-gpt2&quot;). This is the first parameter passed into the `src` function. Can also be formatted as {src}/{repo name} (e.g. &quot;models/google/vit-base-patch16-224&quot;) if `src` is not provided.🔗 ```\nsrc: Callable[[str, str | None], Blocks] | Literal['models', 'spaces', 'huggingface'] | None\n``` default = None function that accepts a string model `name` and a string or None `token` and returns a Gradio app. Alternatively, this parameter takes one of two strings for convenience: &quot;models&quot; (for loading a Hugging Face model through the Inference API) or &quot;spaces&quot; (for loading a Hugging Face Space). If None, uses the prefix of the `name` parameter to determine `src`.🔗 ```\ntoken: str | None\n``` default = None optional token that is passed as the second parameter to the `src` function. If not explicitly provided, will use the HF_TOKEN environment variable or fallback to the locally-saved HF token when loading models but not Spaces (when loading Spaces, only provide a token if you are loading a trusted private Space as the token can be read by the Space you are loading). Find your HF tokens here: https://huggingface.co/settings/tokens.🔗 ```\naccept_token: bool | LoginButton\n``` default = False if True, a Textbox component is first rendered to allow the user to provide a token, which will be used instead of the `token` parameter when calling the loaded model or Space. Can also provide an instance of a gr.LoginButton in the same Blocks scope, which allows the user to login with a Hugging Face account whose token will be used instead of the `token` parameter when calling the loaded model or Space.🔗 ```\nprovider: PROVIDER_T | None\n``` default = None the name of the third-party (non-Hugging Face) providers to use for model inference (e.g. &quot;replicate&quot;, &quot;sambanova&quot;, &quot;fal-ai&quot;, etc). Should be one of the providers supported by `huggingface_hub.InferenceClient`. This parameter is only used when `src` is &quot;models&quot;🔗 ```\nkwargs: \n```  additional keyword parameters to pass into the `src` function. If `src` is &quot;models&quot; or &quot;Spaces&quot;, these parameters are passed into the `gr.Interface` or `gr.ChatInterface` constructor.   Using HuggingFace Integrations","type":"DOCS"},{"title":"load_chat","slug":"/main/docs/gradio/load_chat","content":"load_chat ```\ngradio.load_chat(···)\n``` Description Load a chat interface from an OpenAI API chat compatible endpoint. Example Usage ```\nimport gradio as gr\ndemo = gr.load_chat(\"http://localhost:11434/v1\", model=\"deepseek-r1\")\ndemo.launch()\n``` Initialization Parameters ▼ 🔗 ```\nbase_url: str\n```  The base URL of the endpoint, e.g. &quot;http://localhost:11434/v1/&quot;🔗 ```\nmodel: str\n```  The name of the model you are loading, e.g. &quot;llama3.2&quot;🔗 ```\ntoken: str | None\n``` default = None The API token or a placeholder string if you are using a local model, e.g. &quot;ollama&quot;🔗 ```\nfile_types: Literal['text_encoded', 'image'] | list[Literal['text_encoded', 'image']] | None\n``` default = \"text_encoded\" The file types allowed to be uploaded by the user. &quot;text_encoded&quot; allows uploading any text-encoded file (which is simply appended to the prompt), and &quot;image&quot; adds image upload support. Set to None to disable file uploads.🔗 ```\nsystem_message: str | None\n``` default = None The system message to use for the conversation, if any.🔗 ```\nstreaming: bool\n``` default = True Whether the response should be streamed.🔗 ```\nkwargs: \n```  Additional keyword arguments to pass into ChatInterface for customization.   Creating a Chatbot Fast","type":"DOCS"},{"title":"on","slug":"/main/docs/gradio/on","content":"on ```\ngradio.on(···)\n``` Description Sets up an event listener that triggers a function when the specified event(s) occur. This is especially useful when the same function should be triggered by multiple events. Only a single API endpoint is generated for all events in the triggers list.  Example Usage ```\nimport gradio as gr\n\nwith gr.Blocks() as demo:\n    with gr.Row():\n        input = gr.Textbox()\n        button = gr.Button(\"Submit\")\n    output = gr.Textbox()\n    gr.on(\n        triggers=[button.click, input.submit],\n        fn=lambda x: x,\n        inputs=[input],\n        outputs=[output]\n    )\n\ndemo.launch()\n``` Initialization Parameters ▼ 🔗 ```\ntriggers: list[Trigger] | Trigger | None\n``` default = None List of triggers to listen to, e.g. [btn.click, number.change]. If None, will run on app load and changes to any inputs.🔗 ```\nfn: Callable[..., Any] | None | Literal['decorator']\n``` default = \"decorator\" the function to call when this event is triggered. Often a machine learning model&#039;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.🔗 ```\ninputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.🔗 ```\noutputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n``` default = None List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.🔗 ```\ninputs_kwargs: dict[str, Component | BlockContext] | None\n``` default = None Dictionary mapping function parameter names to gradio.components. The component values are passed to the function as keyword arguments.🔗 ```\napi_visibility: Literal['public', 'private', 'undocumented']\n``` default = \"public\" controls the visibility and accessibility of this endpoint. Can be &quot;public&quot; (shown in API docs and callable by clients), &quot;private&quot; (hidden from API docs and not callable by the Gradio client libraries), or &quot;undocumented&quot; (hidden from API docs but callable by clients and via gr.load). If fn is None, api_visibility will automatically be set to &quot;private&quot;.🔗 ```\napi_name: str | None\n``` default = None defines how the endpoint appears in the API docs. Can be a string or None. 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.🔗 ```\napi_description: str | None | Literal[False]\n``` default = None 🔗 ```\nscroll_to_output: bool\n``` default = False If True, will scroll to output component on completion🔗 ```\nshow_progress: Literal['full', 'minimal', 'hidden']\n``` default = \"full\" how to show the progress animation while event is running: &quot;full&quot; shows a spinner which covers the output component area as well as a runtime display in the upper right corner, &quot;minimal&quot; only shows the runtime display, &quot;hidden&quot; shows no progress animation at all,🔗 ```\nshow_progress_on: Component | list[Component] | None\n``` 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.🔗 ```\nqueue: bool\n``` 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.🔗 ```\nbatch: bool\n``` 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.🔗 ```\nmax_batch_size: int\n``` default = 4 Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)🔗 ```\npreprocess: bool\n``` default = True If False, will not run preprocessing of component data before running &#039;fn&#039; (e.g. leaving it as a base64 string if this method is called with the `Image` component).🔗 ```\npostprocess: bool\n``` default = True If False, will not run postprocessing of component data before returning &#039;fn&#039; output to the browser.🔗 ```\ncancels: dict[str, Any] | list[dict[str, Any]] | None\n``` 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.🔗 ```\ntrigger_mode: Literal['once', 'multiple', 'always_last'] | None\n``` default = None If &quot;once&quot; (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to &quot;multiple&quot;, unlimited submissions are allowed while pending, and &quot;always_last&quot; (default for `.change()` and `.key_up()` events) would allow a second submission after the pending event is complete.🔗 ```\njs: str | Literal[True] | None\n``` default = None Optional frontend JavaScript to run before &#039;fn&#039;, provided as either a function or a raw code string. A function receives the values of &#039;inputs&#039; as arguments; raw code can access them through `arguments`. Return a list of values for the output components.🔗 ```\nconcurrency_limit: int | None | Literal['default']\n``` 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 &quot;default&quot; to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).🔗 ```\nconcurrency_id: str | None\n``` 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.🔗 ```\ntime_limit: int | None\n``` default = None The time limit for the function to run. Parameter only used for the `.stream()` event.🔗 ```\nstream_every: float\n``` default = 0.5 The latency (in seconds) at which stream chunks are sent to the backend. Defaults to 0.5 seconds. Parameter only used for the `.stream()` event.🔗 ```\nkey: int | str | tuple[int | str, ...] | None\n``` default = None 🔗 ```\nvalidator: Callable | None\n``` 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, including the same keyword arguments when `inputs_kwargs` is used, so its signature must accept those keyword names. It should return a `gr.validate()` for each input value.   Blocks and Event Listeners","type":"DOCS"},{"title":"set_static_paths","slug":"/main/docs/gradio/set_static_paths","content":"set_static_paths ```\ngradio.set_static_paths(···)\n``` Description Set the static paths to be served by the gradio app.  Static files are are served directly from the file system instead of being copied. They are served to users with The Content-Disposition HTTP header set to \"inline\" when sending these files to users. This indicates that the file should be displayed directly in the browser window if possible. This function is useful when you want to serve files that you know will not be modified during the lifetime of the gradio app (like files used in gr.Examples). By setting static paths, your app will launch faster and it will consume less disk space. Calling this function will set the static paths for all gradio applications defined in the same interpreter session until it is called again or the session ends.  Example Usage ```\nimport gradio as gr\n\n# Paths can be a list of strings or pathlib.Path objects\n# corresponding to filenames or directories.\ngr.set_static_paths(paths=[\"test/test_files/\"])\n\n# The example files and the default value of the input\n# will not be copied to the gradio cache and will be served directly.\ndemo = gr.Interface(\n    lambda s: s.rotate(45),\n    gr.Image(value=\"test/test_files/cheetah1.jpg\", type=\"pil\"),\n    gr.Image(),\n    examples=[\"test/test_files/bus.png\"],\n)\n\ndemo.launch()\n``` Initialization Parameters ▼ 🔗 ```\npaths: str | pathlib.Path | list[str | pathlib.Path]\n```  filepath or list of filepaths or directory names to be served by the gradio app. If it is a directory name, ALL files located within that directory will be considered static and not moved to the gradio cache. This also means that ALL files in that directory will be accessible over the network.   File Access","type":"DOCS"},{"title":"Error","slug":"/main/docs/gradio/error","content":"Error ```\nraise gradio.Error(\"An error occurred 💥!\", duration=5)\n``` Description This class allows you to pass custom error messages to the user. You can do so by raising a gr.Error(\"custom message\") anywhere in the code, and when that line is executed the custom message will appear in a modal on the demo. You can control for how long the error message is displayed with the duration parameter. If it’s None, the message will be displayed forever until the user closes it. If it’s a number, it will be shown for that many seconds. You can also hide the error modal from being shown in the UI by setting visible=False. Below is a demo of how different values of duration control the error, info, and warning messages. You can see the code here.  Example Usage ```\nimport gradio as gr\ndef divide(numerator, denominator):\n    if denominator == 0:\n        raise gr.Error(\"Cannot divide by zero!\")\ngr.Interface(divide, [\"number\", \"number\"], \"number\").launch()\n``` Initialization Parameters ▼ 🔗 ```\nmessage: str\n``` default = \"Error raised.\" The error message to be displayed to the user. Can be HTML, which will be rendered in the modal.🔗 ```\nduration: float | None\n``` default = 10 The duration in seconds to display the error message. If None or 0, the error message will be displayed until the user closes it.🔗 ```\nvisible: bool\n``` default = True Whether the error message should be displayed in the UI.🔗 ```\ntitle: str\n``` default = \"Error\" The title to be displayed to the user at the top of the error modal.🔗 ```\nprint_exception: bool\n``` default = True Whether to print traceback of the error to the console when the error is raised. Demos calculatorblocks_chained_events   Alerts","type":"DOCS"},{"title":"Info","slug":"/main/docs/gradio/info","content":"Info ```\ngradio.Info(\"Helpful info message ℹ️\", duration=5)\n``` Description This function allows you to pass custom info messages to the user. You can do so simply by writing gr.Info('message here') in your function, and when that line is executed the custom message will appear in a modal on the demo. The modal is gray by default and has the heading: \"Info.\" Queue must be enabled for this behavior; otherwise, the message will be printed to the console. Example Usage ```\nimport gradio as gr\ndef hello_world():\n    gr.Info('This is some info.')\n    return \"hello world\"\nwith gr.Blocks() as demo:\n    md = gr.Markdown()\n    demo.load(hello_world, inputs=None, outputs=[md])\ndemo.queue().launch()\n``` Initialization Parameters ▼ 🔗 ```\nmessage: str\n``` default = \"Info issued.\" The info message to be displayed to the user. Can be HTML, which will be rendered in the modal.🔗 ```\nduration: float | None\n``` default = 10 The duration in seconds that the info message should be displayed for. If None or 0, the message will be displayed indefinitely until the user closes it.🔗 ```\nvisible: bool\n``` default = True Whether the error message should be displayed in the UI.🔗 ```\ntitle: str\n``` default = \"Info\" The title to be displayed to the user at the top of the modal. Demos blocks_chained_events   Alerts","type":"DOCS"},{"title":"Warning","slug":"/main/docs/gradio/warning","content":"Warning ```\ngradio.Warning(\"A warning occured ⛔️!\", duration=5)\n``` Description This function allows you to pass custom warning messages to the user. You can do so simply by writing gr.Warning('message here') in your function, and when that line is executed the custom message will appear in a modal on the demo. The modal is yellow by default and has the heading: \"Warning.\" Queue must be enabled for this behavior; otherwise, the warning will be printed to the console using the warnings library. Example Usage ```\nimport gradio as gr\ndef hello_world():\n    gr.Warning('This is a warning message.')\n    return \"hello world\"\nwith gr.Blocks() as demo:\n    md = gr.Markdown()\n    demo.load(hello_world, inputs=None, outputs=[md])\ndemo.queue().launch()\n``` Initialization Parameters ▼ 🔗 ```\nmessage: str\n``` default = \"Warning issued.\" The warning message to be displayed to the user. Can be HTML, which will be rendered in the modal.🔗 ```\nduration: float | None\n``` default = 10 The duration in seconds that the warning message should be displayed for. If None or 0, the message will be displayed indefinitely until the user closes it.🔗 ```\nvisible: bool\n``` default = True Whether the error message should be displayed in the UI.🔗 ```\ntitle: str\n``` default = \"Warning\" The title to be displayed to the user at the top of the modal. Demos blocks_chained_events   Alerts","type":"DOCS"},{"title":"mount_gradio_app","slug":"/main/docs/gradio/mount_gradio_app","content":"mount_gradio_app ```\ngradio.mount_gradio_app(···)\n``` Description Mount a gradio.Blocks to an existing FastAPI application.  Example Usage ```\nfrom fastapi import FastAPI\nimport gradio as gr\napp = FastAPI()\n@app.get(\"/\")\ndef read_main():\n    return {\"message\": \"This is your main app\"}\nio = gr.Interface(lambda x: \"Hello, \" + x + \"!\", \"textbox\", \"textbox\")\napp = gr.mount_gradio_app(app, io, path=\"/gradio\")\n``` Then run uvicorn run:app from the terminal and navigate to http://localhost:8000/gradio. Initialization Parameters ▼ 🔗 ```\napp: fastapi.FastAPI\n```  The parent FastAPI application. If it configures its own `CORSMiddleware`, Gradio will not add its own CORS headers to the mounted app, so that your `allow_origins` policy is the one that applies.🔗 ```\nblocks: gradio.Blocks\n```  The blocks object we want to mount to the parent app.🔗 ```\npath: str\n```  The path at which the gradio application will be mounted, e.g. &quot;/gradio&quot;.🔗 ```\nserver_name: str\n``` default = \"0.0.0.0\" The server name on which the Gradio app will be run.🔗 ```\nserver_port: int\n``` default = 7860 The port on which the Gradio app will be run.🔗 ```\nfooter_links: list[Literal['api', 'gradio', 'settings', 'runs'] | dict[str, str]] | None\n``` default = None The links to display in the footer of the app. Accepts a list, where each element of the list must be one of &quot;api&quot;, &quot;gradio&quot;, &quot;settings&quot;, or &quot;runs&quot; corresponding to the API docs, &quot;built with Gradio&quot;, the settings page, and the run history page respectively. The &quot;runs&quot; link only appears if `run_history` is True and the browser has at least one saved run for this app. If None, all four links will be shown in the footer. An empty list means that no footer is shown.🔗 ```\nrun_history: bool | None\n``` default = None If True, users can review and reload calls from the run history page at /gradio_api/runs. Runs are saved privately in the browser by default; from that page, a user can instead connect a Hugging Face bucket and save future runs there. Browser history is scoped to the logged-in user if the app uses `auth`. If False, nothing is recorded, the run history page is disabled, and any runs previously saved by this app are deleted from the browser. If None, will use the GRADIO_RUN_HISTORY environment variable or default to True.🔗 ```\napp_kwargs: dict[str, Any] | None\n``` default = None Additional keyword arguments to pass to the underlying FastAPI app as a dictionary of parameter keys and argument values. For example, `{&quot;docs_url&quot;: &quot;/docs&quot;}`🔗 ```\nauth: Callable | tuple[str, str] | list[tuple[str, str]] | None\n``` default = None If provided, username and password (or list of username-password tuples) required to access the gradio app. Can also provide function that takes username and password and returns True if valid login.🔗 ```\nauth_message: str | None\n``` default = None If provided, HTML message provided on login page for this gradio app.🔗 ```\nauth_dependency: Callable[[fastapi.Request], str | None | Awaitable[str | None]] | None\n``` default = None A function that takes a FastAPI request and returns a string user ID or None. If the function returns None for a specific request, that user is not authorized to access the gradio app (they will see a 401 Unauthorized response). To be used with external authentication systems like OAuth. Cannot be used with `auth`.🔗 ```\nroot_path: str | None\n``` default = None The subpath corresponding to the public deployment of this FastAPI application. For example, if the application is served at &quot;https://example.com/myapp&quot;, the `root_path` should be set to &quot;/myapp&quot;. A full URL beginning with http:// or https:// can be provided, which will be used in its entirety. Normally, this does not need to provided (even if you are using a custom `path`). However, if you are serving the FastAPI app behind a proxy, the proxy may not provide the full path to the Gradio app in the request headers. In which case, you can provide the root path here.🔗 ```\nallowed_paths: list[str] | None\n``` default = None List of complete filepaths or parent directories that this gradio app is allowed to serve. Must be absolute paths. Warning: if you provide directories, any files in these directories or their subdirectories are accessible to all users of your app.🔗 ```\nblocked_paths: list[str] | None\n``` default = None List of complete filepaths or parent directories that this gradio app is not allowed to serve (i.e. users of your app are not allowed to access). Must be absolute paths. Warning: takes precedence over `allowed_paths` and all other directories exposed by Gradio by default.🔗 ```\nfavicon_path: str | None\n``` default = None If a path to a file (.png, .gif, or .ico) is provided, it will be used as the favicon for this gradio app&#039;s page.🔗 ```\nshow_error: bool\n``` default = True If True, any errors in the gradio app will be displayed in an alert modal and printed in the browser console log. Otherwise, errors will only be visible in the terminal session running the Gradio app.🔗 ```\nmax_file_size: str | int | None\n``` default = None The maximum file size in bytes that can be uploaded. Can be a string of the form &quot;&lt;value&gt;&lt;unit&gt;&quot;, where value is any positive integer and unit is one of &quot;b&quot;, &quot;kb&quot;, &quot;mb&quot;, &quot;gb&quot;, &quot;tb&quot;. If None, no limit is set.🔗 ```\nssr_mode: bool | None\n``` default = None If True, the Gradio app will be rendered using server-side rendering mode, which is typically more performant and provides better SEO, but this requires Node 20+ to be installed on the system. If False, the app will be rendered using client-side rendering mode. If None, will use GRADIO_SSR_MODE environment variable or default to False.🔗 ```\nnode_server_name: str | None\n``` default = None The name of the Node server to use for SSR. If None, will use GRADIO_NODE_SERVER_NAME environment variable or search for a node binary in the system.🔗 ```\nnode_port: int | None\n``` default = None The port on which the Node server should run. If None, will use GRADIO_NODE_SERVER_PORT environment variable or find a free port.🔗 ```\nenable_monitoring: bool | None\n``` default = None 🔗 ```\npwa: bool | None\n``` default = None 🔗 ```\ni18n: I18n | None\n``` default = None If provided, the i18n instance to use for this gradio app.🔗 ```\nmcp_server: bool | None\n``` default = None If True, the MCP server will be launched on the gradio app. If None, will use GRADIO_MCP_SERVER environment variable or default to False.🔗 ```\ntheme: Theme | str | None\n``` default = None A Theme object or a string representing a theme. If a string, will look for a built-in theme with that name (e.g. &quot;soft&quot; or &quot;default&quot;), or will attempt to load a theme from the Hugging Face Hub (e.g. &quot;gradio/monochrome&quot;). If None, will use the Default theme.🔗 ```\ncss: str | None\n``` default = None Custom css as a code string. This css will be included in the demo webpage.🔗 ```\ncss_paths: str | Path | list[str | Path] | None\n``` default = None Custom css as a pathlib.Path to a css file or a list of such paths. This css files will be read, concatenated, and included in the demo webpage. If the `css` parameter is also set, the css from `css` will be included first.🔗 ```\njs: str | Literal[True] | None\n``` default = None Custom JavaScript provided as either a function or a raw code string. A function is automatically invoked; otherwise the code is executed directly when the page loads. To run JavaScript as a document-level `&lt;script&gt;` tag, use the `head` parameter.🔗 ```\nhead: str | None\n``` default = None Custom html code to insert into the head of the demo webpage. This can be used to add custom meta tags, multiple scripts, stylesheets, etc. to the page.🔗 ```\nhead_paths: str | Path | list[str | Path] | None\n``` default = None Custom html code as a pathlib.Path to a html file or a list of such paths. This html files will be read, concatenated, and included in the head of the demo webpage. If the `head` parameter is also set, the html from `head` will be included first.   Sharing Your App","type":"DOCS"},{"title":"Request","slug":"/main/docs/gradio/request","content":"Request ```\ngradio.Request(···)\n``` Description A Gradio request object that can be used to access the request headers, cookies, query parameters and other information about the request from within the prediction function. The class is a thin wrapper around the fastapi.Request class. Attributes of this class include: headers, client, query_params, session_hash, and path_params. If auth is enabled, the username attribute can be used to get the logged in user. In some environments, the dict-like attributes (e.g. requests.headers, requests.query_params) of this class are automatically converted to dictionaries, so we recommend converting them to dictionaries before accessing attributes for consistent behavior in different environments. Example Usage ```\nimport gradio as gr\ndef echo(text, request: gr.Request):\n    if request:\n        print(\"Request headers dictionary:\", request.headers)\n        print(\"IP address:\", request.client.host)\n        print(\"Query parameters:\", dict(request.query_params))\n        print(\"Session hash:\", request.session_hash)\n    return text\nio = gr.Interface(echo, \"textbox\", \"textbox\").launch()\n``` Initialization Parameters ▼ 🔗 ```\nrequest: fastapi.Request | None\n``` default = None A fastapi.Request🔗 ```\nusername: str | None\n``` default = None The username of the logged in user (if auth is enabled)🔗 ```\nsession_hash: str | None\n``` default = None The session hash of the current session. It is unique for each page load. Demos request_ip_headers   ","type":"DOCS"},{"title":"Flagging","slug":"/main/docs/gradio/flagging","content":"Flagging Description A Gradio Interface includes a ‘Flag’ button that appears underneath the output. By default, clicking on the Flag button sends the input and output data back to the machine where the gradio demo is running, and saves it to a CSV log file. But this default behavior can be changed. To set what happens when the Flag button is clicked, you pass an instance of a subclass of FlaggingCallback to the flagging_callback parameter in the Interface constructor. You can use one of the FlaggingCallback subclasses that are listed below, or you can create your own, which lets you do whatever you want with the data that is being flagged.  SimpleCSVLogger ```\ngradio.SimpleCSVLogger(···)\n``` Description A simplified implementation of the FlaggingCallback abstract class provided for illustrative purposes.  Each flagged sample (both the input and output data) is logged to a CSV file on the machine running the gradio app. Example Usage ```\nimport gradio as gr\ndef image_classifier(inp):\n    return {'cat': 0.3, 'dog': 0.7}\ndemo = gr.Interface(fn=image_classifier, inputs=\"image\", outputs=\"label\",\n                    flagging_callback=SimpleCSVLogger())\n```      CSVLogger ```\ngradio.CSVLogger(···)\n``` Description The default implementation of the FlaggingCallback abstract class in gradio>=5.0. Each flagged sample (both the input and output data) is logged to a CSV file with headers on the machine running the gradio app. Unlike ClassicCSVLogger, this implementation is concurrent-safe and it creates a new dataset file every time the headers of the CSV (derived from the labels of the components) change. It also only creates columns for \"username\" and \"flag\" if the flag_option and username are provided, respectively.  Example Usage ```\nimport gradio as gr\ndef image_classifier(inp):\n    return {'cat': 0.3, 'dog': 0.7}\ndemo = gr.Interface(fn=image_classifier, inputs=\"image\", outputs=\"label\",\n                    flagging_callback=CSVLogger())\n``` Initialization Parameters ▼ 🔗 ```\nsimplify_file_data: bool\n``` default = True If True, the file data will be simplified before being written to the CSV file. If CSVLogger is being used to cache examples, this is set to False to preserve the original FileData class🔗 ```\nverbose: bool\n``` default = True If True, prints messages to the console about the dataset file creation🔗 ```\ndataset_file_name: str | None\n``` default = None The name of the dataset file to be created (should end in &quot;.csv&quot;). If None, the dataset file will be named &quot;dataset1.csv&quot; or the next available number.   Using Flagging","type":"DOCS"},{"title":"Theming","slug":"/main/docs/gradio/themes","content":"Theming Introduction Gradio features a built-in theming engine that lets you customize the look and feel of your app. You can choose from a variety of themes, or create your own. To do so, pass the theme= kwarg to the Blocks or Interface constructor. For example: ```\nwith gr.Blocks(theme=gr.themes.Soft()) as demo:\n    ...\n```  Gradio comes with a set of prebuilt themes which you can load from gr.themes.*. These are: — gr.themes.Base() — gr.themes.Default() — gr.themes.Glass() — gr.themes.Monochrome() — gr.themes.Soft() Each of these themes set values for hundreds of CSS variables. You can use prebuilt themes as a starting point for your own custom themes, or you can create your own themes from scratch. Let’s take a look at each approach. Using the Theme Builder The easiest way to build a theme is using the Theme Builder. To launch the Theme Builder locally, run the following code: ```\nimport gradio as gr\n\ngr.themes.builder()\n```  You can use the Theme Builder running on Spaces above, though it runs much faster when you launch it locally via gr.themes.builder(). As you edit the values in the Theme Builder, the app will preview updates in real time. You can download the code to generate the theme you’ve created so you can use it in any Gradio app. In the rest of the guide, we will cover building themes programmatically. Extending Themes via the Constructor Although each theme has hundreds of CSS variables, the values for most these variables are drawn from 8 core variables which can be set through the constructor of each prebuilt theme. Modifying these 8 arguments allows you to quickly change the look and feel of your app. Core Colors The first 3 constructor arguments set the colors of the theme and are gradio.themes.Color objects. Internally, these Color objects hold brightness values for the palette of a single hue, ranging from 50, 100, 200…, 800, 900, 950. Other CSS variables are derived from these 3 colors. The 3 color constructor arguments are: — primary_hue: This is the color draws attention in your theme. In the default theme, this is set to gradio.themes.colors.orange. — secondary_hue: This is the color that is used for secondary elements in your theme. In the default theme, this is set to gradio.themes.colors.blue. — neutral_hue: This is the color that is used for text and other neutral elements in your theme. In the default theme, this is set to gradio.themes.colors.gray. You could modify these values using their string shortcuts, such as ```\nwith gr.Blocks(theme=gr.themes.Default(primary_hue=\"red\", secondary_hue=\"pink\")) as demo:\n    ...\n``` or you could use the Color objects directly, like this: ```\nwith gr.Blocks(theme=gr.themes.Default(primary_hue=gr.themes.colors.red, secondary_hue=gr.themes.colors.pink)) as demo:\n    ...\n```  Predefined colors are: — slate — gray — zinc — neutral — stone — red — orange — amber — yellow — lime — green — emerald — teal — cyan — sky — blue — indigo — violet — purple — fuchsia — pink — rose You could also create your own custom Color objects and pass them in. Core Sizing The next 3 constructor arguments set the sizing of the theme and are gradio.themes.Size objects. Internally, these Size objects hold pixel size values that range from xxs to xxl. Other CSS variables are derived from these 3 sizes. — spacing_size: This sets the padding within and spacing between elements. In the default theme, this is set to gradio.themes.sizes.spacing_md. — radius_size: This sets the roundedness of corners of elements. In the default theme, this is set to gradio.themes.sizes.radius_md. — text_size: This sets the font size of text. In the default theme, this is set to gradio.themes.sizes.text_md. You could modify these values using their string shortcuts, such as ```\nwith gr.Blocks(theme=gr.themes.Default(spacing_size=\"sm\", radius_size=\"none\")) as demo:\n    ...\n``` or you could use the Size objects directly, like this: ```\nwith gr.Blocks(theme=gr.themes.Default(spacing_size=gr.themes.sizes.spacing_sm, radius_size=gr.themes.sizes.radius_none)) as demo:\n    ...\n```  The predefined size objects are: — radius_none — radius_sm — radius_md — radius_lg — spacing_sm — spacing_md — spacing_lg — text_sm — text_md — text_lg You could also create your own custom Size objects and pass them in. Core Fonts The final 2 constructor arguments set the fonts of the theme. You can pass a list of fonts to each of these arguments to specify fallbacks. If you provide a string, it will be loaded as a system font. If you provide a gradio.themes.GoogleFont, the font will be loaded from Google Fonts. — font: This sets the primary font of the theme. In the default theme, this is set to gradio.themes.GoogleFont(\"Source Sans Pro\"). — font_mono: This sets the monospace font of the theme. In the default theme, this is set to gradio.themes.GoogleFont(\"IBM Plex Mono\"). You could modify these values such as the following: ```\nwith gr.Blocks(theme=gr.themes.Default(font=[gr.themes.GoogleFont(\"Inconsolata\"), \"Arial\", \"sans-serif\"])) as demo:\n    ...\n```  Extending Themes via .set() You can also modify the values of CSS variables after the theme has been loaded. To do so, use the .set() method of the theme object to get access to the CSS variables. For example: ```\ntheme = gr.themes.Default(primary_hue=\"blue\").set(\n    loader_color=\"#FF0000\",\n    slider_color=\"#FF0000\",\n)\n\nwith gr.Blocks(theme=theme) as demo:\n    ...\n``` In the example above, we’ve set the loader_color and slider_color variables to #FF0000, despite the overall primary_color using the blue color palette. You can set any CSS variable that is defined in the theme in this manner. Your IDE type hinting should help you navigate these variables. Since there are so many CSS variables, let’s take a look at how these variables are named and organized. CSS Variable Naming Conventions CSS variable names can get quite long, like button_primary_background_fill_hover_dark! However they follow a common naming convention that makes it easy to understand what they do and to find the variable you’re looking for. Separated by underscores, the variable name is made up of: — 1. The target element, such as button, slider, or block. — 2. The target element type or sub-element, such as button_primary, or block_label. — 3. The property, such as button_primary_background_fill, or block_label_border_width. — 4. Any relevant state, such as button_primary_background_fill_hover. — 5. If the value is different in dark mode, the suffix _dark. For example, input_border_color_focus_dark. Of course, many CSS variable names are shorter than this, such as table_border_color, or input_shadow. CSS Variable Organization Though there are hundreds of CSS variables, they do not all have to have individual values. They draw their values by referencing a set of core variables and referencing each other. This allows us to only have to modify a few variables to change the look and feel of the entire theme, while also getting finer control of individual elements that we may want to modify. Referencing Core Variables To reference one of the core constructor variables, precede the variable name with an asterisk. To reference a core color, use the *primary_, *secondary_, or *neutral_ prefix, followed by the brightness value. For example: ```\ntheme = gr.themes.Default(primary_hue=\"blue\").set(\n    button_primary_background_fill=\"*primary_200\",\n    button_primary_background_fill_hover=\"*primary_300\",\n)\n``` In the example above, we’ve set the button_primary_background_fill and button_primary_background_fill_hover variables to *primary_200 and *primary_300. These variables will be set to the 200 and 300 brightness values of the blue primary color palette, respectively. Similarly, to reference a core size, use the *spacing_, *radius_, or *text_ prefix, followed by the size value. For example: ```\ntheme = gr.themes.Default(radius_size=\"md\").set(\n    button_primary_border_radius=\"*radius_xl\",\n)\n``` In the example above, we’ve set the button_primary_border_radius variable to *radius_xl. This variable will be set to the xl setting of the medium radius size range. Referencing Other Variables Variables can also reference each other. For example, look at the example below: ```\ntheme = gr.themes.Default().set(\n    button_primary_background_fill=\"#FF0000\",\n    button_primary_background_fill_hover=\"#FF0000\",\n    button_primary_border=\"#FF0000\",\n)\n``` Having to set these values to a common color is a bit tedious. Instead, we can reference the button_primary_background_fill variable in the button_primary_background_fill_hover and button_primary_border variables, using a * prefix. ```\ntheme = gr.themes.Default().set(\n    button_primary_background_fill=\"#FF0000\",\n    button_primary_background_fill_hover=\"*button_primary_background_fill\",\n    button_primary_border=\"*button_primary_background_fill\",\n)\n``` Now, if we change the button_primary_background_fill variable, the button_primary_background_fill_hover and button_primary_border variables will automatically update as well. This is particularly useful if you intend to share your theme - it makes it easy to modify the theme without having to change every variable. Note that dark mode variables automatically reference each other. For example: ```\ntheme = gr.themes.Default().set(\n    button_primary_background_fill=\"#FF0000\",\n    button_primary_background_fill_dark=\"#AAAAAA\",\n    button_primary_border=\"*button_primary_background_fill\",\n    button_primary_border_dark=\"*button_primary_background_fill_dark\",\n)\n``` button_primary_border_dark will draw its value from button_primary_background_fill_dark, because dark mode always draw from the dark version of the variable. Creating a Full Theme Let’s say you want to create a theme from scratch! We’ll go through it step by step - you can also see the source of prebuilt themes in the gradio source repo for reference - here’s the source for the Monochrome theme. Our new theme class will inherit from gradio.themes.Base, a theme that sets a lot of convenient defaults. Let’s make a simple demo that creates a dummy theme called Seafoam, and make a simple app that uses it. $code_theme_new_step_1  The Base theme is very barebones, and uses gr.themes.Blue as it primary color - you’ll note the primary button and the loading animation are both blue as a result. Let’s change the defaults core arguments of our app. We’ll overwrite the constructor and pass new defaults for the core constructor arguments. We’ll use gr.themes.Emerald as our primary color, and set secondary and neutral hues to gr.themes.Blue. We’ll make our text larger using text_lg. We’ll use Quicksand as our default font, loaded from Google Fonts. $code_theme_new_step_2  See how the primary button and the loading animation are now green? These CSS variables are tied to the primary_hue variable. Let’s modify the theme a bit more directly. We’ll call the set() method to overwrite CSS variable values explicitly. We can use any CSS logic, and reference our core constructor arguments using the * prefix. $code_theme_new_step_3  Look how fun our theme looks now! With just a few variable changes, our theme looks completely different. You may find it helpful to explore the source code of the other prebuilt themes to see how they modified the base theme. You can also find your browser’s Inspector useful to select elements from the UI and see what CSS variables are being used in the styles panel. Sharing Themes Once you have created a theme, you can upload it to the HuggingFace Hub to let others view it, use it, and build off of it! Uploading a Theme There are two ways to upload a theme, via the theme class instance or the command line. We will cover both of them with the previously created seafoam theme. Via the class instance Each theme instance has a method called push_to_hub we can use to upload a theme to the HuggingFace hub. ```\nseafoam.push_to_hub(repo_name=\"seafoam\",\n                    version=\"0.0.1\",\n\t\t\t\t\thf_token=\"&lt;token>\")\n``` Via the command line First save the theme to disk ```\nseafoam.dump(filename=\"seafoam.json\")\n``` Then use the upload_theme command: ```\nupload_theme\\\n\"seafoam.json\"\\\n\"seafoam\"\\\n--version \"0.0.1\"\\\n--hf_token \"&lt;token>\"\n``` In order to upload a theme, you must have a HuggingFace account and pass your Access Token as the hf_token argument. However, if you log in via the HuggingFace command line (which comes installed with gradio),\nyou can omit the hf_token argument. The version argument lets you specify a valid semantic version string for your theme.\nThat way your users are able to specify which version of your theme they want to use in their apps. This also lets you publish updates to your theme without worrying\nabout changing how previously created apps look. The version argument is optional. If omitted, the next patch version is automatically applied. Theme Previews By calling push_to_hub or upload_theme, the theme assets will be stored in a HuggingFace space. The theme preview for our seafoam theme is here: seafoam preview.  Discovering Themes The Theme Gallery shows all the public gradio themes. After publishing your theme,\nit will automatically show up in the theme gallery after a couple of minutes. You can sort the themes by the number of likes on the space and from most to least recently created as well as toggling themes between light and dark mode.  Downloading To use a theme from the hub, use the from_hub method on the ThemeClass and pass it to your app: ```\nmy_theme = gr.Theme.from_hub(\"gradio/seafoam\")\n\nwith gr.Blocks(theme=my_theme) as demo:\n    ....\n``` You can also pass the theme string directly to Blocks or Interface (gr.Blocks(theme=\"gradio/seafoam\")) You can pin your app to an upstream theme version by using semantic versioning expressions. For example, the following would ensure the theme we load from the seafoam repo was between versions 0.0.1 and 0.1.0: ```\nwith gr.Blocks(theme=\"gradio/seafoam@>=0.0.1,&lt;0.1.0\") as demo:\n    ....\n``` Enjoy creating your own themes! If you make one you’re proud of, please share it with the world by uploading it to the hub!\nIf you tag us on Twitter we can give your theme a shout out!","type":"DOCS"},{"title":"NO_RELOAD","slug":"/main/docs/gradio/NO_RELOAD","content":"NO_RELOAD ```\nif gr.NO_RELOAD:\n``` Description Any code in a if gr.NO_RELOAD code-block will not be re-evaluated when the source file is reloaded. This is helpful for importing modules that do not like to be reloaded (tiktoken, numpy) as well as database connections and long running set up code. Example Usage ```\nimport gradio as gr\n\nif gr.NO_RELOAD:\n\tfrom transformers import pipeline\n\tpipe = pipeline(\"text-classification\", model=\"cardiffnlp/twitter-roberta-base-sentiment-latest\")\n\ngr.Interface.from_pipeline(pipe).launch()\n```","type":"DOCS"},{"title":"Introduction","slug":"/main/docs/python-client/introduction","content":"Introduction The lightweight Gradio client libraries make it easy to use any Gradio app as an API. We currently support both a Python client library as well as a JavaScript client library. The Python client library is gradio_client. It’s included in the latest versions of the gradio package, but for a more lightweight experience, you can install it using pip without having to install gradio: ```bash\npip install gradio_client\n``` Getting Started with the Gradio Python client The Gradio Python client makes it very easy to use any Gradio app as an API. As an example, consider this Hugging Face Space that transcribes audio files that are recorded from the microphone.  Using the gradio_client library, we can easily use the Gradio as an API to transcribe audio files programmatically. Here’s the entire code to do it: ```python\nfrom gradio_client import Client, file\n\nclient = Client(\"abidlabs/whisper\")\n\nclient.predict(\n    audio=file(\"audio_sample.wav\")\n)\n\n>> \"This is a test of the whisper speech recognition model.\"\n``` The Gradio client works with any hosted Gradio app! Although the Client is mostly used with apps hosted on Hugging Face Spaces, your app can be hosted anywhere, such as your own server. Prerequisites: To use the Gradio client, you do not need to know the gradio library in great detail. However, it is helpful to have general familiarity with Gradio’s concepts of input and output components. Installation If you already have a recent version of gradio, then the gradio_client is included as a dependency. But note that this documentation reflects the latest version of the gradio_client, so upgrade if you’re not sure! The lightweight gradio_client package can be installed from pip (or pip3) and is tested to work with Python versions 3.9 or higher: ```bash\n$ pip install --upgrade gradio_client\n``` Connecting to a Gradio App on Hugging Face Spaces Start by connecting instantiating a Client object and connecting it to a Gradio app that is running on Hugging Face Spaces. ```python\nfrom gradio_client import Client\n\nclient = Client(\"abidlabs/en2fr\")  # a Space that translates from English to French\n``` You can also connect to private Spaces by passing in your HF token with the hf_token parameter. You can get your HF token here: https://huggingface.co/settings/tokens ```python\nfrom gradio_client import Client\n\nclient = Client(\"abidlabs/my-private-space\", hf_token=\"...\")\n``` Duplicating a Space for private use While you can use any public Space as an API, you may get rate limited by Hugging Face if you make too many requests. For unlimited usage of a Space, simply duplicate the Space to create a private Space,\nand then use it to make as many requests as you’d like! The gradio_client includes a class method: Client.duplicate() to make this process simple (you’ll need to pass in your Hugging Face token or be logged in using the Hugging Face CLI): ```python\nimport os\nfrom gradio_client import Client, file\n\nHF_TOKEN = os.environ.get(\"HF_TOKEN\")\n\nclient = Client.duplicate(\"abidlabs/whisper\", hf_token=HF_TOKEN)\nclient.predict(file(\"audio_sample.wav\"))\n\n>> \"This is a test of the whisper speech recognition model.\"\n``` If you have previously duplicated a Space, re-running duplicate() will not create a new Space. Instead, the Client will attach to the previously-created Space. So it is safe to re-run the Client.duplicate() method multiple times. Note: if the original Space uses GPUs, your private Space will as well, and your Hugging Face account will get billed based on the price of the GPU. To minimize charges, your Space will automatically go to sleep after 1 hour of inactivity. You can also set the hardware using the hardware parameter of duplicate(). Connecting a general Gradio app If your app is running somewhere else, just provide the full URL instead, including the “http://” or “https://“. Here’s an example of making predictions to a Gradio app that is running on a share URL: ```python\nfrom gradio_client import Client\n\nclient = Client(\"https://bec81a83-5b5c-471e.gradio.live\")\n``` Inspecting the API endpoints Once you have connected to a Gradio app, you can view the APIs that are available to you by calling the Client.view_api() method. For the Whisper Space, we see the following: ```bash\nClient.predict() Usage Info\n---------------------------\nNamed API endpoints: 1\n\n - predict(audio, api_name=\"/predict\") -> output\n    Parameters:\n     - [Audio] audio: filepath (required)  \n    Returns:\n     - [Textbox] output: str \n``` We see  that we have 1 API endpoint in this space, and shows us how to use the API endpoint to make a prediction: we should call the .predict() method (which we will explore below), providing a parameter input_audio of type str, which is a filepath or URL. We should also provide the api_name='/predict' argument to the predict() method. Although this isn’t necessary if a Gradio app has only 1 named endpoint, it does allow us to call different endpoints in a single app if they are available. The “View API” Page As an alternative to running the .view_api() method, you can click on the “Use via API” link in the footer of the Gradio app, which shows us the same information, along with example usage.  The View API page also includes an “API Recorder” that lets you interact with the Gradio UI normally and converts your interactions into the corresponding code to run with the Python Client. Making a prediction The simplest way to make a prediction is simply to call the .predict() function with the appropriate arguments: ```python\nfrom gradio_client import Client\n\nclient = Client(\"abidlabs/en2fr\", api_name='/predict')\nclient.predict(\"Hello\")\n\n>> Bonjour\n``` If there are multiple parameters, then you should pass them as separate arguments to .predict(), like this: ```python\nfrom gradio_client import Client\n\nclient = Client(\"gradio/calculator\")\nclient.predict(4, \"add\", 5)\n\n>> 9.0\n``` It is recommended to provide key-word arguments instead of positional arguments: ```python\nfrom gradio_client import Client\n\nclient = Client(\"gradio/calculator\")\nclient.predict(num1=4, operation=\"add\", num2=5)\n\n>> 9.0\n``` This allows you to take advantage of default arguments. For example, this Space includes the default value for the Slider component so you do not need to provide it when accessing it with the client. ```python\nfrom gradio_client import Client\n\nclient = Client(\"abidlabs/image_generator\")\nclient.predict(text=\"an astronaut riding a camel\")\n``` The default value is the initial value of the corresponding Gradio component. If the component does not have an initial value, but if the corresponding argument in the predict function has a default value of None, then that parameter is also optional in the client. Of course, if you’d like to override it, you can include it as well: ```python\nfrom gradio_client import Client\n\nclient = Client(\"abidlabs/image_generator\")\nclient.predict(text=\"an astronaut riding a camel\", steps=25)\n``` For providing files or URLs as inputs, you should pass in the filepath or URL to the file enclosed within gradio_client.file(). This takes care of uploading the file to the Gradio server and ensures that the file is preprocessed correctly: ```python\nfrom gradio_client import Client, file\n\nclient = Client(\"abidlabs/whisper\")\nclient.predict(\n    audio=file(\"https://audio-samples.github.io/samples/mp3/blizzard_unconditional/sample-0.mp3\")\n)\n\n>> \"My thought I have nobody by a beauty and will as you poured. Mr. Rochester is serve in that so don't find simpus, and devoted abode, to at might in a r—\"\n``` Running jobs asynchronously Oe should note that .predict() is a blocking operation as it waits for the operation to complete before returning the prediction. In many cases, you may be better off letting the job run in the background until you need the results of the prediction. You can do this by creating a Job instance using the .submit() method, and then later calling .result() on the job to get the result. For example: ```python\nfrom gradio_client import Client\n\nclient = Client(space=\"abidlabs/en2fr\")\njob = client.submit(\"Hello\", api_name=\"/predict\")  # This is not blocking\n\n# Do something else\n\njob.result()  # This is blocking\n\n>> Bonjour\n``` Adding callbacks Alternatively, one can add one or more callbacks to perform actions after the job has completed running, like this: ```python\nfrom gradio_client import Client\n\ndef print_result(x):\n    print(\"The translated result is: {x}\")\n\nclient = Client(space=\"abidlabs/en2fr\")\n\njob = client.submit(\"Hello\", api_name=\"/predict\", result_callbacks=[print_result])\n\n# Do something else\n\n>> The translated result is: Bonjour\n\n``` Status The Job object also allows you to get the status of the running job by calling the .status() method. This returns a StatusUpdate object with the following attributes: code (the status code, one of a set of defined strings representing the status. See the utils.Status class), rank (the current position of this job in the queue), queue_size (the total queue size), eta (estimated time this job will complete), success (a boolean representing whether the job completed successfully), and time (the time that the status was generated). ```py\nfrom gradio_client import Client\n\nclient = Client(src=\"gradio/calculator\")\njob = client.submit(5, \"add\", 4, api_name=\"/predict\")\njob.status()\n\n>> &lt;Status.STARTING: 'STARTING'>\n``` Note: The Job class also has a .done() instance method which returns a boolean indicating whether the job has completed. Cancelling Jobs The Job class also has a .cancel() instance method that cancels jobs that have been queued but not started. For example, if you run: ```py\nclient = Client(\"abidlabs/whisper\")\njob1 = client.submit(file(\"audio_sample1.wav\"))\njob2 = client.submit(file(\"audio_sample2.wav\"))\njob1.cancel()  # will return False, assuming the job has started\njob2.cancel()  # will return True, indicating that the job has been canceled\n``` If the first job has started processing, then it will not be canceled. If the second job\nhas not yet started, it will be successfully canceled and removed from the queue. Generator Endpoints Some Gradio API endpoints do not return a single value, rather they return a series of values. You can get the series of values that have been returned at any time from such a generator endpoint by running job.outputs(): ```py\nfrom gradio_client import Client\n\nclient = Client(src=\"gradio/count_generator\")\njob = client.submit(3, api_name=\"/count\")\nwhile not job.done():\n    time.sleep(0.1)\njob.outputs()\n\n>> ['0', '1', '2']\n``` Note that running job.result() on a generator endpoint only gives you the first value returned by the endpoint. The Job object is also iterable, which means you can use it to display the results of a generator function as they are returned from the endpoint. Here’s the equivalent example using the Job as a generator: ```py\nfrom gradio_client import Client\n\nclient = Client(src=\"gradio/count_generator\")\njob = client.submit(3, api_name=\"/count\")\n\nfor o in job:\n    print(o)\n\n>> 0\n>> 1\n>> 2\n``` You can also cancel jobs that that have iterative outputs, in which case the job will finish as soon as the current iteration finishes running. ```py\nfrom gradio_client import Client\nimport time\n\nclient = Client(\"abidlabs/test-yield\")\njob = client.submit(\"abcdef\")\ntime.sleep(3)\njob.cancel()  # job cancels after 2 iterations\n``` Demos with Session State Gradio demos can include session state, which provides a way for demos to persist information from user interactions within a page session. For example, consider the following demo, which maintains a list of words that a user has submitted in a gr.State component. When a user submits a new word, it is added to the state, and the number of previous occurrences of that word is displayed: ```python\nimport gradio as gr\n\ndef count(word, list_of_words):\n    return list_of_words.count(word), list_of_words + [word]\n\nwith gr.Blocks() as demo:\n    words = gr.State([])\n    textbox = gr.Textbox()\n    number = gr.Number()\n    textbox.submit(count, inputs=[textbox, words], outputs=[number, words])\n    \ndemo.launch()\n``` If you were to connect this this Gradio app using the Python Client, you would notice that the API information only shows a single input and output: ```csv\nClient.predict() Usage Info\n---------------------------\nNamed API endpoints: 1\n\n - predict(word, api_name=\"/count\") -> value_31\n    Parameters:\n     - [Textbox] word: str (required)  \n    Returns:\n     - [Number] value_31: float \n``` That is because the Python client handles state automatically for you — as you make a series of requests, the returned state from one request is stored internally and automatically supplied for the subsequent request. If you’d like to reset the state, you can do that by calling Client.reset_session().","type":"DOCS"},{"title":"Clients 1.0 Launch!","slug":"/main/docs/python-client/version-1-release","content":"Clients 1.0 Launch! We’re excited to unveil the first major release of the Gradio clients.\nWe’ve made it even easier to turn any Gradio application into a production endpoint thanks to the clients’ ergonomic, transparent, and portable design. Ergonomic API 💆  Stream From a Gradio app in 5 lines  Use the submit method to get a job you can iterate over.  In python: ```python\nfrom gradio_client import Client\n\nclient = Client(\"gradio/llm_stream\")\n\nfor result in client.submit(\"What's the best UI framework in Python?\"):\n    print(result)\n```  In typescript: ```ts\nimport { Client } from \"@gradio/client\";\n\nconst client = await Client.connect(\"gradio/llm_stream\")\nconst job = client.submit(\"/predict\", {\"text\": \"What's the best UI framework in Python?\"})\n\nfor await (const msg of job) console.log(msg.data)\n```  Use the same keyword arguments as the app  In the examples below, the upstream app has a function with parameters called `message`, `system_prompt`, and `tokens`.\nWe can see that the client `predict` call uses the same arguments. In python: ```python\nfrom gradio_client import Client\n\nclient = Client(\"http://127.0.0.1:7860/\")\nresult = client.predict(\n\t\tmessage=\"Hello!!\",\n\t\tsystem_prompt=\"You are helpful AI.\",\n\t\ttokens=10,\n\t\tapi_name=\"/chat\"\n)\nprint(result)\n``` In typescript: ```ts\nimport { Client } from \"@gradio/client\";\n\nconst client = await Client.connect(\"http://127.0.0.1:7860/\");\nconst result = await client.predict(\"/chat\", { \t\t\n\t\tmessage: \"Hello!!\", \t\t\n\t\tsystem_prompt: \"Hello!!\", \t\t\n\t\ttokens: 10, \n});\n\nconsole.log(result.data);\n```  Better Error Messages  If something goes wrong in the upstream app, the client will raise the same exception as the app provided that `show_error=True` in the original app's `launch()` function, or it's a `gr.Error` exception. Transparent Design 🪟 Anything you can do in the UI, you can do with the client: 🔐Authentication 🛑 Job Cancelling ℹ️ Access Queue Position and API 📕 View the API information  Here's an example showing how to display the queue position of a pending job: ```python\nfrom gradio_client import Client\n\nclient = Client(\"gradio/diffusion_model\")\n\njob = client.submit(\"A cute cat\")\nwhile not job.done():\n    status = job.status()\n    print(f\"Current in position {status.rank} out of {status.queue_size}\")\n``` Portable Design ⛺️  The client can run from pretty much any python and javascript environment (node, deno, the browser, Service Workers).  Here's an example using the client from a Flask server using gevent: ```python\nfrom gevent import monkey\nmonkey.patch_all()\n\nfrom gradio_client import Client\nfrom flask import Flask, send_file\nimport time\n\napp = Flask(__name__)\n\nimageclient = Client(\"gradio/diffusion_model\")\n\n@app.route(\"/gen\")\ndef gen():\n      result = imageclient.predict(\n                \"A cute cat\",\n                api_name=\"/predict\"\n              )\n      return send_file(result)\n\nif __name__ == \"__main__\":\n      app.run(host=\"0.0.0.0\", port=5000)\n``` v1.0 Migration Guide and Breaking Changes  Python The `serialize` argument of the `Client` class was removed and has no effect. The `upload_files` argument of the `Client` was removed. All filepaths must be wrapped in the `handle_file` method. For example, `caption = client.predict(handle_file('./dog.jpg'))`. The `output_dir` argument was removed. It is not specified in the `download_files` argument.  Javascript  The client has been redesigned entirely. It was refactored from a function into a class. An instance can now be constructed by awaiting the `connect` method. ```js\nconst app = await Client.connect(\"gradio/whisper\")\n``` The app variable has the same methods as the python class (submit, predict, view_api, duplicate).","type":"DOCS"},{"title":"Using ZeroGPU Spaces with the Clients","slug":"/main/docs/python-client/using-zero-gpu-spaces","content":"Using ZeroGPU Spaces with the Clients Hugging Face Spaces now offers a new hardware option called ZeroGPU.\nZeroGPU is a “serverless” cluster of spaces that let Gradio applications run on A100 GPUs for free.\nThese kinds of spaces are a great foundation to build new applications on top of with the python gradio client, but you need to take care to avoid ZeroGPU’s rate limiting. Explaining Rate Limits for ZeroGPU ZeroGPU spaces are rate-limited to ensure that a single user does not hog all of the available GPUs.\nThe limit is controlled by a special token that the Hugging Face Hub infrastructure adds to all incoming requests to Spaces.\nThis token is a request header called X-IP-Token and its value changes depending on the user who makes a request to the ZeroGPU space.  Let’s say you want to create a space (Space A) that uses a ZeroGPU space (Space B) programmatically.\nNormally, calling Space B from Space A with the Gradio Python client would quickly exhaust Space B’s rate limit, as all the requests to the ZeroGPU space\nwould be missing the X-IP-Token request header and would therefore be treated as unauthenticated. In order to avoid this, we need to extract the X-IP-Token of the user using Space A before we call Space B programmatically.\nWhere possible, specifically in the case of functions that are passed into event listeners directly, Gradio automatically\nextracts the X-IP-Token from the incoming request and passes it into the Gradio Client. But if the Client\nis instantiated outside of such a function, then you may need to pass in the token manually. How to do this will be explained in the following section. Avoiding Rate Limits by Manually Passing an IP Token In the following hypothetical example, when a user presses enter in the textbox, the generate() function\nis called, which calls a second function, text_to_image(). Because the Gradio Client is being\ninstantiated indirectly, in text_to_image(), we will need to extract their token from the X-IP-Token header of the incoming request.\nWe will use this header when constructing the gradio client. ```python\nimport gradio as gr\nfrom gradio_client import Client\n\ndef text_to_image(prompt, request: gr.Request):\n    x_ip_token = request.headers['x-ip-token']\n    client = Client(\"hysts/SDXL\", headers={\"x-ip-token\": x_ip_token})\n    img = client.predict(prompt, api_name=\"/predict\")\n    return img\n\ndef generate(prompt, request: gr.Request):\n    prompt = prompt[:300]\n    return text_to_image(prompt, request)\n\nwith gr.Blocks() as demo:\n    image = gr.Image()\n    prompt = gr.Textbox(max_lines=1)\n    prompt.submit(generate, [prompt], [image])\n\ndemo.launch()\n```","type":"DOCS"},{"title":"Client","slug":"/main/docs/python-client/client","content":"Client ```python\ngradio_client.Client(···)\n``` Description The main Client class for the Python client. This class is used to connect to a remote Gradio app and call its API endpoints.  Example usage ```python\nfrom gradio_client import Client\n\nclient = Client(\"abidlabs/whisper-large-v2\")  # connecting to a Hugging Face Space\nclient.predict(\"test.mp4\", api_name=\"/predict\")\n>> What a nice recording! # returns the result of the remote API call\n\nclient = Client(\"https://bec81a83-5b5c-471e.gradio.live\")  # connecting to a temporary Gradio share URL\njob = client.submit(\"hello\", api_name=\"/predict\")  # runs the prediction in a background thread\njob.result()\n>> 49 # returns the result of the remote API call (blocking call)\n``` Initialization Parameters ▼ 🔗 ```python\nsrc: str\n```  either the name of the Hugging Face Space to load, (e.g. &quot;abidlabs/whisper-large-v2&quot;) or the full URL (including &quot;http&quot; or &quot;https&quot;) of the hosted Gradio app to load (e.g. &quot;http://mydomain.com/app&quot; or &quot;https://bec81a83-5b5c-471e.gradio.live/&quot;).🔗 ```python\ntoken: str | None\n``` default = None optional Hugging Face token to use to access private Spaces. By default, the locally saved token is used if there is one. Find your tokens here: https://huggingface.co/settings/tokens.🔗 ```python\nmax_workers: int\n``` default = 40 maximum number of thread workers that can be used to make requests to the remote Gradio app simultaneously.🔗 ```python\nverbose: bool\n``` default = True whether the client should print statements to the console.🔗 ```python\nauth: tuple[str, str] | None\n``` default = None 🔗 ```python\nhttpx_kwargs: dict[str, Any] | None\n``` default = None additional keyword arguments to pass to `httpx.Client`, `httpx.stream`, `httpx.get` and `httpx.post`. This can be used to set timeouts, proxies, http auth, etc.🔗 ```python\nheaders: dict[str, str] | None\n``` default = None additional headers to send to the remote Gradio app on every request. By default only the HF authorization and user-agent headers are sent. This parameter will override the default headers if they have the same keys.🔗 ```python\ndownload_files: str | Path | Literal[False]\n``` default = \"/tmp/gradio\" directory where the client should download output files  on the local machine from the remote API. By default, uses the value of the GRADIO_TEMP_DIR environment variable which, if not set by the user, is a temporary directory on your machine. If False, the client does not download files and returns a FileData dataclass object with the filepath on the remote machine instead.🔗 ```python\nssl_verify: bool\n``` default = True if False, skips certificate validation which allows the client to connect to Gradio apps that are using self-signed certificates.🔗 ```python\nanalytics_enabled: bool\n``` default = True Whether to allow basic telemetry. If None, will use GRADIO_ANALYTICS_ENABLED environment variable or default to True.🔗 ```python\noauth_token: str | None\n``` default = None optional Hugging Face token for the app to act on your behalf, for endpoints whose function takes a `gr.OAuthToken`. Unlike `token`, which only authenticates you to the app, this is passed to the app&#039;s code, so it is sent only to endpoints that declare they need it — `view_api()` marks those. It is never sent anywhere else, and is not inferred from your locally saved token.   Event Listeners Description Event listeners allow you to respond to user interactions with the UI\n\t\tcomponents you've defined in a Gradio Blocks app. When a user interacts with\n\t\tan element, such as changing a slider value or uploading an image, a\n\t\tfunction is called. Supported Event Listeners The Client component supports the following event listeners. Each event listener takes the\n\t\tsame parameters, which are listed in the Event Parameters table below. Listeners Client.predict(fn, ···) Calls the Gradio API and returns the result (this is a blocking call). Arguments can be provided as positional arguments or as keyword arguments (latter is recommended). &lt;br&gt;Client.submit(fn, ···) Creates and returns a Job object which calls the Gradio API in a background thread. The job can be used to retrieve the status and result of the remote API call.  Arguments can be provided as positional arguments or as keyword arguments (latter is recommended). &lt;br&gt;Client.view_api(fn, ···) Prints the usage info for the API. If the Gradio app has multiple API endpoints, the usage info for each endpoint will be printed separately. If return_format=&quot;dict&quot; the info is returned in dictionary format, as shown in the example below. &lt;br&gt;Client.duplicate(fn, ···) Duplicates a Hugging Face Space under your account and returns a Client object for the new Space. No duplication is created if the Space already exists in your account (to override this, provide a new name for the new Space using to_id). To use this method, you must provide an token or be logged in via the Hugging Face Hub CLI. &lt;br&gt; The new Space will be private by default and use the same hardware as the original Space. This can be changed by using the private and hardware parameters. For hardware upgrades (beyond the basic CPU tier), you may be required to provide billing information on Hugging Face: https://huggingface.co/settings/billing &lt;br&gt; Event Parameters Parameters ▼ 🔗 ```python\nargs: \n```  The positional arguments to pass to the remote API endpoint. The order of the arguments must match the order of the inputs in the Gradio app.🔗 ```python\napi_name: str | None\n``` default = None The name of the API endpoint to call starting with a leading slash, e.g. &quot;/predict&quot;. Does not need to be provided if the Gradio app has only one named API endpoint.🔗 ```python\nfn_index: int | None\n``` default = None As an alternative to api_name, this parameter takes the index of the API endpoint to call, e.g. 0. Both api_name and fn_index can be provided, but if they conflict, api_name will take precedence.🔗 ```python\nheaders: dict[str, str] | None\n``` default = None Additional headers to send to the remote Gradio app on this request. This parameter will overrides the headers provided in the Client constructor if they have the same keys.🔗 ```python\nkwargs: \n```  The keyword arguments to pass to the remote API endpoint.  ","type":"DOCS"},{"title":"Job","slug":"/main/docs/python-client/job","content":"Job ```python\ngradio_client.Job(···)\n``` Description A Job is a wrapper over the Future class that represents a prediction call that has been submitted by the Gradio client. This class is not meant to be instantiated directly, but rather is created by the Client.submit() method.  A Job object includes methods to get the status of the prediction call, as well to get the outputs of the prediction call. Job objects are also iterable, and can be used in a loop to get the outputs of prediction calls as they become available for generator endpoints. Initialization Parameters ▼ 🔗 ```python\nfuture: Future\n```  The future object that represents the prediction call, created by the Client.submit() method🔗 ```python\ncommunicator: Communicator | None\n``` default = None The communicator object that is used to communicate between the client and the background thread running the job🔗 ```python\nverbose: bool\n``` default = True Whether to print any status-related messages to the console🔗 ```python\nspace_id: str | None\n``` default = None The space ID corresponding to the Client object that created this Job object   Event Listeners Description Event listeners allow you to respond to user interactions with the UI\n\t\tcomponents you've defined in a Gradio Blocks app. When a user interacts with\n\t\tan element, such as changing a slider value or uploading an image, a\n\t\tfunction is called. Supported Event Listeners The Job component supports the following event listeners. Each event listener takes the\n\t\tsame parameters, which are listed in the Event Parameters table below. Listeners Job.result(fn, ···) Return the result of the call that the future represents. Raises CancelledError: If the future was cancelled, TimeoutError: If the future didn&#x27;t finish executing before the given timeout, and Exception: If the call raised then that exception will be raised. &lt;br&gt;Job.outputs(fn, ···) Returns a list containing the latest outputs from the Job. &lt;br&gt; If the endpoint has multiple output components, the list will contain a tuple of results. Otherwise, it will contain the results without storing them in tuples. &lt;br&gt; For endpoints that are queued, this list will contain the final job output even if that endpoint does not use a generator function. &lt;br&gt;Job.status(fn, ···) Returns the latest status update from the Job in the form of a StatusUpdate object, which contains the following fields: code, rank, queue_size, success, time, eta, and progress_data. &lt;br&gt; progress_data is a list of updates emitted by the gr.Progress() tracker of the event handler. Each element of the list has the following fields: index, length, unit, progress, desc. If the event handler does not have a gr.Progress() tracker, the progress_data field will be None. &lt;br&gt; Event Parameters Parameters ▼ 🔗 ```python\ntimeout: float | None\n``` default = None The number of seconds to wait for the result if the future isn&#039;t done. If None, then there is no limit on the wait time.  ","type":"DOCS"},{"title":"Gradio And Comet","slug":"/guides/Gradio-and-Comet/","content":"Using Gradio and Comet\nIntroduction\nIn this guide we will demonstrate some of the ways you can use Gradio with Comet. We will cover the basics of using Comet with Gradio and show you some of the ways that you can leverage Gradio's advanced features such as Embedding with iFrames and State to build some amazing model evaluation workflows.\nHere is a list of the topics covered in this guide.\nLogging Gradio UI's to your Comet Experiments\nEmbedding Gradio Applications directly into your Comet Projects\nEmbedding Hugging Face Spaces directly into your Comet Projects\nLogging Model Inferences from your Gradio Application to Comet\nWhat is Comet?\nComet is an MLOps Platform that is designed to help Data Scientists and Teams build better models faster! Comet provides tooling to Track, Explain, Manage, and Monitor your models in a single place! It works with Jupyter Notebooks and Scripts and most importantly it's 100% free!\nSetup\nFirst, install the dependencies needed to run these examples\n``shell\npip install comet_ml torch torchvision transformers gradio shap requests Pillow\n`\nNext, you will need to sign up for a Comet Account. Once you have your account set up, grab your API Key and configure your Comet credentials\nIf you're running these examples as a script, you can either export your credentials as environment variables\n`shell\nexport COMETAPIKEY=\"\"\nexport COMET_WORKSPACE=\"\"\nexport COMETPROJECTNAME=\"\"\n`\nor set them in a .comet.config file in your working directory. You file should be formatted in the following way.\n`shell\n[comet]\napi_key=\nworkspace=\nproject_name=\n`\nIf you are using the provided Colab Notebooks to run these examples, please run the cell with the following snippet before starting the Gradio UI. Running this cell allows you to interactively add your API key to the notebook.\n`python\nimport comet_ml\ncomet_ml.init()\n`\nLogging Gradio UI's to your Comet Experiments\nIn this example, we will go over how to log your Gradio Applications to Comet and interact with them using the Gradio Custom Panel.\nLet's start by building a simple Image Classification example using resnet18.\n`python\nimport comet_ml\nimport requests\nimport torch\nfrom PIL import Image\nfrom torchvision import transforms\ntorch.hub.downloadurlto_file(\"https://github.com/pytorch/hub/raw/master/images/dog.jpg\", \"dog.jpg\")\nif torch.cuda.is_available():\n    device = \"cuda\"\nelse:\n    device = \"cpu\"\nmodel = torch.hub.load(\"pytorch/vision:v0.6.0\", \"resnet18\", pretrained=True).eval()\nmodel = model.to(device)\nDownload human-readable labels for ImageNet.\nresponse = requests.get(\"https://git.io/JJkYN\")\nlabels = response.text.split(\"\\n\")\ndef predict(inp):\n    inp = Image.fromarray(inp.astype(\"uint8\"), \"RGB\")\n    inp = transforms.ToTensor()(inp).unsqueeze(0)\n    with torch.no_grad():\n        prediction = torch.nn.functional.softmax(model(inp.to(device))[0], dim=0)\n    return {labels[i]: float(prediction[i]) for i in range(1000)}\ninputs = gr.Image()\noutputs = gr.Label(numtopclasses=3)\nio = gr.Interface(\n    fn=predict, inputs=inputs, outputs=outputs, examples=[\"dog.jpg\"]\n)\nio.launch(inline=False, share=True)\nexperiment = comet_ml.Experiment()\nexperiment.add_tag(\"image-classifier\")\nio.integrate(comet_ml=experiment)\n`\nThe last line in this snippet will log the URL of the Gradio Application to your Comet Experiment. You can find the URL in the Text Tab of your Experiment.\n    \nAdd the Gradio Panel to your Experiment to interact with your application.\nEmbedding Gradio Applications directly into your Comet Projects\nIf you are permanently hosting your Gradio application, you can embed the UI using the Gradio Panel Extended custom Panel.\nGo to your Comet Project page, and head over to the Panels tab. Click the + Add button to bring up the Panels search page.\nNext, search for Gradio Panel Extended in the Public Panels section and click Add.\nOnce you have added your Panel, click Edit to access to the Panel Options page and paste in the URL of your Gradio application.\nEmbedding Hugging Face Spaces directly into your Comet Projects\nYou can also embed Gradio Applications that are hosted on Hugging Faces Spaces into your Comet Projects using the Hugging Face Spaces Panel.\nGo to your Comet Project page, and head over to the Panels tab. Click the + Add button to bring up the Panels search page. Next, search for the Hugging Face Spaces Panel in the Public Panels section and click Add.\nOnce you have added your Panel, click Edit to access to the Panel Options page and paste in the path of your Hugging Face Space e.g. pytorch/ResNet\nLogging Model Inferences to Comet\nIn the previous examples, we demonstrated the various ways in which you can interact with a Gradio application through the Comet UI. Additionally, you can also log model inferences, such as SHAP plots, from your Gradio application to Comet.\nIn the following snippet, we're going to log inferences from a Text Generation model. We can persist an Experiment across multiple inference calls using Gradio's State object. This will allow you to log multiple inferences from a model to a single Experiment.\n`python\nimport comet_ml\nimport gradio as gr\nimport shap\nimport torch\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\nif torch.cuda.is_available():\n    device = \"cuda\"\nelse:\n    device = \"cpu\"\nMODEL_NAME = \"gpt2\"\nmodel = AutoModelForCausalLM.frompretrained(MODELNAME)\nset model decoder to true\nmodel.config.is_decoder = True\nset text-generation params under taskspecificparams\nmodel.config.taskspecificparams[\"text-generation\"] = {\n    \"do_sample\": True,\n    \"max_length\": 50,\n    \"temperature\": 0.7,\n    \"top_k\": 50,\n    \"norepeatngram_size\": 2,\n}\nmodel = model.to(device)\ntokenizer = AutoTokenizer.frompretrained(MODELNAME)\nexplainer = shap.Explainer(model, tokenizer)\ndef start_experiment():\n    \"\"\"Returns an APIExperiment object that is thread safe\n    and can be used to log inferences to a single Experiment\n    \"\"\"\n    try:\n        api = comet_ml.API()\n        workspace = api.getdefaultworkspace()\n        projectname = cometml.config.getconfig()[\"comet.projectname\"]\n        experiment = comet_ml.APIExperiment(\n            workspace=workspace, projectname=projectname\n        )\n        experiment.log_other(\"Created from\", \"gradio-inference\")\n        message = f\"Started Experiment: {experiment.name}\"\n        return (experiment, message)\n    except Exception as e:\n        return None, None\ndef predict(text, state, message):\n    experiment = state\n    shap_values = explainer([text])\n    plot = shap.plots.text(shap_values, display=False)\n    if experiment is not None:\n        experiment.log_other(\"message\", message)\n        experiment.log_html(plot)\n    return plot\nwith gr.Blocks() as demo:\n    startexperimentbtn = gr.Button(\"Start New Experiment\")\n    experiment_status = gr.Markdown()\n    # Log a message to the Experiment to provide more context\n    experiment_message = gr.Textbox(label=\"Experiment Message\")\n    experiment = gr.State()\n    input_text = gr.Textbox(label=\"Input Text\", lines=5, interactive=True)\n    submit_btn = gr.Button(\"Submit\")\n    output = gr.HTML(interactive=True)\n    startexperimentbtn.click(\n        startexperiment, outputs=[experiment, experimentstatus]\n    )\n    submit_btn.click(\n        predict, inputs=[inputtext, experiment, experimentmessage], outputs=[output]\n    )\n``\nInferences from this snippet will be saved in the HTML tab of your experiment.\n    \nConclusion\nWe hope you found this guide useful and that it provides some inspiration to help you build awesome model evaluation workflows with Comet and Gradio.\nHow to contribute Gradio demos on HF spaces on the Comet organization\nCreate an account on Hugging Face here.\nAdd Gradio Demo under your username, see this course for setting up Gradio Demo on Hugging Face.\nRequest to join the Comet organization here.\nAdditional Resources\nComet Documentation","type":"GUIDE"},{"title":"Gradio And ONNX On Hugging Face","slug":"/guides/Gradio-and-ONNX-on-Hugging-Face/","content":"Gradio and ONNX on Hugging Face\nIntroduction\nIn this Guide, we'll walk you through:\nIntroduction of ONNX, ONNX model zoo, Gradio, and Hugging Face Spaces\nHow to setup a Gradio demo for EfficientNet-Lite4\nHow to contribute your own Gradio demos for the ONNX organization on Hugging Face\nHere's an example of an ONNX model.\nWhat is the ONNX Model Zoo?\nOpen Neural Network Exchange (ONNX) is an open standard format for representing machine learning models. ONNX is supported by a community of partners who have implemented it in many frameworks and tools. For example, if you have trained a model in TensorFlow or PyTorch, you can convert it to ONNX easily, and from there run it on a variety of devices using an engine/compiler like ONNX Runtime.\nThe ONNX Model Zoo is a collection of pre-trained, state-of-the-art models in the ONNX format contributed by community members. Accompanying each model are Jupyter notebooks for model training and running inference with the trained model. The notebooks are written in Python and include links to the training dataset as well as references to the original paper that describes the model architecture.\nWhat are Hugging Face Spaces & Gradio?\nGradio\nGradio lets users demo their machine learning models as a web app all in python code. Gradio wraps a python function into a user interface and the demos can be launched inside jupyter notebooks, colab notebooks, as well as embedded in your own website and hosted on Hugging Face Spaces for free.\nGet started here\nHugging Face Spaces\nHugging Face Spaces is a free hosting option for Gradio demos. Spaces comes with 3 SDK options: Gradio, Streamlit and Static HTML demos. Spaces can be public or private and the workflow is similar to github repos. There are over 2000+ spaces currently on Hugging Face. Learn more about spaces here.\nHugging Face Models\nHugging Face Model Hub also supports ONNX models and ONNX models can be filtered through the ONNX tag\nHow did Hugging Face help the ONNX Model Zoo?\nThere are a lot of Jupyter notebooks in the ONNX Model Zoo for users to test models. Previously, users needed to download the models themselves and run those notebooks locally for testing. With Hugging Face, the testing process can be much simpler and more user-friendly. Users can easily try certain ONNX Model Zoo model on Hugging Face Spaces and run a quick demo powered by Gradio with ONNX Runtime, all on cloud without downloading anything locally. Note, there are various runtimes for ONNX, e.g., ONNX Runtime, MXNet.\nWhat is the role of ONNX Runtime?\nONNX Runtime is a cross-platform inference and training machine-learning accelerator. It makes live Gradio demos with ONNX Model Zoo model on Hugging Face possible.\nONNX Runtime inference can enable faster customer experiences and lower costs, supporting models from deep learning frameworks such as PyTorch and TensorFlow/Keras as well as classical machine learning libraries such as scikit-learn, LightGBM, XGBoost, etc. ONNX Runtime is compatible with different hardware, drivers, and operating systems, and provides optimal performance by leveraging hardware accelerators where applicable alongside graph optimizations and transforms. For more information please see the official website.\nSetting up a Gradio Demo for EfficientNet-Lite4\nEfficientNet-Lite 4 is the largest variant and most accurate of the set of EfficientNet-Lite models. It is an integer-only quantized model that produces the highest accuracy of all of the EfficientNet models. It achieves 80.4% ImageNet top-1 accuracy, while still running in real-time (e.g. 30ms/image) on a Pixel 4 CPU. To learn more read the model card\nHere we walk through setting up a example demo for EfficientNet-Lite4 using Gradio\nFirst we import our dependencies and download and load the efficientnet-lite4 model from the onnx model zoo. Then load the labels from the labels_map.txt file. We then setup our preprocessing functions, load the model for inference, and setup the inference function. Finally, the inference function is wrapped into a gradio interface for a user to interact with. See the full code below.\n``python\nimport numpy as np\nimport math\nimport matplotlib.pyplot as plt\nimport cv2\nimport json\nimport gradio as gr\nfrom huggingfacehub import hfhub_download\nfrom onnx import hub\nimport onnxruntime as ort\nloads ONNX model from ONNX Model Zoo\nmodel = hub.load(\"efficientnet-lite4\")\nloads the labels text file\nlabels = json.load(open(\"labels_map.txt\", \"r\"))\nsets image file dimensions to 224x224 by resizing and cropping image from center\ndef preprocessedgetpu(img, dims):\n    outputheight, outputwidth, _ = dims\n    img = resizewithaspectratio(img, outputheight, outputwidth, interpol=cv2.INTERLINEAR)\n    img = centercrop(img, outputheight, output_width)\n    img = np.asarray(img, dtype='float32')\n    # converts jpg pixel value from [0 - 255] to float array [-1.0 - 1.0]\n    img -= [127.0, 127.0, 127.0]\n    img /= [128.0, 128.0, 128.0]\n    return img\nresizes the image with a proportional scale\ndef resizewithaspectratio(img, outheight, outwidth, scale=87.5, interpol=cv2.INTERLINEAR):\n    height, width, _ = img.shape\n    newheight = int(100. * outheight / scale)\n    newwidth = int(100. * outwidth / scale)\n    if height > width:\n        w = new_width\n        h = int(new_height * height / width)\n    else:\n        h = new_height\n        w = int(new_width * width / height)\n    img = cv2.resize(img, (w, h), interpolation=inter_pol)\n    return img\ncrops the image around the center based on given height and width\ndef centercrop(img, outheight, out_width):\n    height, width, _ = img.shape\n    left = int((width - out_width) / 2)\n    right = int((width + out_width) / 2)\n    top = int((height - out_height) / 2)\n    bottom = int((height + out_height) / 2)\n    img = img[top:bottom, left:right]\n    return img\nsess = ort.InferenceSession(model)\ndef inference(img):\n  img = cv2.imread(img)\n  img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n  img = preprocessedgetpu(img, (224, 224, 3))\n  imgbatch = np.expanddims(img, axis=0)\n  results = sess.run([\"Softmax:0\"], {\"images:0\": img_batch})[0]\n  result = reversed(results[0].argsort()[-5:])\n  resultdic = {}\n  for r in result:\n      resultdic[labels[str(r)]] = float(results[0][r])\n  return resultdic\ntitle = \"EfficientNet-Lite4\"\ndescription = \"EfficientNet-Lite 4 is the largest variant and most accurate of the set of EfficientNet-Lite model. It is an integer-only quantized model that produces the highest accuracy of all of the EfficientNet models. It achieves 80.4% ImageNet top-1 accuracy, while still running in real-time (e.g. 30ms/image) on a Pixel 4 CPU.\"\nexamples = [['catonnx.jpg']]\ngr.Interface(inference, gr.Image(type=\"filepath\"), \"label\", title=title, description=description, examples=examples).launch()\n``\nHow to contribute Gradio demos on HF spaces using ONNX models\nAdd model to the onnx model zoo\nCreate an account on Hugging Face here.\nSee list of models left to add to ONNX organization, please refer to the table with the Models list\nAdd Gradio Demo under your username, see this blog post for setting up Gradio Demo on Hugging Face.\nRequest to join ONNX Organization here.\nOnce approved transfer model from your username to ONNX organization\nAdd a badge for model in model table, see examples in Models list","type":"GUIDE"},{"title":"Gradio And Wandb Integration","slug":"/guides/Gradio-and-Wandb-Integration/","content":"Gradio and W&B Integration\nIntroduction\nIn this Guide, we'll walk you through:\nIntroduction of Gradio, and Hugging Face Spaces, and Wandb\nHow to setup a Gradio demo using the Wandb integration for JoJoGAN\nHow to contribute your own Gradio demos after tracking your experiments on wandb to the Wandb organization on Hugging Face\nWhat is Wandb?\nWeights and Biases (W&B) allows data scientists and machine learning scientists to track their machine learning experiments at every stage, from training to production. Any metric can be aggregated over samples and shown in panels in a customizable and searchable dashboard, like below:\nWhat are Hugging Face Spaces & Gradio?\nGradio\nGradio lets users demo their machine learning models as a web app, all in a few lines of Python. Gradio wraps any Python function (such as a machine learning model's inference function) into a user interface and the demos can be launched inside jupyter notebooks, colab notebooks, as well as embedded in your own website and hosted on Hugging Face Spaces for free.\nGet started here\nHugging Face Spaces\nHugging Face Spaces is a free hosting option for Gradio demos. Spaces comes with 3 SDK options: Gradio, Streamlit and Static HTML demos. Spaces can be public or private and the workflow is similar to github repos. There are over 2000+ spaces currently on Hugging Face. Learn more about spaces here.\nSetting up a Gradio Demo for JoJoGAN\nNow, let's walk you through how to do this on your own. We'll make the assumption that you're new to W&B and Gradio for the purposes of this tutorial.\nLet's get started!\nCreate a W&B account\n   Follow these quick instructions to create your free account if you don’t have one already. It shouldn't take more than a couple minutes. Once you're done (or if you've already got an account), next, we'll run a quick colab.\nOpen Colab Install Gradio and W&B\n   We'll be following along with the colab provided in the JoJoGAN repo with some minor modifications to use Wandb and Gradio more effectively.\n   \n   Install Gradio and Wandb at the top:\n   ``sh\n   pip install gradio wandb\n   `\nFinetune StyleGAN and W&B experiment tracking\n   This next step will open a W&B dashboard to track your experiments and a gradio panel showing pretrained models to choose from a drop down menu from a Gradio Demo hosted on Huggingface Spaces. Here's the code you need for that:\n   `python\n   alpha =  1.0\n   alpha = 1-alpha\n   preserve_color = True\n   num_iter = 100\n   log_interval = 50\n   samples = []\n   column_names = [\"Reference (y)\", \"Style Code(w)\", \"Real Face Image(x)\"]\n   wandb.init(project=\"JoJoGAN\")\n   config = wandb.config\n   config.numiter = numiter\n   config.preservecolor = preservecolor\n   wandb.log(\n   {\"Style reference\": [wandb.Image(transforms.ToPILImage()(target_im))]},\n   step=0)\n   # load discriminator for perceptual loss\n   discriminator = Discriminator(1024, 2).eval().to(device)\n   ckpt = torch.load('models/stylegan2-ffhq-config-f.pt', map_location=lambda storage, loc: storage)\n   discriminator.loadstatedict(ckpt[\"d\"], strict=False)\n   # reset generator\n   del generator\n   generator = deepcopy(original_generator)\n   g_optim = optim.Adam(generator.parameters(), lr=2e-3, betas=(0, 0.99))\n   # Which layers to swap for generating a family of plausible real images -> fake image\n   if preserve_color:\n       id_swap = [9,11,15,16,17]\n   else:\n       idswap = list(range(7, generator.nlatent))\n   for idx in tqdm(range(num_iter)):\n       meanw = generator.getlatent(torch.randn([latents.size(0), latentdim]).to(device)).unsqueeze(1).repeat(1, generator.nlatent, 1)\n       in_latent = latents.clone()\n       inlatent[:, idswap] = alphalatents[:, id_swap] + (1-alpha)meanw[:, idswap]\n       img = generator(inlatent, inputis_latent=True)\n       with torch.no_grad():\n           real_feat = discriminator(targets)\n       fake_feat = discriminator(img)\n       loss = sum([F.l1loss(a, b) for a, b in zip(fakefeat, realfeat)])/len(fakefeat)\n       wandb.log({\"loss\": loss}, step=idx)\n       if idx % log_interval == 0:\n           generator.eval()\n           mysample = generator(myw, inputislatent=True)\n           generator.train()\n           mysample = transforms.ToPILImage()(utils.makegrid(my_sample, normalize=True, range=(-1, 1)))\n           wandb.log(\n           {\"Current stylization\": [wandb.Image(my_sample)]},\n           step=idx)\n       table_data = [\n               wandb.Image(transforms.ToPILImage()(target_im)),\n               wandb.Image(img),\n               wandb.Image(my_sample),\n           ]\n       samples.append(table_data)\n       goptim.zerograd()\n       loss.backward()\n       g_optim.step()\n   outtable = wandb.Table(data=samples, columns=columnnames)\n   wandb.log({\"Current Samples\": out_table})\n   `\nSave, Download, and Load Model\n    Here's how to save and download your model.\n   `python\n   from PIL import Image\n   import torch\n   torch.backends.cudnn.benchmark = True\n   from torchvision import transforms, utils\n   from util import *\n   import math\n   import random\n   import numpy as np\n   from torch import nn, autograd, optim\n   from torch.nn import functional as F\n   from tqdm import tqdm\n   import lpips\n   from model import *\n   from e4eprojection import projection as e4eprojection\n   \n   from copy import deepcopy\n   import imageio\n   \n   import os\n   import sys\n   import torchvision.transforms as transforms\n   from argparse import Namespace\n   from e4e.models.psp import pSp\n   from util import *\n   from huggingfacehub import hfhub_download\n   from google.colab import files\n   \n   torch.save({\"g\": generator.state_dict()}, \"your-model-name.pt\")\n   \n   files.download('your-model-name.pt')\n   \n   latent_dim = 512\n   device=\"cuda\"\n   modelpaths = hfhubdownload(repo_id=\"akhaliq/jojogan-stylegan2-ffhq-config-f\", filename=\"stylegan2-ffhq-config-f.pt\")\n   originalgenerator = Generator(1024, latentdim, 8, 2).to(device)\n   ckpt = torch.load(modelpaths, map_location=lambda storage, loc: storage)\n   originalgenerator.loadstatedict(ckpt[\"gema\"], strict=False)\n   meanlatent = originalgenerator.mean_latent(10000)\n   \n   generator = deepcopy(original_generator)\n   \n   ckpt = torch.load(\"/content/JoJoGAN/your-model-name.pt\", map_location=lambda storage, loc: storage)\n   generator.loadstatedict(ckpt[\"g\"], strict=False)\n   generator.eval()\n   \n   plt.rcParams['figure.dpi'] = 150\n   \n   transform = transforms.Compose(\n       [\n           transforms.Resize((1024, 1024)),\n           transforms.ToTensor(),\n           transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\n       ]\n   )\n   \n   def inference(img):\n       img.save('out.jpg')\n       alignedface = alignface('out.jpg')\n   \n       myw = e4eprojection(aligned_face, \"out.pt\", device).unsqueeze(0)\n       with torch.no_grad():\n           mysample = generator(myw, inputislatent=True)\n   \n       npimage = my_sample[0].cpu().permute(1, 2, 0).detach().numpy()\n       imageio.imwrite('filename.jpeg', npimage)\n       return 'filename.jpeg'\n   ``\nBuild a Gradio Demo\n   `python\n   import gradio as gr\n   \n   title = \"JoJoGAN\"\n   description = \"Gradio Demo for JoJoGAN: One Shot Face Stylization. To use it, simply upload your image, or click one of the examples to load them. Read more at the links below.\"\n   \n   demo = gr.Interface(\n       inference,\n       gr.Image(type=\"pil\"),\n       gr.Image(type=\"file\"),\n       title=title,\n       description=description\n   )\n   \n   demo.launch(share=True)\n   `\nIntegrate Gradio into your W&B Dashboard\n   The last step—integrating your Gradio demo with your W&B dashboard—is just one extra line:\n   `python\n   demo.integrate(wandb=wandb)\n   `\n   Once you call integrate, a demo will be created and you can integrate it into your dashboard or report.\n   Outside of W&B with Web components, using the gradio-app tags, anyone can embed Gradio demos on HF spaces directly into their blogs, websites, documentation, etc.:\n   \n   `html\n    \n   `\n(Optional) Embed W&B plots in your Gradio App\n   It's also possible to embed W&B plots within Gradio apps. To do so, you can create a W&B Report of your plots and\n   embed them within your Gradio app within a gr.HTML block.\n   The Report will need to be public and you will need to wrap the URL within an iFrame like this:\n   `python\n   import gradio as gr\n   \n   def wandb_report(url):\n       iframe = f''\n       return gr.HTML(iframe)\n   \n   with gr.Blocks() as demo:\n       reporturl = 'https://wandb.ai/scott/pytorch-sweeps-demo/reports/loss-22-10-07-16-00-17---VmlldzoyNzU2NzAx'\n       report = wandbreport(reporturl)\n   \n   demo.launch(share=True)\n   ``\nConclusion\nWe hope you enjoyed this brief demo of embedding a Gradio demo to a W&B report! Thanks for making it to the end. To recap:\nOnly one single reference image is needed for fine-tuning JoJoGAN which usually takes about 1 minute on a GPU in colab. After training, style can be applied to any input image. Read more in the paper.\nW&B tracks experiments with just a few lines of code added to a colab and you can visualize, sort, and understand your experiments in a single, centralized dashboard.\nGradio, meanwhile, demos the model in a user friendly interface to share anywhere on the web.\nHow to contribute Gradio demos on HF spaces on the Wandb organization\nCreate an account on Hugging Face here.\nAdd Gradio Demo under your username, see this course for setting up Gradio Demo on Hugging Face.\nRequest to join wandb organization here.\nOnce approved transfer model from your username to Wandb organization","type":"GUIDE"},{"title":"Gradio Skills For Ai Coding Assistants","slug":"/guides/Gradio-skills-for-ai-coding-assistants/","content":"Gradio Skills for AI Coding Assistants\nAI coding assistants like Claude Code, Cursor, Codex, and OpenCode can write better Gradio code when they have access to up-to-date API knowledge. Gradio skills solve this — they are structured reference files that get loaded into your assistant's context so it knows exactly how Gradio's components, events, and ecosystem work.\nThe gradio skills add command installs these reference files into the shared skills location used by compatible assistants, so they can use them automatically.\nPrerequisites\nMake sure you have Gradio installed along with a recent version of huggingface_hub:\n``bash\npip install --upgrade gradio huggingface_hub\n`\nhuggingface_hub >= 1.4.0 is required for the skills command.\nInstalling the General Gradio Skill\nThe general Gradio skill gives your assistant comprehensive knowledge of the Gradio API — components, event listeners, layout patterns, and working examples.\nTo install for Codex, Cursor, OpenCode, and other assistants that use the shared .agents/skills directory:\n`bash\ngradio skills add\n`\nThis downloads the Gradio and HF Gradio skill files into the central .agents/skills/ location. To also create a link from an assistant-specific skills directory, pass its flag: --claude, --cursor, --codex, or --opencode. On Windows systems without permission to create symlinks, Gradio copies the skill into the assistant-specific directory instead.\nProject-Level vs. Global Installation\nBy default, skills are installed locally in your current project directory. This means the assistant only has Gradio knowledge when working in that project.\nTo install globally (user-level, available in all projects):\n`bash\ngradio skills add --global\n`\nOr using the short flag:\n`bash\ngradio skills add -g\n`\nGenerating a Skill for a Specific HuggingFace Space\nOne of the most powerful features is generating a skill for any public HuggingFace Space. This gives your assistant full knowledge of that Space's API — endpoints, parameters, return types, and ready-to-use code snippets.\n`bash\ngradio skills add abidlabs/english-translator\n`\nThis connects to the Space, extracts its API schema, and generates a SKILL.md file with:\nA description of each API endpoint\nParameter names, types, defaults, and whether they're required\nReturn value types\nCode snippets in Python, JavaScript, and cURL\nFor private Spaces, set your Hugging Face token:\n`bash\nexport HFTOKEN=hfxxxxx\ngradio skills add my-org/private-space\n`\nOverwriting Existing Skills\nIf a skill is already installed, the command will exit with an error. To overwrite it:\n`bash\ngradio skills add --force\n`\nWhat Gets Installed\nGeneral Gradio Skill\n| File | Contents |\n|------|----------|\n| SKILL.md | Core API reference — component signatures, event listeners, layout patterns, ChatInterface, and links to detailed guides |\n| examples.md | Complete working Gradio apps covering common patterns (forms, chatbots, streaming, image processing, etc.) |\nSpace-Specific Skill\n| File | Contents |\n|------|----------|\n| SKILL.md | Auto-generated API reference for the Space's endpoints, with code snippets in Python, JavaScript, and cURL |\nExample Workflow\nHere's a typical workflow using skills with Claude Code:\nInstall the skill in your project:\n   `bash\n   cd my-project\n   gradio skills add --claude\n   `\nStart Claude Code and ask it to build a Gradio app:\n   `\n   > Build me a Gradio app with an image input that applies a sepia filter\n     and displays the result\n   `\n   Claude Code now has full knowledge of gr.Image, gr.Interface, event listeners, and can write correct, idiomatic Gradio code.\nAdd a Space skill if you want to integrate with an existing Space:\n   `bash\n   gradio skills add abidlabs/english-translator --claude\n   `\n   Now you can ask:\n   `\n   > Use the english-translator Space API to add a translation feature\n     to my app\n   ``","type":"GUIDE"},{"title":"Agents And Tool Usage","slug":"/guides/agents-and-tool-usage/","content":"Building a UI for an LLM Agent\nThe Gradio Chatbot can natively display intermediate thoughts and tool usage in a collapsible accordion next to a chat message. This makes it perfect for creating UIs for LLM agents and chain-of-thought (CoT) or reasoning demos. This guide will show you how to display thoughts and tool usage with gr.Chatbot and gr.ChatInterface.\nThe ChatMessage dataclass\nEvery element of the chatbot value is a dictionary of role and content keys. You can always use plain python dictionaries to add new values to the chatbot but Gradio also provides the ChatMessage dataclass to help you with IDE autocompletion. The schema of ChatMessage is as follows:\n ``py\nMessageContent = Union[str, FileDataDict, FileData, Component]\n@dataclass\nclass ChatMessage:\n    content: MessageContent | [MessageContent]\n    role: Literal[\"user\", \"assistant\"]\n    metadata: MetadataDict = None\n    options: list[OptionDict] = None\nclass MetadataDict(TypedDict):\n    title: NotRequired[str]\n    id: NotRequired[int | str]\n    parent_id: NotRequired[int | str]\n    log: NotRequired[str]\n    duration: NotRequired[float]\n    status: NotRequired[Literal[\"pending\", \"done\"]]\nclass OptionDict(TypedDict):\n    label: NotRequired[str]\n    value: str\n `\nFor our purposes, the most important key is the metadata key, which accepts a dictionary. If this dictionary includes a title for the message, it will be displayed in a collapsible accordion representing a thought. It's that simple! Take a look at this example:\n`python\nimport gradio as gr\nwith gr.Blocks() as demo:\n    chatbot = gr.Chatbot(\n        value=[\n            gr.ChatMessage(\n                role=\"user\", \n                content=\"What is the weather in San Francisco?\"\n            ),\n            gr.ChatMessage(\n                role=\"assistant\", \n                content=\"I need to use the weather API tool?\",\n                metadata={\"title\":  \"🧠 Thinking\"}\n            )\n        ]\n    )\ndemo.launch()\n`\nIn addition to title, the dictionary provided to metadata can take several optional keys:\nlog: an optional string value to be displayed in a subdued font next to the thought title.\nduration: an optional numeric value representing the duration of the thought/tool usage, in seconds. Displayed in a subdued font next inside parentheses next to the thought title.\nstatus: if set to \"pending\", a spinner appears next to the thought title and the accordion is initialized open.  If status is \"done\", the thought accordion is initialized closed. If status is not provided, the thought accordion is initialized open and no spinner is displayed.\nid and parent_id: if these are provided, they can be used to nest thoughts inside other thoughts.\nBelow, we show several complete examples of using gr.Chatbot and gr.ChatInterface to display tool use or thinking UIs.\nBuilding with Agents\nA real example using transformers.agents\nWe'll create a Gradio application simple agent that has access to a text-to-image tool.\n            \n                \n                    \n                    \n                    \n                \n                Make sure you read the smolagents documentation first\n            \n                \nWe'll start by importing the necessary classes from transformers and gradio. \n`python\nimport gradio as gr\nfrom gradio import ChatMessage\nfrom transformers import Tool, ReactCodeAgent  # type: ignore\nfrom transformers.agents import streamtogradio, HfApiEngine  # type: ignore\nImport tool from Hub\nimagegenerationtool = Tool.from_space(\n    space_id=\"black-forest-labs/FLUX.1-schnell\",\n    name=\"image_generator\",\n    description=\"Generates an image following your prompt. Returns a PIL Image.\",\n    api_name=\"/infer\",\n)\nllm_engine = HfApiEngine(\"Qwen/Qwen2.5-Coder-32B-Instruct\")\nInitialize the agent with both tools and engine\nagent = ReactCodeAgent(tools=[imagegenerationtool], llmengine=llmengine)\n`\nThen we'll build the UI:\n`python\ndef interactwithagent(prompt, history):\n    messages = []\n    yield messages\n    for msg in streamtogradio(agent, prompt):\n        messages.append(asdict(msg))\n        yield messages\n    yield messages\ndemo = gr.ChatInterface(\n    interactwithagent,\n    chatbot= gr.Chatbot(\n        label=\"Agent\",\n        avatar_images=(\n            None,\n            \"https://em-content.zobj.net/source/twitter/53/robot-face_1f916.png\",\n        ),\n    ),\n    examples=[\n        [\"Generate an image of an astronaut riding an alligator\"],\n        [\"I am writing a children's book for my daughter. Can you help me with some illustrations?\"],\n    ],\n)\n`\nYou can see the full demo code here.\nA real example using langchain agents\nWe'll create a UI for langchain agent that has access to a search engine.\nWe'll begin with imports and setting up the langchain agent. Note that you'll need an .env file with the following environment variables set - \n`\nSERPAPIAPIKEY=\nHF_TOKEN=\nOPENAIAPIKEY=\n`\n`python\nfrom langchain import hub\nfrom langchain.agents import AgentExecutor, createopenaitoolsagent, loadtools\nfrom langchain_openai import ChatOpenAI\nfrom gradio import ChatMessage\nimport gradio as gr\nfrom dotenv import load_dotenv\nload_dotenv()\nmodel = ChatOpenAI(temperature=0, streaming=True)\ntools = load_tools([\"serpapi\"])\nGet the prompt to use - you can modify this!\nprompt = hub.pull(\"hwchase17/openai-tools-agent\")\nagent = createopenaitools_agent(\n    model.withconfig({\"tags\": [\"agentllm\"]}), tools, prompt\n)\nagentexecutor = AgentExecutor(agent=agent, tools=tools).withconfig(\n    {\"run_name\": \"Agent\"}\n)\n`\nThen we'll create the Gradio UI\n`python\nasync def interactwithlangchain_agent(prompt, messages):\n    messages.append(ChatMessage(role=\"user\", content=prompt))\n    yield messages\n    async for chunk in agent_executor.astream(\n        {\"input\": prompt}\n    ):\n        if \"steps\" in chunk:\n            for step in chunk[\"steps\"]:\n                messages.append(ChatMessage(role=\"assistant\", content=step.action.log,\n                                  metadata={\"title\": f\"🛠️ Used tool {step.action.tool}\"}))\n                yield messages\n        if \"output\" in chunk:\n            messages.append(ChatMessage(role=\"assistant\", content=chunk[\"output\"]))\n            yield messages\nwith gr.Blocks() as demo:\n    gr.Markdown(\"# Chat with a LangChain Agent 🦜⛓️ and see its thoughts 💭\")\n    chatbot = gr.Chatbot(\n        label=\"Agent\",\n        avatar_images=(\n            None,\n            \"https://em-content.zobj.net/source/twitter/141/parrot_1f99c.png\",\n        ),\n    )\n    input = gr.Textbox(lines=1, label=\"Chat Message\")\n    input.submit(interactwithlangchainagent, [input2, chatbot2], [chatbot2])\ndemo.launch()\n`\nThat's it! See our finished langchain demo here.\nBuilding with Visibly Thinking LLMs\nThe Gradio Chatbot can natively display intermediate thoughts of a thinking LLM. This makes it perfect for creating UIs that show how an AI model \"thinks\" while generating responses. Below guide will show you how to build a chatbot that displays Gemini AI's thought process in real-time.\nA real example using Gemini 2.0 Flash Thinking API\nLet's create a complete chatbot that shows its thoughts and responses in real-time. We'll use Google's Gemini API for accessing Gemini 2.0 Flash Thinking LLM and Gradio for the UI.\nWe'll begin with imports and setting up the gemini client. Note that you'll need to acquire a Google Gemini API key first -\n`python\nimport gradio as gr\nfrom gradio import ChatMessage\nfrom typing import Iterator\nimport google.generativeai as genai\ngenai.configure(api_key=\"your-gemini-api-key\")\nmodel = genai.GenerativeModel(\"gemini-2.0-flash-thinking-exp-1219\")\n`\nFirst, let's set up our streaming function that handles the model's output:\n`python\ndef streamgeminiresponse(user_message: str, messages: list) -> Iterator[list]:\n    \"\"\"\n    Streams both thoughts and responses from the Gemini model.\n    \"\"\"\n    # Initialize response from Gemini\n    response = model.generatecontent(usermessage, stream=True)\n    \n    # Initialize buffers\n    thought_buffer = \"\"\n    response_buffer = \"\"\n    thinking_complete = False\n    \n    # Add initial thinking message\n    messages.append(\n        ChatMessage(\n            role=\"assistant\",\n            content=\"\",\n            metadata={\"title\": \"⏳Thinking: *The thoughts produced by the Gemini2.0 Flash model are experimental\"}\n        )\n    )\n    \n    for chunk in response:\n        parts = chunk.candidates[0].content.parts\n        current_chunk = parts[0].text\n        \n        if len(parts) == 2 and not thinking_complete:\n            # Complete thought and start response\n            thoughtbuffer += currentchunk\n            messages[-1] = ChatMessage(\n                role=\"assistant\",\n                content=thought_buffer,\n                metadata={\"title\": \"⏳Thinking: *The thoughts produced by the Gemini2.0 Flash model are experimental\"}\n            )\n            \n            # Add response message\n            messages.append(\n                ChatMessage(\n                    role=\"assistant\",\n                    content=parts[1].text\n                )\n            )\n            thinking_complete = True\n            \n        elif thinking_complete:\n            # Continue streaming response\n            responsebuffer += currentchunk\n            messages[-1] = ChatMessage(\n                role=\"assistant\",\n                content=response_buffer\n            )\n            \n        else:\n            # Continue streaming thoughts\n            thoughtbuffer += currentchunk\n            messages[-1] = ChatMessage(\n                role=\"assistant\",\n                content=thought_buffer,\n                metadata={\"title\": \"⏳Thinking: *The thoughts produced by the Gemini2.0 Flash model are experimental\"}\n            )\n        \n        yield messages\n`\nThen, let's create the Gradio interface:\n`python\nwith gr.Blocks() as demo:\n    gr.Markdown(\"# Chat with Gemini 2.0 Flash and See its Thoughts 💭\")\n    \n    chatbot = gr.Chatbot(\n        label=\"Gemini2.0 'Thinking' Chatbot\",\n        render_markdown=True,\n    )\n    \n    input_box = gr.Textbox(\n        lines=1,\n        label=\"Chat Message\",\n        placeholder=\"Type your message here and press Enter...\"\n    )\n    \n    # Set up event handlers\n    msg_store = gr.State(\"\")  # Store for preserving user message\n    \n    input_box.submit(\n        lambda msg: (msg, msg, \"\"),  # Store message and clear input\n        inputs=[input_box],\n        outputs=[msgstore, inputbox, input_box],\n        queue=False\n    ).then(\n        user_message,  # Add user message to chat\n        inputs=[msg_store, chatbot],\n        outputs=[input_box, chatbot],\n        queue=False\n    ).then(\n        streamgeminiresponse,  # Generate and stream response\n        inputs=[msg_store, chatbot],\n        outputs=chatbot\n    )\ndemo.launch()\n`\nThis creates a chatbot that:\nDisplays the model's thoughts in a collapsible section\nStreams the thoughts and final response in real-time\nMaintains a clean chat history\n That's it! You now have a chatbot that not only responds to users but also shows its thinking process, creating a more transparent and engaging interaction. See our finished Gemini 2.0 Flash Thinking demo here.\n ## Building with Citations \nThe Gradio Chatbot can display citations from LLM responses, making it perfect for creating UIs that show source documentation and references. This guide will show you how to build a chatbot that displays Claude's citations in real-time.\nA real example using Anthropic's Citations API\nLet's create a complete chatbot that shows both responses and their supporting citations. We'll use Anthropic's Claude API with citations enabled and Gradio for the UI.\nWe'll begin with imports and setting up the Anthropic client. Note that you'll need an ANTHROPICAPIKEY environment variable set:\n`python\nimport gradio as gr\nimport anthropic\nimport base64\nfrom typing import List, Dict, Any\nclient = anthropic.Anthropic()\n`\nFirst, let's set up our message formatting functions that handle document preparation:\n`python\ndef encodepdftobase64(fileobj) -> str:\n    \"\"\"Convert uploaded PDF file to base64 string.\"\"\"\n    if file_obj is None:\n        return None\n    with open(file_obj.name, 'rb') as f:\n        return base64.b64encode(f.read()).decode('utf-8')\ndef formatmessagehistory(\n    history: list, \n    enable_citations: bool,\n    doc_type: str,\n    text_input: str,\n    pdf_file: str\n) -> List[Dict]:\n    \"\"\"Convert Gradio chat history to Anthropic message format.\"\"\"\n    formatted_messages = []\n    \n    # Add previous messages\n    for msg in history[:-1]:\n        if msg[\"role\"] == \"user\":\n            formatted_messages.append({\"role\": \"user\", \"content\": msg[\"content\"]})\n    \n    # Prepare the latest message with document\n    latest_message = {\"role\": \"user\", \"content\": []}\n    \n    if enable_citations:\n        if doctype == \"plaintext\":\n            latest_message[\"content\"].append({\n                \"type\": \"document\",\n                \"source\": {\n                    \"type\": \"text\",\n                    \"media_type\": \"text/plain\",\n                    \"data\": text_input.strip()\n                },\n                \"title\": \"Text Document\",\n                \"citations\": {\"enabled\": True}\n            })\n        elif doctype == \"pdf\" and pdffile:\n            pdfdata = encodepdftobase64(pdf_file)\n            if pdf_data:\n                latest_message[\"content\"].append({\n                    \"type\": \"document\",\n                    \"source\": {\n                        \"type\": \"base64\",\n                        \"media_type\": \"application/pdf\",\n                        \"data\": pdf_data\n                    },\n                    \"title\": pdf_file.name,\n                    \"citations\": {\"enabled\": True}\n                })\n    \n    # Add the user's question\n    latest_message[\"content\"].append({\"type\": \"text\", \"text\": history[-1][\"content\"]})\n    \n    formattedmessages.append(latestmessage)\n    return formatted_messages\n`\nThen, let's create our bot response handler that processes citations:\n`python\ndef bot_response(\n    history: list,\n    enable_citations: bool,\n    doc_type: str,\n    text_input: str,\n    pdf_file: str\n) -> List[Dict[str, Any]]:\n    try:\n        messages = formatmessagehistory(history, enablecitations, doctype, textinput, pdffile)\n        response = client.messages.create(model=\"claude-3-5-sonnet-20241022\", max_tokens=1024, messages=messages)\n        \n        # Initialize main response and citations\n        main_response = \"\"\n        citations = []\n        \n        # Process each content block\n        for block in response.content:\n            if block.type == \"text\":\n                main_response += block.text\n                if enable_citations and hasattr(block, 'citations') and block.citations:\n                    for citation in block.citations:\n                        if citation.cited_text not in citations:\n                            citations.append(citation.cited_text)\n        \n        # Add main response\n        history.append({\"role\": \"assistant\", \"content\": main_response})\n        \n        # Add citations in a collapsible section\n        if enable_citations and citations:\n            history.append({\n                \"role\": \"assistant\",\n                \"content\": \"\\n\".join([f\"• {cite}\" for cite in citations]),\n                \"metadata\": {\"title\": \"📚 Citations\"}\n            })\n        \n        return history\n            \n    except Exception as e:\n        history.append({\n            \"role\": \"assistant\",\n            \"content\": \"I apologize, but I encountered an error while processing your request.\"\n        })\n        return history\n`\nFinally, let's create the Gradio interface:\n`python\nwith gr.Blocks() as demo:\n    gr.Markdown(\"# Chat with Citations\")\n    \n    with gr.Row(scale=1):\n        with gr.Column(scale=4):\n            chatbot = gr.Chatbot(bubblefullwidth=False, show_label=False, scale=1)\n            msg = gr.Textbox(placeholder=\"Enter your message here...\", show_label=False, container=False)\n            \n        with gr.Column(scale=1):\n            enable_citations = gr.Checkbox(label=\"Enable Citations\", value=True, info=\"Toggle citation functionality\" )\n            doctyperadio = gr.Radio( choices=[\"plaintext\", \"pdf\"], value=\"plaintext\", label=\"Document Type\", info=\"Choose the type of document to use\")\n            text_input = gr.Textbox(label=\"Document Content\", lines=10, info=\"Enter the text you want to reference\")\n            pdfinput = gr.File(label=\"Upload PDF\", filetypes=[\".pdf\"], file_count=\"single\", visible=False)\n    \n    # Handle message submission\n    msg.submit(\n        user_message,\n        [msg, chatbot, enablecitations, doctyperadio, textinput, pdf_input],\n        [msg, chatbot]\n    ).then(\n        bot_response,\n        [chatbot, enablecitations, doctyperadio, textinput, pdf_input],\n        chatbot\n    )\ndemo.launch()\n`\nThis creates a chatbot that:\nSupports both plain text and PDF documents for Claude to cite from \nDisplays Citations in collapsible sections using our metadata feature\nShows source quotes directly from the given documents\nThe citations feature works particularly well with the Gradio Chatbot's metadata` support, allowing us to create collapsible sections that keep the chat interface clean while still providing easy access to source documentation.\nThat's it! You now have a chatbot that not only responds to users but also shows its sources, creating a more transparent and trustworthy interaction. See our finished Citations demo here.","type":"GUIDE"},{"title":"Alerts","slug":"/guides/alerts/","content":"Alerts\nYou may wish to display alerts to the user. To do so, raise a gr.Error(\"custom message\") in your function to halt the execution of your function and display an error message to the user.\nYou can also issue gr.Warning(\"custom message\") or gr.Info(\"custom message\") by having them as standalone lines in your function, which will immediately display modals while continuing the execution of your function. The only difference between gr.Info() and gr.Warning() is the color of the alert. \n``python\ndef start_process(name):\n    gr.Info(\"Starting process\")\n    if name is None:\n        gr.Warning(\"Name is empty\")\n    ...\n    if success == False:\n        raise gr.Error(\"Process failed\")\n``\n            \n                \n                    \n                    \n                    \n                \n                Note that gr.Error() is an exception that has to be raised, while gr.Warning() and gr.Info() are functions that are called directly.","type":"GUIDE"},{"title":"Automatic Voice Detection","slug":"/guides/automatic-voice-detection/","content":"Multimodal Gradio App Powered by Groq with Automatic Speech Detection\nIntroduction\nModern voice applications should feel natural and responsive, moving beyond the traditional \"click-to-record\" pattern. By combining Groq's fast inference capabilities with automatic speech detection, we can create a more intuitive interaction model where users can simply start talking whenever they want to engage with the AI.\nCredits: VAD and Gradio code inspired by WillHeld's Diva-audio-chat.\nIn this tutorial, you will learn how to create a multimodal Gradio and Groq app that has automatic speech detection. You can also watch the full video tutorial which includes a demo of the application:\nBackground\nMany voice apps currently work by the user clicking record, speaking, then stopping the recording. While this can be a powerful demo, the most natural mode of interaction with voice requires the app to dynamically detect when the user is speaking, so they can talk back and forth without having to continually click a record button. \nCreating a natural interaction with voice and text requires a dynamic and low-latency response. Thus, we need both automatic voice detection and fast inference. With @ricky0123/vad-web powering speech detection and Groq powering the LLM, both of these requirements are met. Groq provides a lightning fast response, and Gradio allows for easy creation of impressively functional apps.\nThis tutorial shows you how to build a calorie tracking app where you speak to an AI that automatically detects when you start and stop your response, and provides its own text response back to guide you with questions that allow it to give a calorie estimate of your last meal.\nKey Components\nGradio: Provides the web interface and audio handling capabilities\n@ricky0123/vad-web: Handles voice activity detection\nGroq: Powers fast LLM inference for natural conversations\nWhisper: Transcribes speech to text\nSetting Up the Environment\nFirst, let’s install and import our essential libraries and set up a client for using the Groq API. Here’s how to do it:\nrequirements.txt\n``\ngradio\ngroq\nnumpy\nsoundfile\nlibrosa\nspaces\nxxhash\ndatasets\n`\napp.py\n`python\nimport groq\nimport gradio as gr\nimport soundfile as sf\nfrom dataclasses import dataclass, field\nimport os\nInitialize Groq client securely\napikey = os.environ.get(\"GROQAPI_KEY\")\nif not api_key:\n    raise ValueError(\"Please set the GROQAPIKEY environment variable.\")\nclient = groq.Client(apikey=apikey)\n`\nHere, we’re pulling in key libraries to interact with the Groq API, build a sleek UI with Gradio, and handle audio data. We’re accessing the Groq API key securely with a key stored in an environment variable, which is a security best practice for avoiding leaking the API key.\nState Management for Seamless Conversations\nWe need a way to keep track of our conversation history, so the chatbot remembers past interactions, and manage other states like whether recording is currently active. To do this, let’s create an AppState class:\n`python\n@dataclass\nclass AppState:\n    conversation: list = field(default_factory=list)\n    stopped: bool = False\n    model_outs: Any = None\n`\nOur AppState class is a handy tool for managing conversation history and tracking whether recording is on or off. Each instance will have its own fresh list of conversations, making sure chat history is isolated to each session. \nTranscribing Audio with Whisper on Groq\nNext, we’ll create a function to transcribe the user’s audio input into text using Whisper, a powerful transcription model hosted on Groq. This transcription will also help us determine whether there’s meaningful speech in the input. Here’s how:\n`python\ndef transcribeaudio(client, filename):\n    if file_name is None:\n        return None\n    try:\n        with open(filename, \"rb\") as audiofile:\n            response = client.audio.transcriptions.withrawresponse.create(\n                model=\"whisper-large-v3-turbo\",\n                file=(\"audio.wav\", audio_file),\n                responseformat=\"verbosejson\",\n            )\n            completion = processwhisperresponse(response.parse())\n            return completion\n    except Exception as e:\n        print(f\"Error in transcription: {e}\")\n        return f\"Error in transcription: {str(e)}\"\n`\nThis function opens the audio file and sends it to Groq’s Whisper model for transcription, requesting detailed JSON output. verbose_json is needed to get information to determine if speech was included in the audio. We also handle any potential errors so our app doesn’t fully crash if there’s an issue with the API request. \n`python\ndef processwhisperresponse(completion):\n    \"\"\"\n    Process Whisper transcription response and return text or null based on nospeechprob\n    \n    Args:\n        completion: Whisper transcription response object\n        \n    Returns:\n        str or None: Transcribed text if nospeechprob  0:\n        nospeechprob = completion.segments[0].get('nospeechprob', 0)\n        print(\"No speech prob:\", nospeechprob)\n        if nospeechprob > 0.7:\n            return None\n            \n        return completion.text.strip()\n    \n    return None\n`\nWe also need to interpret the audio data response. The processwhisperresponse function takes the resulting completion from Whisper and checks if the audio was just background noise or had actual speaking that was transcribed. It uses a threshold of 0.7 to interpret the nospeechprob, and will return None if there was no speech. Otherwise, it will return the text transcript of the conversational response from the human.\nAdding Conversational Intelligence with LLM Integration\nOur chatbot needs to provide intelligent, friendly responses that flow naturally. We’ll use a Groq-hosted Llama-3.2 for this:\n`python\ndef generatechatcompletion(client, history):\n    messages = []\n    messages.append(\n        {\n            \"role\": \"system\",\n            \"content\": \"In conversation with the user, ask questions to estimate and provide (1) total calories, (2) protein, carbs, and fat in grams, (3) fiber and sugar content. Only ask one question at a time. Be conversational and natural.\",\n        }\n    )\n    for message in history:\n        messages.append(message)\n    try:\n        completion = client.chat.completions.create(\n            model=\"llama-3.2-11b-vision-preview\",\n            messages=messages,\n        )\n        return completion.choices[0].message.content\n    except Exception as e:\n        return f\"Error in generating chat completion: {str(e)}\"\n`\nWe’re defining a system prompt to guide the chatbot’s behavior, ensuring it asks one question at a time and keeps things conversational. This setup also includes error handling to ensure the app gracefully manages any issues.\nVoice Activity Detection for Hands-Free Interaction\nTo make our chatbot hands-free, we’ll add Voice Activity Detection (VAD) to automatically detect when someone starts or stops speaking. Here’s how to implement it using ONNX in JavaScript:\n`javascript\nasync function main() {\n  const script1 = document.createElement(\"script\");\n  script1.src = \"https://cdn.jsdelivr.net/npm/onnxruntime-web@1.14.0/dist/ort.js\";\n  document.head.appendChild(script1)\n  const script2 = document.createElement(\"script\");\n  script2.onload = async () =>  {\n    console.log(\"vad loaded\");\n    var record = document.querySelector('.record-button');\n    record.textContent = \"Just Start Talking!\"\n    \n    const myvad = await vad.MicVAD.new({\n      onSpeechStart: () => {\n        var record = document.querySelector('.record-button');\n        var player = document.querySelector('#streaming-out')\n        if (record != null && (player == null || player.paused)) {\n          record.click();\n        }\n      },\n      onSpeechEnd: (audio) => {\n        var stop = document.querySelector('.stop-button');\n        if (stop != null) {\n          stop.click();\n        }\n      }\n    })\n    myvad.start()\n  }\n  script2.src = \"https://cdn.jsdelivr.net/npm/@ricky0123/vad-web@0.0.7/dist/bundle.min.js\";\n}\n`\nThis script loads our VAD model and sets up functions to start and stop recording automatically. When the user starts speaking, it triggers the recording, and when they stop, it ends the recording.\nBuilding a User Interface with Gradio\nNow, let’s create an intuitive and visually appealing user interface with Gradio. This interface will include an audio input for capturing voice, a chat window for displaying responses, and state management to keep things synchronized.\n`python\nwith gr.Blocks() as demo:\n    with gr.Row():\n        input_audio = gr.Audio(\n            label=\"Input Audio\",\n            sources=[\"microphone\"],\n            type=\"numpy\",\n            streaming=False,\n            waveformoptions=gr.WaveformOptions(waveformcolor=\"#B83A4B\"),\n        )\n    with gr.Row():\n        chatbot = gr.Chatbot(label=\"Conversation\")\n    state = gr.State(value=AppState())\ndemo.launch(theme=theme, js=js)\n`\nIn this code block, we’re using Gradio’s Blocks API to create an interface with an audio input, a chat display, and an application state manager. The color customization for the waveform adds a nice visual touch.\nHandling Recording and Responses\nFinally, let’s link the recording and response components to ensure the app reacts smoothly to user inputs and provides responses in real-time.\n`python\n    stream = inputaudio.startrecording(\n        process_audio,\n        [input_audio, state],\n        [input_audio, state],\n    )\n    respond = inputaudio.stoprecording(\n        response, [state, input_audio], [state, chatbot]\n    )\n``\nThese lines set up event listeners for starting and stopping the recording, processing the audio input, and generating responses. By linking these events, we create a cohesive experience where users can simply talk, and the chatbot handles the rest.\nSummary\nWhen you open the app, the VAD system automatically initializes and starts listening for speech\nAs soon as you start talking, it triggers the recording automatically\nWhen you stop speaking, the recording ends and:\nThe audio is transcribed using Whisper\nThe transcribed text is sent to the LLM\nThe LLM generates a response about calorie tracking\nThe response is displayed in the chat interface\nThis creates a natural back-and-forth conversation where you can simply talk about your meals and get instant feedback on nutritional content\nThis app demonstrates how to create a natural voice interface that feels responsive and intuitive. By combining Groq's fast inference with automatic speech detection, we've eliminated the need for manual recording controls while maintaining high-quality interactions. The result is a practical calorie tracking assistant that users can simply talk to as naturally as they would to a human nutritionist.\nLink to GitHub repository: Groq Gradio Basics","type":"GUIDE"},{"title":"Backend","slug":"/guides/backend/","content":"The Backend 🐍\nThis guide will cover everything you need to know to implement your custom component's backend processing.\nWhich Class to Inherit From\nAll components inherit from one of three classes Component, FormComponent, or BlockContext.\nYou need to inherit from one so that your component behaves like all other gradio components.\nWhen you start from a template with gradio cc create --template, you don't need to worry about which one to choose since the template uses the correct one. \nFor completeness, and in the event that you need to make your own component from scratch, we explain what each class is for.\nFormComponent: Use this when you want your component to be grouped together in the same Form layout with other FormComponents. The Slider, Textbox, and Number components are all FormComponents.\nBlockContext: Use this when you want to place other components \"inside\" your component. This enabled with MyComponent() as component: syntax.\nComponent: Use this for all other cases.\n            \n                \n                    \n                    \n                    \n                \n                If your component supports streaming output, inherit from the StreamingOutput class.\n            \n                \n            \n                \n                    \n                    \n                    \n                \n                If you inherit from BlockContext, you also need to set the metaclass to be ComponentMeta. See example below.\n            \n                \n``python\nfrom gradio.blocks import BlockContext\nfrom gradio.component_meta import ComponentMeta\n@document()\nclass Row(BlockContext, metaclass=ComponentMeta):\n    pass\n`\nThe methods you need to implement\nWhen you inherit from any of these classes, the following methods must be implemented.\nOtherwise the Python interpreter will raise an error when you instantiate your component!\npreprocess and postprocess\nExplained in the Key Concepts guide. \nThey handle the conversion from the data sent by the frontend to the format expected by the python function.\n`python\n    def preprocess(self, x: Any) -> Any:\n        \"\"\"\n        Convert from the web-friendly (typically JSON) value in the frontend to the format expected by the python function.\n        \"\"\"\n        return x\n    def postprocess(self, y):\n        \"\"\"\n        Convert from the data returned by the python function to the web-friendly (typically JSON) value expected by the frontend.\n        \"\"\"\n        return y\n`\nprocess_example\nTakes in the original Python value and returns the modified value that should be displayed in the examples preview in the app. \nIf not provided, the .postprocess() method is used instead. Let's look at the following example from the SimpleDropdown component.\n`python\ndef processexample(self, inputdata):\n    return next((c[0] for c in self.choices if c[1] == input_data), None)\n`\nSince self.choices is a list of tuples corresponding to (display_name, value), this converts the value that a user provides to the display value (or if the value is not present in self.choices, it is converted to None).\napi_info\nA JSON-schema representation of the value that the preprocess expects. \nThis powers api usage via the gradio clients. \nYou do not need to implement this yourself if you components specifies a data_model. \nThe data_model in the following section.\n`python\ndef api_info(self) -> dict[str, list[str]]:\n    \"\"\"\n    A JSON-schema representation of the value that the preprocess expects and the postprocess returns.\n    \"\"\"\n    pass\n`\nexample_payload\nAn example payload for your component, e.g. something that can be passed into the .preprocess() method\nof your component. The example input is displayed in the View API page of a Gradio app that uses your custom component. \nMust be JSON-serializable. If your component expects a file, it is best to use a publicly accessible URL.\n`python\ndef example_payload(self) -> Any:\n    \"\"\"\n    The example inputs for this component for API usage. Must be JSON-serializable.\n    \"\"\"\n    pass\n`\nexample_value\nAn example value for your component, e.g. something that can be passed into the .postprocess() method\nof your component. This is used as the example value in the default app that is created in custom component development.\n`python\ndef example_payload(self) -> Any:\n    \"\"\"\n    The example inputs for this component for API usage. Must be JSON-serializable.\n    \"\"\"\n    pass\n`\nflag\nWrite the component's value to a format that can be stored in the csv or json file used for flagging.\nYou do not need to implement this yourself if you components specifies a data_model. \nThe data_model in the following section.\n`python\ndef flag(self, x: Any | GradioDataModel, flag_dir: str | Path = \"\") -> str:\n    pass\n`\nreadfromflag\nConvert from the format stored in the csv or json file used for flagging to the component's python value.\nYou do not need to implement this yourself if you components specifies a data_model. \nThe data_model in the following section.\n`python\ndef readfromflag(\n    self,\n    x: Any,\n) -> GradioDataModel | Any:\n    \"\"\"\n    Convert the data from the csv or jsonl file into the component state.\n    \"\"\"\n    return x\n`\nThe data_model\nThe data_model is how you define the expected data format your component's value will be stored in the frontend.\nIt specifies the data format your preprocess method expects and the format the postprocess method returns.\nIt is not necessary to define a data_model for your component but it greatly simplifies the process of creating a custom component.\nIf you define a custom component you only need to implement four methods - preprocess, postprocess, examplepayload, and examplevalue!\nYou define a data_model by defining a pydantic model that inherits from either GradioModel or GradioRootModel.\nThis is best explained with an example. Let's look at the core Video component, which stores the video data as a JSON object with two keys video and subtitles which point to separate files.\n`python\nfrom gradio.data_classes import FileData, GradioModel\nclass VideoData(GradioModel):\n    video: FileData\n    subtitles: Optional[FileData] = None\nclass Video(Component):\n    data_model = VideoData\n`\nBy adding these four lines of code, your component automatically implements the methods needed for API usage, the flagging methods, and example caching methods!\nIt also has the added benefit of self-documenting your code.\nAnyone who reads your component code will know exactly the data it expects.\n            \n                \n                    \n                    \n                    \n                \n                If your component expects files to be uploaded from the frontend, your must use the FileData model! It will be explained in the following section. \n            \n                \n            \n                \n                    \n                    \n                    \n                \n                Read the pydantic docs here.\n            \n                \nThe difference between a GradioModel and a GradioRootModel is that the RootModel will not serialize the data to a dictionary.\nFor example, the Names model will serialize the data to {'names': ['freddy', 'pete']} whereas the NamesRoot model will serialize it to ['freddy', 'pete'].\n`python\nfrom typing import List\nclass Names(GradioModel):\n    names: List[str]\nclass NamesRoot(GradioRootModel):\n    root: List[str]\n`\nEven if your component does not expect a \"complex\" JSON data structure it can be beneficial to define a GradioRootModel so that you don't have to worry about implementing the API and flagging methods.\n            \n                \n                    \n                    \n                    \n                \n                Use classes from the Python typing library to type your models. e.g. List instead of list.\n            \n                \nHandling Files\nIf your component expects uploaded files as input, or returns saved files to the frontend, you MUST use the FileData to type the files in your data_model.\nWhen you use the FileData:\nGradio knows that it should allow serving this file to the frontend. Gradio automatically blocks requests to serve arbitrary files in the computer running the server.\nGradio will automatically place the file in a cache so that duplicate copies of the file don't get saved.\nThe client libraries will automatically know that they should upload input files prior to sending the request. They will also automatically download files.\nIf you do not use the FileData, your component will not work as expected!\nAdding Event Triggers To Your Component\nThe events triggers for your component are defined in the EVENTS class attribute.\nThis is a list that contains the string names of the events.\nAdding an event to this list will automatically add a method with that same name to your component!\nYou can import the Events enum from gradio.events to access commonly used events in the core gradio components.\nFor example, the following code will define textsubmit, fileupload and change methods in the MyComponent class.\n`python\nfrom gradio.events import Events\nfrom gradio.components import FormComponent\nclass MyComponent(FormComponent):\n    EVENTS = [\n        \"text_submit\",\n        \"file_upload\",\n        Events.change\n    ]\n``\n            \n                \n                    \n                    \n                    \n                \n                Don't forget to also handle these events in the JavaScript code!\n            \n                \nConclusion","type":"GUIDE"},{"title":"Batch Functions","slug":"/guides/batch-functions/","content":"Batch functions\nGradio supports the ability to pass batch functions. Batch functions are just\nfunctions which take in a list of inputs and return a list of predictions.\nFor example, here is a batched function that takes in two lists of inputs (a list of\nwords and a list of ints), and returns a list of trimmed words as output:\n``py\nimport time\ndef trim_words(words, lens):\n    trimmed_words = []\n    time.sleep(5)\n    for w, l in zip(words, lens):\n        trimmed_words.append(w[:int(l)])\n    return [trimmed_words]\n`\nThe advantage of using batched functions is that if you enable queuing, the Gradio server can automatically batch incoming requests and process them in parallel,\npotentially speeding up your demo. Here's what the Gradio code looks like (notice the batch=True and maxbatchsize=16)\nWith the gr.Interface class:\n`python\ndemo = gr.Interface(\n    fn=trim_words, \n    inputs=[\"textbox\", \"number\"], \n    outputs=[\"output\"],\n    batch=True, \n    maxbatchsize=16\n)\ndemo.launch()\n`\nWith the gr.Blocks class:\n`py\nimport gradio as gr\nwith gr.Blocks() as demo:\n    with gr.Row():\n        word = gr.Textbox(label=\"word\")\n        leng = gr.Number(label=\"leng\")\n        output = gr.Textbox(label=\"Output\")\n    with gr.Row():\n        run = gr.Button()\n    event = run.click(trimwords, [word, leng], output, batch=True, maxbatch_size=16)\ndemo.launch()\n`\nIn the example above, 16 requests could be processed in parallel (for a total inference time of 5 seconds), instead of each request being processed separately (for a total\ninference time of 80 seconds). Many Hugging Face transformers and diffusers` models work very naturally with Gradio's batch mode: here's [an example demo using diffusers to\ngenerate images in batches](https://github.com/gradio-app/gradio/blob/main/demo/diffuserswithbatching/run.py)","type":"GUIDE"},{"title":"Blocks And Event Listeners","slug":"/guides/blocks-and-event-listeners/","content":"Blocks and Event Listeners\nWe briefly described the Blocks class in the Quickstart as a way to build custom demos. Let's dive deeper. \nBlocks Structure\nTake a look at the demo below.\n``python\nimport gradio as gr\ndef greet(name):\n    return \"Hello \" + name + \"!\"\nwith gr.Blocks() as demo:\n    name = gr.Textbox(label=\"Name\")\n    output = gr.Textbox(label=\"Output Box\")\n    greet_btn = gr.Button(\"Greet\")\n    greetbtn.click(fn=greet, inputs=name, outputs=output, apiname=\"greet\")\ndemo.launch()\n`\nFirst, note the with gr.Blocks() as demo: clause. The Blocks app code will be contained within this clause.\nNext come the Components. These are the same Components used in Interface. However, instead of being passed to some constructor, Components are automatically added to the Blocks as they are created within the with clause.\nFinally, the click() event listener. Event listeners define the data flow within the app. In the example above, the listener ties the two Textboxes together. The Textbox name acts as the input and Textbox output acts as the output to the greet method. This dataflow is triggered when the Button greet_btn is clicked. Like an Interface, an event listener can take multiple inputs or outputs.\nYou can also attach event listeners using decorators - skip the fn argument and assign inputs and outputs directly:\n`python\nimport gradio as gr\nwith gr.Blocks() as demo:\n    name = gr.Textbox(label=\"Name\")\n    output = gr.Textbox(label=\"Output Box\")\n    greet_btn = gr.Button(\"Greet\")\n    @greet_btn.click(inputs=name, outputs=output)\n    def greet(name):\n        return \"Hello \" + name + \"!\"\ndemo.launch()\n`\nEvent Listeners and Interactivity\nIn the example above, you'll notice that you are able to edit Textbox name, but not Textbox output. This is because any Component that acts as an input to an event listener is made interactive. However, since Textbox output acts only as an output, Gradio determines that it should not be made interactive. You can override the default behavior and directly configure the interactivity of a Component with the boolean interactive keyword argument, e.g. gr.Textbox(interactive=True).\n`python\noutput = gr.Textbox(label=\"Output\", interactive=True)\n`\nNote: What happens if a Gradio component is neither an input nor an output? If a component is constructed with a default value, then it is presumed to be displaying content and is rendered non-interactive. Otherwise, it is rendered interactive. Again, this behavior can be overridden by specifying a value for the interactive argument.\nTypes of Event Listeners\nTake a look at the demo below:\n`python\nimport gradio as gr\ndef welcome(name):\n    return f\"Welcome to Gradio, {name}!\"\nwith gr.Blocks() as demo:\n    gr.Markdown(\n    \"\"\"\n    # Hello World!\n    Start typing below to see the output.\n    \"\"\")\n    inp = gr.Textbox(placeholder=\"What is your name?\")\n    out = gr.Textbox()\n    inp.change(welcome, inp, out)\ndemo.launch()\n`\nInstead of being triggered by a click, the welcome function is triggered by typing in the Textbox inp. This is due to the change() event listener. Different Components support different event listeners. For example, the Video Component supports a play() event listener, triggered when a user presses play. See the Docs for the event listeners for each Component.\nMultiple Data Flows\nA Blocks app is not limited to a single data flow the way Interfaces are. Take a look at the demo below:\n`python\nimport gradio as gr\ndef increase(num):\n    return num + 1\nwith gr.Blocks() as demo:\n    a = gr.Number(label=\"a\")\n    b = gr.Number(label=\"b\")\n    atob = gr.Button(\"a > b\")\n    btoa = gr.Button(\"b > a\")\n    atob.click(increase, a, b)\n    btoa.click(increase, b, a)\ndemo.launch()\n`\nNote that num1 can act as input to num2, and also vice-versa! As your apps get more complex, you will have many data flows connecting various Components.\nHere's an example of a \"multi-step\" demo, where the output of one model (a speech-to-text model) gets fed into the next model (a sentiment classifier).\n`python\nfrom transformers import pipeline\nimport gradio as gr\nasr = pipeline(\"automatic-speech-recognition\", \"facebook/wav2vec2-base-960h\")\nclassifier = pipeline(\"text-classification\")\ndef speechtotext(speech):\n    text = asr(speech)[\"text\"]  \n    return text\ndef texttosentiment(text):\n    return classifier(text)[0][\"label\"]  \ndemo = gr.Blocks()\nwith demo:\n    audio_file = gr.Audio(type=\"filepath\")\n    text = gr.Textbox()\n    label = gr.Label()\n    b1 = gr.Button(\"Recognize Speech\")\n    b2 = gr.Button(\"Classify Sentiment\")\n    b1.click(speechtotext, inputs=audio_file, outputs=text)\n    b2.click(texttosentiment, inputs=text, outputs=label)\ndemo.launch()\n`\nFunction Input List vs Set\nThe event listeners you've seen so far have a single input component. If you'd like to have multiple input components pass data to the function, you have two options on how the function can accept input component values:\nas a list of arguments, or\nas a single dictionary of values, keyed by the component\nLet's see an example of each:\n`python\nimport gradio as gr\nwith gr.Blocks() as demo:\n    a = gr.Number(label=\"a\")\n    b = gr.Number(label=\"b\")\n    with gr.Row():\n        add_btn = gr.Button(\"Add\")\n        sub_btn = gr.Button(\"Subtract\")\n    c = gr.Number(label=\"sum\")\n    def add(num1, num2):\n        return num1 + num2\n    add_btn.click(add, inputs=[a, b], outputs=c)\n    def sub(data):\n        return data[a] - data[b]\n    sub_btn.click(sub, inputs={a, b}, outputs=c)\ndemo.launch()\n`\nBoth add() and sub() take a and b as inputs. However, the syntax is different between these listeners.\nTo the add_btn listener, we pass the inputs as a list. The function add() takes each of these inputs as arguments. The value of a maps to the argument num1, and the value of b maps to the argument num2.\nTo the sub_btn listener, we pass the inputs as a set (note the curly brackets!). When you pass a set, the function sub() receives a single dictionary argument data, where the keys are the input components and the values are the values of those components.\nIt is a matter of preference which syntax you prefer! For functions with many input components, option 2 may be easier to manage.\nPassing Inputs by Parameter Name\nUse inputs_kwargs when a component value should be passed to an event function by parameter name instead of by position. This is especially useful when calling an existing function with keyword-only parameters: the function can be connected directly without writing a wrapper just to rearrange its arguments.\n`python\nimport gradio as gr\ndef greet(firstname: str, *, lastname: str) -> str:\n    return f\"Hello, {firstname} {lastname}!\"\nwith gr.Blocks() as demo:\n    first_name = gr.Textbox(label=\"First name\")\n    last_name = gr.Textbox(label=\"Last name\")\n    greeting = gr.Textbox(label=\"Greeting\")\n    greet_button = gr.Button(\"Greet\", variant=\"primary\")\n    greet_button.click(\n        greet,\n        inputs=[first_name],\n        inputskwargs={\"lastname\": last_name},\n        outputs=greeting,\n    )\ndemo.launch()\n`\nIn this example, firstname is passed positionally through inputs, while the lastname component is mapped to the keyword-only lastname parameter. Each key in inputskwargs must match a parameter accepted by the event function. Keyword inputs can be combined with a component or list of components in inputs, but not with the set syntax described above, since a set already passes all input values together as one component-keyed dictionary.\nIf the event uses a validator, the validator receives values with the same positional and keyword mapping as the main function. Its signature must therefore accept every name used in inputs_kwargs; if it does not, the event raises a ValueError when it is defined.\nOne thing to keep in mind: a parameter annotated with a component type (such as tb: gr.Textbox) receives the full component instead of just its value, but only when Gradio can fill it positionally. A keyword-only parameter with a component annotation receives the plain value, so annotate such parameters with the value type they actually receive.\nNamed inputs are particularly helpful for larger forms because the mapping remains clear even when controls are arranged differently in the interface. The following live inventory dashboard connects five filter controls to explicit keyword-only parameters. Because gr.on() has no explicit triggers, it listens to changes from both inputs and inputs_kwargs, as well as the app's load event.\n`python\nfrom typing import Any\nimport gradio as gr\nINVENTORY: list[dict[str, Any]] = [\n    {\"name\": \"Studio Headphones\", \"category\": \"Audio\", \"price\": 149, \"stock\": 18},\n    {\"name\": \"Podcast Microphone\", \"category\": \"Audio\", \"price\": 89, \"stock\": 0},\n    {\n        \"name\": \"Mechanical Keyboard\",\n        \"category\": \"Accessories\",\n        \"price\": 129,\n        \"stock\": 7,\n    },\n    {\"name\": \"Ergonomic Mouse\", \"category\": \"Accessories\", \"price\": 79, \"stock\": 24},\n    {\"name\": \"4K Monitor\", \"category\": \"Displays\", \"price\": 499, \"stock\": 5},\n    {\"name\": \"Portable Monitor\", \"category\": \"Displays\", \"price\": 219, \"stock\": 0},\n    {\"name\": \"Developer Laptop\", \"category\": \"Computers\", \"price\": 1599, \"stock\": 3},\n    {\"name\": \"Mini Desktop\", \"category\": \"Computers\", \"price\": 749, \"stock\": 11},\n    {\"name\": \"USB-C Dock\", \"category\": \"Accessories\", \"price\": 189, \"stock\": 14},\n    {\"name\": \"Conference Speaker\", \"category\": \"Audio\", \"price\": 249, \"stock\": 6},\n]\ndef filter_inventory(\n    query: str,\n    *,\n    category: str,\n    max_price: float,\n    instockonly: bool,\n    sort_by: str,\n    result_limit: int,\n) -> tuple[list[list[Any]], str]:\n    \"\"\"Filter a product catalog while keeping every option explicit and named.\"\"\"\n    normalized_query = query.strip().lower()\n    matches = [\n        item\n        for item in INVENTORY\n        if (not normalizedquery or normalizedquery in item[\"name\"].lower())\n        and (category == \"All\" or item[\"category\"] == category)\n        and item[\"price\"]  0)\n    ]\n    if sort_by == \"Price: low to high\":\n        matches.sort(key=lambda item: item[\"price\"])\n    elif sort_by == \"Price: high to low\":\n        matches.sort(key=lambda item: item[\"price\"], reverse=True)\n    else:\n        matches.sort(key=lambda item: item[\"name\"])\n    visiblematches = matches[: int(resultlimit)]\n    rows = [\n        [item[\"name\"], item[\"category\"], item[\"price\"], item[\"stock\"]]\n        for item in visible_matches\n    ]\n    status = (\n        f\"Showing {len(visible_matches)} of {len(matches)} matching products.\"\n    )\n    return rows, status\nwith gr.Blocks() as demo:\n    gr.Markdown(\n        \"# Inventory explorer\\n\"\n        \"Search and filter a catalog with controls mapped to named function parameters.\"\n    )\n    search = gr.Textbox(label=\"Search\", placeholder=\"Try 'monitor' or 'audio'\")\n    with gr.Row():\n        category = gr.Dropdown(\n            [\"All\", \"Accessories\", \"Audio\", \"Computers\", \"Displays\"],\n            value=\"All\",\n            label=\"Category\",\n        )\n        max_price = gr.Slider(0, 2000, value=2000, step=25, label=\"Maximum price\")\n        instockonly = gr.Checkbox(value=False, label=\"In stock only\")\n    with gr.Row():\n        sort_by = gr.Dropdown(\n            [\"Name\", \"Price: low to high\", \"Price: high to low\"],\n            value=\"Name\",\n            label=\"Sort by\",\n        )\n        result_limit = gr.Slider(1, 10, value=10, step=1, label=\"Result limit\")\n    results = gr.Dataframe(\n        headers=[\"Product\", \"Category\", \"Price ($)\", \"In stock\"],\n        datatype=(\"str\", \"str\", \"number\", \"number\"),\n        interactive=False,\n    )\n    status = gr.Markdown()\n    gr.on(\n        fn=filter_inventory,\n        inputs=[search],\n        inputs_kwargs={\n            \"category\": category,\n            \"instockonly\": instockonly,\n            \"maxprice\": maxprice,\n            \"resultlimit\": resultlimit,\n            \"sortby\": sortby,\n        },\n        outputs=[results, status],\n        triggermode=\"alwayslast\",\n    )\ndemo.launch()\n`\nFunction Return List vs Dict\nSimilarly, you may return values for multiple output components either as:\na list of values, or\na dictionary keyed by the component\nLet's first see an example of (1), where we set the values of two output components by returning two values:\n`python\nwith gr.Blocks() as demo:\n    food_box = gr.Number(value=10, label=\"Food Count\")\n    status_box = gr.Textbox()\n    def eat(food):\n        if food > 0:\n            return food - 1, \"full\"\n        else:\n            return 0, \"hungry\"\n    gr.Button(\"Eat\").click(\n        fn=eat,\n        inputs=food_box,\n        outputs=[foodbox, statusbox]\n    )\n`\nAbove, each return statement returns two values corresponding to foodbox and statusbox, respectively.\nNote: if your event listener has a single output component, you should not return it as a single-item list. This will not work, since Gradio does not know whether to interpret that outer list as part of your return value. You should instead just return that value directly.\nNow, let's see option (2). Instead of returning a list of values corresponding to each output component in order, you can also return a dictionary, with the key corresponding to the output component and the value as the new value. This also allows you to skip updating some output components.\n`python\nwith gr.Blocks() as demo:\n    food_box = gr.Number(value=10, label=\"Food Count\")\n    status_box = gr.Textbox()\n    def eat(food):\n        if food > 0:\n            return {foodbox: food - 1, statusbox: \"full\"}\n        else:\n            return {status_box: \"hungry\"}\n    gr.Button(\"Eat\").click(\n        fn=eat,\n        inputs=food_box,\n        outputs=[foodbox, statusbox]\n    )\n`\nNotice how when there is no food, we only update the statusbox element. We skipped updating the foodbox component.\nDictionary returns are helpful when an event listener affects many components on return, or conditionally affects outputs and not others.\nKeep in mind that with dictionary returns, we still need to specify the possible outputs in the event listener.\nUpdating Component Configurations\nThe return value of an event listener function is usually the updated value of the corresponding output Component. Sometimes we want to update the configuration of the Component as well, such as the visibility. In this case, we return a new Component, setting the properties we want to change.\n`python\nimport gradio as gr\ndef change_textbox(choice):\n    if choice == \"short\":\n        return gr.Textbox(lines=2, visible=True)\n    elif choice == \"long\":\n        return gr.Textbox(lines=8, visible=True, value=\"Lorem ipsum dolor sit amet\")\n    else:\n        return gr.Textbox(visible=False)\nwith gr.Blocks() as demo:\n    radio = gr.Radio(\n        [\"short\", \"long\", \"none\"], label=\"What kind of essay would you like to write?\"\n    )\n    text = gr.Textbox(lines=2, interactive=True, buttons=[\"copy\"])\n    radio.change(fn=change_textbox, inputs=radio, outputs=text)\ndemo.launch()\n`\nSee how we can configure the Textbox itself through a new gr.Textbox() method. The value= argument can still be used to update the value along with Component configuration. Any arguments we do not set will preserve their previous values.\nNot Changing a Component's Value\nIn some cases, you may want to leave a component's value unchanged. Gradio includes a special function, gr.skip(), which can be returned from your function. Returning this function will keep the output component (or components') values as is. Let us illustrate with an example:\n`python\nimport random\nimport gradio as gr\nwith gr.Blocks() as demo:\n    with gr.Row():\n        clear_button = gr.Button(\"Clear\")\n        skip_button = gr.Button(\"Skip\")\n        random_button = gr.Button(\"Random\")\n    numbers = [gr.Number(), gr.Number()]\n    clear_button.click(lambda : (None, None), outputs=numbers)\n    skip_button.click(lambda : [gr.skip(), gr.skip()], outputs=numbers)\n    random_button.click(lambda : (random.randint(0, 100), random.randint(0, 100)), outputs=numbers)\ndemo.launch()\n`\nNote the difference between returning None (which generally resets a component's value to an empty state) versus returning gr.skip(), which leaves the component value unchanged.\n            \n                \n                    \n                    \n                    \n                \n                if you have multiple output components, and you want to leave all of their values unchanged, you can just return a single gr.skip() instead of returning a tuple of skips, one for each element.\n            \n                \nRunning Events Consecutively\nYou can also run events consecutively by using the then method of an event listener. This will run an event after the previous event has finished running. This is useful for running events that update components in multiple steps.\nFor example, in the chatbot example below, we first update the chatbot with the user message immediately, and then update the chatbot with the computer response after a simulated delay.\n`python\nimport gradio as gr\nimport random\nimport time\nwith gr.Blocks() as demo:\n    chatbot = gr.Chatbot()\n    msg = gr.Textbox()\n    clear = gr.Button(\"Clear\")\n    def user(user_message, history):\n        return \"\", history + [{\"role\": \"user\", \"content\": user_message}]\n    def bot(history):\n        bot_message = random.choice([\"How are you?\", \"I love you\", \"I'm very hungry\"])\n        time.sleep(2)\n        history.append({\"role\": \"assistant\", \"content\": bot_message})\n        return history\n    msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(\n        bot, chatbot, chatbot\n    )\n    clear.click(lambda: None, None, chatbot, queue=False)\ndemo.launch()\n`\nThe .then() method of an event listener executes the subsequent event regardless of whether the previous event raised any errors. If you'd like to only run subsequent events if the previous event executed successfully, use the .success() method, which takes the same arguments as .then(). Conversely, if you'd like to only run subsequent events if the previous event failed (i.e., raised an error), use the .failure() method. This is particularly useful for error handling workflows, such as displaying error messages or restoring previous states when an operation fails.\nBinding Multiple Triggers to a Function\nOften times, you may want to bind multiple triggers to the same function. For example, you may want to allow a user to click a submit button, or press enter to submit a form. You can do this using the gr.on method and passing a list of triggers to the trigger.\n`python\nimport gradio as gr\nwith gr.Blocks() as demo:\n    name = gr.Textbox(label=\"Name\")\n    output = gr.Textbox(label=\"Output Box\")\n    greet_btn = gr.Button(\"Greet\")\n    trigger = gr.Textbox(label=\"Trigger Box\")\n    def greet(name, evt_data: gr.EventData):\n        return \"Hello \" + name + \"!\", evt_data.target.class.name\n    def clearname(evtdata: gr.EventData):\n        return \"\"\n    gr.on(\n        triggers=[name.submit, greet_btn.click],\n        fn=greet,\n        inputs=name,\n        outputs=[output, trigger],\n    ).then(clear_name, outputs=[name])\ndemo.launch()\n`\nYou can use decorator syntax as well:\n`python\nimport gradio as gr\nwith gr.Blocks() as demo:\n    name = gr.Textbox(label=\"Name\")\n    output = gr.Textbox(label=\"Output Box\")\n    greet_btn = gr.Button(\"Greet\")\n    @gr.on(triggers=[name.submit, greet_btn.click], inputs=name, outputs=output)\n    def greet(name):\n        return \"Hello \" + name + \"!\"\ndemo.launch()\n`\nYou can use gr.on to create \"live\" events by binding to the change event of components that implement it. If you do not specify any triggers, the function will automatically bind to all change event of all input components that include a change event (for example gr.Textbox has a change event whereas gr.Button does not).\n`python\nimport gradio as gr\nwith gr.Blocks() as demo:\n    with gr.Row():\n        num1 = gr.Slider(1, 10)\n        num2 = gr.Slider(1, 10)\n        num3 = gr.Slider(1, 10)\n    output = gr.Number(label=\"Sum\")\n    @gr.on(inputs=[num1, num2, num3], outputs=output)\n    def sum(a, b, c):\n        return a + b + c\ndemo.launch()\n`\nYou can follow gr.on with .then, just like any regular event listener. This handy method should save you from having to write a lot of repetitive code!\nBinding a Component Value Directly to a Function of Other Components\nIf you want to set a Component's value to always be a function of the value of other Components, you can use the following shorthand:\n`python\nwith gr.Blocks() as demo:\n  num1 = gr.Number()\n  num2 = gr.Number()\n  product = gr.Number(lambda a, b: a * b, inputs=[num1, num2])\n`\nThis functionally the same as:\n`python\nwith gr.Blocks() as demo:\n  num1 = gr.Number()\n  num2 = gr.Number()\n  product = gr.Number()\n  gr.on(\n    [num1.change, num2.change, demo.load], \n    lambda a, b: a * b, \n    inputs=[num1, num2], \n    outputs=product\n  )\n``","type":"GUIDE"},{"title":"Building An Mcp Client With Gradio","slug":"/guides/building-an-mcp-client-with-gradio/","content":"Using the Gradio Chatbot as an MCP Client\nThis guide will walk you through a Model Context Protocol (MCP) Client and Server implementation with Gradio. You'll build a Gradio Chatbot that uses Anthropic's Claude API to respond to user messages, but also, as an MCP Client, generates images (by connecting to an MCP Server, which is a separate Gradio app). \n \nWhat is MCP?\nThe Model Context Protocol (MCP) standardizes how applications provide context to LLMs. It allows Claude to interact with external tools, like image generators, file systems, or APIs, etc.\nPrerequisites\nPython 3.10+\nAn Anthropic API key\nBasic understanding of Python programming\nSetup\nFirst, install the required packages:\n``bash\npip install gradio anthropic mcp\n`\nCreate a .env file in your project directory and add your Anthropic API key:\n`\nANTHROPICAPIKEY=yourapikey_here\n`\nPart 1: Building the MCP Server\nThe server provides tools that Claude can use. In this example, we'll create a server that generates images through a HuggingFace space.\nCreate a file named gradiomcpserver.py:\n`python\nfrom mcp.server.fastmcp import FastMCP\nimport json\nimport sys\nimport io\nimport time\nfrom gradio_client import Client\nsys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')\nsys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8', errors='replace')\nmcp = FastMCP(\"huggingfacespacesimage_display\")\n@mcp.tool()\nasync def generate_image(prompt: str, width: int = 512, height: int = 512) -> str:\n    \"\"\"Generate an image using SanaSprint model.\n    \n    Args:\n        prompt: Text prompt describing the image to generate\n        width: Image width (default: 512)\n        height: Image height (default: 512)\n    \"\"\"\n    client = Client(\"https://ysharma-sanasprint.hf.space/\")\n    \n    try:\n        result = client.predict(\n            prompt,\n            \"0.6B\",\n            0,\n            True,\n            width,\n            height,\n            4.0,\n            2,\n            api_name=\"/infer\"\n        )\n        \n        if isinstance(result, list) and len(result) >= 1:\n            image_data = result[0]\n            if isinstance(imagedata, dict) and \"url\" in imagedata:\n                return json.dumps({\n                    \"type\": \"image\",\n                    \"url\": image_data[\"url\"],\n                    \"message\": f\"Generated image for prompt: {prompt}\"\n                })\n        \n        return json.dumps({\n            \"type\": \"error\",\n            \"message\": \"Failed to generate image\"\n        })\n        \n    except Exception as e:\n        return json.dumps({\n            \"type\": \"error\",\n            \"message\": f\"Error generating image: {str(e)}\"\n        })\nif name == \"main\":\n    mcp.run(transport='stdio')\n`\nWhat this server does:\nIt creates an MCP server that exposes a generate_image tool\nThe tool connects to the SanaSprint model hosted on HuggingFace Spaces\nIt handles the asynchronous nature of image generation by polling for results\nWhen an image is ready, it returns the URL in a structured JSON format\nPart 2: Building the MCP Client with Gradio\nNow let's create a Gradio chat interface as MCP Client that connects Claude to our MCP server.\nCreate a file named app.py:\n`python\nimport asyncio\nimport os\nimport json\nfrom typing import List, Dict, Any, Union\nfrom contextlib import AsyncExitStack\nimport gradio as gr\nfrom gradio.components.chatbot import ChatMessage\nfrom mcp import ClientSession, StdioServerParameters\nfrom mcp.client.stdio import stdio_client\nfrom anthropic import Anthropic\nfrom dotenv import load_dotenv\nload_dotenv()\nloop = asyncio.neweventloop()\nasyncio.seteventloop(loop)\nclass MCPClientWrapper:\n    def init(self):\n        self.session = None\n        self.exit_stack = None\n        self.anthropic = Anthropic()\n        self.tools = []\n    \n    def connect(self, server_path: str) -> str:\n        return loop.rununtilcomplete(self.connect(serverpath))\n    \n    async def connect(self, serverpath: str) -> str:\n        if self.exit_stack:\n            await self.exit_stack.aclose()\n        \n        self.exit_stack = AsyncExitStack()\n        \n        ispython = serverpath.endswith('.py')\n        command = \"python\" if is_python else \"node\"\n        \n        server_params = StdioServerParameters(\n            command=command,\n            args=[server_path],\n            env={\"PYTHONIOENCODING\": \"utf-8\", \"PYTHONUNBUFFERED\": \"1\"}\n        )\n        \n        stdiotransport = await self.exitstack.enterasynccontext(stdioclient(serverparams))\n        self.stdio, self.write = stdio_transport\n        \n        self.session = await self.exitstack.enterasync_context(ClientSession(self.stdio, self.write))\n        await self.session.initialize()\n        \n        response = await self.session.list_tools()\n        self.tools = [{ \n            \"name\": tool.name,\n            \"description\": tool.description,\n            \"input_schema\": tool.inputSchema\n        } for tool in response.tools]\n        \n        tool_names = [tool[\"name\"] for tool in self.tools]\n        return f\"Connected to MCP server. Available tools: {', '.join(tool_names)}\"\n    \n    def process_message(self, message: str, history: List[Union[Dict[str, Any], ChatMessage]]) -> tuple:\n        if not self.session:\n            return history + [\n                {\"role\": \"user\", \"content\": message}, \n                {\"role\": \"assistant\", \"content\": \"Please connect to an MCP server first.\"}\n            ], gr.Textbox(value=\"\")\n        \n        newmessages = loop.rununtilcomplete(self.process_query(message, history))\n        return history + [{\"role\": \"user\", \"content\": message}] + new_messages, gr.Textbox(value=\"\")\n    \n    async def processquery(self, message: str, history: List[Union[Dict[str, Any], ChatMessage]]):\n        claude_messages = []\n        for msg in history:\n            if isinstance(msg, ChatMessage):\n                role, content = msg.role, msg.content\n            else:\n                role, content = msg.get(\"role\"), msg.get(\"content\")\n            \n            if role in [\"user\", \"assistant\", \"system\"]:\n                claude_messages.append({\"role\": role, \"content\": content})\n        \n        claude_messages.append({\"role\": \"user\", \"content\": message})\n        \n        response = self.anthropic.messages.create(\n            model=\"claude-3-5-sonnet-20241022\",\n            max_tokens=1000,\n            messages=claude_messages,\n            tools=self.tools\n        )\n        result_messages = []\n        \n        for content in response.content:\n            if content.type == 'text':\n                result_messages.append({\n                    \"role\": \"assistant\", \n                    \"content\": content.text\n                })\n                \n            elif content.type == 'tool_use':\n                tool_name = content.name\n                tool_args = content.input\n                \n                result_messages.append({\n                    \"role\": \"assistant\",\n                    \"content\": f\"I'll use the {tool_name} tool to help answer your question.\",\n                    \"metadata\": {\n                        \"title\": f\"Using tool: {tool_name}\",\n                        \"log\": f\"Parameters: {json.dumps(toolargs, ensureascii=True)}\",\n                        \"status\": \"pending\",\n                        \"id\": f\"toolcall{tool_name}\"\n                    }\n                })\n                \n                result_messages.append({\n                    \"role\": \"assistant\",\n                    \"content\": \"`json\\n\" + json.dumps(toolargs, indent=2, ensureascii=True) + \"\\n`\",\n                    \"metadata\": {\n                        \"parentid\": f\"toolcall{toolname}\",\n                        \"id\": f\"params{toolname}\",\n                        \"title\": \"Tool Parameters\"\n                    }\n                })\n                \n                result = await self.session.calltool(toolname, tool_args)\n                \n                if resultmessages and \"metadata\" in resultmessages[-2]:\n                    result_messages[-2][\"metadata\"][\"status\"] = \"done\"\n                \n                result_messages.append({\n                    \"role\": \"assistant\",\n                    \"content\": \"Here are the results from the tool:\",\n                    \"metadata\": {\n                        \"title\": f\"Tool Result for {tool_name}\",\n                        \"status\": \"done\",\n                        \"id\": f\"result{toolname}\"\n                    }\n                })\n                \n                result_content = result.content\n                if isinstance(result_content, list):\n                    resultcontent = \"\\n\".join(str(item) for item in resultcontent)\n                \n                try:\n                    resultjson = json.loads(resultcontent)\n                    if isinstance(resultjson, dict) and \"type\" in resultjson:\n                        if resultjson[\"type\"] == \"image\" and \"url\" in resultjson:\n                            result_messages.append({\n                                \"role\": \"assistant\",\n                                \"content\": {\"path\": resultjson[\"url\"], \"alttext\": result_json.get(\"message\", \"Generated image\")},\n                                \"metadata\": {\n                                    \"parentid\": f\"result{tool_name}\",\n                                    \"id\": f\"image{toolname}\",\n                                    \"title\": \"Generated Image\"\n                                }\n                            })\n                        else:\n                            result_messages.append({\n                                \"role\": \"assistant\",\n                                \"content\": \"`\\n\" + result_content + \"\\n`\",\n                                \"metadata\": {\n                                    \"parentid\": f\"result{tool_name}\",\n                                    \"id\": f\"rawresult{tool_name}\",\n                                    \"title\": \"Raw Output\"\n                                }\n                            })\n                except:\n                    result_messages.append({\n                        \"role\": \"assistant\",\n                        \"content\": \"`\\n\" + result_content + \"\\n`\",\n                        \"metadata\": {\n                            \"parentid\": f\"result{tool_name}\",\n                            \"id\": f\"rawresult{tool_name}\",\n                            \"title\": \"Raw Output\"\n                        }\n                    })\n                \n                claudemessages.append({\"role\": \"user\", \"content\": f\"Tool result for {toolname}: {result_content}\"})\n                next_response = self.anthropic.messages.create(\n                    model=\"claude-3-5-sonnet-20241022\",\n                    max_tokens=1000,\n                    messages=claude_messages,\n                )\n                \n                if nextresponse.content and nextresponse.content[0].type == 'text':\n                    result_messages.append({\n                        \"role\": \"assistant\",\n                        \"content\": next_response.content[0].text\n                    })\n        return result_messages\nclient = MCPClientWrapper()\ndef gradio_interface():\n    with gr.Blocks(title=\"MCP Weather Client\") as demo:\n        gr.Markdown(\"# MCP Weather Assistant\")\n        gr.Markdown(\"Connect to your MCP weather server and chat with the assistant\")\n        \n        with gr.Row(equal_height=True):\n            with gr.Column(scale=4):\n                server_path = gr.Textbox(\n                    label=\"Server Script Path\",\n                    placeholder=\"Enter path to server script (e.g., weather.py)\",\n                    value=\"gradiomcpserver.py\"\n                )\n            with gr.Column(scale=1):\n                connect_btn = gr.Button(\"Connect\")\n        \n        status = gr.Textbox(label=\"Connection Status\", interactive=False)\n        \n        chatbot = gr.Chatbot(\n            value=[], \n            height=500,\n            showcopybutton=True,\n            avatar_images=(\"👤\", \"🤖\")\n        )\n        \n        with gr.Row(equal_height=True):\n            msg = gr.Textbox(\n                label=\"Your Question\",\n                placeholder=\"Ask about weather or alerts (e.g., What's the weather in New York?)\",\n                scale=4\n            )\n            clear_btn = gr.Button(\"Clear Chat\", scale=1)\n        \n        connectbtn.click(client.connect, inputs=serverpath, outputs=status)\n        msg.submit(client.process_message, [msg, chatbot], [chatbot, msg])\n        clear_btn.click(lambda: [], None, chatbot)\n        \n    return demo\nif name == \"main\":\n    if not os.getenv(\"ANTHROPICAPIKEY\"):\n        print(\"Warning: ANTHROPICAPIKEY not found in environment. Please set it in your .env file.\")\n    \n    interface = gradio_interface()\n    interface.launch(debug=True)\n`\nWhat this MCP Client does:\nCreates a friendly Gradio chat interface for user interaction\nConnects to the MCP server you specify\nHandles conversation history and message formatting\nMakes call to Claude API with tool definitions\nProcesses tool usage requests from Claude\nDisplays images and other tool outputs in the chat\nSends tool results back to Claude for interpretation\nRunning the Application\nTo run your MCP application:\nStart a terminal window and run the MCP Client:\n   `bash\n   python app.py\n   `\nOpen the Gradio interface at the URL shown (typically http://127.0.0.1:7860)\nIn the Gradio interface, you'll see a field for the MCP Server path. It should default to gradiomcpserver.py.\nClick \"Connect\" to establish the connection to the MCP server.\nYou should see a message indicating the server connection was successful.\nExample Usage\nNow you can chat with Claude and it will be able to generate images based on your descriptions.\nTry prompts like:\n\"Can you generate an image of a mountain landscape at sunset?\"\n\"Create an image of a cool tabby cat\"\n\"Generate a picture of a panda wearing sunglasses\"\nClaude will recognize these as image generation requests and automatically use the generate_image tool from your MCP server.\nHow it Works\nHere's the high-level flow of what happens during a chat session:\nYour prompt enters the Gradio interface\nThe client forwards your prompt to Claude\nClaude analyzes the prompt and decides to use the generate_image` tool\nThe client sends the tool call to the MCP server\nThe server calls the external image generation API\nThe image URL is returned to the client\nThe client sends the image URL back to Claude\nClaude provides a response that references the generated image\nThe Gradio chat interface displays both Claude's response and the image\nNext Steps\nNow that you have a working MCP system, here are some ideas to extend it:\nAdd more tools to your server\nImprove error handling \nAdd private Huggingface Spaces with authentication for secure tool access\nCreate custom tools that connect to your own APIs or services\nImplement streaming responses for better user experience\nConclusion\nCongratulations! You've successfully built an MCP Client and Server that allows Claude to generate images based on text prompts. This is just the beginning of what you can do with Gradio and MCP. This guide enables you to build complex AI applications that can use Claude or any other powerful LLM to interact with virtually any external tool or service.\nRead our other Guide on using Gradio apps as MCP Servers.","type":"GUIDE"},{"title":"Building Chatgpt Apps With Gradio","slug":"/guides/building-chatgpt-apps-with-gradio/","content":"Building ChatGPT Apps with Gradio and Apps SDK\nApps in ChatGPT are a great way to let users try your machine learning models or other kinds of apps entirely by chatting in familiar chat application. OpenAI has released the Apps SDK for developers to build complete applications, but you can use Gradio to build ChatGPT apps very quickly, based off of your Gradio MCP server. We will also see how Gradio's built-in share links make it especially easy to iterate on your ChatGPT app!\nIntroduction\nBuilding a ChatGPT app requires doing two things:\nBuilding a Gradio MCP server with at least one tool exposed. If you're not already familiar with building a Gradio MCP server, we recommend reading this guide first.\nBuilding a custom UI with HTML, JavaScript, and CSS that will be displayed when your tool is called, an exposing that as an MCP resource. \nWe will walk through the steps in more detail below.\nPrerequisites\nYou will need to enable \"developer mode\" in ChatGPT under Settings → Apps & Connectors → Advanced settings in ChatGPT. This currently requires a paid ChatGPT account.\nYou need to have gradio>=6.0 installed with the mcp add-on:\n``bash\npip install --upgrade gradio[mcp]\n`\nNow, let's walk through two examples of how you can build build ChatGPT apps with Gradio. \nExample 1: Letter Counter App\nThe first example is an ChatGPT app that counts the occurrence of letters in a word and displays a card with the word and specified letters highlighted, like this:\nSo how do we build this? You can find the complete code for the letter counter app in a single file here, or follow the steps below:\nStart by writing your Python function. In our case, the function is simply a letter counter:\n`py\ndef letter_counter(word: str, letter: str) -> int:\n    \"\"\"\n    Count the number of letters in a word or phrase.\n    Parameters:\n        word (str): The word or phrase to count the letters of.\n        letter (str): The letter to count the occurrences of.\n    \"\"\"\n    return word.count(letter)\n`\nThen, wrap your Python function with a Gradio UI, something along these lines:\n`py\nwith gr.Blocks() as demo:\n    with gr.Row():\n        with gr.Column():\n            word = gr.Textbox(label=\"Word\")\n            letter = gr.Textbox(label=\"Letter\")\n            btn = gr.Button(\"Count Letters\")\n        with gr.Column():\n            count = gr.Number(label=\"Count\")\n    btn.click(letter_counter, inputs=[word, letter], outputs=count)\n`\nNow, launch your Gradio app with the MCP server enabled, i.e. with mcp_server=True\n`py\n    demo.launch(mcp_server=True)\n`\nAs covered in earlier guides, you will now be able to test the tool using any MCP Client, such as the MCP Inspector tool. Test it and confirm that it behaves as you expect.\nCreate a UI for your ChatGPT app and expose it as a resource. This part requires writing some frontend code and may be unfamiliar at first, but a few examples will help you create an app that works well for your use case. In our case, we'll create a card with HTML, Javascript, and CSS. Inside the card, we'll display the word presented by the user, highlighting each occurrence of the specified letter. Note that we access the user's tool input using window.openai?.toolInput?.word and window.openai?.toolInput?.letter. The window.openai object is automatically inserted by ChatGPT with the data from the user's tool call. This is what the complete function looks like:\n`py\n@gr.mcp.resource(\"ui://widget/app.html\", mime_type=\"text/html+skybridge\")\ndef app_html():\n    visual = \"\"\"\n    \n    \n        const container = document.getElementById('letter-card-container');\n        function render() {\n            const word = window.openai?.toolInput?.word || \"strawberry\";\n            const letter = window.openai?.toolInput?.letter || \"r\";\n            let letterHTML = '';\n            for (let i = 0; i ${char};\n            }\n            container.innerHTML = \n                \n                    \n                        ${letterHTML}\n                    \n                \n            ;\n        }\n        render();\n        window.addEventListener(\"openai:set_globals\", (event) => {\n            if (event.detail?.globals?.toolInput) {\n                render();\n            }\n        }, { passive: true });\n    \n    \"\"\"\n    return visual\n``\nNote that we've provided a URI for the gr.mcp.resource at ui://widget/app.html. This is arbitrary, but we'll need to use the same URI later on. We also need to specify the mimetype of the resource to be mimetype=\"text/html+skybridge\". Finally, note that we attached an event listener in the JavaScript for \"openai:setglobals\", which is generally a good practice as it allows the widget to update whenever a new tool call is triggered. \nCreate an event in your Gradio app corresponding to the resource function. This is necessary because your Gradio app only picks up MCP tools, resources, prompts, etc. if they are associated with a Gradio event. Typically, the convention is to simply display the code for your MCP resource in a gr.Code component, e.g. like this:\n`py\n    html = gr.Code(language=\"html\", max_lines=20)\n    \n    # ... the rest of your Gradio app\n    btn.click(app_html, outputs=html)\n`\nAdd _meta attributes to your MCP tool. We need to connect the MCP tool that we created to the UI that we created for our app. We can do this by adding this decorator to our MCP tool function:\n`py\n@gr.mcp.tool(\n    _meta={\n        \"openai/outputTemplate\": \"ui://widget/app.html\",\n        \"openai/resultCanProduceWidget\": True,\n        \"openai/widgetAccessible\": True,\n    }\n)\n`\nThe key thing to observe is that the \"openai/outputTemplate\" must match the URI of the MCP resource that we created earlier.\nRelaunch your Gradio app with share=True. This will make it very easy to test within ChatGPT. Note the MCP server URL that is printed to your terminal, e.g. https://2e879c6066d729b11b.gradio.live/gradio_api/mcp/.\n`py\n    demo.launch(share=True, mcp_server=True)\n`\nThis will print a public URL that your Gradio app will be running on.\nNow, navigate to ChatGPT (https://chat.com/). As mentioned earlier, you need to enable \"developer mode\" in ChatGPT under Settings → Apps & Connectors → Advanced settings in ChatGPT. Then, navigate to Settings → Apps & Connectors and click the \"Create\" button. Give your connector a name, a description (optional), and paste in the MCP server URL that was printed to your terminal. Choose \"No authentication\" and create.\nAnd that's it! Once the Connector has been created, you can start prompting it by saying something like, \"Use @letter-counter to count the number of r's in Gradio.\"\nExample 2: An Image Brightener\nNext, let's see a more complex ChatGPT app for image enhancement. The ChatGPT app includes a \"Brighten\" button that lets the user call the tool directly from the app UI.\nHere's the complete code for this app:\n`python\nimport gradio as gr\nimport tempfile\nfrom PIL import Image\nimport numpy as np\n@gr.mcp.tool(\n    _meta={\n        \"openai/outputTemplate\": \"ui://widget/app.html\",\n        \"openai/resultCanProduceWidget\": True,\n        \"openai/widgetAccessible\": True,\n    }\n)\ndef powerlawimage(input_path: str, gamma: float = 0.5) -> str:\n    \"\"\"\n    Applies a power-law (gamma) transformation to an image file and saves\n    the result to a temporary file.\n    Args:\n        input_path (str): Path to the input image.\n        gamma (float): Power-law exponent. 1 darkens.\n    Returns:\n        str: Path to the saved temporary output image.\n    \"\"\"\n    img = Image.open(input_path).convert(\"RGB\")\n    arr = np.array(img, dtype=np.float32) / 255.0\n    arr = np.power(arr, gamma)\n    arr = np.clip(arr * 255, 0, 255).astype(np.uint8)\n    out_img = Image.fromarray(arr)\n    tmp_file = tempfile.NamedTemporaryFile(delete=False, suffix=\".png\")\n    outimg.save(tmpfile.name)\n    tmp_file.close()\n    return tmp_file.name\n@gr.mcp.resource(\"ui://widget/app.html\", mime_type=\"text/html+skybridge\")\ndef app_html():\n    visual = \"\"\"\n    \n        #image-container {\n            position: relative;\n            display: inline-block;\n            max-width: 100%;\n        }\n        #image-display {\n            max-width: 100%;\n            height: auto;\n            display: block;\n            border-radius: 8px;\n        }\n        #brighten-btn {\n            position: absolute;\n            bottom: 16px;\n            right: 26px;\n            padding: 12px 24px;\n            background: #1a1a1a;\n            color: white;\n            border: none;\n            border-radius: 8px;\n            font-weight: 600;\n            cursor: pointer;\n            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);\n        }\n        #brighten-btn:hover {\n            background: #000000;\n        }\n    \n    \n        \n        Brighten\n    \n    \n        const imageEl = document.getElementById('image-display');\n        const btnEl = document.getElementById('brighten-btn');\n        function extractImageUrl(data) {\n            if (data?.text?.startsWith('Image URL: ')) {\n                return data.text.substring('Image URL: '.length).trim();\n            }\n            if (data?.content) {\n                for (const item of data.content) {\n                    if (item.type === 'text' && item.text?.startsWith('Image URL: ')) {\n                        return item.text.substring('Image URL: '.length).trim();\n                    }\n                }\n            }\n        }\n        function render() {\n            const url = extractImageUrl(window.openai?.toolOutput);\n            if (url) imageEl.src = url;\n        }\n        async function brightenImage() {\n            btnEl.disabled = true;\n            btnEl.textContent = 'Brightening...';\n            const result = await window.openai.callTool('powerlawimage', {\n                input_path: imageEl.src\n            });\n            const newUrl = extractImageUrl(result);\n            if (newUrl) imageEl.src = newUrl;\n            btnEl.disabled = false;\n            btnEl.textContent = 'Brighten';\n        }\n        btnEl.addEventListener('click', brightenImage);\n        window.addEventListener(\"openai:set_globals\", (event) => {\n            if (event.detail?.globals?.toolOutput) render();\n        }, { passive: true });\n        render();\n    \n    \"\"\"\n    return visual\nwith gr.Blocks() as demo:\n    with gr.Row():\n        with gr.Column():\n            original_image = gr.Image(label=\"Original Image\", type=\"filepath\")\n            btn = gr.Button(\"Brighten Image\")\n        with gr.Column():\n            output_image = gr.Image(label=\"Output Image\", type=\"filepath\")\n            html = gr.Code(language=\"html\", max_lines=20)\n    btn.click(powerlawimage, inputs=originalimage, outputs=originalimage)\n    btn.click(app_html, outputs=html)\nif name == \"main\":\n    demo.launch(mcp_server=True, share=True)\n`\nWe won't break down the code in as much detail since many of the pieces are the same. But note the following differences from the earlier example:\nCalling tools from the widget: The app uses window.openai.callTool() to invoke the MCP tool directly from a button click, without requiring ChatGPT to call it:\n`javascript\nconst result = await window.openai.callTool('powerlawimage', {\n    input_path: imageEl.src\n});\n`\nParsing tool call results: The result from callTool() contains a content array that needs to be parsed to extract data:\n`javascript\nfunction extractImageUrl(data) {\n    if (data?.content) {\n        for (const item of data.content) {\n            if (item.type === 'text' && item.text?.startsWith('Image URL: ')) {\n                return item.text.substring('Image URL: '.length).trim();\n            }\n        }\n    }\n}\n`\nUpdating UI based on tool results: After calling the tool, the app immediately updates the displayed image with the new result:\n`javascript\nconst newUrl = extractImageUrl(result);\nif (newUrl) imageEl.src = newUrl;\n``\nWith these examples, you've seen how to build both simple reactive widgets and more advanced interactive apps that can call tools directly from the UI. By combining Gradio's MCP server capabilities with the OpenAI Apps SDK, it's time to start create richer ChatGPT integrations that enhance the conversational experience with custom visualizations and user interactions!","type":"GUIDE"},{"title":"Building Mcp Server With Gradio","slug":"/guides/building-mcp-server-with-gradio/","content":"Building an MCP Server with Gradio\nIn this guide, we will describe how to launch your Gradio app so that it functions as an MCP Server.\nPunchline: it's as simple as setting mcp_server=True in .launch(). \nPrerequisites\nIf not already installed, please install Gradio with the MCP extra:\n``bash\npip install \"gradio[mcp]\"\n`\nThis will install the necessary dependencies, including the mcp package. Also, you will need an LLM application that supports tool calling using the MCP protocol, such as Claude Desktop, Cursor, or Cline (these are known as \"MCP Clients\").\nWhat is an MCP Server?\nAn MCP (Model Control Protocol) server is a standardized way to expose tools so that they can be used by  LLMs. A tool can provide an LLM functionality that it does not have natively, such as the ability to generate images or calculate the prime factors of a number. \nExample: Counting Letters in a Word\nLLMs are famously not great at counting the number of letters in a word (e.g. the number of \"r\"-s in \"strawberry\"). But what if we equip them with a tool to help? Let's start by writing a simple Gradio app that counts the number of letters in a word or phrase:\n`python\nimport gradio as gr\ndef letter_counter(word, letter):\n    \"\"\"\n    Count the number of occurrences of a letter in a word or text.\n    Args:\n        word (str): The input text to search through\n        letter (str): The letter to search for\n    Returns:\n        str: A message indicating how many times the letter appears\n    \"\"\"\n    word = word.lower()\n    letter = letter.lower()\n    count = word.count(letter)\n    return count\ndemo = gr.Interface(\n    fn=letter_counter,\n    inputs=[gr.Textbox(\"strawberry\"), gr.Textbox(\"r\")],\n    outputs=[gr.Number()],\n    title=\"Letter Counter\",\n    description=\"Enter text and a letter to count how many times the letter appears in the text.\",\n    api_name=\"predict\"\n)\nif name == \"main\":\n    demo.launch(mcp_server=True)\n`\nNotice that we have: (1) included a detailed docstring for our function, and (2) set mcp_server=True in .launch(). This is all that's needed for your Gradio app to serve as an MCP server! Now, when you run this app, it will:\nStart the regular Gradio web interface\nStart the MCP server\nPrint the MCP server URL in the console\nThe MCP server will be accessible at:\n`\nhttp://your-server:port/gradio_api/mcp/\n`\nGradio automatically converts the letter_counter function into an MCP tool that can be used by LLMs. The docstring of the function and the type hints of arguments will be used to generate the description of the tool and its parameters. The name of the function will be used as the name of your tool. Any initial values you provide to your input components (e.g. \"strawberry\" and \"r\" in the gr.Textbox components above) will be used as the default values if your LLM doesn't specify a value for that particular input parameter.\nNow, all you need to do is add this URL endpoint to your MCP Client (e.g. Claude Desktop, Cursor, or Cline), which typically means pasting this config in the settings:\n`\n{\n  \"mcpServers\": {\n    \"gradio\": {\n      \"url\": \"http://your-server:port/gradio_api/mcp/\"\n    }\n  }\n}\n`\n(By the way, you can find the exact config to copy-paste by going to the \"View API\" link in the footer of your Gradio app, and then clicking on \"MCP\").\nKey features of the Gradio  MCP Integration\nTool Conversion: Each API endpoint in your Gradio app is automatically converted into an MCP tool with a corresponding name, description, and input schema. To view the tools and schemas, visit http://your-server:port/gradio_api/mcp/schema or go to the \"View API\" link in the footer of your Gradio app, and then click on \"MCP\".\nEnvironment variable support. There are two ways to enable the MCP server functionality:\nUsing the mcp_server parameter, as shown above:\n   `python\n   demo.launch(mcp_server=True)\n   `\nUsing environment variables:\n   `bash\n   export GRADIOMCPSERVER=True\n   `\nFile Handling: The Gradio MCP server automatically handles file data conversions, including:\nProcessing image files and returning them in the correct format\nManaging temporary file storage\n    By default, the Gradio MCP server accepts input images and files as full URLs (\"http://...\" or \"https:/...\"). For convenience, an additional STDIO-based MCP server is also generated, which can be used to upload files to any remote Gradio app and which returns a URL that can be used for subsequent tool calls.\nHosted MCP Servers on 󠀠🤗 Spaces: You can publish your Gradio application for free on Hugging Face Spaces, which will allow you to have a free hosted MCP server. Here's an example of such a Space: https://huggingface.co/spaces/abidlabs/mcp-tools. Notice that you can add this config to your MCP Client to start using the tools from this Space immediately:\n`\n{\n  \"mcpServers\": {\n    \"gradio\": {\n      \"url\": \"https://abidlabs-mcp-tools.hf.space/gradio_api/mcp/\"\n    }\n  }\n}\n`\n \n            \n                \n                    \n                    \n                    \n                \n                To minimize latency and increase throughput by as much as 10 times, set queue=False in the event handlers of your Gradio app. However, this disables progress notifications so its recommended that long running events set queue=True\n            \n                \nConverting an Existing Space\nIf there's an existing Space that you'd like to use an MCP server, you'll need to do three things:\nFirst, duplicate the Space if it is not your own Space. This will allow you to make changes to the app. If the Space requires a GPU, set the hardware of the duplicated Space to be same as the original Space. You can make it either a public Space or a private Space, since it is possible to use either as an MCP server, as described below.\nThen, add docstrings to the functions that you'd like the LLM to be able to call as a tool. The docstring should be in the same format as the example code above.\nFinally, add mcp_server=True in .launch().\nThat's it!\nPrivate Spaces\nYou can use either a public Space or a private Space as an MCP server. If you'd like to use a private Space as an MCP server (or a ZeroGPU Space with your own quota), then you will need to provide your Hugging Face token when you make your request. To do this, simply add it as a header in your config like this:\n`\n{\n  \"mcpServers\": {\n    \"gradio\": {\n      \"url\": \"https://abidlabs-mcp-tools.hf.space/gradio_api/mcp/\",\n      \"headers\": {\n        \"Authorization\": \"Bearer \"\n      }\n    }\n  }\n}\n`\nAuthentication and Credentials\nYou may wish to authenticate users more precisely or let them provide other kinds of credentials or tokens in order to provide a custom experience for different users. \nGradio allows you to access the underlying starlette.Request that has made the tool call, which means that you can access headers, originating IP address, or any other information that is part of the network request. To do this, simply add a parameter in your function of the type gr.Request, and Gradio will automatically inject the request object as the parameter.\nHere's an example:\n`py\nimport gradio as gr\ndef echo_headers(x, request: gr.Request):\n    return str(dict(request.headers))\ngr.Interface(echoheaders, \"textbox\", \"textbox\").launch(mcpserver=True)\n`\nThis MCP server will simply ignore the user's input and echo back all of the headers from a user's request. One can build more complex apps using the same idea. See the docs on gr.Request for more information (note that only the core Starlette attributes of the gr.Request object will be present, attributes such as Gradio's .session_hash will not be present).\nUsing the gr.Header class\nA common pattern in MCP server development is to use authentication headers to call services on behalf of your users. Instead of using a gr.Request object like in the example above, you can use a gr.Header argument. Gradio will automatically extract that header from the incoming request (if it exists) and pass it to your function.\nIn the example below, the X-API-Token header is extracted from the incoming request and passed in as the xapitoken argument to makeapirequestonbehalfofuser.\nThe benefit of using gr.Header is that the MCP connection docs will automatically display the headers you need to supply when connecting to the server! See the image below:\n`python\nimport gradio as gr\ndef makeapirequestonbehalfofuser(prompt: str, xapitoken: gr.Header):\n    \"\"\"Make a request to everyone's favorite API.\n    Args:\n        prompt: The prompt to send to the API.\n    Returns:\n        The response from the API.\n    Raises:\n        AssertionError: If the API token is not valid.\n    \"\"\"\n    return \"Hello from the API\" if not xapitoken else \"Hello from the API with token!\"\ndemo = gr.Interface(\n    makeapirequestonbehalfofuser,\n    [\n        gr.Textbox(label=\"Prompt\"),\n    ],\n    gr.Textbox(label=\"Response\"),\n)\ndemo.launch(mcp_server=True)\n`\nSending Progress Updates\nThe Gradio MCP server automatically sends progress updates to your MCP Client based on the queue in the Gradio application. If you'd like to send custom progress updates, you can do so using the same mechanism as you would use to display progress updates in the UI of your Gradio app: by using the gr.Progress class!\nHere's an example of how to do this:\n`python\nimport gradio as gr\nimport time\ndef slowtextreverser(text: str, progress=gr.Progress()):\n    for i in range(len(text)):\n        progress(i / len(text), desc=\"Reversing text\")\n        time.sleep(0.3)\n    return text[::-1]\ndemo = gr.Interface(slowtextreverser, gr.Textbox(\"Hello, world!\"), gr.Textbox(), api_name=\"predict\")\nif name == \"main\":\n    demo.launch(mcp_server=True)\n`\nHere are the docs for the gr.Progress class, which can also automatically track tqdm calls.\nNote: by default, progress notifications are enabled for all MCP tools, even if the corresponding Gradio functions do not include a gr.Progress. However, this can add some overhead to the MCP tool (typically ~500ms). To disable progress notification, you can set queue=False in your Gradio event handler to skip the overhead related to subscribing to the queue's progress updates.\nModifying Tool Descriptions\nGradio automatically sets the tool name based on the name of your function, and the description from the docstring of your function. But you may want to change how the description appears to your LLM. You can do this by using the api_description parameter in Interface, ChatInterface, or any event listener. This parameter takes three different kinds of values:\nNone (default): the tool description is automatically created from the docstring of the function (or its parent's docstring if it does not have a docstring but inherits from a method that does.)\nFalse: no tool description appears to the LLM.\nstr: an arbitrary string to use as the tool description.\nIn addition to modifying the tool descriptions, you can also toggle which tools appear to the LLM. You can do this by setting the show_api parameter, which is by default True. Setting it to False hides the endpoint from the API docs and from the MCP server. If you expose multiple tools, users of your app will also be able to toggle which tools they'd like to add to their MCP server by checking boxes in the \"view MCP or API\" panel.\nHere's an example that shows the apidescription and showapi parameters in actions:\n`python\nimport numpy as np\nimport gradio as gr\nfrom pathlib import Path\nimport os\nfrom PIL import Image\ndef prime_factors(n: str):\n    \"\"\"\n    Compute the prime factorization of a positive integer.\n    Args:\n        n (str): The integer to factorize. Must be greater than 1.\n    \"\"\"\n    n_int = int(n)\n    if n_int  1:\n        factors.append(n_int)\n    return factors\ndef generatecheetahimage():\n    \"\"\"\n    Generate a cheetah image.\n    Returns:\n        The generated cheetah image.\n    \"\"\"\n    return Path(os.path.dirname(file)) / \"cheetah.jpg\"\ndef image_orientation(image: Image.Image) -> str:\n    \"\"\"\n    Returns whether image is portrait or landscape.\n    Args:\n        image (Image.Image): The image to check.\n    Returns:\n        str: \"Portrait\" if image is portrait, \"Landscape\" if image is landscape.\n    \"\"\"\n    return \"Portrait\" if image.height > image.width else \"Landscape\"\ndef sepia(input_img):\n    \"\"\"\n    Apply a sepia filter to the input image.\n    Args:\n        input_img (np.array): The input image to apply the sepia filter to.\n    Returns:\n        The sepia filtered image.\n    \"\"\"\n    sepia_filter = np.array([\n        [0.393, 0.769, 0.189],\n        [0.349, 0.686, 0.168],\n        [0.272, 0.534, 0.131]\n    ])\n    sepiaimg = inputimg.dot(sepia_filter.T)\n    sepiaimg /= sepiaimg.max()\n    return sepia_img\ndemo = gr.TabbedInterface(\n    [\n        gr.Interface(prime_factors, gr.Textbox(\"1001\"), gr.Textbox()),\n        gr.Interface(generatecheetahimage, None, gr.Image(), api_description=\"Generates a cheetah image. No arguments are required.\"),\n        gr.Interface(imageorientation, gr.Image(type=\"pil\"), gr.Textbox(), apivisibility=\"private\"),\n        gr.Interface(sepia, gr.Image(), gr.Image(), api_description=False),\n    ],\n    [\n        \"Prime Factors\",\n        \"Cheetah Image\",\n        \"Image Orientation Checker\",\n        \"Sepia Filter\",\n    ]\n)\nif name == \"main\":\n    demo.launch(mcp_server=True)\n`\nMCP Resources and Prompts\nIn addition to tools (which execute functions generally and are the default for any function exposed through the Gradio MCP integration), MCP supports two other important primitives: resources (for exposing data) and prompts (for defining reusable templates). Gradio provides decorators to easily create MCP servers with all three capabilities.\nCreating MCP Resources\nUse the @gr.mcp.resource decorator on any function to expose data through your Gradio app. Resources can be static (always available at a fixed URI) or templated (with parameters in the URI).\n`python\n\"\"\"\nAdapts the FastMCP quickstart example to work with Gradio's MCP integration.\n\"\"\"\nimport gradio as gr\n@gr.mcp.tool()  # Not needed as functions are registered as tools by default\ndef add(a: int, b: int) -> int:\n    \"\"\"Add two numbers\"\"\"\n    return a + b\n@gr.mcp.resource(\"greeting://{name}\")\ndef get_greeting(name: str) -> str:\n    \"\"\"Get a personalized greeting\"\"\"\n    return f\"Hello, {name}!\"\n@gr.mcp.prompt()\ndef greet_user(name: str, style: str = \"friendly\") -> str:\n    \"\"\"Generate a greeting prompt\"\"\"\n    styles = {\n        \"friendly\": \"Please write a warm, friendly greeting\",\n        \"formal\": \"Please write a formal, professional greeting\", \n        \"casual\": \"Please write a casual, relaxed greeting\",\n    }\n    return f\"{styles.get(style, styles['friendly'])} for someone named {name}.\"\ndemo = gr.TabbedInterface(\n    [\n        gr.Interface(add, [gr.Number(value=1), gr.Number(value=2)], gr.Number()),\n        gr.Interface(get_greeting, gr.Textbox(\"Abubakar\"), gr.Textbox()),\n        gr.Interface(greet_user, [gr.Textbox(\"Abubakar\"), gr.Dropdown(choices=[\"friendly\", \"formal\", \"casual\"])], gr.Textbox()),\n    ],\n    [\n        \"Add\",\n        \"Get Greeting\",\n        \"Greet User\",\n    ]\n)\nif name == \"main\":\n    demo.launch(mcp_server=True)\n`\nIn this example:\nThe get_greeting function is exposed as a resource with a URI template greeting://{name}\nWhen an MCP client requests greeting://Alice, it receives \"Hello, Alice!\"\nResources can also return images and other types of files or binary data. In order to return non-text data, you should specify the mime_type parameter in @gr.mcp.resource() and return a Base64 string from your function.\nCreating MCP Prompts  \nPrompts help standardize how users interact with your tools. They're especially useful for complex workflows that require specific formatting or multiple steps.\nThe greet_user function in the example above is decorated with @gr.mcp.prompt(), which:\nMakes it available as a prompt template in MCP clients\nAccepts parameters (name and style) to customize the output\nReturns a structured prompt that guides the LLM's behavior\nAdding MCP-Only Functions\nSo far, all of our MCP tools, resources, or prompts have corresponded to event listeners in the UI. This works well for functions that directly update the UI, but may not work if you wish to expose a \"pure logic\" function that should return raw data (e.g. a JSON object) without directly causing a UI update.\nIn order to expose such an MCP tool, you can create a pure Gradio API endpoint using gr.api (see full docs here). Here's an example of creating an MCP tool that slices a list:\n`python\nimport gradio as gr\ndef slice_list(lst: list, start: int, end: int) -> list:\n    \"\"\"\n    A tool that slices a list given a start and end index.\n    Args:\n        lst: The list to slice.\n        start: The start index.\n        end: The end index.\n    Returns:\n        The sliced list.\n    \"\"\"\n    return lst[start:end]\nwith gr.Blocks() as demo:\n    gr.Markdown(\n        \"\"\"\n        This is a demo of a MCP-only tool.\n        This tool slices a list.\n        This tool is MCP-only, so it does not have a UI.\n        \"\"\"\n    )\n    gr.api(\n        slice_list\n    )\n, url,  = demo.launch(mcp_server=True)\n`\nNote that if you use this approach, your function signature must be fully typed, including the return value, as these signature are used to determine the typing information for the MCP tool.\nGradio with FastMCP\nIn some cases, you may decide not to use Gradio's built-in integration and instead manually create an FastMCP Server that calls a Gradio app. This approach is useful when you want to:\nStore state / identify users between calls instead of treating every tool call completely independently\nStart the Gradio app MCP server when a tool is called (if you are running multiple Gradio apps locally and want to save memory / GPU)\nThis is very doable thanks to the Gradio Python Client and the MCP Python SDK's FastMCP class. Here's an example of creating a custom MCP server that connects to various Gradio apps hosted on HuggingFace Spaces using the stdio protocol:\n`python\nfrom mcp.server.fastmcp import FastMCP\nfrom gradio_client import Client\nimport sys\nimport io\nimport json \nmcp = FastMCP(\"gradio-spaces\")\nclients = {}\ndef getclient(spaceid: str) -> Client:\n    \"\"\"Get or create a Gradio client for the specified space.\"\"\"\n    if space_id not in clients:\n        clients[spaceid] = Client(spaceid)\n    return clients[space_id]\n@mcp.tool()\nasync def generateimage(prompt: str, spaceid: str = \"ysharma/SanaSprint\") -> str:\n    \"\"\"Generate an image using Flux.\n    \n    Args:\n        prompt: Text prompt describing the image to generate\n        space_id: HuggingFace Space ID to use \n    \"\"\"\n    client = getclient(spaceid)\n    result = client.predict(\n            prompt=prompt,\n            model_size=\"1.6B\",\n            seed=0,\n            randomize_seed=True,\n            width=1024,\n            height=1024,\n            guidance_scale=4.5,\n            numinferencesteps=2,\n            api_name=\"/infer\"\n    )\n    return result\n@mcp.tool()\nasync def rundiatts(prompt: str, space_id: str = \"ysharma/Dia-1.6B\") -> str:\n    \"\"\"Text-to-Speech Synthesis.\n    \n    Args:\n        prompt: Text prompt describing the conversation between speakers S1, S2\n        space_id: HuggingFace Space ID to use \n    \"\"\"\n    client = getclient(spaceid)\n    result = client.predict(\n            text_input=f\"\"\"{prompt}\"\"\",\n            audiopromptinput=None, \n            maxnewtokens=3072,\n            cfg_scale=3,\n            temperature=1.3,\n            top_p=0.95,\n            cfgfiltertop_k=30,\n            speed_factor=0.94,\n            apiname=\"/generateaudio\"\n    )\n    return result\nif name == \"main\":\n    import sys\n    import io\n    sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')\n    \n    mcp.run(transport='stdio')\n`\nThis server exposes two tools:\nrundiatts - Generates a conversation for the given transcript in the form of [S1]first-sentence. [S2]second-sentence. [S1]...\ngenerate_image - Generates images using a fast text-to-image model\nTo use this MCP Server with Claude Desktop (as MCP Client):\nSave the code to a file (e.g., gradiomcpserver.py)\nInstall the required dependencies: pip install mcp gradio-client\nConfigure Claude Desktop to use your server by editing the configuration file at ~/Library/Application Support/Claude/claudedesktopconfig.json (macOS) or %APPDATA%\\Claude\\claudedesktopconfig.json (Windows):\n`json\n{\n    \"mcpServers\": {\n        \"gradio-spaces\": {\n            \"command\": \"python\",\n            \"args\": [\n                \"/absolute/path/to/gradiomcpserver.py\"\n            ]\n        }\n    }\n}\n`\nRestart Claude Desktop\nNow, when you ask Claude about generating an image or transcribing audio, it can use your Gradio-powered tools to accomplish these tasks.\nTroubleshooting your MCP Servers\nThe MCP protocol is still in its infancy and you might see issues connecting to an MCP Server that you've built. We generally recommend using the MCP Inspector Tool to try connecting and debugging your MCP Server.\nHere are some things that may help:\nEnsure that you've provided type hints and valid docstrings for your functions\nAs mentioned earlier, Gradio reads the docstrings for your functions and the type hints of input arguments to generate the description of the tool and parameters. A valid function and docstring looks like this (note the \"Args:\" block with indented parameter names underneath):\n`py\ndef image_orientation(image: Image.Image) -> str:\n    \"\"\"\n    Returns whether image is portrait or landscape.\n    Args:\n        image (Image.Image): The image to check.\n    \"\"\"\n    return \"Portrait\" if image.height > image.width else \"Landscape\"\n`\nNote: You can preview the schema that is created for your MCP server by visiting the http://your-server:port/gradio_api/mcp/schema URL.\nTry accepting input arguments as str\nSome MCP Clients do not recognize parameters that are numeric or other complex types, but all of the MCP Clients that we've tested accept str input parameters. When in doubt, change your input parameter to be a str and then cast to a specific type in the function, as in this example:\n`py\ndef prime_factors(n: str):\n    \"\"\"\n    Compute the prime factorization of a positive integer.\n    Args:\n        n (str): The integer to factorize. Must be greater than 1.\n    \"\"\"\n    n_int = int(n)\n    if n_int  1:\n        factors.append(n_int)\n    return factors\n`\nEnsure that your MCP Client Supports Streamable HTTP\nSome MCP Clients do not yet support streamable HTTP-based MCP Servers. In those cases, you can use a tool such as mcp-remote. First install Node.js. Then, add the following to your own MCP Client config:\n`\n{\n  \"mcpServers\": {\n    \"gradio\": {\n      \"command\": \"npx\",\n      \"args\": [\n        \"mcp-remote\",\n        \"http://your-server:port/gradio_api/mcp/\"\n      ]\n    }\n  }\n}\n``\nRestart your MCP Client and MCP Server\nSome MCP Clients require you to restart them every time you update the MCP configuration. Other times, if the connection between the MCP Client and servers breaks, you might need to restart the MCP server. If all else fails, try restarting both your MCP Client and MCP Servers!","type":"GUIDE"},{"title":"Caching","slug":"/guides/caching/","content":"Caching Function Results\nML inference is often expensive: image editing, video classification, or audio transcription can each take seconds, minutes, or longer. If a user submits the same inputs twice, there's no reason to re-run the model. Gradio provides two caching mechanisms: @gr.cache for automatic exact-match caching, and gr.Cache() for manual cache control inside your functions.\nAutomatic caching with @gr.cache\nAdd @gr.cache to any function to automatically cache its results. The decorator hashes inputs by their content — two different numpy arrays with the same pixel values will produce a cache hit. Cache hits bypass the Gradio queue entirely.\n``python\nimport gradio as gr\n@gr.cache\ndef classify(image):\n    return model.predict(image)\n`\nGenerators\nFor generator functions, @gr.cache caches all yielded values and replays them on a hit. This is particularly important for streaming media (gr.Audio or gr.Video with streaming=True) where each yield is a chunk of the output:\n`python\n@gr.cache\ndef stream_response(prompt):\n    response = \"\"\n    for token in model.generate(prompt):\n        response += token\n        yield response\n`\nAsync\nAsync functions and async generators work identically:\n`python\n@gr.cache\nasync def transcribe(audio):\n    return await model.transcribe(audio)\n`\nParameters\nThe behavior of @gr.cache() can be customized with a few parameters, most notably the key:\n`python\n@gr.cache(\n    key=lambda kw: kw[\"prompt\"],  # only cache based on prompt, ignore temperature\n    max_size=256,                  # max entries (LRU eviction), default 128\n    max_memory=\"512mb\",            # max memory before eviction\n    per_session=True,              # isolate cache per user session\n)\ndef generate(prompt, temperature=0.7):\n    return llm(prompt, temperature=temperature)\n`\nkey — function that takes the kwargs dict and returns what to hash. Useful for ignoring parameters like temperature or seed.\nmax_size — maximum number of entries. LRU eviction when full. Default 128. Set to 0 for unlimited.\nmax_memory — maximum memory usage. Accepts strings like \"512mb\", \"2gb\" or raw bytes. LRU eviction when exceeded.\npersession — when True, each user session gets an isolated cache namespace. Prevents one user's cached results from being served to another, clears that session's entries when the client disconnects, and still applies maxsize and max_memory to the shared cache store across all sessions.\nAccess the cache programmatically via fn.cache:\n`python\ngenerate.cache.clear()\nprint(len(generate.cache))\n`\nWhen a queued event is served from @gr.cache, Gradio shows a small from cache timing badge in the UI which appears temporarily in the relevant output components.\nCaching intermediate helper calls\nYou can also apply gr.cache() to a callable at runtime to cache an intermediate step inside a larger Gradio callback:\n`python\ndef embed(text):\n    return embedding_model(text)\ndef predict(text):\n    embedding = gr.cache(embed, per_session=True)(text)\n    return rerank(embedding)\n`\nThis is especially useful when only part of your function is deterministic or reusable. Runtime gr.cache(fn)(...) uses the same cache store for repeated calls to that helper and shows the same used cache badge as gr.Cache() (see below) when a hit is reused during a request.\ngr.cache() must wrap a callable. If you accidentally write gr.cache(fn(...)), Gradio raises an error and tells you to use gr.cache(fn)(...) instead.\nManual cache control with gr.Cache()\nFor full control over what gets cached and when, use gr.Cache() as an injectable parameter (like gr.Progress). Gradio injects the same instance on every call, giving you a thread-safe get/set interface:\n`python\ndef my_function(prompt, c=gr.Cache()):\n    hit = c.get(prompt)\n    if hit is not None:\n        return hit[\"result\"]\n    result = expensive_computation(prompt)\n    c.set(prompt, result=result)\n    return result\n`\nIf a queued function gets a successful hit from c.get(...), Gradio also shows a timing badge in the UI. This badge says used cache instead of from cache, because the request still ran, but part of its work was reused from gr.Cache().\nA minimal example is available in the gr.Cache() manual cache demo.\nWhy use gr.Cache() over a plain dict?\nThread-safe — built-in locking for concurrent requests\nLRU eviction + memory limits — bounded memory usage (maxsize, maxmemory)\nPer-session isolation — gr.Cache(persession=True) partitions the cache by user session, prevents data leakage between users, clears that session's entries when the client disconnects, and still applies maxsize and max_memory across the combined cache entries of all sessions\nContent-aware keys — numpy arrays, PIL images, DataFrames all work as cache keys\nKV Cache Example\nYou can cache arbitrary intermediate state, not just function outputs. Here's how to cache transformer KV states for prefix reuse:\n`python\ndef generate(prompt, c=gr.Cache(per_session=True)):\n    best_key = None\n    best_len = 0\n    for cached_key in c.keys():\n        if prompt.startswith(cachedkey) and len(cachedkey) > best_len:\n            bestkey = cachedkey\n            bestlen = len(cachedkey)\n    if best_key:\n        pastkv = c.get(bestkey)[\"kv\"]\n        output = model.generate(prompt, pastkeyvalues=past_kv)\n    else:\n        output = model.generate(prompt)\n    c.set(prompt, kv=model.pastkeyvalues)\n    return output.text\n`\nFor a full runnable version, see the gr.Cache() KV cache demo.\nWhen to use caching\n@gr.cache is most useful for deterministic functions where the same input always produces the same output: image classification, audio transcription, embedding computation, structured data extraction.\nIt is less useful for non-deterministic functions like text generation or image generation, where users might want different outputs even for the same input. For those, gr.Cache() with manual control may be more appropriate as you can cache intermediate state (like KV caches) without caching the output completely.\nNext steps\nTake a look at these complete examples and then build your own Gradio app with caching!\n@gr.cache() function types demo - sync, async, generator, and async generator caching\ngr.Cache() manual cache demo - normalized manual cache keys with explicit get / set\ngr.Cache()` KV cache demo - transformer prefix reuse with cached KV state","type":"GUIDE"},{"title":"Chatbot Specific Events","slug":"/guides/chatbot-specific-events/","content":"Chatbot-Specific Events\nUsers expect modern chatbot UIs to let them easily interact with individual chat messages: for example, users might want to retry message generations, undo messages, or click on a like/dislike button to upvote or downvote a generated message.\nThankfully, the Gradio Chatbot exposes several events, such as .retry, .undo, .like, and .clear, to let you build this functionality into your application. As an application developer, you can attach functions to any of these event, allowing you to run arbitrary Python functions e.g. when a user interacts with a message.\nIn this demo, we'll build a UI that implements these events. You can see our finished demo deployed on Hugging Face spaces here:\n            \n                \n                    \n                    \n                    \n                \n                gr.ChatInterface automatically uses the retry and .undo events so it's best to start there in order get a fully working application quickly.\n            \n                \nThe UI\nFirst, we'll build the UI without handling these events and build from there. \nWe'll use the Hugging Face InferenceClient in order to get started without setting up\nany API keys.\nThis is what the first draft of our application looks like:\n``python\nfrom huggingface_hub import InferenceClient\nimport gradio as gr\nclient = InferenceClient()\ndef respond(\n    prompt: str,\n    history,\n):\n    if not history:\n        history = [{\"role\": \"system\", \"content\": \"You are a friendly chatbot\"}]\n    history.append({\"role\": \"user\", \"content\": prompt})\n    yield history\n    response = {\"role\": \"assistant\", \"content\": \"\"}\n    for message in client.chat_completion( # type: ignore\n        history,\n        temperature=0.95,\n        top_p=0.9,\n        max_tokens=512,\n        stream=True,\n        model=\"openai/gpt-oss-20b\"\n    ):\n        response[\"content\"] += message.choices[0].delta.content or \"\" if message.choices else \"\"\n        yield history + [response]\nwith gr.Blocks() as demo:\n    gr.Markdown(\"# Chat with GPT-OSS 20b 🤗\")\n    chatbot = gr.Chatbot(\n        label=\"Agent\",\n        avatar_images=(\n            None,\n            \"https://em-content.zobj.net/source/twitter/376/hugging-face_1f917.png\",\n        ),\n    )\n    prompt = gr.Textbox(max_lines=1, label=\"Chat Message\")\n    prompt.submit(respond, [prompt, chatbot], [chatbot])\n    prompt.submit(lambda: \"\", None, [prompt])\nif name == \"main\":\n    demo.launch()\n`\nThe Undo Event\nOur undo event will populate the textbox with the previous user message and also remove all subsequent assistant responses.\nIn order to know the index of the last user message, we can pass gr.UndoData to our event handler function like so:\n`python\ndef handleundo(history, undodata: gr.UndoData):\n    return history[:undodata.index], history[undodata.index]['content'][0][\"text\"]\n`\nWe then pass this function to the undo event!\n`python\n    chatbot.undo(handle_undo, chatbot, [chatbot, prompt])\n`\nYou'll notice that every bot response will now have an \"undo icon\" you can use to undo the response - \n            \n                \n                    \n                    \n                    \n                \n                You can also access the content of the user message with undo_data.value\n            \n                \nThe Retry Event\nThe retry event will work similarly. We'll use gr.RetryData to get the index of the previous user message and remove all the subsequent messages from the history. Then we'll use the respond function to generate a new response. We could also get the previous prompt via the value property of gr.RetryData.\n`python\ndef handleretry(history, retrydata: gr.RetryData):\n    newhistory = history[:retrydata.index]\n    previousprompt = history[retrydata.index]['content'][0][\"text\"]\n    yield from respond(previousprompt, newhistory)\n...\nchatbot.retry(handle_retry, chatbot, chatbot)\n`\nYou'll see that the bot messages have a \"retry\" icon now -\n            \n                \n                    \n                    \n                    \n                \n                The Hugging Face inference API caches responses, so in this demo, the retry button will not generate a new response.\n            \n                \nThe Like Event\nBy now you should hopefully be seeing the pattern!\nTo let users like a message, we'll add a .like event to our chatbot.\nWe'll pass it a function that accepts a gr.LikeData object.\nIn this case, we'll just print the message that was either liked or disliked.\n`python\ndef handle_like(data: gr.LikeData):\n    if data.liked:\n        print(\"You upvoted this response: \", data.value)\n    else:\n        print(\"You downvoted this response: \", data.value)\nchatbot.like(handle_like, None, None)\n`\nThe Edit Event\nSame idea with the edit listener! with gr.Chatbot(editable=True), you can capture user edits. The gr.EditData object tells us the index of the message edited and the new text of the mssage. Below, we use this object to edit the history, and delete any subsequent messages. \n`python\ndef handleedit(history, editdata: gr.EditData):\n    newhistory = history[:editdata.index]\n    newhistory[-1]['content'] = [{\"text\": editdata.value, \"type\": \"text\"}]\n    return new_history\n...\nchatbot.edit(handle_edit, chatbot, chatbot)\n`\nThe Clear Event\nAs a bonus, we'll also cover the .clear() event, which is triggered when the user clicks the clear icon to clear all messages. As a developer, you can attach additional events that should happen when this icon is clicked, e.g. to handle clearing of additional chatbot state:\n`python\nfrom uuid import uuid4\nimport gradio as gr\ndef clear():\n    print(\"Cleared uuid\")\n    return uuid4()\ndef chatfn(userinput, history, uuid):\n    return f\"{user_input} with uuid {uuid}\"\nwith gr.Blocks() as demo:\n    uuid_state = gr.State(\n        uuid4\n    )\n    chatbot = gr.Chatbot()\n    chatbot.clear(clear, outputs=[uuid_state])\n    gr.ChatInterface(\n        chat_fn,\n        additionalinputs=[uuidstate],\n        chatbot=chatbot,\n    )\ndemo.launch()\n`\nIn this example, the clear function, bound to the chatbot.clear event, returns a new UUID into our session state, when the chat history is cleared via the trash icon. This can be seen in the chat_fn function, which references the UUID saved in our session state.\nThis example also shows that you can use these events with gr.ChatInterface by passing in a custom gr.Chatbot` object.\nConclusion\nThat's it! You now know how you can implement the retry, undo, like, and clear events for the Chatbot.","type":"GUIDE"},{"title":"Chatinterface Examples","slug":"/guides/chatinterface-examples/","content":"Using Popular LLM libraries and APIs\nIn this Guide, we go through several examples of how to use gr.ChatInterface with popular LLM libraries and API providers.\nWe will cover the following libraries and API providers:\nLlama Index\nLangChain\nOpenAI\nHugging Face transformers\nSambaNova\nHyperbolic\nAnthropic's Claude\nMiniMax\nFor many LLM libraries and providers, there exist community-maintained integration libraries that make it even easier to spin up Gradio apps. We reference these libraries in the appropriate sections below.\nLlama Index\nLet's start by using llama-index on top of openai to build a RAG chatbot on any text or PDF files that you can demo and share in less than 30 lines of code. You'll need to have an OpenAI key for this example (keep reading for the free, open-source equivalent!)\n``python\nThis is a simple RAG chatbot built on top of Llama Index and Gradio. It allows you to upload any text or PDF files and ask questions about them!\nBefore running this, make sure you have exported your OpenAI API key as an environment variable:\nexport OPENAIAPIKEY=\"your-openai-api-key\"\nfrom llama_index.core import VectorStoreIndex, SimpleDirectoryReader  \nimport gradio as gr\ndef answer(message, history):\n    files = []\n    for msg in history:\n        if msg['role'] == \"user\" and isinstance(msg['content'], tuple):\n            files.append(msg['content'][0])\n    for file in message[\"files\"]:\n        files.append(file)\n    documents = SimpleDirectoryReader(inputfiles=files).loaddata()\n    index = VectorStoreIndex.from_documents(documents)\n    queryengine = index.asquery_engine()\n    return str(query_engine.query(message[\"text\"]))\ndemo = gr.ChatInterface(\n    answer,\n    title=\"Llama Index RAG Chatbot\",\n    description=\"Upload any text or pdf files and ask questions about them!\",\n    textbox=gr.MultimodalTextbox(file_types=[\".pdf\", \".txt\"]),\n    multimodal=True,\n    api_name=\"chat\",\n)\ndemo.launch()\n`\nLangChain\nHere's an example using langchain on top of openai to build a general-purpose chatbot. As before, you'll need to have an OpenAI key for this example.\n`python\nThis is a simple general-purpose chatbot built on top of LangChain and Gradio.\nBefore running this, make sure you have exported your OpenAI API key as an environment variable:\nexport OPENAIAPIKEY=\"your-openai-api-key\"\nimport gradio as gr\nfrom langchain.messages import AIMessage, HumanMessage  \nfrom langchain_openai import ChatOpenAI  \nmodel = ChatOpenAI(model=\"gpt-4o-mini\")\ndef predict(message, history):\n    historylangchainformat = []\n    for msg in history:\n        if msg[\"role\"] == \"user\":\n            historylangchainformat.append(HumanMessage(content=msg[\"content\"]))\n        elif msg[\"role\"] == \"assistant\":\n            historylangchainformat.append(AIMessage(content=msg[\"content\"]))\n    historylangchainformat.append(HumanMessage(content=message))\n    gptresponse = model.invoke(historylangchain_format)\n    return gpt_response.content\ndemo = gr.ChatInterface(\n    predict,\n    api_name=\"chat\",\n)\ndemo.launch()\n`\n            \n                \n                    \n                    \n                    \n                \n                For quick prototyping, the community-maintained langchain-gradio repo  makes it even easier to build chatbots on top of LangChain.\n            \n                \nOpenAI\nOf course, we could also use the openai library directy. Here a similar example to the LangChain , but this time with streaming as well:\n            \n                \n                    \n                    \n                    \n                \n                For quick prototyping, the  openai-gradio library makes it even easier to build chatbots on top of OpenAI models.\n            \n                \nHugging Face transformers\nOf course, in many cases you want to run a chatbot locally. Here's the equivalent example using the SmolLM2-135M-Instruct model using the Hugging Face transformers library.\n`python\nimport gradio as gr\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\ncheckpoint = \"HuggingFaceTB/SmolLM2-135M-Instruct\"\ndevice = \"cpu\"  # \"cuda\" or \"cpu\"\ntokenizer = AutoTokenizer.from_pretrained(checkpoint)\nmodel = AutoModelForCausalLM.from_pretrained(checkpoint).to(device)\ndef predict(message, history):\n    messages = history + [{\"role\": \"user\", \"content\": message}]\n    inputtext = tokenizer.applychat_template(messages, tokenize=False)\n    inputs = tokenizer.encode(inputtext, returntensors=\"pt\").to(device)  \n    outputs = model.generate(inputs, maxnewtokens=100, temperature=0.2, topp=0.9, dosample=True)\n    decoded = tokenizer.decode(outputs[0])\n    response = decoded.split(\"assistant\\n\")[-1].split(\"\")[0]\n    return response\ndemo = gr.ChatInterface(predict, api_name=\"chat\")\ndemo.launch()\n`\nSambaNova\nThe SambaNova Cloud API provides access to full-precision open-source models, such as the Llama family. Here's an example of how to build a Gradio app around the SambaNova API\n`python\nThis is a simple general-purpose chatbot built on top of SambaNova API. \nBefore running this, make sure you have exported your SambaNova API key as an environment variable:\nexport SAMBANOVAAPIKEY=\"your-sambanova-api-key\"\nimport os\nimport gradio as gr\nfrom openai import OpenAI\napikey = os.getenv(\"SAMBANOVAAPI_KEY\")\nclient = OpenAI(\n    base_url=\"https://api.sambanova.ai/v1/\",\n    apikey=apikey,\n)\ndef predict(message, history):\n    history.append({\"role\": \"user\", \"content\": message})\n    stream = client.chat.completions.create(messages=history, model=\"Meta-Llama-3.1-70B-Instruct-8k\", stream=True)\n    chunks = []\n    for chunk in stream:\n        chunks.append(chunk.choices[0].delta.content or \"\")\n        yield \"\".join(chunks)\ndemo = gr.ChatInterface(predict, api_name=\"chat\")\ndemo.launch()\n`\n            \n                \n                    \n                    \n                    \n                \n                For quick prototyping, the  sambanova-gradio library makes it even easier to build chatbots on top of SambaNova models.\n            \n                \nHyperbolic\nThe Hyperbolic AI API provides access to many open-source models, such as the Llama family. Here's an example of how to build a Gradio app around the Hyperbolic\n`python\nThis is a simple general-purpose chatbot built on top of Hyperbolic API. \nBefore running this, make sure you have exported your Hyperbolic API key as an environment variable:\nexport HYPERBOLICAPIKEY=\"your-hyperbolic-api-key\"\nimport os\nimport gradio as gr\nfrom openai import OpenAI\napikey = os.getenv(\"HYPERBOLICAPI_KEY\")\nclient = OpenAI(\n    base_url=\"https://api.hyperbolic.xyz/v1/\",\n    apikey=apikey,\n)\ndef predict(message, history):\n    history.append({\"role\": \"user\", \"content\": message})\n    stream = client.chat.completions.create(messages=history, model=\"gpt-4o-mini\", stream=True)\n    chunks = []\n    for chunk in stream:\n        chunks.append(chunk.choices[0].delta.content or \"\")\n        yield \"\".join(chunks)\ndemo = gr.ChatInterface(predict, api_name=\"chat\")\ndemo.launch()\n`\n            \n                \n                    \n                    \n                    \n                \n                For quick prototyping, the  hyperbolic-gradio library makes it even easier to build chatbots on top of Hyperbolic models.\n            \n                \nAnthropic's Claude \nAnthropic's Claude model can also be used via API. Here's a simple 20 questions-style game built on top of the Anthropic API:\n`python\nThis is a simple 20 questions-style game built on top of the Anthropic API.\nBefore running this, make sure you have exported your Anthropic API key as an environment variable:\nexport ANTHROPICAPIKEY=\"your-anthropic-api-key\"\nimport anthropic  \nimport gradio as gr\nclient = anthropic.Anthropic()\ndef predict(message, history):\n    keystokeep = [\"role\", \"content\"]\n    history = [{k: d[k] for k in keystokeep if k in d} for d in history]\n    history.append({\"role\": \"user\", \"content\": message})\n    if len(history) > 20:\n        history.append({\"role\": \"user\", \"content\": \"DONE\"})\n    output = client.messages.create(\n        messages=history,  \n        model=\"claude-3-5-sonnet-20241022\",\n        max_tokens=1000,\n        system=\"You are guessing an object that the user is thinking of. You can ask 10 yes/no questions. Keep asking questions until the user says DONE\"\n    )\n    return {\n        \"role\": \"assistant\",\n        \"content\": output.content[0].text,  \n        \"options\": [{\"value\": \"Yes\"}, {\"value\": \"No\"}]\n    }\nplaceholder = \"\"\"\n10 QuestionsThink of a person, place, or thing. I'll ask you 10 yes/no questions to try and guess it.\n\"\"\"\ndemo = gr.ChatInterface(\n    predict,\n    examples=[\"Start!\"],\n    chatbot=gr.Chatbot(placeholder=placeholder),\n    api_name=\"chat\",\n)\ndemo.launch()\n`\nMiniMax\nThe MiniMax API exposes the M-series models through an OpenAI-compatible endpoint, so the standard openai client works out of the box. Here's an example of how to build a Gradio app around MiniMax:\n`python\nThis is a simple general-purpose chatbot built on top of the MiniMax API.\nBefore running this, make sure you have exported your MiniMax API key as an environment variable:\nexport MINIMAXAPIKEY=\"your-minimax-api-key\"\nimport os\nimport gradio as gr\nfrom openai import OpenAI\napikey = os.getenv(\"MINIMAXAPI_KEY\")\nclient = OpenAI(\n    base_url=\"https://api.minimax.io/v1\",\n    apikey=apikey,\n)\ndef predict(message, history):\n    history.append({\"role\": \"user\", \"content\": message})\n    stream = client.chat.completions.create(messages=history, model=\"MiniMax-M3\", stream=True)\n    chunks = []\n    for chunk in stream:\n        chunks.append(chunk.choices[0].delta.content or \"\")\n        yield \"\".join(chunks)\ndemo = gr.ChatInterface(predict, api_name=\"chat\")\ndemo.launch()\n``","type":"GUIDE"},{"title":"Client Side Functions","slug":"/guides/client-side-functions/","content":"Client Side Functions\nGradio allows you to run certain \"simple\" functions directly in the browser by setting js=True in your event listeners. This will automatically convert your Python code into JavaScript, which significantly improves the responsiveness of your app by avoiding a round trip to the server for simple UI updates.\nThe difference in responsiveness is most noticeable on hosted applications (like Hugging Face Spaces), when the server is under heavy load, with high-latency connections, or when many users are accessing the app simultaneously.\nWhen to Use Client Side Functions\nClient side functions are ideal for updating component properties (like visibility, placeholders, interactive state, or styling). \nHere's a basic example:\n``py\nimport gradio as gr\nwith gr.Blocks() as demo:\n    with gr.Row() as row:\n        btn = gr.Button(\"Hide this row\")\n    \n    # This function runs in the browser without a server roundtrip\n    btn.click(\n        lambda: gr.Row(visible=False), \n        None, \n        row, \n        js=True\n    )\ndemo.launch()\n`\nLimitations\nClient side functions have some important restrictions:\nThey can only update component properties (not values)\nThey cannot take any inputs\nHere are some functions that will work with js=True:\n`py\nSimple property updates\nlambda: gr.Textbox(lines=4)\nMultiple component updates\nlambda: [gr.Textbox(lines=4), gr.Button(interactive=False)]\nUsing gr.update() for property changes\nlambda: gr.update(visible=True, interactive=False)\n`\nWe are working to increase the space of functions that can be transpiled to JavaScript so that they can be run in the browser. Follow the Groovy library for more info.\nComplete Example\nHere's a more complete example showing how client side functions can improve the user experience:\n`python\n\"\"\"\nThis is a simple todo list app that allows you to edit tasks and mark tasks as complete.\nAll actions are performed on the client side.\n\"\"\"\nimport gradio as gr\ntasks = [\"Get a job\", \"Marry rich\", \"\", \"\", \"\", \"\"]\ntextboxes = []\nbuttons = []\nwith gr.Blocks() as demo:\n    with gr.Row():\n        with gr.Column(scale=3):\n            gr.Markdown(\"# A Simple Interactive Todo List\")\n        with gr.Column(scale=2):\n            with gr.Row():\n                freeze_button = gr.Button(\"Freeze tasks\", variant=\"stop\")\n                edit_button = gr.Button(\"Edit tasks\")\n    for i in range(6):\n        with gr.Row() as r:\n            t = gr.Textbox(tasks[i], placeholder=\"Enter a task\", show_label=False, container=False, scale=7, interactive=True)\n            b = gr.Button(\"✔️\", interactive=bool(tasks[i]), variant=\"primary\" if tasks[i] else \"secondary\")\n            textboxes.append(t)\n            buttons.append(b)\n        t.change(lambda : gr.Button(interactive=True, variant=\"primary\"), None, b, js=True)\n        b.click(lambda : gr.Row(visible=False), None, r, js=True)\n    freeze_button.click(lambda : [gr.Textbox(interactive=False), gr.Textbox(interactive=False), gr.Textbox(interactive=False), gr.Textbox(interactive=False), gr.Textbox(interactive=False), gr.Textbox(interactive=False)], None, textboxes, js=True)\n    edit_button.click(lambda : [gr.Textbox(interactive=True), gr.Textbox(interactive=True), gr.Textbox(interactive=True), gr.Textbox(interactive=True), gr.Textbox(interactive=True), gr.Textbox(interactive=True)], None, textboxes, js=True)\n    freeze_button.click(lambda : [gr.Button(visible=False), gr.Button(visible=False), gr.Button(visible=False), gr.Button(visible=False), gr.Button(visible=False), gr.Button(visible=False)], None, buttons, js=True)\n    edit_button.click(lambda : [gr.Button(visible=True), gr.Button(visible=True), gr.Button(visible=True), gr.Button(visible=True), gr.Button(visible=True), gr.Button(visible=True)], None, buttons, js=True)\ndemo.launch()\n`\nBehind the Scenes\nWhen you set js=True`, Gradio:\nTranspiles your Python function to JavaScript\nRuns the function directly in the browser\nStill sends the request to the server (for consistency and to handle any side effects)\nThis provides immediate visual feedback while ensuring your application state remains consistent.","type":"GUIDE"},{"title":"Configuration","slug":"/guides/configuration/","content":"Configuring Your Custom Component\nThe custom components workflow focuses on convention over configuration to reduce the number of decisions you as a developer need to make when developing your custom component.\nThat being said, you can still configure some aspects of the custom component package and directory.\nThis guide will cover how.\nThe Package Name\nBy default, all custom component packages are called gradio_ where component-name is the name of the component's python class in lowercase.\nAs an example, let's walkthrough changing the name of a component from gradio_mytextbox to supertextbox. \nModify the name in the pyproject.toml file. \n``bash\n[project]\nname = \"supertextbox\"\n`\nChange all occurrences of gradio_ in pyproject.toml to \n`bash\n[tool.hatch.build]\nartifacts = [\"/backend/supertextbox/templates\", \"*.pyi\"]\n[tool.hatch.build.targets.wheel]\npackages = [\"/backend/supertextbox\"]\n`\nRename the gradio_ directory in backend/ to \n`bash\nmv backend/gradio_mytextbox backend/supertextbox\n`\n            \n                \n                    \n                    \n                    \n                \n                Remember to change the import statement in demo/app.py!\n            \n                \nTop Level Python Exports\nBy default, only the custom component python class is a top level export. \nThis means that when users type from gradio_ import ..., the only class that will be available is the custom component class.\nTo add more classes as top level exports, modify the all property in init.py\n`python\nfrom .mytextbox import MyTextbox\nfrom .mytextbox import AdditionalClass, additional_function\nall = ['MyTextbox', 'AdditionalClass', 'additional_function']\n`\nPython Dependencies\nYou can add python dependencies by modifying the dependencies key in pyproject.toml\n`bash\ndependencies = [\"gradio\", \"numpy\", \"PIL\"]\n`\n            \n                \n                    \n                    \n                    \n                \n                Remember to run gradio cc install when you add dependencies!\n            \n                \nJavascript Dependencies\nYou can add JavaScript dependencies by modifying the \"dependencies\" key in frontend/package.json\n`json\n\"dependencies\": {\n    \"@gradio/atoms\": \"0.2.0-beta.4\",\n    \"@gradio/statustracker\": \"0.3.0-beta.6\",\n    \"@gradio/utils\": \"0.2.0-beta.4\",\n    \"your-npm-package\": \"\"\n}\n`\nDirectory Structure\nBy default, the CLI will place the Python code in backend and the JavaScript code in frontend.\nIt is not recommended to change this structure since it makes it easy for a potential contributor to look at your source code and know where everything is.\nHowever, if you did want to this is what you would have to do:\nPlace the Python code in the subdirectory of your choosing. Remember to modify the [tool.hatch.build] [tool.hatch.build.targets.wheel] in the pyproject.toml to match!\nPlace the JavaScript code in the subdirectory of your choosing.\nAdd the FRONTEND_DIR property on the component python class. It must be the relative path from the file where the class is defined to the location of the JavaScript directory.\n`python\nclass SuperTextbox(Component):\n    FRONTEND_DIR = \"../../frontend/\"\n``\nThe JavaScript and Python directories must be under the same common directory!\nConclusion\nSticking to the defaults will make it easy for others to understand and contribute to your custom component.\nAfter all, the beauty of open source is that anyone can help improve your code!\nBut if you ever need to deviate from the defaults, you know how!","type":"GUIDE"},{"title":"Connecting To A Database","slug":"/guides/connecting-to-a-database/","content":"Connecting to a Database\nThe data you wish to visualize may be stored in a database. Let's use SQLAlchemy to quickly extract database content into pandas Dataframe format so we can use it in gradio.\nFirst install pip install sqlalchemy and then let's see some examples.\nSQLite\n``python\nfrom sqlalchemy import create_engine\nimport pandas as pd\nengine = createengine('sqlite:///yourdatabase.db')\nwith gr.Blocks() as demo:\n    gr.LinePlot(pd.readsqlquery(\"SELECT time, price from flight_info;\", engine), x=\"time\", y=\"price\")\n`\nLet's see a a more interactive plot involving filters that modify your SQL query:\n`python\nfrom sqlalchemy import create_engine\nimport pandas as pd\nengine = createengine('sqlite:///yourdatabase.db')\nwith gr.Blocks() as demo:\n    origin = gr.Dropdown([\"DFW\", \"DAL\", \"HOU\"], value=\"DFW\", label=\"Origin\")\n    gr.LinePlot(lambda origin: pd.readsqlquery(f\"SELECT time, price from flight_info WHERE origin = {origin};\", engine), inputs=origin, x=\"time\", y=\"price\")\n`\nPostgres, mySQL, and other databases\nIf you're using a different database format, all you have to do is swap out the engine, e.g.\n`python\nengine = createengine('postgresql://username:password@host:port/databasename')\n`\n`python\nengine = createengine('mysql://username:password@host:port/databasename')\n`\n`python\nengine = createengine('oracle://username:password@host:port/databasename')\n``","type":"GUIDE"},{"title":"Controlling Layout","slug":"/guides/controlling-layout/","content":"Controlling Layout\nBy default, Components in Blocks are arranged vertically. Let's take a look at how we can rearrange Components. Under the hood, this layout structure uses the flexbox model of web development.\nRows\nElements within a with gr.Row clause will all be displayed horizontally. For example, to display two Buttons side by side:\n``python\nwith gr.Blocks() as demo:\n    with gr.Row():\n        btn1 = gr.Button(\"Button 1\")\n        btn2 = gr.Button(\"Button 2\")\n`\nYou can set every element in a Row to have the same height. Configure this with the equal_height argument.\n`python\nwith gr.Blocks() as demo:\n    with gr.Row(equal_height=True):\n        textbox = gr.Textbox()\n        btn2 = gr.Button(\"Button 2\")\n`\nThe widths of elements in a Row can be controlled via a combination of scale and min_width arguments that are present in every Component.\nscale is an integer that defines how an element will take up space in a Row. If scale is set to 0, the element will not expand to take up space. If scale is set to 1 or greater, the element will expand. Multiple elements in a row will expand proportional to their scale. Below, btn2 will expand twice as much as btn1, while btn0 will not expand at all:\n`python\nwith gr.Blocks() as demo:\n    with gr.Row():\n        btn0 = gr.Button(\"Button 0\", scale=0)\n        btn1 = gr.Button(\"Button 1\", scale=1)\n        btn2 = gr.Button(\"Button 2\", scale=2)\n`\nminwidth will set the minimum width the element will take. The Row will wrap if there isn't sufficient space to satisfy all minwidth values.\nLearn more about Rows in the docs.\nColumns and Nesting\nComponents within a Column will be placed vertically atop each other. Since the vertical layout is the default layout for Blocks apps anyway, to be useful, Columns are usually nested within Rows. For example:\n`python\nimport gradio as gr\nwith gr.Blocks() as demo:\n    with gr.Row():\n        text1 = gr.Textbox(label=\"t1\")\n        slider2 = gr.Textbox(label=\"s2\")\n        drop3 = gr.Dropdown([\"a\", \"b\", \"c\"], label=\"d3\")\n    with gr.Row():\n        with gr.Column(scale=1, min_width=300):\n            text1 = gr.Textbox(label=\"prompt 1\")\n            text2 = gr.Textbox(label=\"prompt 2\")\n            inbtw = gr.Button(\"Between\")\n            text4 = gr.Textbox(label=\"prompt 1\")\n            text5 = gr.Textbox(label=\"prompt 2\")\n        with gr.Column(scale=2, min_width=300):\n            img1 = gr.Image(\"images/cheetah.jpg\")\n            btn = gr.Button(\"Go\")\ndemo.launch()\n`\nSee how the first column has two Textboxes arranged vertically. The second column has an Image and Button arranged vertically. Notice how the relative widths of the two columns is set by the scale parameter. The column with twice the scale value takes up twice the width.\nLearn more about Columns in the docs.\nFill Browser Height / Width\nTo make an app take the full width of the browser by removing the side padding, use gr.Blocks(fill_width=True). \nTo make top level Components expand to take the full height of the browser, use fill_height and apply scale to the expanding Components.\n`python\nimport gradio as gr\nwith gr.Blocks(fill_height=True) as demo:\n    gr.Chatbot(scale=1)\n    gr.Textbox(scale=0)\n`\nDimensions\nSome components support setting height and width. These parameters accept either a number (interpreted as pixels) or a string. Using a string allows the direct application of any CSS unit to the encapsulating Block element.\nBelow is an example illustrating the use of viewport width (vw):\n`python\nimport gradio as gr\nwith gr.Blocks() as demo:\n    im = gr.ImageEditor(width=\"50vw\")\ndemo.launch()\n`\nTabs and Accordions\nYou can also create Tabs using the with gr.Tab('tabname'): clause. Any component created inside of a with gr.Tab('tabname'): context appears in that tab. Consecutive Tab clauses are grouped together so that a single tab can be selected at one time, and only the components within that Tab's context are shown.\nFor example:\n`python\nimport numpy as np\nimport gradio as gr\ndef flip_text(x):\n    return x[::-1]\ndef flip_image(x):\n    return np.fliplr(x)\nwith gr.Blocks() as demo:\n    gr.Markdown(\"Flip text or image files using this demo.\")\n    with gr.Tab(\"Flip Text\"):\n        text_input = gr.Textbox()\n        text_output = gr.Textbox()\n        text_button = gr.Button(\"Flip\")\n    with gr.Tab(\"Flip Image\"):\n        with gr.Row():\n            image_input = gr.Image()\n            image_output = gr.Image()\n        image_button = gr.Button(\"Flip\")\n    with gr.Accordion(\"Open for More!\", open=False):\n        gr.Markdown(\"Look at me...\")\n        temp_slider = gr.Slider(\n            0, 1,\n            value=0.1,\n            step=0.1,\n            interactive=True,\n            label=\"Slide me\",\n        )\n    textbutton.click(fliptext, inputs=textinput, outputs=textoutput)\n    imagebutton.click(flipimage, inputs=imageinput, outputs=imageoutput)\ndemo.launch()\n`\nAlso note the gr.Accordion('label') in this example. The Accordion is a layout that can be toggled open or closed. Like Tabs, it is a layout element that can selectively hide or show content. Any components that are defined inside of a with gr.Accordion('label'): will be hidden or shown when the accordion's toggle icon is clicked.\nLearn more about Tabs and Accordions in the docs.\nSidebar\nThe sidebar is a collapsible panel that renders child components on the left side of the screen and can be expanded or collapsed.\nFor example:\n`python\nimport gradio as gr\nimport random\ndef generatepetname(animal_type, personality):\n    cute_prefixes = [\"Fluffy\", \"Ziggy\", \"Bubbles\", \"Pickle\", \"Waffle\", \"Mochi\", \"Cookie\", \"Pepper\"]\n    animal_suffixes = {\n        \"Cat\": [\"Whiskers\", \"Paws\", \"Mittens\", \"Purrington\"],\n        \"Dog\": [\"Woofles\", \"Barkington\", \"Waggins\", \"Pawsome\"],\n        \"Bird\": [\"Feathers\", \"Wings\", \"Chirpy\", \"Tweets\"],\n        \"Rabbit\": [\"Hops\", \"Cottontail\", \"Bouncy\", \"Fluff\"]\n    }\n    prefix = random.choice(cute_prefixes)\n    suffix = random.choice(animalsuffixes[animaltype])\n    if personality == \"Silly\":\n        prefix = random.choice([\"Sir\", \"Lady\", \"Captain\", \"Professor\"]) + \" \" + prefix\n    elif personality == \"Royal\":\n        suffix += \" the \" + random.choice([\"Great\", \"Magnificent\", \"Wise\", \"Brave\"])\n    return f\"{prefix} {suffix}\"\nwith gr.Blocks() as demo:\n    with gr.Sidebar(position=\"left\"):\n        gr.Markdown(\"# 🐾 Pet Name Generator\")\n        gr.Markdown(\"Use the options below to generate a unique pet name!\")\n        animal_type = gr.Dropdown(\n            choices=[\"Cat\", \"Dog\", \"Bird\", \"Rabbit\"],\n            label=\"Choose your pet type\",\n            value=\"Cat\"\n        )\n        personality = gr.Radio(\n            choices=[\"Normal\", \"Silly\", \"Royal\"],\n            label=\"Personality type\",\n            value=\"Normal\"\n        )\n    name_output = gr.Textbox(label=\"Your pet's fancy name:\", lines=2)\n    generate_btn = gr.Button(\"Generate Name! 🎲\", variant=\"primary\")\n    generate_btn.click(\n        fn=generatepetname,\n        inputs=[animal_type, personality],\n        outputs=name_output\n    )\nif name == \"main\":\n    demo.launch(theme=gr.themes.Soft())\n`\nLearn more about Sidebar in the docs.\nMulti-step walkthroughs\nIn order to provide a guided set of ordered steps, a controlled workflow, you can use the Walkthrough component with accompanying Step components.\nThe Walkthrough component has a visual style and user experience tailored for this usecase.\nAuthoring this component is very similar to Tab, except it is the app developers responsibility to progress through each step, by setting the appropriate ID for the parent Walkthrough which should correspond to an ID provided to an indvidual Step. \nLearn more about Walkthrough in the docs.\nVisibility\nBoth Components and Layout elements have a visible argument that can set initially and also updated. Setting gr.Column(visible=...) on a Column can be used to show or hide a set of Components.\n`python\nimport gradio as gr\nwith gr.Blocks() as demo:\n    name_box = gr.Textbox(label=\"Name\")\n    age_box = gr.Number(label=\"Age\", minimum=0, maximum=100)\n    symptoms_box = gr.CheckboxGroup([\"Cough\", \"Fever\", \"Runny Nose\"])\n    submit_btn = gr.Button(\"Submit\")\n    with gr.Column(visible=False) as output_col:\n        diagnosis_box = gr.Textbox(label=\"Diagnosis\")\n        patientsummarybox = gr.Textbox(label=\"Patient Summary\")\n    def submit(name, age, symptoms):\n        return {\n            submit_btn: gr.Button(visible=False),\n            output_col: gr.Column(visible=True),\n            diagnosis_box: \"covid\" if \"Cough\" in symptoms else \"flu\",\n            patientsummarybox: f\"{name}, {age} y/o\",\n        }\n    submit_btn.click(\n        submit,\n        [namebox, agebox, symptoms_box],\n        [submitbtn, diagnosisbox, patientsummarybox, output_col],\n    )\ndemo.launch()\n`\nDefining and Rendering Components Separately\nIn some cases, you might want to define components before you actually render them in your UI. For instance, you might want to show an examples section using gr.Examples above the corresponding gr.Textbox input. Since gr.Examples requires as a parameter the input component object, you will need to first define the input component, but then render it later, after you have defined the gr.Examples object.\nThe solution to this is to define the gr.Textbox outside of the gr.Blocks() scope and use the component's .render() method wherever you'd like it placed in the UI.\nHere's a full code example:\n`python\ninput_textbox = gr.Textbox()\nwith gr.Blocks() as demo:\n    gr.Examples([\"hello\", \"bonjour\", \"merhaba\"], input_textbox)\n    input_textbox.render()\n`\nSimilarly, if you have already defined a component in a Gradio app, but wish to unrender it so that you can define in a different part of your application, then you can call the .unrender() method. In the following example, the Textbox will appear in the third column:\n`py\nimport gradio as gr\nwith gr.Blocks() as demo:\n    with gr.Row():\n        with gr.Column():\n            gr.Markdown(\"Row 1\")\n            textbox = gr.Textbox()\n        with gr.Column():\n            gr.Markdown(\"Row 2\")\n            textbox.unrender()\n        with gr.Column():\n            gr.Markdown(\"Row 3\")\n            textbox.render()\ndemo.launch()\n``","type":"GUIDE"},{"title":"Conversational Chatbot","slug":"/guides/conversational-chatbot/","content":"Building Conversational Chatbots with Gradio\nIntroduction\nThe next generation of AI user interfaces is moving towards audio-native experiences. Users will be able to speak to chatbots and receive spoken responses in return. Several models have been built under this paradigm, including GPT-4o and mini omni.\nIn this guide, we'll walk you through building your own conversational chat application using mini omni as an example. You can see a demo of the finished app below:\nApplication Overview\nOur application will enable the following user experience:\nUsers click a button to start recording their message\nThe app detects when the user has finished speaking and stops recording\nThe user's audio is passed to the omni model, which streams back a response\nAfter omni mini finishes speaking, the user's microphone is reactivated\nAll previous spoken audio, from both the user and omni, is displayed in a chatbot component\nLet's dive into the implementation details.\nProcessing User Audio\nWe'll stream the user's audio from their microphone to the server and determine if the user has stopped speaking on each new chunk of audio.\nHere's our process_audio function:\n``python\nimport numpy as np\nfrom utils import determine_pause\ndef process_audio(audio: tuple, state: AppState):\n    if state.stream is None:\n        state.stream = audio[1]\n        state.sampling_rate = audio[0]\n    else:\n        state.stream = np.concatenate((state.stream, audio[1]))\n    pausedetected = determinepause(state.stream, state.sampling_rate, state)\n    state.pausedetected = pausedetected\n    if state.pausedetected and state.startedtalking:\n        return gr.Audio(recording=False), state\n    return None, state\n`\nThis function takes two inputs:\nThe current audio chunk (a tuple of (sampling_rate, numpy array of audio))\nThe current application state\nWe'll use the following AppState dataclass to manage our application state:\n`python\nfrom dataclasses import dataclass\n@dataclass\nclass AppState:\n    stream: np.ndarray | None = None\n    sampling_rate: int = 0\n    pause_detected: bool = False\n    stopped: bool = False\n    conversation: list = []\n`\nThe function concatenates new audio chunks to the existing stream and checks if the user has stopped speaking. If a pause is detected, it returns an update to stop recording. Otherwise, it returns None to indicate no changes.\nThe implementation of the determine_pause function is specific to the omni-mini project and can be found here.\nGenerating the Response\nAfter processing the user's audio, we need to generate and stream the chatbot's response. Here's our response function:\n`python\nimport io\nimport tempfile\nfrom pydub import AudioSegment\ndef response(state: AppState):\n    if not state.pausedetected and not state.startedtalking:\n        return None, AppState()\n    \n    audio_buffer = io.BytesIO()\n    segment = AudioSegment(\n        state.stream.tobytes(),\n        framerate=state.samplingrate,\n        sample_width=state.stream.dtype.itemsize,\n        channels=(1 if len(state.stream.shape) == 1 else state.stream.shape[1]),\n    )\n    segment.export(audio_buffer, format=\"wav\")\n    with tempfile.NamedTemporaryFile(suffix=\".wav\", delete=False) as f:\n        f.write(audio_buffer.getvalue())\n    \n    state.conversation.append({\"role\": \"user\",\n                                \"content\": {\"path\": f.name,\n                                \"mime_type\": \"audio/wav\"}})\n    \n    output_buffer = b\"\"\n    for mp3bytes in speaking(audiobuffer.getvalue()):\n        outputbuffer += mp3bytes\n        yield mp3_bytes, state\n    with tempfile.NamedTemporaryFile(suffix=\".mp3\", delete=False) as f:\n        f.write(output_buffer)\n    \n    state.conversation.append({\"role\": \"assistant\",\n                    \"content\": {\"path\": f.name,\n                                \"mime_type\": \"audio/mp3\"}})\n    yield None, AppState(conversation=state.conversation)\n`\nThis function:\nConverts the user's audio to a WAV file\nAdds the user's message to the conversation history\nGenerates and streams the chatbot's response using the speaking function\nSaves the chatbot's response as an MP3 file\nAdds the chatbot's response to the conversation history\nNote: The implementation of the speaking function is specific to the omni-mini project and can be found here.\nBuilding the Gradio App\nNow let's put it all together using Gradio's Blocks API:\n`python\nimport gradio as gr\ndef startrecordinguser(state: AppState):\n    if not state.stopped:\n        return gr.Audio(recording=True)\nwith gr.Blocks() as demo:\n    with gr.Row():\n        with gr.Column():\n            input_audio = gr.Audio(\n                label=\"Input Audio\", sources=\"microphone\", type=\"numpy\"\n            )\n        with gr.Column():\n            chatbot = gr.Chatbot(label=\"Conversation\")\n            output_audio = gr.Audio(label=\"Output Audio\", streaming=True, autoplay=True)\n    state = gr.State(value=AppState())\n    stream = input_audio.stream(\n        process_audio,\n        [input_audio, state],\n        [input_audio, state],\n        stream_every=0.5,\n        time_limit=30,\n    )\n    respond = inputaudio.stoprecording(\n        response,\n        [state],\n        [output_audio, state]\n    )\n    respond.then(lambda s: s.conversation, [state], [chatbot])\n    restart = output_audio.stop(\n        startrecordinguser,\n        [state],\n        [input_audio]\n    )\n    cancel = gr.Button(\"Stop Conversation\", variant=\"stop\")\n    cancel.click(lambda: (AppState(stopped=True), gr.Audio(recording=False)), None,\n                [state, input_audio], cancels=[respond, restart])\nif name == \"main\":\n    demo.launch()\n``\nThis setup creates a user interface with:\nAn input audio component for recording user messages\nA chatbot component to display the conversation history\nAn output audio component for the chatbot's responses\nA button to stop and reset the conversation\nThe app streams user audio in 0.5-second chunks, processes it, generates responses, and updates the conversation history accordingly.\nConclusion\nThis guide demonstrates how to build a conversational chatbot application using Gradio and the mini omni model. You can adapt this framework to create various audio-based chatbot demos. To see the full application in action, visit the Hugging Face Spaces demo: https://huggingface.co/spaces/gradio/omni-mini\nFeel free to experiment with different models, audio processing techniques, or user interface designs to create your own unique conversational AI experiences!","type":"GUIDE"},{"title":"Create Immersive Demo","slug":"/guides/create-immersive-demo/","content":"Create a Real-Time Immersive Audio + Video Demo with FastRTC\nFastRTC is a library that lets you build low-latency real-time apps over WebRTC. In this guide, you’ll implement a fun demo where Gemini is an art critic and will critique your uploaded artwork:\nStreams your webcam and microphone to a Gemini real-time session\nSends periodic video frames (and an optional uploaded image) to the model\nStreams back the model’s audio responses in real time\nCreates a polished full-screen Gradio WebRTC UI\nWhat you’ll build\n  \nPrerequisites\nPython 3.10+\nA Gemini API key: GEMINIAPIKEY\nInstall the dependencies:\n``bash\npip install \"fastrtc[vad, tts]\" gradio google-genai python-dotenv websockets pillow\n`\n1) Encoders for audio and images\nEncoder functions to send audio as base64-encoded data and images as base64-encoded JPEG.\n`python\nimport base64\nimport numpy as np\nfrom io import BytesIO\nfrom PIL import Image\ndef encode_audio(data: np.ndarray) -> dict:\n    \"\"\"Encode audio data (int16 mono) for Gemini.\"\"\"\n    return {\n        \"mime_type\": \"audio/pcm\",\n        \"data\": base64.b64encode(data.tobytes()).decode(\"UTF-8\"),\n    }\ndef encode_image(data: np.ndarray) -> dict:\n    with BytesIO() as output_bytes:\n        pil_image = Image.fromarray(data)\n        pilimage.save(outputbytes, \"JPEG\")\n        bytesdata = outputbytes.getvalue()\n    base64str = str(base64.b64encode(bytesdata), \"utf-8\")\n    return {\"mimetype\": \"image/jpeg\", \"data\": base64str}\n`\n2) Implement the Gemini audio-video handler\nThis handler:\nOpens a Gemini Live session on startup\nReceives streaming audio from Gemini and yields it back to the client\nSends microphone audio as it arrives\nSends a video frame at most once per second (to avoid flooding the API)\nOptionally sends an uploaded image (gr.Image) alongside the webcam frame\n`python\nimport asyncio\nimport os\nimport time\nimport numpy as np\nimport websockets\nfrom dotenv import load_dotenv\nfrom google import genai\nfrom fastrtc import AsyncAudioVideoStreamHandler, waitforitem, WebRTCError\nload_dotenv()\nclass GeminiHandler(AsyncAudioVideoStreamHandler):\n    def init(self) -> None:\n        super().init(\n            \"mono\",\n            outputsamplerate=24000,\n            inputsamplerate=16000,\n        )\n        self.audio_queue = asyncio.Queue()\n        self.video_queue = asyncio.Queue()\n        self.session = None\n        self.lastframetime = 0.0\n        self.quit = asyncio.Event()\n    def copy(self) -> \"GeminiHandler\":\n        return GeminiHandler()\n    async def start_up(self):\n        await self.waitforargs()\n        apikey = self.latestargs[3]\n        hftoken = self.latestargs[4]\n        if hftoken is None or hftoken == \"\":\n            raise WebRTCError(\"HF Token is required\")\n        os.environ[\"HFTOKEN\"] = hftoken\n        client = genai.Client(\n            apikey=apikey, httpoptions={\"apiversion\": \"v1alpha\"}\n        )\n        config = {\"responsemodalities\": [\"AUDIO\"], \"systeminstruction\": \"You are an art critic that will critique the artwork passed in as an image to the user. Critique the artwork in a funny and lighthearted way. Be concise and to the point. Be friendly and engaging. Be helpful and informative. Be funny and lighthearted.\"}\n        async with client.aio.live.connect(\n            model=\"gemini-2.0-flash-exp\",\n            config=config,\n        ) as session:\n            self.session = session\n            while not self.quit.is_set():\n                turn = self.session.receive()\n                try:\n                    async for response in turn:\n                        if data := response.data:\n                            audio = np.frombuffer(data, dtype=np.int16).reshape(1, -1)\n                        self.audioqueue.putnowait(audio)\n                except websockets.exceptions.ConnectionClosedOK:\n                    print(\"connection closed\")\n                    break\n    # Video: receive and (optionally) send frames to Gemini\n    async def video_receive(self, frame: np.ndarray):\n        self.videoqueue.putnowait(frame)\n        if self.session and (time.time() - self.lastframetime > 1.0):\n            self.lastframetime = time.time()\n            await self.session.send(input=encode_image(frame))\n            # If there is an uploaded image passed alongside the WebRTC component,\n            # it will be available in latest_args[2]\n            if self.latest_args[2] is not None:\n                await self.session.send(input=encodeimage(self.latestargs[2]))\n    async def video_emit(self) -> np.ndarray:\n        frame = await waitforitem(self.video_queue, 0.01)\n        if frame is not None:\n            return frame\n        # Fallback while waiting for first frame\n        return np.zeros((100, 100, 3), dtype=np.uint8)\n    # Audio: forward microphone audio to Gemini\n    async def receive(self, frame: tuple[int, np.ndarray]) -> None:\n        _, array = frame\n        array = array.squeeze()  # (num_samples,)\n        audiomessage = encodeaudio(array)\n        if self.session:\n            await self.session.send(input=audio_message)\n    # Audio: emit Gemini’s audio back to the client\n    async def emit(self):\n        array = await waitforitem(self.audio_queue, 0.01)\n        if array is not None:\n            return (self.outputsamplerate, array)\n        return array\n    async def shutdown(self) -> None:\n        if self.session:\n            self.quit.set()\n            await self.session.close()\n            self.quit.clear()\n`\n3) Setup Stream and Gradio UI\nWe’ll add an optional gr.Image input alongside the WebRTC component. The handler will access this in self.latest_args[1] when sending frames to Gemini.\n`python\nimport gradio as gr\nfrom fastrtc import Stream, WebRTC, gethfturn_credentials\nstream = Stream(\n    handler=GeminiHandler(),\n    modality=\"audio-video\",\n    mode=\"send-receive\",\n    serverrtcconfiguration=gethfturn_credentials(ttl=600*10000),\n    rtcconfiguration=gethfturncredentials(),\n    additional_inputs=[\n        gr.Markdown(\n            \"## 🎨 Art Critic\\n\\n\"\n            \"Provide an image of your artwork or hold it up to the webcam, and Gemini will critique it for you.\"\n            \"To get a Gemini API key, please visit the Gemini API Key page.\"\n            \"To get an HF Token, please visit the HF Token page.\"\n        ),\n        gr.Image(label=\"Artwork\", value=\"mona_lisa.jpg\", type=\"numpy\", sources=[\"upload\", \"clipboard\"]),\n        gr.Textbox(label=\"Gemini API Key\", type=\"password\"),\n        gr.Textbox(label=\"HF Token\", type=\"password\"),\n    ],\n    ui_args={\n        \"icon\": \"https://www.gstatic.com/lamda/images/geminifaviconf069958c85030456e93de685481c559f160ea06b.png\",\n        \"pulse_color\": \"rgb(255, 255, 255)\",\n        \"iconbuttoncolor\": \"rgb(255, 255, 255)\",\n        \"title\": \"Gemini Audio Video Chat\",\n    },\n    time_limit=90,\n    concurrency_limit=5,\n)\nif name == \"main\":\n    stream.ui.launch()\n`\nReferences\nGemini Audio Video Chat reference code: Hugging Face Space\nFastRTC docs: https://fastrtc.org\nAudio + video user guide: https://fastrtc.org/userguide/audio-video/\nGradio component integration: https://fastrtc.org/userguide/gradio/\nCookbook (live demos + code): https://fastrtc.org/cookbook/`","type":"GUIDE"},{"title":"Create Your Own Friends With A Gan","slug":"/guides/create-your-own-friends-with-a-gan/","content":"Create Your Own Friends with a GAN\nIntroduction\nIt seems that cryptocurrencies, NFTs, and the web3 movement are all the rage these days! Digital assets are being listed on marketplaces for astounding amounts of money, and just about every celebrity is debuting their own NFT collection. While your crypto assets may be taxable, such as in Canada, today we'll explore some fun and tax-free ways to generate your own assortment of procedurally generated CryptoPunks.\nGenerative Adversarial Networks, often known just as GANs, are a specific class of deep-learning models that are designed to learn from an input dataset to create (generate!) new material that is convincingly similar to elements of the original training set. Famously, the website thispersondoesnotexist.com went viral with lifelike, yet synthetic, images of people generated with a model called StyleGAN2. GANs have gained traction in the machine learning world, and are now being used to generate all sorts of images, text, and even music!\nToday we'll briefly look at the high-level intuition behind GANs, and then we'll build a small demo around a pre-trained GAN to see what all the fuss is about. Here's a peek at what we're going to be putting together.\nPrerequisites\nMake sure you have the gradio Python package already installed. To use the pretrained model, also install torch and torchvision.\nGANs: a very brief introduction\nOriginally proposed in Goodfellow et al. 2014, GANs are made up of neural networks which compete with the intention of outsmarting each other. One network, known as the generator, is responsible for generating images. The other network, the discriminator, receives an image at a time from the generator along with a real image from the training data set. The discriminator then has to guess: which image is the fake?\nThe generator is constantly training to create images which are trickier for the discriminator to identify, while the discriminator raises the bar for the generator every time it correctly detects a fake. As the networks engage in this competitive (adversarial!) relationship, the images that get generated improve to the point where they become indistinguishable to human eyes!\nFor a more in-depth look at GANs, you can take a look at this excellent post on Analytics Vidhya or this PyTorch tutorial. For now, though, we'll dive into a demo!\nStep 1 — Create the Generator model\nTo generate new images with a GAN, you only need the generator model. There are many different architectures that the generator could use, but for this demo we'll use a pretrained GAN generator model with the following architecture:\n``python\nfrom torch import nn\nclass Generator(nn.Module):\n    # Refer to the link below for explanations about nc, nz, and ngf\n    # https://pytorch.org/tutorials/beginner/dcganfacestutorial.html#inputs\n    def init(self, nc=4, nz=100, ngf=64):\n        super(Generator, self).init()\n        self.network = nn.Sequential(\n            nn.ConvTranspose2d(nz, ngf * 4, 3, 1, 0, bias=False),\n            nn.BatchNorm2d(ngf * 4),\n            nn.ReLU(True),\n            nn.ConvTranspose2d(ngf  4, ngf  2, 3, 2, 1, bias=False),\n            nn.BatchNorm2d(ngf * 2),\n            nn.ReLU(True),\n            nn.ConvTranspose2d(ngf * 2, ngf, 4, 2, 0, bias=False),\n            nn.BatchNorm2d(ngf),\n            nn.ReLU(True),\n            nn.ConvTranspose2d(ngf, nc, 4, 2, 1, bias=False),\n            nn.Tanh(),\n        )\n    def forward(self, input):\n        output = self.network(input)\n        return output\n`\nWe're taking the generator from this repo by @teddykoker, where you can also see the original discriminator model structure.\nAfter instantiating the model, we'll load in the weights from the Hugging Face Hub, stored at nateraw/cryptopunks-gan:\n`python\nfrom huggingfacehub import hfhub_download\nimport torch\nmodel = Generator()\nweightspath = hfhub_download('nateraw/cryptopunks-gan', 'generator.pth')\nmodel.loadstatedict(torch.load(weightspath, maplocation=torch.device('cpu'))) # Use 'cuda' if you have a GPU available\n`\nStep 2 — Defining a predict function\nThe predict function is the key to making Gradio work! Whatever inputs we choose through the Gradio interface will get passed through our predict function, which should operate on the inputs and generate outputs that we can display with Gradio output components. For GANs it's common to pass random noise into our model as the input, so we'll generate a tensor of random numbers and pass that through the model. We can then use torchvision's save_image function to save the output of the model as a png file, and return the file name:\n`python\nfrom torchvision.utils import save_image\ndef predict(seed):\n    num_punks = 4\n    torch.manual_seed(seed)\n    z = torch.randn(num_punks, 100, 1, 1)\n    punks = model(z)\n    save_image(punks, \"punks.png\", normalize=True)\n    return 'punks.png'\n`\nWe're giving our predict function a seed parameter, so that we can fix the random tensor generation with a seed. We'll then be able to reproduce punks if we want to see them again by passing in the same seed.\nNote! Our model needs an input tensor of dimensions 100x1x1 to do a single inference, or (BatchSize)x100x1x1 for generating a batch of images. In this demo we'll start by generating 4 punks at a time.\nStep 3 — Creating a Gradio interface\nAt this point you can even run the code you have with predict(), and you'll find your freshly generated punks in your file system at ./punks.png. To make a truly interactive demo, though, we'll build out a simple interface with Gradio. Our goals here are to:\nSet a slider input so users can choose the \"seed\" value\nUse an image component for our output to showcase the generated punks\nUse our predict() to take the seed and generate the images\nWith gr.Interface(), we can define all of that with a single function call:\n`python\nimport gradio as gr\ngr.Interface(\n    predict,\n    inputs=[\n        gr.Slider(0, 1000, label='Seed', value=42),\n    ],\n    outputs=\"image\",\n).launch()\n`\nStep 4 — Even more punks!\nGenerating 4 punks at a time is a good start, but maybe we'd like to control how many we want to make each time. Adding more inputs to our Gradio interface is as simple as adding another item to the inputs list that we pass to gr.Interface:\n`python\ngr.Interface(\n    predict,\n    inputs=[\n        gr.Slider(0, 1000, label='Seed', value=42),\n        gr.Slider(4, 64, label='Number of Punks', step=1, value=10), # Adding another slider!\n    ],\n    outputs=\"image\",\n).launch()\n`\nThe new input will be passed to our predict() function, so we have to make some changes to that function to accept a new parameter:\n`python\ndef predict(seed, num_punks):\n    torch.manual_seed(seed)\n    z = torch.randn(num_punks, 100, 1, 1)\n    punks = model(z)\n    save_image(punks, \"punks.png\", normalize=True)\n    return 'punks.png'\n`\nWhen you relaunch your interface, you should see a second slider that'll let you control the number of punks!\nStep 5 - Polishing it up\nYour Gradio app is pretty much good to go, but you can add a few extra things to really make it ready for the spotlight ✨\nWe can add some examples that users can easily try out by adding this to the gr.Interface:\n`python\ngr.Interface(\n    # ...\n    # keep everything as it is, and then add\n    examples=[[123, 15], [42, 29], [456, 8], [1337, 35]],\n    cacheexamples=True, # cacheexamples is optional\n).launch()\n`\nThe examples parameter takes a list of lists, where each item in the sublists is ordered in the same order that we've listed the inputs. So in our case, [seed, num_punks]. Give it a try!\nYou can also try adding a title, description, and article to the gr.Interface. Each of those parameters accepts a string, so try it out and see what happens 👀 article will also accept HTML, as explored in a previous guide!\nWhen you're all done, you may end up with something like this.\nFor reference, here is our full code:\n`python\nimport torch\nfrom torch import nn\nfrom huggingfacehub import hfhub_download\nfrom torchvision.utils import save_image\nimport gradio as gr\nclass Generator(nn.Module):\n    # Refer to the link below for explanations about nc, nz, and ngf\n    # https://pytorch.org/tutorials/beginner/dcganfacestutorial.html#inputs\n    def init(self, nc=4, nz=100, ngf=64):\n        super(Generator, self).init()\n        self.network = nn.Sequential(\n            nn.ConvTranspose2d(nz, ngf * 4, 3, 1, 0, bias=False),\n            nn.BatchNorm2d(ngf * 4),\n            nn.ReLU(True),\n            nn.ConvTranspose2d(ngf  4, ngf  2, 3, 2, 1, bias=False),\n            nn.BatchNorm2d(ngf * 2),\n            nn.ReLU(True),\n            nn.ConvTranspose2d(ngf * 2, ngf, 4, 2, 0, bias=False),\n            nn.BatchNorm2d(ngf),\n            nn.ReLU(True),\n            nn.ConvTranspose2d(ngf, nc, 4, 2, 1, bias=False),\n            nn.Tanh(),\n        )\n    def forward(self, input):\n        output = self.network(input)\n        return output\nmodel = Generator()\nweightspath = hfhub_download('nateraw/cryptopunks-gan', 'generator.pth')\nmodel.loadstatedict(torch.load(weightspath, maplocation=torch.device('cpu'))) # Use 'cuda' if you have a GPU available\ndef predict(seed, num_punks):\n    torch.manual_seed(seed)\n    z = torch.randn(num_punks, 100, 1, 1)\n    punks = model(z)\n    save_image(punks, \"punks.png\", normalize=True)\n    return 'punks.png'\ngr.Interface(\n    predict,\n    inputs=[\n        gr.Slider(0, 1000, label='Seed', value=42),\n        gr.Slider(4, 64, label='Number of Punks', step=1, value=10),\n    ],\n    outputs=\"image\",\n    examples=[[123, 15], [42, 29], [456, 8], [1337, 35]],\n    cache_examples=True,\n).launch()\n``\nCongratulations! You've built out your very own GAN-powered CryptoPunks generator, with a fancy Gradio interface that makes it easy for anyone to use. Now you can scour the Hub for more GANs (or train your own) and continue making even more awesome demos 🤗","type":"GUIDE"},{"title":"Creating A Chatbot Fast","slug":"/guides/creating-a-chatbot-fast/","content":"How to Create a Chatbot with Gradio\nIntroduction\nChatbots are a popular application of large language models (LLMs). Using Gradio, you can easily build a chat application and share that with your users, or try it yourself using an intuitive UI.\nThis tutorial uses gr.ChatInterface(), which is a high-level abstraction that allows you to create your chatbot UI fast, often with a few lines of Python. It can be easily adapted to support multimodal chatbots, or chatbots that require further customization.\nPrerequisites: please make sure you are using the latest version of Gradio:\n``bash\n$ pip install --upgrade gradio\n`\nNote for OpenAI-API compatible endpoints\nIf you have a chat server serving an OpenAI-API compatible endpoint (such as Ollama), you can spin up a ChatInterface in a single line of Python. First, also run pip install openai. Then, with your own URL, model, and optional token:\n`python\nimport gradio as gr\ngr.load_chat(\"http://localhost:11434/v1/\", model=\"llama3.2\", token=\"*\").launch()\n`\nRead about gr.loadchat in the docs. If you have your own model, keep reading to see how to create an application around any chat model in Python!\nDefining a chat function\nTo create a chat application with gr.ChatInterface(), the first thing you should do is define your chat function. In the simplest case, your chat function should accept two arguments: message and history (the arguments can be named anything, but must be in this order).\nmessage: a str representing the user's most recent message.\nhistory: a list of openai-style dictionaries with role and content keys, representing the previous conversation history. May also include additional keys representing message metadata.\nThe history would look like this:\n`python\n[\n    {\"role\": \"user\", \"content\": [{\"type\": \"text\", \"text\": \"What is the capital of France?\"}]},\n    {\"role\": \"assistant\", \"content\": [{\"type\": \"text\", \"text\": \"Paris\"}]}\n]\n`\nwhile the next message would be:\n`py\n\"And what is its largest city?\"\n`\nYour chat function simply needs to return: \na str value, which is the chatbot's response based on the chat history and most recent message, for example, in this case:\n`\nParis is also the largest city.\n`\nLet's take a look at a few example chat functions:\nExample: a chatbot that randomly responds with yes or no\nLet's write a chat function that responds Yes or No randomly.\nHere's our chat function:\n`python\nimport random\ndef random_response(message, history):\n    return random.choice([\"Yes\", \"No\"])\n`\nNow, we can plug this into gr.ChatInterface() and call the .launch() method to create the web interface:\n`python\nimport gradio as gr\ngr.ChatInterface(\n    fn=random_response, \n).launch()\n`\nThat's it! Here's our running demo, try it out:\nExample: a chatbot that alternates between agreeing and disagreeing\nOf course, the previous example was very simplistic, it didn't take user input or the previous history into account! Here's another simple example showing how to incorporate a user's input as well as the history.\n`python\nimport gradio as gr\ndef alternatingly_agree(message, history):\n    if len([h for h in history if h['role'] == \"assistant\"]) % 2 == 0:\n        return f\"Yes, I do think that: {message}\"\n    else:\n        return \"I don't think so\"\ngr.ChatInterface(\n    fn=alternatingly_agree, \n).launch()\n`\nWe'll look at more realistic examples of chat functions in our next Guide, which shows examples of using gr.ChatInterface with popular LLMs. \nStreaming chatbots\nIn your chat function, you can use yield to generate a sequence of partial responses, each replacing the previous ones. This way, you'll end up with a streaming chatbot. It's that simple!\n`python\nimport time\nimport gradio as gr\ndef slow_echo(message, history):\n    for i in range(len(message)):\n        time.sleep(0.3)\n        yield \"You typed: \" + message[: i+1]\ngr.ChatInterface(\n    fn=slow_echo, \n).launch()\n`\nWhile the response is streaming, the \"Submit\" button turns into a \"Stop\" button that can be used to stop the generator function.\n            \n                \n                    \n                    \n                    \n                \n                Even though you are yielding the latest message at each iteration, Gradio only sends the \"diff\" of each message from the server to the frontend, which reduces latency and data consumption over your network.\n            \n                \nCustomizing the Chat UI\nIf you're familiar with Gradio's gr.Interface class, the gr.ChatInterface includes many of the same arguments that you can use to customize the look and feel of your Chatbot. For example, you can:\nadd a title and description above your chatbot using title and description arguments.\nadd a theme or custom css using theme and css arguments respectively in the launch() method.\nadd examples and even enable cache_examples, which make your Chatbot easier for users to try it out.\ncustomize the chatbot (e.g. to change the height or add a placeholder) or textbox (e.g. to add a max number of characters or add a placeholder).\nAdding examples\nYou can add preset examples to your gr.ChatInterface with the examples parameter, which takes a list of string examples. Any examples will appear as \"buttons\" within the Chatbot before any messages are sent. If you'd like to include images or other files as part of your examples, you can do so by using this dictionary format for each example instead of a string: {\"text\": \"What's in this image?\", \"files\": [\"cheetah.jpg\"]}. Each file will be a separate message that is added to your Chatbot history.\nYou can change the displayed text for each example by using the examplelabels argument. You can add icons to each example as well using the exampleicons argument. Both of these arguments take a list of strings, which should be the same length as the examples list.\nIf you'd like to cache the examples so that they are pre-computed and the results appear instantly, set cache_examples=True.\nCustomizing the chatbot or textbox component\nIf you want to customize the gr.Chatbot or gr.Textbox that compose the ChatInterface, then you can pass in your own chatbot or textbox components. Here's an example of how we to apply the parameters we've discussed in this section:\n`python\nimport gradio as gr\ndef yes_man(message, history):\n    if message.endswith(\"?\"):\n        return \"Yes\"\n    else:\n        return \"Ask me anything!\"\ngr.ChatInterface(\n    yes_man,\n    chatbot=gr.Chatbot(height=300),\n    textbox=gr.Textbox(placeholder=\"Ask me a yes or no question\", container=False, scale=7),\n    title=\"Yes Man\",\n    description=\"Ask Yes Man any question\",\n    examples=[\"Hello\", \"Am I cool?\", \"Are tomatoes vegetables?\"],\n    cache_examples=True,\n).launch(theme=\"ocean\")\n`\nHere's another example that adds a \"placeholder\" for your chat interface, which appears before the user has started chatting. The placeholder argument of gr.Chatbot accepts Markdown or HTML:\n`python\ngr.ChatInterface(\n    yes_man,\n    chatbot=gr.Chatbot(placeholder=\"Your Personal Yes-ManAsk Me Anything\"),\n...\n`\nThe placeholder appears vertically and horizontally centered in the chatbot.\nMultimodal Chat Interface\nYou may want to add multimodal capabilities to your chat interface. For example, you may want users to be able to upload images or files to your chatbot and ask questions about them. You can make your chatbot \"multimodal\" by passing in a single parameter (multimodal=True) to the gr.ChatInterface class.\nWhen multimodal=True, the signature of your chat function changes slightly: the first parameter of your function (what we referred to as message above) should accept a dictionary consisting of the submitted text and uploaded files that looks like this: \n`py\n{\n    \"text\": \"user input\", \n    \"files\": [\n        \"updatedfile1_path.ext\",\n        \"updatedfile2_path.ext\", \n        ...\n    ]\n}\n`\nThis second parameter of your chat function, history, will be in the same openai-style dictionary format as before. However, if the history contains uploaded files, the content key will be a dictionary with a \"type\" key whose value is \"file\" and the file will be represented as a dictionary. All the files will be grouped in message in the history. So after uploading two files and asking a question, your history might look like this:\n`python\n[\n    {\"role\": \"user\", \"content\": [{\"type\": \"file\", \"file\": {\"path\": \"cat1.png\"}},\n                                 {\"type\": \"file\", \"file\": {\"path\": \"cat1.png\"}},\n                                 {\"type\": \"text\", \"text\": \"What's the difference between these two images?\"}]}\n]\n`\nThe return type of your chat function does not change when setting multimodal=True (i.e. in the simplest case, you should still return a string value). We discuss more complex cases, e.g. returning files below.\nIf you are customizing a multimodal chat interface, you should pass in an instance of gr.MultimodalTextbox to the textbox parameter. You can customize the MultimodalTextbox further by passing in the sources parameter, which is a list of sources to enable. Here's an example that illustrates how to set up and customize and multimodal chat interface:\n \n`python\nimport gradio as gr\ndef count_images(message, history):\n    num_images = len(message[\"files\"])\n    total_images = 0\n    for message in history:\n        for content in message[\"content\"]:\n            if content[\"type\"] == \"file\":\n                total_images += 1\n    return f\"You just uploaded {numimages} images, total uploaded: {totalimages+num_images}\"\ndemo = gr.ChatInterface(\n    fn=count_images, \n    examples=[\n        {\"text\": \"No files\", \"files\": []}\n    ], \n    multimodal=True,\n    textbox=gr.MultimodalTextbox(filecount=\"multiple\", filetypes=[\"image\"], sources=[\"upload\", \"microphone\"])\n)\ndemo.launch()\n`\nAdditional Inputs\nYou may want to add additional inputs to your chat function and expose them to your users through the chat UI. For example, you could add a textbox for a system prompt, or a slider that sets the number of tokens in the chatbot's response. The gr.ChatInterface class supports an additional_inputs parameter which can be used to add additional input components.\nThe additionalinputs parameters accepts a component or a list of components. You can pass the component instances directly, or use their string shortcuts (e.g. \"textbox\" instead of gr.Textbox()). If you pass in component instances, and they have not_ already been rendered, then the components will appear underneath the chatbot within a gr.Accordion(). \nHere's a complete example:\n`python\nimport gradio as gr\nimport time\ndef echo(message, history, system_prompt, tokens):\n    response = f\"System prompt: {system_prompt}\\n Message: {message}.\"\n    for i in range(min(len(response), int(tokens))):\n        time.sleep(0.05)\n        yield response[: i + 1]\ndemo = gr.ChatInterface(\n    echo,\n    additional_inputs=[\n        gr.Textbox(\"You are helpful AI.\", label=\"System Prompt\"),\n        gr.Slider(10, 100),\n    ],\n)\ndemo.launch()\n`\nIf the components you pass into the additionalinputs have already been rendered in a parent gr.Blocks(), then they will not_ be re-rendered in the accordion. This provides flexibility in deciding where to lay out the input components. In the example below, we position the gr.Textbox() on top of the Chatbot UI, while keeping the slider underneath.\n`python\nimport gradio as gr\nimport time\ndef echo(message, history, system_prompt, tokens):\n    response = f\"System prompt: {system_prompt}\\n Message: {message}.\"\n    for i in range(min(len(response), int(tokens))):\n        time.sleep(0.05)\n        yield response[: i+1]\nwith gr.Blocks() as demo:\n    system_prompt = gr.Textbox(\"You are helpful AI.\", label=\"System Prompt\")\n    slider = gr.Slider(10, 100, render=False)\n    gr.ChatInterface(\n        echo, additionalinputs=[systemprompt, slider],\n    )\ndemo.launch()\n`\nExamples with additional inputs\nYou can also add example values for your additional inputs. Pass in a list of lists to the examples parameter, where each inner list represents one sample, and each inner list should be 1 + len(additional_inputs) long. The first element in the inner list should be the example value for the chat message, and each subsequent element should be an example value for one of the additional inputs, in order. When additional inputs are provided, examples are rendered in a table underneath the chat interface.\nIf you need to create something even more custom, then its best to construct the chatbot UI using the low-level gr.Blocks() API. We have a dedicated guide for that here.\nAdditional Outputs\nIn the same way that you can accept additional inputs into your chat function, you can also return additional outputs. Simply pass in a list of components to the additional_outputs parameter in gr.ChatInterface and return additional values for each component from your chat function. Here's an example that extracts code and outputs it into a separate gr.Code component:\n`python\nimport gradio as gr\npython_code = \"\"\"\ndef fib(n):\n    if n Write Python or JavaScript\")\n            gr.ChatInterface(\n                chat,\n                examples=[\"Python\", \"JavaScript\"],\n                additional_outputs=[code],\n                api_name=\"chat\",\n            )\n        with gr.Column():\n            gr.Markdown(\"Code Artifacts\")\n            code.render()\ndemo.launch()\n`\nNote: unlike the case of additional inputs, the components passed in additional_outputs must be already defined in your gr.Blocks context -- they are not rendered automatically. If you need to render them after your gr.ChatInterface, you can set render=False when they are first defined and then .render() them in the appropriate section of your gr.Blocks() as we do in the example above.\nReturning Complex Responses\nWe mentioned earlier that in the simplest case, your chat function should return a str response, which will be rendered as Markdown in the chatbot. However, you can also return more complex responses as we discuss below:\nReturning files or Gradio components\nCurrently, the following Gradio components can be displayed inside the chat interface:\ngr.Image\ngr.Plot\ngr.Audio\ngr.HTML\ngr.Video\ngr.Gallery\ngr.File\nSimply return one of these components from your function to use it with gr.ChatInterface. Here's an example that returns an audio file:\n`py\nimport gradio as gr\ndef music(message, history):\n    if message.strip():\n        return gr.Audio(\"https://github.com/gradio-app/gradio/raw/main/test/testfiles/audiosample.wav\")\n    else:\n        return \"Please provide the name of an artist\"\ngr.ChatInterface(\n    music,\n    textbox=gr.Textbox(placeholder=\"Which artist's music do you want to listen to?\", scale=7),\n).launch()\n`\nSimilarly, you could return image files with gr.Image, video files with gr.Video, or arbitrary files with the gr.File component.\nReturning Multiple Messages\nYou can return multiple assistant messages from your chat function simply by returning a list of messages, each of which is a valid chat type. This lets you, for example, send a message along with files, as in the following example:\n`python\nimport gradio as gr\ndef echo_multimodal(message, history):\n    response = []\n    response.append(\"You wrote: '\" + message[\"text\"] + \"' and uploaded:\")\n    if message.get(\"files\"):\n        for file in message[\"files\"]:\n            response.append(gr.File(value=file))\n    return response\ndemo = gr.ChatInterface(\n    echo_multimodal,\n    multimodal=True,\n    textbox=gr.MultimodalTextbox(file_count=\"multiple\"),\n    api_name=\"chat\",\n)\ndemo.launch()\n`\nDisplaying intermediate thoughts or tool usage\nThe gr.ChatInterface class supports displaying intermediate thoughts or tool usage direct in the chatbot.\n To do this, you will need to return a gr.ChatMessage object from your chat function. Here is the schema of the gr.ChatMessage data class as well as two internal typed dictionaries:\n \n `py\nMessageContent = Union[str, FileDataDict, FileData, Component]\n@dataclass\nclass ChatMessage:\n    content: MessageContent | list[MessageContent]\n    metadata: MetadataDict = None\n    options: list[OptionDict] = None\nclass MetadataDict(TypedDict):\n    title: NotRequired[str]\n    id: NotRequired[int | str]\n    parent_id: NotRequired[int | str]\n    log: NotRequired[str]\n    duration: NotRequired[float]\n    status: NotRequired[Literal[\"pending\", \"done\"]]\nclass OptionDict(TypedDict):\n    label: NotRequired[str]\n    value: str\n `\n \nAs you can see, the gr.ChatMessage dataclass is similar to the openai-style message format, e.g. it has a \"content\" key that refers to the chat message content. But it also includes a \"metadata\" key whose value is a dictionary. If this dictionary includes a \"title\" key, the resulting message is displayed as an intermediate thought with the title being displayed on top of the thought. Here's an example showing the usage:\n`python\nimport gradio as gr\nfrom gradio import ChatMessage\nimport time\nsleep_time = 0.5\ndef simulatethinkingchat(message, history):\n    start_time = time.time()\n    response = ChatMessage(\n        content=\"\",\n        metadata={\"title\": \"Thinking step-by-step\", \"id\": 0, \"status\": \"pending\"}\n    )\n    yield response\n    thoughts = [\n        \"First, I need to understand the core aspects of the query...\",\n        \"Now, considering the broader context and implications...\",\n        \"Analyzing potential approaches to formulate a comprehensive answer...\",\n        \"Finally, structuring the response for clarity and completeness...\"\n    ]\n    accumulated_thoughts = \"\"\n    for thought in thoughts:\n        time.sleep(sleep_time)\n        accumulated_thoughts += f\"- {thought}\\n\\n\"\n        response.content = accumulated_thoughts.strip()\n        yield response\n    response.metadata[\"status\"] = \"done\"\n    response.metadata[\"duration\"] = time.time() - start_time\n    yield response\n    response = [\n        response,\n        ChatMessage(\n            content=\"Based on my thoughts and analysis above, my response is: This dummy repro shows how thoughts of a thinking LLM can be progressively shown before providing its final answer.\"\n        )\n    ]\n    yield response\ndemo = gr.ChatInterface(\n    simulatethinkingchat,\n    title=\"Thinking LLM Chat Interface 🤔\",\n)\ndemo.launch()\n`\nYou can even show nested thoughts, which is useful for agent demos in which one tool may call other tools. To display nested thoughts, include \"id\" and \"parent_id\" keys in the \"metadata\" dictionary. Read our dedicated guide on displaying intermediate thoughts and tool usage for more realistic examples.\nProviding preset responses\nWhen returning an assistant message, you may want to provide preset options that a user can choose in response. To do this, again, you will again return a gr.ChatMessage instance from your chat function. This time, make sure to set the options key specifying the preset responses.\nAs shown in the schema for gr.ChatMessage above, the value corresponding to the options key should be a list of dictionaries, each with a value (a string that is the value that should be sent to the chat function when this response is clicked) and an optional label (if provided, is the text displayed as the preset response instead of the value). \nThis example illustrates how to use preset responses:\n`python\nimport gradio as gr\nimport random\nexample_code = \"\"\"\nHere's an example Python lambda function:\nlambda x: x + {}\nIs this correct?\n\"\"\"\ndef chat(message, history):\n    if message == \"Yes, that's correct.\":\n        return \"Great!\"\n    else:\n        return gr.ChatMessage(\n            content=example_code.format(random.randint(1, 100)),\n            options=[\n                {\"value\": \"Yes, that's correct.\", \"label\": \"Yes\"},\n                {\"value\": \"No\"}\n            ]\n        )\ndemo = gr.ChatInterface(\n    chat,\n    examples=[\"Write an example Python lambda function.\"],\n    api_name=\"chat\",\n)\ndemo.launch()\n`\nModifying the Chatbot Value Directly\nYou may wish to modify the value of the chatbot with your own events, other than those prebuilt in the gr.ChatInterface. For example, you could create a dropdown that prefills the chat history with certain conversations or add a separate button to clear the conversation history. The gr.ChatInterface supports these events, but you need to use the gr.ChatInterface.chatbot_value as the input or output component in such events. In this example, we use a gr.Radio component to prefill the the chatbot with certain conversations:\n`python\nimport gradio as gr\nimport random\ndef prefill_chatbot(choice):\n    if choice == \"Greeting\":\n        return [\n            {\"role\": \"user\", \"content\": \"Hi there!\"},\n            {\"role\": \"assistant\", \"content\": \"Hello! How can I assist you today?\"}\n        ]\n    elif choice == \"Complaint\":\n        return [\n            {\"role\": \"user\", \"content\": \"I'm not happy with the service.\"},\n            {\"role\": \"assistant\", \"content\": \"I'm sorry to hear that. Can you please tell me more about the issue?\"}\n        ]\n    else:\n        return []\ndef random_response(message, history):\n    return random.choice([\"Yes\", \"No\"])\nwith gr.Blocks() as demo:\n    radio = gr.Radio([\"Greeting\", \"Complaint\", \"Blank\"])\n    chat = gr.ChatInterface(randomresponse, apiname=\"chat\")\n    radio.change(prefillchatbot, radio, chat.chatbotvalue)\ndemo.launch()\n`\nUsing Your Chatbot via API\nOnce you've built your Gradio chat interface and are hosting it on Hugging Face Spaces or somewhere else, then you can query it with a simple API. The API route will be the name of the function you pass to the ChatInterface. So if gr.ChatInterface(respond), then the API route is /respond. The endpoint just expects the user's message and will return the response, internally keeping track of the message history.\nTo use the endpoint, you should use either the Gradio Python Client or the Gradio JS client. Or, you can deploy your Chat Interface to other platforms, such as a:\nSlack bot [tutorial]\nWebsite widget [tutorial]\nChat History\nYou can enable persistent chat history for your ChatInterface, allowing users to maintain multiple conversations and easily switch between them. When enabled, conversations are stored locally and privately in the user's browser using local storage. So if you deploy a ChatInterface e.g. on Hugging Face Spaces, each user will have their own separate chat history that won't interfere with other users' conversations. This means multiple users can interact with the same ChatInterface simultaneously while maintaining their own private conversation histories.\nTo enable this feature, simply set gr.ChatInterface(save_history=True) (as shown in the example in the next section). Users will then see their previous conversations in a side panel and can continue any previous chat or start a new one.\nCollecting User Feedback\nTo gather feedback on your chat model, set gr.ChatInterface(flaggingmode=\"manual\") and users will be able to thumbs-up or thumbs-down assistant responses. Each flagged response, along with the entire chat history, will get saved in a CSV file in the app working directory (this can be configured via the flaggingdir parameter). \nYou can also change the feedback options via flagging_options parameter. The default options are \"Like\" and \"Dislike\", which appear as the thumbs-up and thumbs-down icons. Any other options appear under a dedicated flag icon. This example shows a ChatInterface that has both chat history (mentioned in the previous section) and user feedback enabled:\n`python\nimport time\nimport gradio as gr\ndef slow_echo(message, history):\n    for i in range(len(message)):\n        time.sleep(0.05)\n        yield \"You typed: \" + message[: i + 1]\ndemo = gr.ChatInterface(\n    slow_echo,\n    flagging_mode=\"manual\",\n    flagging_options=[\"Like\", \"Spam\", \"Inappropriate\", \"Other\"],\n    save_history=True,\n)\ndemo.launch()\n`\nNote that in this example, we set several flagging options: \"Like\", \"Spam\", \"Inappropriate\", \"Other\". Because the case-sensitive string \"Like\" is one of the flagging options, the user will see a thumbs-up icon next to each assistant message. The three other flagging options will appear in a dropdown under the flag icon.\nWhat's Next?\nNow that you've learned about the gr.ChatInterface class and how it can be used to create chatbot UIs quickly, we recommend reading one of the following:\nOur next Guide shows examples of how to use gr.ChatInterface` with popular LLM libraries.\nIf you'd like to build very custom chat applications from scratch, you can build them using the low-level Blocks API, as discussed in this Guide.\nOnce you've deployed your Gradio Chat Interface, its easy to use in other applications because of the built-in API. Here's a tutorial on how to deploy a Gradio chat interface as a Discord bot.","type":"GUIDE"},{"title":"Creating A Custom Chatbot With Blocks","slug":"/guides/creating-a-custom-chatbot-with-blocks/","content":"How to Create a Custom Chatbot with Gradio Blocks\nIntroduction\nImportant Note: if you are getting started, we recommend using the gr.ChatInterface to create chatbots -- its a high-level abstraction that makes it possible to create beautiful chatbot applications fast, often with a single line of code. Read more about it here.\nThis tutorial will show how to make chatbot UIs from scratch with Gradio's low-level Blocks API. This will give you full control over your Chatbot UI. You'll start by first creating a a simple chatbot to display text, a second one to stream text responses, and finally a chatbot that can handle media files as well. The chatbot interface that we create will look something like this:\nPrerequisite: We'll be using the gradio.Blocks class to build our Chatbot demo.\nYou can read the Guide to Blocks first if you are not already familiar with it. Also please make sure you are using the latest version version of Gradio: pip install --upgrade gradio.\nA Simple Chatbot Demo\nLet's start with recreating the simple demo above. As you may have noticed, our bot simply randomly responds \"How are you?\", \"Today is a great day\", or \"I'm very hungry\" to any input. Here's the code to create this with Gradio:\n``python\nimport gradio as gr\nimport random\nimport time\nwith gr.Blocks() as demo:\n    chatbot = gr.Chatbot()\n    msg = gr.Textbox()\n    clear = gr.ClearButton([msg, chatbot])\n    def respond(message, chat_history):\n        bot_message = random.choice([\"How are you?\", \"Today is a great day\", \"I'm very hungry\"])\n        chat_history.append({\"role\": \"user\", \"content\": message})\n        chathistory.append({\"role\": \"assistant\", \"content\": botmessage})\n        time.sleep(2)\n        return \"\", chat_history\n    msg.submit(respond, [msg, chatbot], [msg, chatbot])\ndemo.launch()\n`\nThere are three Gradio components here:\nA Chatbot, whose value stores the entire history of the conversation, as a list of response pairs between the user and bot.\nA Textbox where the user can type their message, and then hit enter/submit to trigger the chatbot response\nA ClearButton button to clear the Textbox and entire Chatbot history\nWe have a single function, respond(), which takes in the entire history of the chatbot, appends a random message, waits 1 second, and then returns the updated chat history. The respond() function also clears the textbox when it returns.\nOf course, in practice, you would replace respond() with your own more complex function, which might call a pretrained model or an API, to generate a response.\n            \n                \n                    \n                    \n                    \n                \n                For better type hinting and auto-completion in your IDE, you can use the gr.ChatMessage dataclass:\n            \n                \n`python\nfrom gradio import ChatMessage\ndef chat_function(message, history):\n    history.append(ChatMessage(role=\"user\", content=message))\n    history.append(ChatMessage(role=\"assistant\", content=\"Hello, how can I help you?\"))\n    return history\n`\nAdd Streaming to your Chatbot\nThere are several ways we can improve the user experience of the chatbot above. First, we can stream responses so the user doesn't have to wait as long for a message to be generated. Second, we can have the user message appear immediately in the chat history, while the chatbot's response is being generated. Here's the code to achieve that:\n`python\nimport gradio as gr\nimport random\nimport time\nwith gr.Blocks() as demo:\n    chatbot = gr.Chatbot()\n    msg = gr.Textbox()\n    clear = gr.Button(\"Clear\")\n    def user(user_message, history: list):\n        return \"\", history + [{\"role\": \"user\", \"content\": user_message}]\n    def bot(history: list):\n        bot_message = random.choice([\"How are you?\", \"I love you\", \"I'm very hungry\"])\n        history.append({\"role\": \"assistant\", \"content\": \"\"})\n        for character in bot_message:\n            history[-1]['content'] += character\n            time.sleep(0.05)\n            yield history\n    msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(\n        bot, chatbot, chatbot\n    )\n    clear.click(lambda: None, None, chatbot, queue=False)\ndemo.launch()\n`\nYou'll notice that when a user submits their message, we now chain two event events with .then():\nThe first method user() updates the chatbot with the user message and clears the input field. Because we want this to happen instantly, we set queue=False, which would skip any queue had it been enabled. The chatbot's history is appended with {\"role\": \"user\", \"content\": user_message}.\nThe second method, bot() updates the chatbot history with the bot's response. Finally, we construct the message character by character and yield the intermediate outputs as they are being constructed. Gradio automatically turns any function with the yield keyword into a streaming output interface.\nOf course, in practice, you would replace bot() with your own more complex function, which might call a pretrained model or an API, to generate a response.\nAdding Markdown, Images, Audio, or Videos\nThe gr.Chatbot component supports a subset of markdown including bold, italics, and code. For example, we could write a function that responds to a user's message, with a bold That's cool!, like this:\n`py\ndef bot(history):\n    response = {\"role\": \"assistant\", \"content\": \"That's cool!\"}\n    history.append(response)\n    return history\n`\nIn addition, it can handle media files, such as images, audio, and video. You can use the MultimodalTextbox component to easily upload all types of media files to your chatbot. You can customize the MultimodalTextbox further by passing in the sources parameter, which is a list of sources to enable. To pass in a media file, we must pass in the file a dictionary with a path key pointing to a local file and an alttext key. The alttext is optional, so you can also just pass in a tuple with a single element {\"path\": \"filepath\"}, like this:\n`python\ndef add_message(history, message):\n    for x in message[\"files\"]:\n        history.append({\"role\": \"user\", \"content\": {\"path\": x}})\n    if message[\"text\"] is not None:\n        history.append({\"role\": \"user\", \"content\": message[\"text\"]})\n    return history, gr.MultimodalTextbox(value=None, interactive=False, file_types=[\"image\"], sources=[\"upload\", \"microphone\"])\n`\nPutting this together, we can create a multimodal chatbot with a multimodal textbox for a user to submit text and media files. The rest of the code looks pretty much the same as before:\n`python\nimport gradio as gr\nimport time\nChatbot demo with multimodal input (text, markdown, LaTeX, code blocks, image, audio, & video). Plus shows support for streaming text.\ndef printlikedislike(x: gr.LikeData):\n    print(x.index, x.value, x.liked)\ndef add_message(history, message):\n    user_msg = {\"role\": \"user\", \"content\": []}\n    for x in message[\"files\"]:  \n        user_msg[\"content\"].append({\"path\": x})  \n    if message[\"text\"] is not None:  \n       user_msg[\"content\"].append(message[\"text\"])  \n    history.append(user_msg)\n    return history, gr.MultimodalTextbox(value=None, interactive=False)\ndef bot(history: list):\n    response = \"That's cool!\"\n    history.append({\"role\": \"assistant\", \"content\": \"\"})\n    for character in response:\n        history[-1][\"content\"] += character\n        time.sleep(0.05)\n        yield history\nwith gr.Blocks() as demo:\n    chatbot = gr.Chatbot(elemid=\"chatbot\", likeuser_message=True)\n    chat_input = gr.MultimodalTextbox(\n        interactive=True,\n        file_count=\"multiple\",\n        placeholder=\"Enter message or upload file...\",\n        show_label=False,\n        sources=[\"microphone\", \"upload\"],\n    )\n    chatmsg = chatinput.submit(\n        addmessage, [chatbot, chatinput], [chatbot, chat_input]\n    )\n    botmsg = chatmsg.then(bot, chatbot, chatbot, apiname=\"botresponse\")\n    botmsg.then(lambda: gr.MultimodalTextbox(interactive=True), None, [chatinput])\n    chatbot.like(printlikedislike, None, None)\ndemo.launch()\n`\nAnd you're done! That's all the code you need to build an interface for your chatbot model. Finally, we'll end our Guide with some links to Chatbots that are running on Spaces so that you can get an idea of what else is possible:\ngradio/chatbotstreaming: A streaming chatbot demo built with gr.Chatbot` and Blocks.\ngradio/chatbotexamples: A chatbot that presents new visitors with a list of multimodal examples they can use to start the conversation.","type":"GUIDE"},{"title":"Creating A Dashboard From Bigquery Data","slug":"/guides/creating-a-dashboard-from-bigquery-data/","content":"Creating a Real-Time Dashboard from BigQuery Data\nGoogle BigQuery is a cloud-based service for processing very large data sets. It is a serverless and highly scalable data warehousing solution that enables users to analyze data using SQL-like queries.\nIn this tutorial, we will show you how to query a BigQuery dataset in Python and display the data in a dashboard that updates in real time using gradio. The dashboard will look like this:\nWe'll cover the following steps in this Guide:\nSetting up your BigQuery credentials\nUsing the BigQuery client\nBuilding the real-time dashboard (in just 7 lines of Python)\nWe'll be working with the New York Times' COVID dataset that is available as a public dataset on BigQuery. The dataset, named covid19nyt.uscounties contains the latest information about the number of confirmed cases and deaths from COVID across US counties.\nPrerequisites: This Guide uses Gradio Blocks, so make your are familiar with the Blocks class.\nSetting up your BigQuery Credentials\nTo use Gradio with BigQuery, you will need to obtain your BigQuery credentials and use them with the BigQuery Python client. If you already have BigQuery credentials (as a .json file), you can skip this section. If not, you can do this for free in just a couple of minutes.\nFirst, log in to your Google Cloud account and go to the Google Cloud Console (https://console.cloud.google.com/)\nIn the Cloud Console, click on the hamburger menu in the top-left corner and select \"APIs & Services\" from the menu. If you do not have an existing project, you will need to create one.\nThen, click the \"+ Enabled APIs & services\" button, which allows you to enable specific services for your project. Search for \"BigQuery API\", click on it, and click the \"Enable\" button. If you see the \"Manage\" button, then the BigQuery is already enabled, and you're all set.\nIn the APIs & Services menu, click on the \"Credentials\" tab and then click on the \"Create credentials\" button.\nIn the \"Create credentials\" dialog, select \"Service account key\" as the type of credentials to create, and give it a name. Also grant the service account permissions by giving it a role such as \"BigQuery User\", which will allow you to run queries.\nAfter selecting the service account, select the \"JSON\" key type and then click on the \"Create\" button. This will download the JSON key file containing your credentials to your computer. It will look something like this:\n``json\n{\n\t\"type\": \"service_account\",\n\t\"project_id\": \"your project\",\n\t\"privatekeyid\": \"your private key id\",\n\t\"private_key\": \"private key\",\n\t\"client_email\": \"email\",\n\t\"client_id\": \"client id\",\n\t\"auth_uri\": \"https://accounts.google.com/o/oauth2/auth\",\n\t\"token_uri\": \"https://accounts.google.com/o/oauth2/token\",\n\t\"authproviderx509certurl\": \"https://www.googleapis.com/oauth2/v1/certs\",\n\t\"clientx509certurl\": \"https://www.googleapis.com/robot/v1/metadata/x509/emailid\"\n}\n`\nUsing the BigQuery Client\nOnce you have the credentials, you will need to use the BigQuery Python client to authenticate using your credentials. To do this, you will need to install the BigQuery Python client by running the following command in the terminal:\n`bash\npip install google-cloud-bigquery[pandas]\n`\nYou'll notice that we've installed the pandas add-on, which will be helpful for processing the BigQuery dataset as a pandas dataframe. Once the client is installed, you can authenticate using your credentials by running the following code:\n`py\nfrom google.cloud import bigquery\nclient = bigquery.Client.fromserviceaccount_json(\"path/to/key.json\")\n`\nWith your credentials authenticated, you can now use the BigQuery Python client to interact with your BigQuery datasets.\nHere is an example of a function which queries the covid19nyt.uscounties dataset in BigQuery to show the top 20 counties with the most confirmed cases as of the current day:\n`py\nimport numpy as np\nQUERY = (\n    'SELECT * FROM bigquery-public-data.covid19nyt.uscounties '\n    'ORDER BY date DESC,confirmed_cases DESC '\n    'LIMIT 20')\ndef run_query():\n    query_job = client.query(QUERY)\n    queryresult = queryjob.result()\n    df = queryresult.todataframe()\n    # Select a subset of columns\n    df = df[[\"confirmedcases\", \"deaths\", \"county\", \"statename\"]]\n    # Convert numeric columns to standard numpy types\n    df = df.astype({\"deaths\": np.int64, \"confirmed_cases\": np.int64})\n    return df\n`\nBuilding the Real-Time Dashboard\nOnce you have a function to query the data, you can use the gr.DataFrame component from the Gradio library to display the results in a tabular format. This is a useful way to inspect the data and make sure that it has been queried correctly.\nHere is an example of how to use the gr.DataFrame component to display the results. By passing in the run_query function to gr.DataFrame, we instruct Gradio to run the function as soon as the page loads and show the results. In addition, you also pass in the keyword every to tell the dashboard to refresh every hour (60\\*60 seconds).\n`py\nimport gradio as gr\nwith gr.Blocks() as demo:\n    gr.DataFrame(run_query, every=gr.Timer(60*60))\ndemo.launch()\n`\nPerhaps you'd like to add a visualization to our dashboard. You can use the gr.ScatterPlot() component to visualize the data in a scatter plot. This allows you to see the relationship between different variables such as case count and case deaths in the dataset and can be useful for exploring the data and gaining insights. Again, we can do this in real-time\nby passing in the every parameter.\nHere is a complete example showing how to use the gr.ScatterPlot to visualize in addition to displaying data with the gr.DataFrame\n`py\nimport gradio as gr\nwith gr.Blocks() as demo:\n    gr.Markdown(\"# 💉 Covid Dashboard (Updated Hourly)\")\n    with gr.Row():\n        gr.DataFrame(run_query, every=gr.Timer(60*60))\n        gr.ScatterPlot(runquery, every=gr.Timer(60*60), x=\"confirmedcases\",\n                        y=\"deaths\", tooltip=\"county\", width=500, height=500)\ndemo.queue().launch()  # Run the demo with queuing enabled\n``","type":"GUIDE"},{"title":"Creating A Dashboard From Supabase Data","slug":"/guides/creating-a-dashboard-from-supabase-data/","content":"Create a Dashboard from Supabase Data\nSupabase is a cloud-based open-source backend that provides a PostgreSQL database, authentication, and other useful features for building web and mobile applications. In this tutorial, you will learn how to read data from Supabase and plot it in real-time on a Gradio Dashboard.\nPrerequisites: To start, you will need a free Supabase account, which you can sign up for here: https://app.supabase.com/\nIn this end-to-end guide, you will learn how to:\nCreate tables in Supabase\nWrite data to Supabase using the Supabase Python Client\nVisualize the data in a real-time dashboard using Gradio\nIf you already have data on Supabase that you'd like to visualize in a dashboard, you can skip the first two sections and go directly to visualizing the data!\nCreate a table in Supabase\nFirst of all, we need some data to visualize. Following this excellent guide, we'll create fake commerce data and put it in Supabase.\n1\\. Start by creating a new project in Supabase. Once you're logged in, click the \"New Project\" button\n2\\. Give your project a name and database password. You can also choose a pricing plan (for our purposes, the Free Tier is sufficient!)\n3\\. You'll be presented with your API keys while the database spins up (can take up to 2 minutes).\n4\\. Click on \"Table Editor\" (the table icon) in the left pane to create a new table. We'll create a single table called Product, with the following schema:\nproduct_idint8\ninventory_countint8\npricefloat8\nproduct_namevarchar\n5\\. Click Save to save the table schema.\nOur table is now ready!\nWrite data to Supabase\nThe next step is to write data to a Supabase dataset. We will use the Supabase Python library to do this.\n6\\. Install supabase by running the following command in your terminal:\n``bash\npip install supabase\n`\n7\\. Get your project URL and API key. Click the Settings (gear icon) on the left pane and click 'API'. The URL is listed in the Project URL box, while the API key is listed in Project API keys (with the tags service_role, secret)\n8\\. Now, run the following Python script to write some fake data to the table (note you have to put the values of SUPABASEURL and SUPABASESECRET_KEY from step 7):\n`python\nimport supabase\nInitialize the Supabase client\nclient = supabase.createclient('SUPABASEURL', 'SUPABASESECRETKEY')\nDefine the data to write\nimport random\nmain_list = []\nfor i in range(10):\n    value = {'product_id': i,\n             'product_name': f\"Item {i}\",\n             'inventory_count': random.randint(1, 100),\n             'price': random.random()*100\n            }\n    main_list.append(value)\nWrite the data to the table\ndata = client.table('Product').insert(main_list).execute()\n`\nReturn to your Supabase dashboard and refresh the page, you should now see 10 rows populated in the Product table!\nVisualize the Data in a Real-Time Gradio Dashboard\nFinally, we will read the data from the Supabase dataset using the same supabase Python library and create a realtime dashboard using gradio.\nNote: We repeat certain steps in this section (like creating the Supabase client) in case you did not go through the previous sections. As described in Step 7, you will need the project URL and API Key for your database.\n9\\. Write a function that loads the data from the Product table and returns it as a pandas Dataframe:\n`python\nimport supabase\nimport pandas as pd\nclient = supabase.createclient('SUPABASEURL', 'SUPABASESECRETKEY')\ndef read_data():\n    response = client.table('Product').select(\"*\").execute()\n    df = pd.DataFrame(response.data)\n    return df\n`\n10\\. Create a small Gradio Dashboard with 2 Barplots that plots the prices and inventories of all of the items every minute and updates in real-time:\n`python\nimport gradio as gr\nwith gr.Blocks() as dashboard:\n    with gr.Row():\n        gr.BarPlot(readdata, x=\"productid\", y=\"price\", title=\"Prices\", every=gr.Timer(60))\n        gr.BarPlot(readdata, x=\"productid\", y=\"inventory_count\", title=\"Inventory\", every=gr.Timer(60))\ndashboard.queue().launch()\n`\nNotice that by passing in a function to gr.BarPlot(), we have the BarPlot query the database as soon as the web app loads (and then again every 60 seconds because of the every` parameter). Your final dashboard should look something like this:\nConclusion\nThat's it! In this tutorial, you learned how to write data to a Supabase dataset, and then read that data and plot the results as bar plots. If you update the data in the Supabase database, you'll notice that the Gradio dashboard will update within a minute.\nTry adding more plots and visualizations to this example (or with a different dataset) to build a more complex dashboard!","type":"GUIDE"},{"title":"Creating A Discord Bot From A Gradio App","slug":"/guides/creating-a-discord-bot-from-a-gradio-app/","content":"🚀 Creating Discord Bots with Gradio 🚀\nYou can make your Gradio app available as a Discord bot to let users in your Discord server interact with it directly. \nHow does it work?\nThe Discord bot will listen to messages mentioning it in channels. When it receives a message (which can include text as well as files), it will send it to your Gradio app via Gradio's built-in API. Your bot will reply with the response it receives from the API. \nBecause Gradio's API is very flexible, you can create Discord bots that support text, images, audio, streaming, chat history, and a wide variety of other features very easily. \nPrerequisites\nInstall the latest version of gradio and the discord.py libraries:\n``\npip install --upgrade gradio discord.py~=2.0\n`\nHave a running Gradio app. This app can be running locally or on Hugging Face Spaces. In this example, we will be using the Gradio Playground Space, which takes in an image and/or text and generates the code to generate the corresponding Gradio app.\nNow, we are ready to get started!\nCreate a Discord application\nFirst, go to the Discord apps dashboard. Look for the \"New Application\" button and click it. Give your application a name, and then click \"Create\".\nOn the resulting screen, you will see basic information about your application. Under the Settings section, click on the \"Bot\" option. You can update your bot's username if you would like.\nThen click on the \"Reset Token\" button. A new token will be generated. Copy it as we will need it for the next step.\nScroll down to the section that says \"Privileged Gateway Intents\". Your bot will need certain permissions to work correctly. In this tutorial, we will only be using the \"Message Content Intent\" so click the toggle to enable this intent. Save the changes.\nWrite a Discord bot\nLet's start by writing a very simple Discord bot, just to make sure that everything is working. Write the following Python code in a file called bot.py, pasting the discord bot token from the previous step:\n`python\nbot.py\nimport discord\nTOKEN = #PASTE YOUR DISCORD BOT TOKEN HERE\nclient = discord.Client()\n@client.event\nasync def on_ready():\n    print(f'{client.user} has connected to Discord!')\nclient.run(TOKEN)\n`\nNow, run this file: python bot.py, which should run and print a message like:\n`text\nWe have logged in as GradioPlaygroundBot#1451\n`\nIf that is working, we are ready to add Gradio-specific code. We will be using the Gradio Python Client to query the Gradio Playground Space mentioned above. Here's the updated bot.py file:\n`python\nimport discord\nfrom gradioclient import Client, handlefile\nimport httpx\nimport os\nTOKEN = #PASTE YOUR DISCORD BOT TOKEN HERE\nintents = discord.Intents.default()\nintents.message_content = True\nclient = discord.Client(intents=intents)\ngradio_client = Client(\"abidlabs/gradio-playground-bot\")\ndef download_image(attachment):\n    response = httpx.get(attachment.url)\n    image_path = f\"./images/{attachment.filename}\"\n    os.makedirs(\"./images\", exist_ok=True)\n    with open(image_path, \"wb\") as f:\n        f.write(response.content)\n    return image_path\n@client.event\nasync def on_ready():\n    print(f'We have logged in as {client.user}')\n@client.event\nasync def on_message(message):\n    # Ignore messages from the bot itself\n    if message.author == client.user:\n        return\n    # Check if the bot is mentioned in the message and reply\n    if client.user in message.mentions:\n        # Extract the message content without the bot mention\n        clean_message = message.content.replace(f\"\", \"\").strip()\n        # Handle images (only the first image is used)\n        files = []\n        if message.attachments:\n            for attachment in message.attachments:\n                if any(attachment.filename.lower().endswith(ext) for ext in ['png', 'jpg', 'jpeg', 'gif', 'webp']):\n                    imagepath = downloadimage(attachment)\n                    files.append(handlefile(imagepath))\n                    break\n        \n        # Stream the responses to the channel\n        for response in gradio_client.submit(\n            message={\"text\": clean_message, \"files\": files},\n        ):\n            await message.channel.send(response[-1])\nclient.run(TOKEN)\n`\nAdd the bot to your Discord Server\nNow we are ready to install the bot on our server. Go back to the Discord apps dashboard. Under the Settings section, click on the \"OAuth2\" option. Scroll down to the \"OAuth2 URL Generator\" box and select the \"bot\" checkbox:\nThen in \"Bot Permissions\" box that pops up underneath, enable the following permissions:\nCopy the generated URL that appears underneath, which should look something like:\n`text\nhttps://discord.com/oauth2/authorize?clientid=1319011745452265575&permissions=377957238784&integrationtype=0&scope=bot\n``\nPaste it into your browser, which should allow you to add the Discord bot to any Discord server that you manage.\nThat's it!\nNow you can mention your bot from any channel in your Discord server, optionally attach an image, and it will respond with generated Gradio app code!\nThe bot will:\nListen for mentions\nProcess any attached images\nSend the text and images to your Gradio app\nStream the responses back to the Discord channel\n This is just a basic example - you can extend it to handle more types of files, add error handling, or integrate with different Gradio apps.\nIf you build a Discord bot from a Gradio app, feel free to share it on X and tag the Gradio account, and we are happy to help you amplify!","type":"GUIDE"},{"title":"Creating A Realtime Dashboard From Google Sheets","slug":"/guides/creating-a-realtime-dashboard-from-google-sheets/","content":"Creating a Real-Time Dashboard from Google Sheets\nGoogle Sheets are an easy way to store tabular data in the form of spreadsheets. With Gradio and pandas, it's easy to read data from public or private Google Sheets and then display the data or plot it. In this blog post, we'll build a small real-time dashboard, one that updates when the data in the Google Sheets updates.\nBuilding the dashboard itself will just be 9 lines of Python code using Gradio, and our final dashboard will look like this:\nPrerequisites: This Guide uses Gradio Blocks, so make you are familiar with the Blocks class.\nThe process is a little different depending on if you are working with a publicly accessible or a private Google Sheet. We'll cover both, so let's get started!\nPublic Google Sheets\nBuilding a dashboard from a public Google Sheet is very easy, thanks to the pandas library:\n1\\. Get the URL of the Google Sheets that you want to use. To do this, simply go to the Google Sheets, click on the \"Share\" button in the top-right corner, and then click on the \"Get shareable link\" button. This will give you a URL that looks something like this:\n``html\nhttps://docs.google.com/spreadsheets/d/1UoKzzRzOCt-FXLLqDKLbryEKEgllGAQUEJ5qtmmQwpU/edit#gid=0\n`\n2\\. Now, let's modify this URL and then use it to read the data from the Google Sheets into a Pandas DataFrame. (In the code below, replace the URL variable with the URL of your public Google Sheet):\n`python\nimport pandas as pd\nURL = \"https://docs.google.com/spreadsheets/d/1UoKzzRzOCt-FXLLqDKLbryEKEgllGAQUEJ5qtmmQwpU/edit#gid=0\"\ncsv_url = URL.replace('/edit#gid=', '/export?format=csv&gid=')\ndef get_data():\n    return pd.readcsv(csvurl)\n`\n3\\. The data query is a function, which means that it's easy to display it real-time using the gr.DataFrame component, or plot it real-time using the gr.LinePlot component (of course, depending on the data, a different plot may be appropriate). To do this, just pass the function into the respective components, and set the every parameter based on how frequently (in seconds) you would like the component to refresh. Here's the Gradio code:\n`python\nimport gradio as gr\nwith gr.Blocks() as demo:\n    gr.Markdown(\"# 📈 Real-Time Line Plot\")\n    with gr.Row():\n        with gr.Column():\n            gr.DataFrame(get_data, every=gr.Timer(5))\n        with gr.Column():\n            gr.LinePlot(getdata, every=gr.Timer(5), x=\"Date\", y=\"Sales\", ytitle=\"Sales ($ millions)\", overlay_point=True, width=500, height=500)\ndemo.queue().launch()  # Run the demo with queuing enabled\n`\nAnd that's it! You have a dashboard that refreshes every 5 seconds, pulling the data from your Google Sheet.\nPrivate Google Sheets\nFor private Google Sheets, the process requires a little more work, but not that much! The key difference is that now, you must authenticate yourself to authorize access to the private Google Sheets.\nAuthentication\nTo authenticate yourself, obtain credentials from Google Cloud. Here's how to set up google cloud credentials:\n1\\. First, log in to your Google Cloud account and go to the Google Cloud Console (https://console.cloud.google.com/)\n2\\. In the Cloud Console, click on the hamburger menu in the top-left corner and select \"APIs & Services\" from the menu. If you do not have an existing project, you will need to create one.\n3\\. Then, click the \"+ Enabled APIs & services\" button, which allows you to enable specific services for your project. Search for \"Google Sheets API\", click on it, and click the \"Enable\" button. If you see the \"Manage\" button, then Google Sheets is already enabled, and you're all set.\n4\\. In the APIs & Services menu, click on the \"Credentials\" tab and then click on the \"Create credentials\" button.\n5\\. In the \"Create credentials\" dialog, select \"Service account key\" as the type of credentials to create, and give it a name. Note down the email of the service account\n6\\. After selecting the service account, select the \"JSON\" key type and then click on the \"Create\" button. This will download the JSON key file containing your credentials to your computer. It will look something like this:\n`json\n{\n\t\"type\": \"service_account\",\n\t\"project_id\": \"your project\",\n\t\"privatekeyid\": \"your private key id\",\n\t\"private_key\": \"private key\",\n\t\"client_email\": \"email\",\n\t\"client_id\": \"client id\",\n\t\"auth_uri\": \"https://accounts.google.com/o/oauth2/auth\",\n\t\"token_uri\": \"https://accounts.google.com/o/oauth2/token\",\n\t\"authproviderx509certurl\": \"https://www.googleapis.com/oauth2/v1/certs\",\n\t\"clientx509certurl\": \"https://www.googleapis.com/robot/v1/metadata/x509/emailid\"\n}\n`\nQuerying\nOnce you have the credentials .json file, you can use the following steps to query your Google Sheet:\n1\\. Click on the \"Share\" button in the top-right corner of the Google Sheet. Share the Google Sheets with the email address of the service from Step 5 of authentication subsection (this step is important!). Then click on the \"Get shareable link\" button. This will give you a URL that looks something like this:\n`html\nhttps://docs.google.com/spreadsheets/d/1UoKzzRzOCt-FXLLqDKLbryEKEgllGAQUEJ5qtmmQwpU/edit#gid=0\n`\n2\\. Install the gspread library, which makes it easy to work with the Google Sheets API in Python by running in the terminal: pip install gspread\n3\\. Write a function to load the data from the Google Sheet, like this (replace the URL variable with the URL of your private Google Sheet):\n`python\nimport gspread\nimport pandas as pd\nAuthenticate with Google and get the sheet\nURL = 'https://docs.google.com/spreadsheets/d/1_91Vps76SKOdDQ8cFxZQdgjTJiz23375sAT7vPvaj4k/edit#gid=0'\ngc = gspread.service_account(\"path/to/key.json\")\nsh = gc.openbyurl(URL)\nworksheet = sh.sheet1\ndef get_data():\n    values = worksheet.getallvalues()\n    df = pd.DataFrame(values[1:], columns=values[0])\n    return df\n`\n4\\. The data query is a function, which means that it's easy to display it real-time using the gr.DataFrame component, or plot it real-time using the gr.LinePlot component (of course, depending on the data, a different plot may be appropriate). To do this, we just pass the function into the respective components, and set the every parameter based on how frequently (in seconds) we would like the component to refresh. Here's the Gradio code:\n`python\nimport gradio as gr\nwith gr.Blocks() as demo:\n    gr.Markdown(\"# 📈 Real-Time Line Plot\")\n    with gr.Row():\n        with gr.Column():\n            gr.DataFrame(get_data, every=gr.Timer(5))\n        with gr.Column():\n            gr.LinePlot(getdata, every=gr.Timer(5), x=\"Date\", y=\"Sales\", ytitle=\"Sales ($ millions)\", overlay_point=True, width=500, height=500)\ndemo.queue().launch()  # Run the demo with queuing enabled\n`\nYou now have a Dashboard that refreshes every 5 seconds, pulling the data from your Google Sheet.\nConclusion\nAnd that's all there is to it! With just a few lines of code, you can use gradio` and other libraries to read data from a public or private Google Sheet and then display and plot the data in a real-time dashboard.","type":"GUIDE"},{"title":"Creating A Slack Bot From A Gradio App","slug":"/guides/creating-a-slack-bot-from-a-gradio-app/","content":"🚀 Creating a Slack Bot from a Gradio App 🚀\nYou can make your Gradio app available as a Slack bot to let users in your Slack workspace interact with it directly. \nHow does it work?\nThe Slack bot will listen to messages mentioning it in channels. When it receives a message (which can include text as well as files), it will send it to your Gradio app via Gradio's built-in API. Your bot will reply with the response it receives from the API. \nBecause Gradio's API is very flexible, you can create Slack bots that support text, images, audio, streaming, chat history, and a wide variety of other features very easily. \nPrerequisites\nInstall the latest version of gradio and the slack-bolt library:\n``bash\npip install --upgrade gradio slack-bolt~=1.0\n`\nHave a running Gradio app. This app can be running locally or on Hugging Face Spaces. In this example, we will be using the Gradio Playground Space, which takes in an image and/or text and generates the code to generate the corresponding Gradio app.\nNow, we are ready to get started!\nCreate a Slack App\nGo to api.slack.com/apps and click \"Create New App\"\nChoose \"From scratch\" and give your app a name\nSelect the workspace where you want to develop your app\nUnder \"OAuth & Permissions\", scroll to \"Scopes\" and add these Bot Token Scopes:\napp_mentions:read\nchat:write\nfiles:read\nfiles:write\nIn the same \"OAuth & Permissions\" page, scroll back up and click the button to install the app to your workspace.\nNote the \"Bot User OAuth Token\" (starts with xoxb-) that appears as we'll need it later\nClick on \"Socket Mode\" in the menu bar. When the page loads, click the toggle to \"Enable Socket Mode\"\nGive your token a name, such as socket-token and copy the token that is generated (starts with xapp-) as we'll need it later.\nFinally, go to the \"Event Subscription\" option in the menu bar. Click the toggle to \"Enable Events\" and subscribe to the app_mention bot event.\nWrite a Slack bot\nLet's start by writing a very simple Slack bot, just to make sure that everything is working. Write the following Python code in a file called bot.py, pasting the two tokens from step 6 and step 8 in the previous section.\n`py\nfrom slack_bolt import App\nfrom slackbolt.adapter.socketmode import SocketModeHandler\nSLACKBOTTOKEN = # PASTE YOUR SLACK BOT TOKEN HERE\nSLACKAPPTOKEN = # PASTE YOUR SLACK APP TOKEN HERE\napp = App(token=SLACKBOTTOKEN)\n@app.event(\"app_mention\")\ndef handleappmention_events(body, say):\n    user_id = body[\"event\"][\"user\"]\n    say(f\"Hi ! You mentioned me and said: {body['event']['text']}\")\nif name == \"main\":\n    handler = SocketModeHandler(app, SLACKAPPTOKEN)\n    handler.start()\n`\nIf that is working, we are ready to add Gradio-specific code. We will be using the Gradio Python Client to query the Gradio Playground Space mentioned above. Here's the updated bot.py file:\n`python\nfrom slack_bolt import App\nfrom slackbolt.adapter.socketmode import SocketModeHandler\nSLACKBOTTOKEN = # PASTE YOUR SLACK BOT TOKEN HERE\nSLACKAPPTOKEN = # PASTE YOUR SLACK APP TOKEN HERE\napp = App(token=SLACKBOTTOKEN)\ngradio_client = Client(\"abidlabs/gradio-playground-bot\")\ndef download_image(url, filename):\n    headers = {\"Authorization\": f\"Bearer {SLACKBOTTOKEN}\"}\n    response = httpx.get(url, headers=headers)\n    image_path = f\"./images/{filename}\"\n    os.makedirs(\"./images\", exist_ok=True)\n    with open(image_path, \"wb\") as f:\n        f.write(response.content)\n    return image_path\ndef slackify_message(message):   \n    # Replace markdown links with slack format and remove code language specifier after triple backticks\n    pattern = r'\\[(.?)\\]\\((.?)\\)'\n    cleaned = re.sub(pattern, r'', message)\n    cleaned = re.sub(r'`\\w+\\n', '`', cleaned)\n    return cleaned.strip()\n@app.event(\"app_mention\")\ndef handleappmention_events(body, say):\n    # Extract the message content without the bot mention\n    text = body[\"event\"][\"text\"]\n    botuserid = body[\"authorizations\"][0][\"user_id\"]\n    clean_message = text.replace(f\"\", \"\").strip()\n    \n    # Handle images if present\n    files = []\n    if \"files\" in body[\"event\"]:\n        for file in body[\"event\"][\"files\"]:\n            if file[\"filetype\"] in [\"png\", \"jpg\", \"jpeg\", \"gif\", \"webp\"]:\n                imagepath = downloadimage(file[\"urlprivatedownload\"], file[\"name\"])\n                files.append(handlefile(imagepath))\n                break\n    \n    # Submit to Gradio and send responses back to Slack\n    for response in gradio_client.submit(\n        message={\"text\": clean_message, \"files\": files},\n    ):\n        cleanedresponse = slackifymessage(response[-1])\n        say(cleaned_response)\nif name == \"main\":\n    handler = SocketModeHandler(app, SLACKAPPTOKEN)\n    handler.start()\n`\nAdd the bot to your Slack Workplace\nNow, create a new channel or navigate to an existing channel in your Slack workspace where you want to use the bot. Click the \"+\" button next to \"Channels\" in your Slack sidebar and follow the prompts to create a new channel.\nFinally, invite your bot to the channel:\nIn your new channel, type /invite @YourBotName`\nSelect your bot from the dropdown\nClick \"Invite to Channel\"\nThat's it!\nNow you can mention your bot in any channel it's in, optionally attach an image, and it will respond with generated Gradio app code!\nThe bot will:\nListen for mentions\nProcess any attached images\nSend the text and images to your Gradio app\nStream the responses back to the Slack channel\nThis is just a basic example - you can extend it to handle more types of files, add error handling, or integrate with different Gradio apps!\nIf you build a Slack bot from a Gradio app, feel free to share it on X and tag the Gradio account, and we are happy to help you amplify!","type":"GUIDE"},{"title":"Creating A Website Widget From A Gradio Chatbot","slug":"/guides/creating-a-website-widget-from-a-gradio-chatbot/","content":"🚀 Creating a Website Chat Widget with Gradio 🚀\nYou can make your Gradio Chatbot available as an embedded chat widget on your website, similar to popular customer service widgets like Intercom. This is particularly useful for:\nAdding AI assistance to your documentation pages\nProviding interactive help on your portfolio or product website\nCreating a custom chatbot interface for your Gradio app\nHow does it work?\nThe chat widget appears as a small button in the corner of your website. When clicked, it opens a chat interface that communicates with your Gradio app via the JavaScript Client API. Users can ask questions and receive responses directly within the widget.\nPrerequisites\nA running Gradio app (local or on Hugging Face Spaces). In this example, we'll use the Gradio Playground Space, which helps generate code for Gradio apps based on natural language descriptions.\nCreate and Style the Chat Widget\nFirst, add this HTML and CSS to your website:\n``html\n    💬\n    \n        \n            Gradio Assistant\n            ×\n        \n        \n        \n            \n            Send\n        \n    \n.chat-widget {\n    position: fixed;\n    bottom: 20px;\n    right: 20px;\n    z-index: 1000;\n}\n.chat-toggle {\n    width: 50px;\n    height: 50px;\n    border-radius: 50%;\n    background: #007bff;\n    border: none;\n    color: white;\n    font-size: 24px;\n    cursor: pointer;\n}\n.chat-container {\n    position: fixed;\n    bottom: 80px;\n    right: 20px;\n    width: 300px;\n    height: 400px;\n    background: white;\n    border-radius: 10px;\n    box-shadow: 0 0 10px rgba(0,0,0,0.1);\n    display: flex;\n    flex-direction: column;\n}\n.chat-container.hidden {\n    display: none;\n}\n#chat-header {\n    padding: 10px;\n    background: #007bff;\n    color: white;\n    border-radius: 10px 10px 0 0;\n    display: flex;\n    justify-content: space-between;\n    align-items: center;\n}\n#chat-messages {\n    flex-grow: 1;\n    overflow-y: auto;\n    padding: 10px;\n}\n#chat-input-area {\n    padding: 10px;\n    border-top: 1px solid #eee;\n    display: flex;\n}\n#chat-input {\n    flex-grow: 1;\n    padding: 8px;\n    border: 1px solid #ddd;\n    border-radius: 4px;\n    margin-right: 8px;\n}\n.message {\n    margin: 8px 0;\n    padding: 8px;\n    border-radius: 4px;\n}\n.user-message {\n    background: #e9ecef;\n    margin-left: 20px;\n}\n.bot-message {\n    background: #f8f9fa;\n    margin-right: 20px;\n}\n`\nAdd the JavaScript\nThen, add the following JavaScript code (which uses the Gradio JavaScript Client to connect to the Space) to your website by including this in the  section of your website:\n`html\n    import { Client } from \"https://cdn.jsdelivr.net/npm/@gradio/client/dist/index.min.js\";\n    \n    async function initChatWidget() {\n        const client = await Client.connect(\"https://abidlabs-gradio-playground-bot.hf.space\");\n        \n        const chatToggle = document.getElementById('chat-toggle');\n        const chatContainer = document.getElementById('chat-container');\n        const closeChat = document.getElementById('close-chat');\n        const chatInput = document.getElementById('chat-input');\n        const sendButton = document.getElementById('send-message');\n        const messagesContainer = document.getElementById('chat-messages');\n    \n        chatToggle.addEventListener('click', () => {\n            chatContainer.classList.remove('hidden');\n        });\n    \n        closeChat.addEventListener('click', () => {\n            chatContainer.classList.add('hidden');\n        });\n    \n        async function sendMessage() {\n            const userMessage = chatInput.value.trim();\n            if (!userMessage) return;\n            appendMessage(userMessage, 'user');\n            chatInput.value = '';\n            try {\n                const result = await client.predict(\"/chat\", {\n                    message: {\"text\": userMessage, \"files\": []}\n                });\n                const message = result.data[0];\n                console.log(result.data[0]);\n                const botMessage = result.data[0].join('\\n');\n                appendMessage(botMessage, 'bot');\n            } catch (error) {\n                console.error('Error:', error);\n                appendMessage('Sorry, there was an error processing your request.', 'bot');\n            }\n        }\n    \n        function appendMessage(text, sender) {\n            const messageDiv = document.createElement('div');\n            messageDiv.className = message ${sender}-message;\n            \n            if (sender === 'bot') {\n                messageDiv.innerHTML = marked.parse(text);\n            } else {\n                messageDiv.textContent = text;\n            }\n            \n            messagesContainer.appendChild(messageDiv);\n            messagesContainer.scrollTop = messagesContainer.scrollHeight;\n        }\n    \n        sendButton.addEventListener('click', sendMessage);\n        chatInput.addEventListener('keypress', (e) => {\n            if (e.key === 'Enter') sendMessage();\n        });\n    }\n    \n    initChatWidget();\n``\nThat's it!\nYour website now has a chat widget that connects to your Gradio app! Users can click the chat button to open the widget and start interacting with your app.\nCustomization\nYou can customize the appearance of the widget by modifying the CSS. Some ideas:\nChange the colors to match your website's theme\nAdjust the size and position of the widget\nAdd animations for opening/closing\nModify the message styling\nIf you build a website widget from a Gradio app, feel free to share it on X and tag the Gradio account, and we are happy to help you amplify!","type":"GUIDE"},{"title":"Creating Plots","slug":"/guides/creating-plots/","content":"Creating Plots\nGradio is a great way to create extremely customizable dashboards. Gradio comes with three native Plot components: gr.LinePlot, gr.ScatterPlot and gr.BarPlot. All these plots have the same API. Let's take a look how to set them up.\nCreating a Plot with a pd.Dataframe\nPlots 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:\n``python\nimport gradio as gr\nimport pandas as pd\nimport numpy as np\nimport random\ndf = pd.DataFrame({\n    'height': np.random.randint(50, 70, 25),\n    'weight': np.random.randint(120, 320, 25),\n    'age': np.random.randint(18, 65, 25),\n    'ethnicity': [random.choice([\"white\", \"black\", \"asian\"]) for _ in range(25)]\n})\nwith gr.Blocks() as demo:\n    gr.LinePlot(df, x=\"weight\", y=\"height\")\ndemo.launch()\n`\nAll plots have the same API, so you could swap this out with a gr.ScatterPlot:\n`python\nimport gradio as gr\nfrom data import df  \nwith gr.Blocks() as demo:\n    gr.ScatterPlot(df, x=\"weight\", y=\"height\")\ndemo.launch()\n`\nThe 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.\n`python\nimport gradio as gr\nfrom data import df  \nwith gr.Blocks() as demo:\n    gr.ScatterPlot(df, x=\"ethnicity\", y=\"height\")\ndemo.launch()\n`\nBreaking out Series by Color\nYou can break out your plot into series using the color argument.\n`python\nimport gradio as gr\nfrom data import df  \nwith gr.Blocks() as demo:\n    gr.ScatterPlot(df, x=\"weight\", y=\"height\", color=\"ethnicity\")\ndemo.launch()\n`\nIf you wish to assign series specific colors, use the colormap arg, e.g. gr.ScatterPlot(..., colormap={'white': '#FF9988', 'asian': '#88EEAA', 'black': '#333388'})\nThe color column can be numeric type as well.\n`python\nimport gradio as gr\nfrom data import df  \nwith gr.Blocks() as demo:\n    gr.ScatterPlot(df, x=\"weight\", y=\"height\", color=\"age\")\ndemo.launch()\n`\nAggregating Values\nYou can aggregate values into groups using the xbin and yaggregate arguments. If your x-axis is numeric, providing an x_bin will create a histogram-style binning:\n`python\nimport gradio as gr\nfrom data import df  \nwith gr.Blocks() as demo:\n    gr.BarPlot(df, x=\"weight\", y=\"height\", xbin=10, yaggregate=\"sum\")\ndemo.launch()\n`\nIf your x-axis is a string type instead, they will act as the category bins automatically:\n`python\nimport gradio as gr\nfrom data import df  \nwith gr.Blocks() as demo:\n    gr.BarPlot(df, x=\"ethnicity\", y=\"height\", y_aggregate=\"mean\")\ndemo.launch()\n`\nSelecting Regions\nYou can use the .select listener to select regions of a plot. Click and drag on the plot below to select part of the plot.\n`python\nimport gradio as gr\nfrom data import df  \nwith gr.Blocks() as demo:\n    plt = gr.LinePlot(df, x=\"weight\", y=\"height\")\n    selection_total = gr.Number(label=\"Total Weight of Selection\")\n    def select_region(selection: gr.SelectData):\n        minw, maxw = selection.index\n        return df[(df[\"weight\"] >= min_w) & (df[\"weight\"] \nYou can combine this and the .doubleclick listener to create some zoom in/out effects by changing xlim which sets the bounds of the x-axis:\n`python\nimport gradio as gr\nfrom data import df  \nwith gr.Blocks() as demo:\n    plt = gr.LinePlot(df, x=\"weight\", y=\"height\")\n    def select_region(selection: gr.SelectData):\n        minw, maxw = selection.index\n        return gr.LinePlot(xlim=(minw, max_w)) \n    plt.select(select_region, None, plt)\n    plt.doubleclick(lambda: gr.LinePlot(xlim=None), None, plt)\ndemo.launch()\n`\nIf 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.\n`python\nimport gradio as gr\nfrom data import df  \nwith gr.Blocks() as demo:\n    plt1 = gr.LinePlot(df, x=\"weight\", y=\"height\")\n    plt2 = gr.BarPlot(df, x=\"weight\", y=\"age\", x_bin=10)\n    plots = [plt1, plt2]\n    def select_region(selection: gr.SelectData):\n        minw, maxw = selection.index\n        return [gr.LinePlot(xlim=(minw, max_w))] * len(plots) \n    for plt in plots:\n        plt.select(select_region, None, plots)\n        plt.doubleclick(lambda: [gr.LinePlot(xlim=None)] * len(plots), None, plots)\ndemo.launch()\n`\nMaking an Interactive Dashboard\nTake a look how you can have an interactive dashboard where the plots are functions of other Components.\n``python\nimport gradio as gr\nfrom data import df  \nwith gr.Blocks() as demo:\n    with gr.Row():\n        ethnicity = gr.Dropdown([\"all\", \"white\", \"black\", \"asian\"], value=\"all\")\n        max_age = gr.Slider(18, 65, value=65)\n    def filtered_df(ethnic, age):\n        _df = df if ethnic == \"all\" else df[df[\"ethnicity\"] == ethnic]\n        df = df[_df[\"age\"] \nIt's that simple to filter and control the data presented in your visualization!","type":"GUIDE"},{"title":"Css Variables Reference","slug":"/guides/css-variables-reference/","content":"CSS Variables Reference\nThis page lists all available CSS variables that can be set via the .set() method on a Gradio theme, organized by category. The CSS Variable column shows the variable name as used in CSS (e.g. in custom stylesheets), while the Default column shows the value set by the Base theme.\nFor more information on how to use these variables, see the Theming Guide.\nBody Attributes\n| CSS Variable | Description | Default |\n| --- | --- | --- |\n| --body-background-fill | The background of the entire app. | *backgroundfillprimary |\n| --body-background-fill-dark | The background of the entire app in dark mode. | *backgroundfillprimary |\n| --body-text-color | The default text color. | *neutral_800 |\n| --body-text-color-dark | The default text color in dark mode. | *neutral_100 |\n| --body-text-size | The default text size. | *text_md |\n| --body-text-color-subdued | The text color used for softer, less important text. | *neutral_400 |\n| --body-text-color-subdued-dark | The text color used for softer, less important text in dark mode. | *neutral_400 |\n| --body-text-weight | The default text weight. | 400 |\n| --embed-radius | The corner radius used for embedding when the app is embedded within a page. | *radius_sm |\nElement Colors\n| CSS Variable | Description | Default |\n| --- | --- | --- |\n| --background-fill-primary | The background primarily used for items placed directly on the page. | white |\n| --background-fill-primary-dark | The background primarily used for items placed directly on the page in dark mode. | *neutral_950 |\n| --background-fill-secondary | The background primarily used for items placed on top of another item. | *neutral_50 |\n| --background-fill-secondary-dark | The background primarily used for items placed on top of another item in dark mode. | *neutral_900 |\n| --border-color-accent | The border color used for accented items. | *primary_300 |\n| --border-color-accent-dark | The border color used for accented items in dark mode. | *neutral_600 |\n| --border-color-accent-subdued | The subdued border color for accented items. | *bordercoloraccent |\n| --border-color-accent-subdued-dark | The subdued border color for accented items in dark mode. | *bordercoloraccent |\n| --border-color-primary | The border color primarily used for items placed directly on the page. | *neutral_200 |\n| --border-color-primary-dark | The border color primarily used for items placed directly on the page in dark mode. | *neutral_700 |\n| --color-accent | The color used for accented items. | *primary_500 |\n| --color-accent-soft | The softer color used for accented items. | *primary_50 |\n| --color-accent-soft-dark | The softer color used for accented items in dark mode. | *neutral_700 |\n| --link-text-color | The text color used for links. | *secondary_600 |\n| --link-text-color-dark | The text color used for links in dark mode. | *secondary_500 |\n| --link-text-color-active | The text color used for links when they are active. | *secondary_600 |\n| --link-text-color-active-dark | The text color used for links when they are active in dark mode. | *secondary_500 |\n| --link-text-color-hover | The text color used for links when they are hovered over. | *secondary_700 |\n| --link-text-color-hover-dark | The text color used for links when they are hovered over in dark mode. | *secondary_400 |\n| --link-text-color-visited | The text color used for links when they have been visited. | *secondary_500 |\n| --link-text-color-visited-dark | The text color used for links when they have been visited in dark mode. | *secondary_600 |\n| --prose-text-size | The text size used for markdown and other prose. | *text_md |\n| --prose-text-weight | The text weight used for markdown and other prose. | 400 |\n| --prose-header-text-weight | The text weight of a header used for markdown and other prose. | 600 |\n| --code-background-fill | The background color of code blocks. | *neutral_100 |\n| --code-background-fill-dark | The background color of code blocks in dark mode. | *neutral_800 |\nShadows\n| CSS Variable | Description | Default |\n| --- | --- | --- |\n| --shadow-drop | Drop shadow used by other shadowed items. | rgba(0,0,0,0.05) 0px 1px 2px 0px |\n| --shadow-drop-lg | Larger drop shadow used by other shadowed items. | 0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1) |\n| --shadow-inset | Inset shadow used by other shadowed items. | rgba(0,0,0,0.05) 0px 2px 4px 0px inset |\n| --shadow-spread | Size of shadow spread used by shadowed items. | 3px |\n| --shadow-spread-dark | Size of shadow spread used by shadowed items in dark mode. | 1px |\nLayout Atoms\n| CSS Variable | Description | Default |\n| --- | --- | --- |\n| --block-background-fill | The background around an item. | *backgroundfillprimary |\n| --block-background-fill-dark | The background around an item in dark mode. | *neutral_800 |\n| --block-border-color | The border color around an item. | *bordercolorprimary |\n| --block-border-color-dark | The border color around an item in dark mode. | *bordercolorprimary |\n| --block-border-width | The border width around an item. | 1px |\n| --block-border-width-dark | The border width around an item in dark mode. |  |\n| --block-info-text-color | The color of the info text. | *bodytextcolor_subdued |\n| --block-info-text-color-dark | The color of the info text in dark mode. | *bodytextcolor_subdued |\n| --block-info-text-size | The size of the info text. | *text_sm |\n| --block-info-text-weight | The weight of the info text. | 400 |\n| --block-label-background-fill | The background of the title label of a media element (e.g. image). | *backgroundfillprimary |\n| --block-label-background-fill-dark | The background of the title label of a media element (e.g. image) in dark mode. | *backgroundfillsecondary |\n| --block-label-border-color | The border color of the title label of a media element (e.g. image). | *bordercolorprimary |\n| --block-label-border-color-dark | The border color of the title label of a media element (e.g. image) in dark mode. | *bordercolorprimary |\n| --block-label-border-width | The border width of the title label of a media element (e.g. image). | 1px |\n| --block-label-border-width-dark | The border width of the title label of a media element (e.g. image) in dark mode. |  |\n| --block-label-shadow | The shadow of the title label of a media element (e.g. image). | *block_shadow |\n| --block-label-text-color | The text color of the title label of a media element (e.g. image). | *neutral_500 |\n| --block-label-text-color-dark | The text color of the title label of a media element (e.g. image) in dark mode. | *neutral_200 |\n| --block-label-margin | The margin of the title label of a media element (e.g. image) from its surrounding container. | 0 |\n| --block-label-padding | The padding of the title label of a media element (e.g. image). | spacing_sm spacing_lg |\n| --block-label-radius | The corner radius of the title label of a media element (e.g. image). | calc(radius_sm - 1px) 0 calc(radius_sm - 1px) 0 |\n| --block-label-right-radius | The corner radius of a right-aligned helper label. | 0 calc(radius_sm - 1px) 0 calc(radius_sm - 1px) |\n| --block-label-text-size | The text size of the title label of a media element (e.g. image). | *text_sm |\n| --block-label-text-weight | The text weight of the title label of a media element (e.g. image). | 400 |\n| --block-padding | The padding around an item. | spacing_xl calc(spacing_xl + 2px) |\n| --block-radius | The corner radius around an item. | *radius_sm |\n| --block-shadow | The shadow under an item. | none |\n| --block-shadow-dark | The shadow under an item in dark mode. |  |\n| --block-title-background-fill | The background of the title of a form element (e.g. textbox). | none |\n| --block-title-background-fill-dark | The background of the title of a form element (e.g. textbox) in dark mode. |  |\n| --block-title-border-color | The border color of the title of a form element (e.g. textbox). | none |\n| --block-title-border-color-dark | The border color of the title of a form element (e.g. textbox) in dark mode. |  |\n| --block-title-border-width | The border width of the title of a form element (e.g. textbox). | 0px |\n| --block-title-border-width-dark | The border width of the title of a form element (e.g. textbox) in dark mode. |  |\n| --block-title-text-color | The text color of the title of a form element (e.g. textbox). | *neutral_500 |\n| --block-title-text-color-dark | The text color of the title of a form element (e.g. textbox) in dark mode. | *neutral_200 |\n| --block-title-padding | The padding of the title of a form element (e.g. textbox). | 0 |\n| --block-title-radius | The corner radius of the title of a form element (e.g. textbox). | none |\n| --block-title-text-size | The text size of the title of a form element (e.g. textbox). | *text_md |\n| --block-title-text-weight | The text weight of the title of a form element (e.g. textbox). | 400 |\n| --container-radius | The corner radius of a layout component that holds other content. | *radius_sm |\n| --form-gap-width | The border gap between form elements, (e.g. consecutive textboxes). | 0px |\n| --layout-gap | The gap between items within a row or column. | *spacing_xxl |\n| --panel-background-fill | The background of a panel. | *backgroundfillsecondary |\n| --panel-background-fill-dark | The background of a panel in dark mode. | *backgroundfillsecondary |\n| --panel-border-color | The border color of a panel. | *bordercolorprimary |\n| --panel-border-color-dark | The border color of a panel in dark mode. | *bordercolorprimary |\n| --panel-border-width | The border width of a panel. | 0 |\n| --panel-border-width-dark | The border width of a panel in dark mode. |  |\n| --section-header-text-size | The text size of a section header (e.g. tab name). | *text_md |\n| --section-header-text-weight | The text weight of a section header (e.g. tab name). | 400 |\nComponent Atoms\n| CSS Variable | Description | Default |\n| --- | --- | --- |\n| --accordion-text-color | The body text color in the accordion. | *bodytextcolor |\n| --accordion-text-color-dark | The body text color in the accordion in dark mode. | *bodytextcolor |\n| --table-text-color | The body text color in the table. | *bodytextcolor |\n| --table-text-color-dark | The body text color in the table in dark mode. | *bodytextcolor |\n| --checkbox-background-color | The background of a checkbox square or radio circle. | *backgroundfillprimary |\n| --chatbot-text-size | The text size of the chatbot text. | *text_lg |\n| --checkbox-background-color-dark | The background of a checkbox square or radio circle in dark mode. | *neutral_800 |\n| --checkbox-background-color-focus | The background of a checkbox square or radio circle when focused. | *checkboxbackgroundcolor |\n| --checkbox-background-color-focus-dark | The background of a checkbox square or radio circle when focused in dark mode. | *checkboxbackgroundcolor |\n| --checkbox-background-color-hover | The background of a checkbox square or radio circle when hovered over. | *checkboxbackgroundcolor |\n| --checkbox-background-color-hover-dark | The background of a checkbox square or radio circle when hovered over in dark mode. | *checkboxbackgroundcolor |\n| --checkbox-background-color-selected | The background of a checkbox square or radio circle when selected. | *color_accent |\n| --checkbox-background-color-selected-dark | The background of a checkbox square or radio circle when selected in dark mode. | *color_accent |\n| --checkbox-border-color | The border color of a checkbox square or radio circle. | *neutral_300 |\n| --checkbox-border-color-dark | The border color of a checkbox square or radio circle in dark mode. | *neutral_700 |\n| --checkbox-border-color-focus | The border color of a checkbox square or radio circle when focused. | *color_accent |\n| --checkbox-border-color-focus-dark | The border color of a checkbox square or radio circle when focused in dark mode. | *color_accent |\n| --checkbox-border-color-hover | The border color of a checkbox square or radio circle when hovered over. | *neutral_300 |\n| --checkbox-border-color-hover-dark | The border color of a checkbox square or radio circle when hovered over in dark mode. | *neutral_600 |\n| --checkbox-border-color-selected | The border color of a checkbox square or radio circle when selected. | *color_accent |\n| --checkbox-border-color-selected-dark | The border color of a checkbox square or radio circle when selected in dark mode. | *color_accent |\n| --checkbox-border-radius | The corner radius of a checkbox square. | *radius_sm |\n| --checkbox-border-width | The border width of a checkbox square or radio circle. | *inputborderwidth |\n| --checkbox-border-width-dark | The border width of a checkbox square or radio circle in dark mode. | *inputborderwidth |\n| --checkbox-check | The checkmark visual of a checkbox square. | url(\"data:image/svg+xml,%3csvg viewBox='0 0 16 16' fill='white' xmlns='http://www.w3.org/2000/svg'%3e%3cpath d='M12.207 4.793a1 1 0 010 1.414l-5 5a1 1 0 01-1.414 0l-2-2a1 1 0 011.414-1.414L6.5 9.086l4.293-4.293a1 1 0 011.414 0z'/%3e%3c/svg%3e\") |\n| --radio-circle | The circle visual of a radio circle. | url(\"data:image/svg+xml,%3csvg viewBox='0 0 16 16' fill='white' xmlns='http://www.w3.org/2000/svg'%3e%3ccircle cx='8' cy='8' r='3'/%3e%3c/svg%3e\") |\n| --checkbox-shadow | The shadow of a checkbox square or radio circle. | *input_shadow |\n| --checkbox-label-background-fill | The background of the surrounding button of a checkbox or radio element. | *buttonsecondarybackground_fill |\n| --checkbox-label-background-fill-dark | The background of the surrounding button of a checkbox or radio element in dark mode. | *buttonsecondarybackground_fill |\n| --checkbox-label-background-fill-hover | The background of the surrounding button of a checkbox or radio element when hovered over. | *buttonsecondarybackgroundfillhover |\n| --checkbox-label-background-fill-hover-dark | The background of the surrounding button of a checkbox or radio element when hovered over in dark mode. | *buttonsecondarybackgroundfillhover |\n| --checkbox-label-background-fill-selected | The background of the surrounding button of a checkbox or radio element when selected. | *checkboxlabelbackground_fill |\n| --checkbox-label-background-fill-selected-dark | The background of the surrounding button of a checkbox or radio element when selected in dark mode. | *checkboxlabelbackground_fill |\n| --checkbox-label-border-color | The border color of the surrounding button of a checkbox or radio element. | *bordercolorprimary |\n| --checkbox-label-border-color-dark | The border color of the surrounding button of a checkbox or radio element in dark mode. | *bordercolorprimary |\n| --checkbox-label-border-color-hover | The border color of the surrounding button of a checkbox or radio element when hovered over. | *checkboxlabelborder_color |\n| --checkbox-label-border-color-hover-dark | The border color of the surrounding button of a checkbox or radio element when hovered over in dark mode. | *checkboxlabelborder_color |\n| --checkbox-label-border-color-selected | The border color of the surrounding button of a checkbox or radio element when selected. | *checkboxlabelborder_color |\n| --checkbox-label-border-color-selected-dark | The border color of the surrounding button of a checkbox or radio element when selected in dark mode. | *checkboxlabelborder_color |\n| --checkbox-label-border-width | The border width of the surrounding button of a checkbox or radio element. | *inputborderwidth |\n| --checkbox-label-border-width-dark | The border width of the surrounding button of a checkbox or radio element in dark mode. | *inputborderwidth |\n| --checkbox-label-gap | The gap consecutive checkbox or radio elements. | *spacing_lg |\n| --checkbox-label-padding | The padding of the surrounding button of a checkbox or radio element. | spacing_md calc(2  *spacing_md) |\n| --checkbox-label-shadow | The shadow of the surrounding button of a checkbox or radio element. | none |\n| --checkbox-label-shadow-dark | The shadow of the surrounding button of a checkbox or radio element in dark mode. |  |\n| --checkbox-label-shadow-hover | The shadow of the surrounding button of a checkbox or radio element on hover. | *checkboxlabelshadow |\n| --checkbox-label-shadow-hover-dark |  |  |\n| --checkbox-label-shadow-active | The shadow of the surrounding button of a checkbox or radio element when active. | *checkboxlabelshadow |\n| --checkbox-label-shadow-active-dark |  |  |\n| --checkbox-label-text-size | The text size of the label accompanying a checkbox or radio element. | *text_md |\n| --checkbox-label-text-weight | The text weight of the label accompanying a checkbox or radio element. | 400 |\n| --checkbox-label-text-color | The text color of the label accompanying a checkbox or radio element. | *bodytextcolor |\n| --checkbox-label-text-color-dark | The text color of the label accompanying a checkbox or radio element in dark mode. | *bodytextcolor |\n| --checkbox-label-text-color-selected | The text color of the label accompanying a checkbox or radio element when selected. | *checkboxlabeltext_color |\n| --checkbox-label-text-color-selected-dark | The text color of the label accompanying a checkbox or radio element when selected in dark mode. | *checkboxlabeltext_color |\n| --error-background-fill | The background of an error message. | #fef2f2 |\n| --error-background-fill-dark | The background of an error message in dark mode. | *backgroundfillprimary |\n| --error-border-color | The border color of an error message. | #b91c1c |\n| --error-border-color-dark | The border color of an error message in dark mode. | #ef4444 |\n| --error-border-width | The border width of an error message. | 1px |\n| --error-border-width-dark | The border width of an error message in dark mode. |  |\n| --error-text-color | The text color of an error message. | #b91c1c |\n| --error-text-color-dark | The text color of an error message in dark mode. | #fef2f2 |\n| --error-icon-color |  | #b91c1c |\n| --error-icon-color-dark |  | #ef4444 |\n| --input-background-fill | The background of an input field. | *neutral_100 |\n| --input-background-fill-dark | The background of an input field in dark mode. | *neutral_700 |\n| --input-background-fill-focus | The background of an input field when focused. | *inputbackgroundfill |\n| --input-background-fill-focus-dark | The background of an input field when focused in dark mode. |  |\n| --input-background-fill-hover | The background of an input field when hovered over. | *inputbackgroundfill |\n| --input-background-fill-hover-dark | The background of an input field when hovered over in dark mode. | *inputbackgroundfill |\n| --input-border-color | The border color of an input field. | *bordercolorprimary |\n| --input-border-color-dark | The border color of an input field in dark mode. | *bordercolorprimary |\n| --input-border-color-focus | The border color of an input field when focused. | *secondary_300 |\n| --input-border-color-focus-dark | The border color of an input field when focused in dark mode. | *neutral_700 |\n| --input-border-color-hover | The border color of an input field when hovered over. | *inputbordercolor |\n| --input-border-color-hover-dark | The border color of an input field when hovered over in dark mode. | *inputbordercolor |\n| --input-border-width | The border width of an input field. | 0px |\n| --input-border-width-dark | The border width of an input field in dark mode. |  |\n| --input-padding | The padding of an input field. | *spacing_xl |\n| --input-placeholder-color | The placeholder text color of an input field. | *neutral_400 |\n| --input-placeholder-color-dark | The placeholder text color of an input field in dark mode. | *neutral_500 |\n| --input-radius | The corner radius of an input field. | *radius_sm |\n| --input-shadow | The shadow of an input field. | none |\n| --input-shadow-dark | The shadow of an input field in dark mode. |  |\n| --input-shadow-focus | The shadow of an input field when focused. | *input_shadow |\n| --input-shadow-focus-dark | The shadow of an input field when focused in dark mode. |  |\n| --input-text-size | The text size of an input field. | *text_md |\n| --input-text-weight | The text weight of an input field. | 400 |\n| --loader-color | The color of the loading animation while a request is pending. | *color_accent |\n| --loader-color-dark | The color of the loading animation while a request is pending in dark mode. |  |\n| --slider-color | The color of the slider in a range element. | *color_accent |\n| --slider-color-dark | The color of the slider in a range element in dark mode. |  |\n| --stat-background-fill | The background used for stats visuals (e.g. confidence bars in label). | *primary_300 |\n| --stat-background-fill-dark | The background used for stats visuals (e.g. confidence bars in label) in dark mode. | *primary_500 |\n| --table-border-color | The border color of a table. | *neutral_300 |\n| --table-border-color-dark | The border color of a table in dark mode. | *neutral_700 |\n| --table-even-background-fill | The background of even rows in a table. | white |\n| --table-even-background-fill-dark | The background of even rows in a table in dark mode. | *neutral_950 |\n| --table-odd-background-fill | The background of odd rows in a table. | *neutral_50 |\n| --table-odd-background-fill-dark | The background of odd rows in a table in dark mode. | *neutral_900 |\n| --table-radius | The corner radius of a table. | *radius_sm |\n| --table-row-focus | The background of a focused row in a table. | *coloraccentsoft |\n| --table-row-focus-dark | The background of a focused row in a table in dark mode. | *coloraccentsoft |\nButtons\n| CSS Variable | Description | Default |\n| --- | --- | --- |\n| --button-border-width | The border width of a button. | *inputborderwidth |\n| --button-border-width-dark | The border width of a button in dark mode. |  |\n| --button-transform-hover | The transform animation of a button on hover. | none |\n| --button-transform-active | The transform animation of a button when pressed. | none |\n| --button-transition | The transition animation duration of a button between regular, hover, and focused states. | all 0.2s ease |\n| --button-large-padding | The padding of a button with the default \"large\" size. | spacing_lg calc(2  *spacing_lg) |\n| --button-large-radius | The corner radius of a button with the default \"large\" size. | *radius_md |\n| --button-large-text-size | The text size of a button with the default \"large\" size. | *text_lg |\n| --button-large-text-weight | The text weight of a button with the default \"large\" size. | 600 |\n| --button-small-padding | The padding of a button set to \"small\" size. | spacing_sm calc(1.5  *spacing_sm) |\n| --button-small-radius | The corner radius of a button set to \"small\" size. | *radius_md |\n| --button-small-text-size | The text size of a button set to \"small\" size. | *text_sm |\n| --button-small-text-weight | The text weight of a button set to \"small\" size. | 400 |\n| --button-medium-padding | The padding of a button set to \"medium\" size. | spacing_md calc(2  *spacing_md) |\n| --button-medium-radius | The corner radius of a button set to \"medium\" size. | *radius_md |\n| --button-medium-text-size | The text size of a button set to \"medium\" size. | *text_md |\n| --button-medium-text-weight | The text weight of a button set to \"medium\" size. | 600 |\n| --button-primary-background-fill | The background of a button of \"primary\" variant. | *primary_500 |\n| --button-primary-background-fill-dark | The background of a button of \"primary\" variant in dark mode. | *primary_600 |\n| --button-primary-background-fill-hover | The background of a button of \"primary\" variant when hovered over. | *primary_600 |\n| --button-primary-background-fill-hover-dark | The background of a button of \"primary\" variant when hovered over in dark mode. | *primary_700 |\n| --button-primary-border-color | The border color of a button of \"primary\" variant. | *primary_500 |\n| --button-primary-border-color-dark | The border color of a button of \"primary\" variant in dark mode. | *primary_600 |\n| --button-primary-border-color-hover | The border color of a button of \"primary\" variant when hovered over. | *primary_500 |\n| --button-primary-border-color-hover-dark | The border color of a button of \"primary\" variant when hovered over in dark mode. | *primary_500 |\n| --button-primary-text-color | The text color of a button of \"primary\" variant. | white |\n| --button-primary-text-color-dark | The text color of a button of \"primary\" variant in dark mode. | white |\n| --button-primary-text-color-hover | The text color of a button of \"primary\" variant when hovered over. | *buttonprimarytext_color |\n| --button-primary-text-color-hover-dark | The text color of a button of \"primary\" variant when hovered over in dark mode. | *buttonprimarytext_color |\n| --button-primary-shadow | The shadow under a primary button. | none |\n| --button-primary-shadow-hover | The shadow under a primary button when hovered over. | *buttonprimaryshadow |\n| --button-primary-shadow-active | The shadow under a primary button when pressed. | *buttonprimaryshadow |\n| --button-primary-shadow-dark | The shadow under a primary button in dark mode. |  |\n| --button-primary-shadow-hover-dark | The shadow under a primary button when hovered over in dark mode. | *buttonprimaryshadow |\n| --button-primary-shadow-active-dark | The shadow under a primary button when pressed in dark mode. | *buttonprimaryshadow |\n| --button-secondary-background-fill | The background of a button of default \"secondary\" variant. | *neutral_200 |\n| --button-secondary-background-fill-dark | The background of a button of default \"secondary\" variant in dark mode. | *neutral_600 |\n| --button-secondary-background-fill-hover | The background of a button of default \"secondary\" variant when hovered over. | *neutral_300 |\n| --button-secondary-background-fill-hover-dark | The background of a button of default \"secondary\" variant when hovered over in dark mode. | *neutral_700 |\n| --button-secondary-border-color | The border color of a button of default \"secondary\" variant. | *neutral_200 |\n| --button-secondary-border-color-dark | The border color of a button of default \"secondary\" variant in dark mode. | *neutral_600 |\n| --button-secondary-border-color-hover | The border color of a button of default \"secondary\" variant when hovered over. | *neutral_200 |\n| --button-secondary-border-color-hover-dark | The border color of a button of default \"secondary\" variant when hovered over in dark mode. | *neutral_500 |\n| --button-secondary-text-color | The text color of a button of default \"secondary\" variant. | black |\n| --button-secondary-text-color-dark | The text color of a button of default \"secondary\" variant in dark mode. | white |\n| --button-secondary-text-color-hover | The text color of a button of default \"secondary\" variant when hovered over. | *buttonsecondarytext_color |\n| --button-secondary-text-color-hover-dark | The text color of a button of default \"secondary\" variant when hovered over in dark mode. | *buttonsecondarytext_color |\n| --button-secondary-shadow | The shadow under a secondary button. | *buttonprimaryshadow |\n| --button-secondary-shadow-hover | The shadow under a secondary button when hovered over. | *buttonsecondaryshadow |\n| --button-secondary-shadow-active | The shadow under a secondary button when pressed. | *buttonsecondaryshadow |\n| --button-secondary-shadow-dark | The shadow under a secondary button in dark mode. |  |\n| --button-secondary-shadow-hover-dark | The shadow under a secondary button when hovered over in dark mode. | *buttonsecondaryshadow |\n| --button-secondary-shadow-active-dark | The shadow under a secondary button when pressed in dark mode. | *buttonsecondaryshadow |\n| --button-cancel-background-fill | The background of a button of \"cancel\" variant. | *buttonsecondarybackground_fill |\n| --button-cancel-background-fill-dark | The background of a button of \"cancel\" variant in dark mode. | *buttonsecondarybackground_fill |\n| --button-cancel-background-fill-hover | The background of a button of \"cancel\" variant when hovered over. | *buttonsecondarybackgroundfillhover |\n| --button-cancel-background-fill-hover-dark | The background of a button of \"cancel\" variant when hovered over in dark mode. | *buttonsecondarybackgroundfillhover |\n| --button-cancel-border-color | The border color of a button of \"cancel\" variant. | *buttonsecondaryborder_color |\n| --button-cancel-border-color-dark | The border color of a button of \"cancel\" variant in dark mode. | *buttonsecondaryborder_color |\n| --button-cancel-border-color-hover | The border color of a button of \"cancel\" variant when hovered over. | *buttonsecondarybordercolorhover |\n| --button-cancel-border-color-hover-dark | The border color of a button of \"cancel\" variant when hovered over in dark mode. | *buttonsecondarybordercolorhover |\n| --button-cancel-text-color | The text color of a button of \"cancel\" variant. | *buttonsecondarytext_color |\n| --button-cancel-text-color-dark | The text color of a button of \"cancel\" variant in dark mode. | *buttonsecondarytext_color |\n| --button-cancel-text-color-hover | The text color of a button of \"cancel\" variant when hovered over. | *buttonsecondarytextcolorhover |\n| --button-cancel-text-color-hover-dark | The text color of a button of \"cancel\" variant when hovered over in dark mode. | white |\n| --button-cancel-shadow | The shadow under a button of \"cancel\" variant. | *buttonsecondaryshadow |\n| --button-cancel-shadow-hover | The shadow under a button of \"cancel\" variant when hovered over. | *buttonsecondaryshadow_hover |\n| --button-cancel-shadow-active | The shadow under a button of \"cancel\" variant when pressed. | *buttonsecondaryshadow_active |\n| --button-cancel-shadow-dark | The shadow under a button of \"cancel\" variant in dark mode. | *buttonsecondaryshadow |\n| --button-cancel-shadow-hover-dark | The shadow under a button of \"cancel\" variant when hovered over in dark mode. | *buttonsecondaryshadow_hover |\n| --button-cancel-shadow-active-dark | The shadow under a button of \"cancel\" variant when pressed in dark mode. | *buttonsecondaryshadow_active |","type":"GUIDE"},{"title":"Custom CSS And JS","slug":"/guides/custom-CSS-and-JS/","content":"Customizing your demo with CSS and Javascript\nGradio allows you to customize your demo in several ways. You can customize the layout of your demo, add custom HTML, and add custom theming as well. This tutorial will go beyond that and walk you through how to add custom CSS and JavaScript code to your demo in order to add custom styling, animations, custom UI functionality, analytics, and more.\nAdding custom CSS to your demo\nGradio themes are the easiest way to customize the look and feel of your app. You can choose from a variety of themes, or create your own. To do so, pass the theme= kwarg to the launch() method of the Blocks constructor. For example:\n``python\nwith gr.Blocks() as demo:\n    ... # your code here\ndemo.launch(theme=gr.themes.Glass())\n    ...\n`\nGradio comes with a set of prebuilt themes which you can load from gr.themes.*. You can extend these themes or create your own themes from scratch - see the Theming guide for more details.\nFor additional styling ability, you can pass any CSS to your app as a string using the css= kwarg in the launch() method. You can also pass a pathlib.Path to a css file or a list of such paths to the css_paths= kwarg in the launch() method.\nWarning: The use of query selectors in custom JS and CSS is not guaranteed to work across Gradio versions that bind to Gradio's own HTML elements as the Gradio HTML DOM may change. We recommend using query selectors sparingly.\nThe base class for the Gradio app is gradio-container, so here's an example that changes the background color of the Gradio app:\n`python\nwith gr.Blocks() as demo:\n    ... # your code here\ndemo.launch(css=\".gradio-container {background-color: red}\")\n    ...\n`\nIf you'd like to reference external files in your css, preface the file path (which can be a relative or absolute path) with \"/gradio_api/file=\", for example:\n`python\nwith gr.Blocks() as demo:\n    ... # your code here\ndemo.launch(css=\".gradio-container {background: url('/gradio_api/file=clouds.jpg')}\")\n    ...\n`\nNote: By default, most files in the host machine are not accessible to users running the Gradio app. As a result, you should make sure that any referenced files (such as clouds.jpg here) are either URLs or allowed paths, as described here.\nThe elemid and elemclasses Arguments\nYou can elemid to add an HTML element id to any component, and elemclasses to add a class or list of classes. This will allow you to select elements more easily with CSS. This approach is also more likely to be stable across Gradio versions as built-in class names or ids may change (however, as mentioned in the warning above, we cannot guarantee complete compatibility between Gradio versions if you use custom CSS as the DOM elements may themselves change).\n`python\ncss = \"\"\"\n#warning {background-color: #FFCCCB}\n.feedback textarea {font-size: 24px !important}\n\"\"\"\nwith gr.Blocks() as demo:\n    box1 = gr.Textbox(value=\"Good Job\", elem_classes=\"feedback\")\n    box2 = gr.Textbox(value=\"Failure\", elemid=\"warning\", elemclasses=\"feedback\")\ndemo.launch(css=css)\n`\nThe CSS #warning ruleset will only target the second Textbox, while the .feedback ruleset will target both. Note that when targeting classes, you might need to put the !important selector to override the default Gradio styles.\nAdding custom JavaScript to your demo\nThere are 3 ways to add javascript code to your Gradio demo:\nYou can add JavaScript code as a string to the js parameter of the Blocks or Interface initializer. This will run the JavaScript code when the demo is first loaded.\nBelow is an example of adding custom js to show an animated welcome message when the demo first loads.\n`python\nimport gradio as gr\ndef welcome(name):\n    return f\"Welcome to Gradio, {name}!\"\njs = \"\"\"\nfunction createGradioAnimation() {\n    var container = document.createElement('div');\n    container.id = 'gradio-animation';\n    container.style.fontSize = '2em';\n    container.style.fontWeight = 'bold';\n    container.style.textAlign = 'center';\n    container.style.marginBottom = '20px';\n    var text = 'Welcome to Gradio!';\n    for (var i = 0; i \nWhen using Blocks and event listeners, events have a js argument that can take a JavaScript function as a string and treat it just like a Python event listener function. You can pass both a JavaScript function and a Python function (in which case the JavaScript function is run first) or only Javascript (and set the Python fn to None). Take a look at the code below:\n   \n`python\nimport gradio as gr\nblocks = gr.Blocks()\nwith blocks as demo:\n    subject = gr.Textbox(placeholder=\"subject\")\n    verb = gr.Radio([\"ate\", \"loved\", \"hated\"])\n    object = gr.Textbox(placeholder=\"object\")\n    with gr.Row():\n        btn = gr.Button(\"Create sentence.\")\n        reverse_btn = gr.Button(\"Reverse sentence.\")\n        foobarbtn = gr.Button(\"Append foo\")\n        reversethentotheserver_btn = gr.Button(\n            \"Reverse sentence and send to server.\"\n        )\n    def sentence_maker(w1, w2, w3):\n        return f\"{w1} {w2} {w3}\"\n    output1 = gr.Textbox(label=\"output 1\")\n    output2 = gr.Textbox(label=\"verb\")\n    output3 = gr.Textbox(label=\"verb reversed\")\n    output4 = gr.Textbox(label=\"front end process and then send to backend\")\n    btn.click(sentence_maker, [subject, verb, object], output1)\n    reverse_btn.click(\n        None, [subject, verb, object], output2, js=\"(s, v, o) => o + ' ' + v + ' ' + s\"\n    )\n    verb.change(None, verb, output3, js=\"(x) => [...x].reverse().join('')\")\n    foobarbtn.click(None, [], subject, js=\"(x) => x + ' foo'\")\n    reversethentotheserver_btn.click(\n        None,\n        [subject, verb, object],\n        output4,\n        js=\"(s, v, o) => [s, v, o].map(x => [...x].reverse().join('')).join(' ')\",\n    )\ndemo.launch()\n`\nLastly, you can add JavaScript code to the head param of the Blocks initializer. This will add the code to the head of the HTML document. For example, you can add Google Analytics to your demo like so:\n`python\nhead = f\"\"\"\n  window.dataLayer = window.dataLayer || [];\n  function gtag(){{dataLayer.push(arguments);}}\n  gtag('js', new Date());\n  gtag('config', '{googleanalyticstracking_id}');\n\"\"\"\nwith gr.Blocks() as demo:\n    gr.HTML(\"My App\")\ndemo.launch(head=head)\n`\nThe head parameter accepts any HTML tags you would normally insert into the  of a page. For example, you can also include  tags to head in order to update the social sharing preview for your Gradio app like this:\n`py\nimport gradio as gr\ncustom_head = \"\"\"\nSample App\n  \n\"\"\"\nwith gr.Blocks(title=\"My App\") as demo:\n    gr.HTML(\"My App\")\ndemo.launch(head=custom_head)\n`\nNote that injecting custom JS can affect browser behavior and accessibility (e.g. keyboard shortcuts may be lead to unexpected behavior if your Gradio app is embedded in another webpage). You should test your interface across different browsers and be mindful of how scripts may interact with browser defaults. Here's an example where pressing Shift + s triggers the click event of a specific Button component if the browser focus is not on an input component (e.g. Textbox component):\n`python\nimport gradio as gr\nshortcut_js = \"\"\"\nfunction shortcuts(e) {\n    var event = document.all ? window.event : e;\n    switch (e.target.tagName.toLowerCase()) {\n        case \"input\":\n        case \"textarea\":\n        break;\n        default:\n        if (e.key.toLowerCase() == \"s\" && e.shiftKey) {\n            document.getElementById(\"my_btn\").click();\n        }\n    }\n}\ndocument.addEventListener('keypress', shortcuts, false);\n\"\"\"\nwith gr.Blocks() as demo:\n    actionbutton = gr.Button(value=\"Name\", elemid=\"my_btn\")\n    textbox = gr.Textbox()\n    action_button.click(lambda : \"button pressed\", None, textbox)\n    \ndemo.launch(head=shortcut_js)\n``","type":"GUIDE"},{"title":"Custom HTML Components","slug":"/guides/custom-HTML-components/","content":"Custom Components with gr.HTML\nIf you wish to create custom HTML in your app, use the gr.HTML component. Here's a basic \"HTML-only\" example:\n``python\ngr.HTML(value=\"Hello World!\")\n`\nYou can also use html-templates to organize your HTML. Take a look at the example below:\n`python\ngr.HTML(value=\"John\", html_template\"Hello, {{value}}!${value.length} letters\")\n`\n\"John\" becomes value when injected into the template, resulting in:\n`html\nHello, John!4 letters\n`\nNotice how we support two types of templating syntaxes: ${} for custom JavaScript expressions, and {{}} for Handlebars templating. You can use either or both in your templates - ${} allows for completely custom JS logic, while Handlebars provides structured templating for loops and conditionals.\nLet's look at another example for displaying a list of items:\n`python\ngr.HTML(value=[\"apple\", \"banana\", \"cherry\"], html_templates=\"\"\"\n    ${value.length} fruits:\n    \n      {{#each value}}\n        {{this}}\n      {{/each}}\n    \n\"\"\")\n`\nBy default, the content of gr.HTML will have some CSS styles applied to match the Gradio theme. You can disable this with applydefaultcss=False. You can also provide your own CSS styles via the css_template argument as shown in the next example.\nLet's build a simple star rating component using gr.HTML, and then extend it with more features.\n`python\nimport gradio as gr\nwith gr.Blocks() as demo:\n    threestarrating = gr.HTML(\"\"\"\n        Star Rating:\n        \n        \n        \n        \n        \n    \"\"\", css_template=\"\"\"\n        img { height: 50px; display: inline-block; }\n        .faded { filter: grayscale(100%); opacity: 0.3; }\n    \"\"\")\ndemo.launch()\n`\nNote how we used the css_template argument to add custom CSS that styles the HTML inside the gr.HTML component.\nLet's see how the template automatically updates when we update the value.\n`python\nimport gradio as gr\nwith gr.Blocks() as demo:\n    star_rating = gr.HTML(\n        value=3,\n        html_template=\"\"\"\n        Star Rating:\n        ${Array.from({length: 5}, (_, i) => ).join('')}\"\"\", \n        css_template=\"\"\"\n            img { height: 50px; display: inline-block; }\n            .faded { filter: grayscale(100%); opacity: 0.3; }\n        \"\"\")\n    rating_slider = gr.Slider(0, 5, 3, step=1, label=\"Select Rating\")\n    ratingslider.change(fn=lambda x: x, inputs=ratingslider, outputs=star_rating)\ndemo.launch()\n`\nWe may wish to pass additional props beyond just value to the htmltemplate. Simply add these props to your templates and pass them as kwargs to the gr.HTML component. For example, lets add size and maxstars props to the star rating component.\n`python\nimport gradio as gr\nwith gr.Blocks() as demo:\n    star_rating = gr.HTML(\n        7, \n        size=40,\n        max_stars=10,\n        html_template=\"\"\"\n        Star Rating:\n        ${Array.from({length: maxstars}, (, i) => ).join('')}\"\"\", \n        css_template=\"\"\"\n            img { height: ${size}px; display: inline-block; }\n            .faded { filter: grayscale(100%); opacity: 0.3; }\n        \"\"\"\n    )\n    rating_slider = gr.Slider(0, 10, step=1, label=\"Select Rating\")\n    ratingslider.change(fn=lambda x: x, inputs=ratingslider, outputs=star_rating)\n    size_slider = gr.Slider(20, 100, 40, step=1, label=\"Select Size\")\n    sizeslider.change(fn=lambda x: gr.HTML(size=x), inputs=sizeslider, outputs=star_rating)\ndemo.launch()\n`\nNote how both htmltemplate and csstemplate can format these extra props. Note also how any of these props can be updated via Gradio event listeners.\nTriggering Events and Custom Input Components\nThe gr.HTML component can also be used to create custom input components by triggering events. You will provide jsonload, javascript code that runs when the component loads. The code has access to the trigger function to trigger events that Gradio can listen to, and the object props which has access to all the props of the component, including value.\n`python\nimport gradio as gr\nwith gr.Blocks() as demo:\n    star_rating = gr.HTML(\n        value=3, \n        html_template=\"\"\"\n        Star Rating:\n        ${Array.from({length: 5}, (_, i) => ).join('')}\n        Submit Rating\n        \"\"\", \n        css_template=\"\"\"\n            img { height: 50px; display: inline-block; cursor: pointer; }\n            .faded { filter: grayscale(100%); opacity: 0.3; }\n        \"\"\",\n        jsonload=\"\"\"\n            const imgs = element.querySelectorAll('img');\n            imgs.forEach((img, index) => {\n                img.addEventListener('click', () => {\n                    props.value = index + 1;\n                });\n            });\n            const submitBtn = element.querySelector('#submit-btn');\n            submitBtn.addEventListener('click', () => {\n                trigger('submit');\n            });\n        \"\"\")\n    rating_output = gr.Textbox(label=\"Submitted Rating\")\n    starrating.submit(lambda x: x, inputs=starrating, outputs=rating_output)\ndemo.launch()\n`\nTake a look at the jsonload code above. We add click event listeners to each star image to update the value via props.value when a star is clicked. This also re-renders the template to show the updated value. We also add a click event listener to the submit button that triggers the submit event. In our app, we listen to this trigger to run a function that outputs the value of the star rating.\nThe jsonload scope also includes an upload async function that lets you upload a JavaScript File object directly to the Gradio server. It returns a dictionary with path (the server-side file path) and url (the public URL to access the file).\n`js\nconst { path, url } = await upload(file);\n`\nHere is an example of a custom file-upload widget built with gr.HTML:\n`python\nimport gradio as gr\nfrom pathlib import Path\nwith gr.Blocks() as demo:\n    file_uploader = gr.HTML(\n        html_template=\"\"\"\n        \n            \n            Upload\n        \n        \"\"\",\n        jsonload=\"\"\"\n        const input = element.querySelector('#file-input');\n        const btn = element.querySelector('#upload-btn');\n        btn.addEventListener('click', async () => {\n            const file = input.files[0];\n            const { path } = await upload(file);\n            props.value = path;\n        });\n        \"\"\",\n        elemid=\"fileuploader\"\n    )\n    viewcontentbtn = gr.Button(\"View Uploaded File Content\")\n    upload_content = gr.Textbox(label=\"Uploaded File Content\")\n    viewcontentbtn.click(lambda path: Path(path).readtext(), fileuploader, upload_content)\ndemo.launch()\n`\nYou can update any other props of the component via props., and trigger events via trigger(''). The trigger event can also be send event data, e.g.\n`js\ntrigger('event_name', { key: value, count: 123 });\n`\nThis event data will be accessible the Python event listener functions via gr.EventData.\n`python\ndef handle_event(evt: gr.EventData):\n    print(evt.key)\n    print(evt.count)\nstarrating.event(fn=handleevent, inputs=[], outputs=[])\n`\nKeep in mind that event listeners attached in jsonload are only attached once when the component is first rendered. If your component creates new elements dynamically that need event listeners, attach the event listener to a parent element that exists when the component loads, and check for the target. For example:\n`js\nelement.addEventListener('click', (e) =>\n    if (e.target && e.target.matches('.child-element')) {\n        props.value = e.target.dataset.value;\n    }\n);\n`\nYou can trigger an event with any name. As long as the event name appears enclosed in quotes in your jsonload string, you can attach a Python listener using component.do_something(fn, ...).\nWatching Props with watch\nThe watch function, available inside jsonload, lets you run a callback whenever specific props change when the component is an output to a Python event listener. Read current values directly from props inside the callback.\n`js\n// Watch a single prop\nwatch('value', () => {\n    console.log('value is now:', props.value);\n});\n// Watch multiple props\nwatch(['value', 'color'], () => {\n    console.log('value or color changed');\n});\n`\nLoading Third-Party Scripts with head\nThe head parameter lets you load external JavaScript or CSS libraries directly on the component. The head content is injected and loaded before jsonload runs, so your code can immediately use the library.\n`python\ngr.HTML(\n    value=[30, 70, 45, 90, 60],\n    html_template=\"\",\n    jsonload=\"\"\"\n        new Chart(element.querySelector('#chart'), {\n            type: 'bar',\n            data: {\n                labels: props.value.map((_, i) => 'Item ' + (i + 1)),\n                datasets: [{ label: 'Values', data: props.value }]\n            }\n        });\n    \"\"\",\n    head='',\n)\n`\nServer Functions\nYou can call Python functions directly from your jsonload code using the serverfunctions parameter. Pass a list of Python functions to serverfunctions, and they become available as async methods on a server object inside jsonload.\n`python\nimport os\nimport gradio as gr\ndef list_files(path):\n    try:\n        return os.listdir(path)\n    except (FileNotFoundError, PermissionError) as e:\n        return [f\"Error: {e}\"]\nwith gr.Blocks() as demo:\n    gr.Markdown(\n        \"# Server Functions Demo\\nClick 'Load Files' to list files in the directory.\"\n    )\n    filetree = gr.HTML(\n        value=os.path.dirname(file),\n        html_template=\"\"\"\n            \n                Directory: ${value}\n                \n                Load Files\n            \n        \"\"\",\n        jsonload=\"\"\"\n            const loadBtn = element.querySelector('.load-btn');\n            const tree = element.querySelector('.tree');\n            loadBtn.addEventListener('click', async () => {\n                const files = await server.list_files(props.value);\n                tree.innerHTML = '';\n                files.forEach(file => {\n                    const fileEl = document.createElement('div');\n                    fileEl.textContent = file;\n                    tree.appendChild(fileEl);\n                });\n            });\n        \"\"\",\n        serverfunctions=[listfiles],\n    )\ndemo.launch()\n`\nComponent Classes\nIf you are reusing the same HTML component in multiple places, you can create a custom component class by subclassing gr.HTML and setting default values for the templates and other arguments. Here's an example of creating a reusable StarRating component.\n`python\nimport gradio as gr\nclass StarRating(gr.HTML):\n    def init(self, label, value=0, kwargs):\n        html_template = \"\"\"\n        ${label} rating:\n        ${Array.from({length: 5}, (_, i) => ).join('')}\n        \"\"\"\n        css_template = \"\"\"\n            img { height: 50px; display: inline-block; cursor: pointer; }\n            .faded { filter: grayscale(100%); opacity: 0.3; }\n        \"\"\"\n        jsonload = \"\"\"\n            const imgs = element.querySelectorAll('img');\n            imgs.forEach((img, index) => {\n                img.addEventListener('click', () => {\n                    props.value = index + 1;\n                });\n            });\n        \"\"\"\n        super().init(value=value, label=label, htmltemplate=htmltemplate, csstemplate=csstemplate, jsonload=jsonload, kwargs)\n    def api_info(self):\n        return {\"type\": \"integer\", \"minimum\": 0, \"maximum\": 5}\nwith gr.Blocks() as demo:\n    gr.Markdown(\"# Restaurant Review\")\n    food_rating = StarRating(label=\"Food\", value=3)\n    service_rating = StarRating(label=\"Service\", value=3)\n    ambience_rating = StarRating(label=\"Ambience\", value=3)\n    average_btn = gr.Button(\"Calculate Average Rating\")\n    rating_output = StarRating(label=\"Average\", value=3)\n    def calculate_average(food, service, ambience):\n        return round((food + service + ambience) / 3)\n    average_btn.click(\n        fn=calculate_average,\n        inputs=[foodrating, servicerating, ambience_rating],\n        outputs=rating_output\n    )\ndemo.launch()\n`\nNote: Gradio requires all components to accept certain arguments, such as render. You do not need\nto handle these arguments, but you do need to accept them in your component constructor and pass\nthem to the parent gr.HTML class. Otherwise, your component may not behave correctly. The easiest\nway is to add kwargs to your init method and pass it to super().init(), just like in the code example above.\nWe've created several custom HTML components as reusable components as examples you can reference in this directory.\nEmbedding Components in HTML\nThe gr.HTML component can also be used as a container for other Gradio components using the @children placeholder. This allows you to create custom layouts with HTML/CSS. \nThe @children must be at the top-level of the html_template. Since children cannot be nested inside the template, target the parent element directly with your CSS and JavaScript if you need to style or interact with the container of the children.\nHere's a basic example:\n`python\nimport gradio as gr\nwith gr.Blocks() as demo:\n    with gr.HTML(html_template='''\n        &#x26F6;\n        ${form_name}\n        @children\n        Submit\n    ''', css_template='''\n        border: 2px solid gray;\n        border-radius: 12px;\n        padding: 20px;\n        .maximize {\n            position: absolute;\n            top: 10px;\n            right: 10px;\n            background: none;\n            border: none;\n            z-index: 1000;\n        }\n    ''', jsonload='''\n        element.querySelector('.submit').addEventListener('click', () => {\n            trigger('submit');\n        });\n        element.querySelector('.maximize').addEventListener('click', () => {\n            element.requestFullscreen();\n        });\n    ''', form_name=\"Custom Form\") as form:\n        name = gr.Textbox(label=\"Name\")\n        email = gr.Textbox(label=\"Email\")\n    output = gr.Textbox(label=\"Output\")\n    \n    form.submit(lambda name, email: f\"Name: {name}, Email: {email}\", inputs=[name, email], outputs=output)\ndemo.launch()\n`\nIn this example, the @children placeholder marks where the child components (the Name and Email textboxes) will be rendered. Notice how in the css_template we target the parent element to style the container div that wraps the children.\nAPI / MCP support\nTo make your custom HTML component work with Gradio's built-in support for API and MCP (Model Context Protocol) usage, you need to define how its data should be serialized. There are two ways to do this:\nOption 1: Define an api_info() method\nAdd an api_info() method that returns a JSON schema dictionary describing your component's data format. This is what we do in the StarRating class above.\nOption 2: Define a Pydantic data model\nFor more complex data structures, you can define a Pydantic model that inherits from GradioModel or GradioRootModel:\n`python\nfrom gradio.data_classes import GradioModel, GradioRootModel\nclass MyComponentData(GradioModel):\n    items: List[str]\n    count: int\nclass MyComponent(gr.HTML):\n    data_model = MyComponentData\n`\nUse GradioModel when your data is a dictionary with named fields, or GradioRootModel when your data is a simple type (string, list, etc.) that doesn't need to be wrapped in a dictionary. By defining a data_model, your component automatically implements API methods.\nSharing Components with pushtohub\nOnce you've built a custom HTML component, you can share it with the community by pushing it to the HTML Components Gallery. The gallery lets anyone browse, interact with, and copy the Python code for community-contributed components.\nCall pushtohub on any gr.HTML instance or subclass:\n`python\nstar_rating = StarRating()\nstarrating.pushto_hub(\n    name=\"Star Rating\",\n    description=\"Interactive 5-star rating with click-to-rate\",\n    author=\"your-hf-username\",\n    tags=[\"input\", \"rating\"],\n    repo_url=\"https://github.com/your-username/your-repo\",\n)\n`\nThis opens a pull request on the gallery's HuggingFace dataset repo. Once approved, your component will appear in the gallery for others to discover and use.\n            \n                \n                    \n                    \n                    \n                \n                The  pushtohub method has a head parameter that deserves special attention. If your component uses an external library loaded via the head parameter of launch (e.g. head='&lt;script src=\"https://cdn.jsdelivr.net/npm/chart.js\"&gt;&lt;/script&gt;'), pass the same head string to pushtohub so that the gallery can load those scripts when rendering your component.\n            \n                \nAuthentication\nYou need a HuggingFace write token to push components. Either pass it directly:\n`python\nstarrating.pushtohub(..., token=\"hfxxxxx\")\n`\nOr log in beforehand with the HuggingFace CLI, and the cached token will be used automatically:\n`bash\nhuggingface-cli login\n`\nSecurity Considerations\nKeep in mind that using gr.HTML to create custom components involves injecting raw HTML and JavaScript into your Gradio app. Be cautious about using untrusted user input into htmltemplate and json_load, as this could lead to cross-site scripting (XSS) vulnerabilities. \nYou should also expect that any Python event listeners that take your gr.HTML component as input could have any arbitrary value passed to them, not just the values you expect the frontend to be able to set for value. Sanitize and validate user input appropriately in public applications.\nNext Steps\nBrowse the HTML Components Gallery to see what the community has built and copy components into your own apps.\nCheck out more examples in this directory.\nShare your own components with pushtohub` to help others!","type":"GUIDE"},{"title":"Custom Buttons","slug":"/guides/custom-buttons/","content":"Custom Buttons\nMany Gradio components support custom buttons in their toolbar, allowing you to add interactive buttons that can trigger Python functions, JavaScript functions, or both. Custom buttons appear alongside built-in buttons (like \"copy\" or \"download\") in the component's toolbar.\nBasic Usage\nTo add custom buttons to a component, pass a list of gr.Button() instances to the buttons parameter:\n``python\nimport gradio as gr\nrefresh_btn = gr.Button(\"Refresh\", variant=\"secondary\", size=\"sm\")\nclear_btn = gr.Button(\"Clear\", variant=\"secondary\", size=\"sm\")\ntextbox = gr.Textbox(\n    value=\"Sample text\",\n    label=\"Text Input\",\n    buttons=[refreshbtn, clearbtn]\n)\n`\nYou can also mix built-in buttons (as strings) with custom buttons:\n`python\ncode = gr.Code(\n    value=\"print('Hello')\",\n    language=\"python\",\n    buttons=[\"copy\", \"download\", refreshbtn, exportbtn]\n)\n`\nConnecting Button Events\nCustom buttons work just like regular gr.Button components. You can connect them to Python functions or JavaScript functions using the .click() method:\nPython Functions\n`python\ndef refresh_data():\n    import random\n    return f\"Refreshed: {random.randint(1000, 9999)}\"\nrefreshbtn.click(refreshdata, outputs=textbox)\n`\nJavaScript Functions\n`python\nclear_btn.click(\n    None,\n    inputs=[],\n    outputs=textbox,\n    js=\"() => ''\"\n)\n`\nCombined Python and JavaScript\nYou can use the same button for both Python and JavaScript logic:\n`python\nalert_btn.click(\n    None,\n    inputs=textbox,\n    outputs=[],\n    js=\"(text) => { alert('Text: ' + text); return []; }\"\n)\n`\nComplete Example\nHere's a complete example showing custom buttons with both Python and JavaScript functions:\n`python\nimport gradio as gr\ndef export_data(text):\n    print(\"Exporting data:\", text)\n    return \"Data exported to server!\"\ndef refresh_data():\n    import random\n    return f\"Refreshed content: {random.randint(1000, 9999)}\"\nwith gr.Blocks() as demo:\n    gr.Markdown(\"\"\"\n    # Textbox with Custom Buttons Demo\n    \n    This demo showcases custom buttons in a Textbox component that can trigger either (or both):\nPython functions \nJS functions (with and without input parameters)\n    \n    You can use emojis, text, or icons for the buttons.\n    \"\"\")\n    \n    gr.Markdown(\"### Textbox with Custom Buttons\")\n    refresh_btn = gr.Button(\"Refresh\")\n    alert_btn = gr.Button(\"⚠️ Alert\")\n    clear_btn = gr.Button(\"🗑️\")\n    \n    textbox = gr.Textbox(\n        value=\"Sample text content that can be exported, refreshed, or transformed.\",\n        buttons=[\"copy\", refreshbtn, alertbtn, clear_btn],\n        label=\"Sample Text\",\n        lines=5\n    )\n    \n    output = gr.Textbox(label=\"Output (Python Function Result)\")\n        \n    \n    refreshbtn.click(refreshdata, outputs=textbox)\n    \n    alert_btn.click(\n        None,\n        inputs=textbox,\n        outputs=[],\n        js=\"(text) => { alert('This is a JavaScript alert!\\\\n\\\\nTextbox content: ' + text); return []; }\"\n    )\n    \n    \n    clear_btn.click(\n        None,\n        inputs=[],\n        outputs=textbox,\n        js=\"() => ''\"\n    )\ndemo.launch()\n`\nNotes\nCustom buttons appear in the component's toolbar, typically in the top-right corner\nOnly the value of the Button is used, other attributes like icon are not used.\nButtons are rendered in the order they appear in the buttons` list\nBuilt-in buttons (like \"copy\", \"download\") can be hidden by omitting them from the list\nCustom buttons work with component events in the same way as as regular buttons","type":"GUIDE"},{"title":"Custom Components In Five Minutes","slug":"/guides/custom-components-in-five-minutes/","content":"Custom Components in 5 minutes\nGradio includes the ability for developers to create their own custom components and use them in Gradio apps. You can publish your components as Python packages so that other users can use them as well.\nUsers will be able to use all of Gradio's existing functions, such as gr.Blocks, gr.Interface, API usage, themes, etc. with Custom Components. This guide will cover how to get started making custom components.\nInstallation\nYou will need to have:\nPython 3.10+ (install here)\npip 21.3+ (python -m pip install --upgrade pip)\nNode.js 20+ (install here)\nnpm 9+ (install here)\nGradio 5+ (pip install --upgrade gradio)\nThe Workflow\nThe Custom Components workflow consists of 4 steps: create, dev, build, and publish.\ncreate: creates a template for you to start developing a custom component.\ndev: launches a development server with a sample app & hot reloading allowing you to easily develop your custom component\nbuild: builds a python package containing to your custom component's Python and JavaScript code -- this makes things official!\npublish: uploads your package to PyPi and/or a sample app to HuggingFace Spaces.\nEach of these steps is done via the Custom Component CLI. You can invoke it with gradio cc or gradio component\n            \n                \n                    \n                    \n                    \n                \n                Run gradio cc --help to get a help menu of all available commands. There are some commands that are not covered in this guide. You can also append --help to any command name to bring up a help page for that command, e.g. gradio cc create --help.\ncreate\nBootstrap a new template by running the following in any working directory:\n``bash\ngradio cc create MyComponent --template SimpleTextbox\n`\nInstead of MyComponent, give your component any name.\nInstead of SimpleTextbox, you can use any Gradio component as a template. SimpleTextbox is actually a special component that a stripped-down version of the Textbox component that makes it particularly useful when creating your first custom component.\nSome other components that are good if you are starting out: SimpleDropdown, SimpleImage, or File.\n            \n                \n                    \n                    \n                    \n                \n                Run gradio cc show to get a list of available component templates.\n            \n                \nThe create command will:\nCreate a directory with your component's name in lowercase with the following structure:\n`directory\nbackend/  Frontend Server (Go here): http://localhost:7861/\nThe port number might be different for you.\nClick on that link to launch the demo app in hot reload mode.\nNow, you can start making changes to the backend and frontend you'll see the results reflected live in the sample app!\nWe'll go through a real example in a later guide.\n            \n                \n                    \n                    \n                    \n                \n                You don't have to run dev mode from your custom component directory. The first argument to dev mode is the path to the directory. By default it uses the current directory.\nbuild\nOnce you are satisfied with your custom component's implementation, you can build it to use it outside of the development server.\nFrom your component directory, run:\n`bash\ngradio cc build\n`\nThis will create a tar.gz and .whl file in a dist/ subdirectory.\nIf you or anyone installs that .whl file (pip install ) they will be able to use your custom component in any gradio app!\nThe build command will also generate documentation for your custom component. This takes the form of an interactive space and a static README.md. You can disable this by passing --no-generate-docs. You can read more about the documentation generator in the dedicated guide.\npublish\nRight now, your package is only available on a .whl file on your computer.\nYou can share that file with the world with the publish command!\nSimply run the following command from your component directory:\n`bash\ngradio cc publish\n``\nThis will guide you through the following process:\nUpload your distribution files to PyPi. This makes it easier to upload the demo to Hugging Face spaces. Otherwise your package must be at a publicly available url. If you decide to upload to PyPi, you will need a PyPI username and password. You can get one here.\nUpload a demo of your component to hugging face spaces. This is also optional.\nHere is an example of what publishing looks like:\n  \nConclusion\nNow that you know the high-level workflow of creating custom components, you can go in depth in the next guides!\nAfter reading the guides, check out this collection of custom components on the HuggingFace Hub so you can learn from other's code.\n            \n                \n                    \n                    \n                    \n                \n                If you want to start off from someone else's custom component see this guide.","type":"GUIDE"},{"title":"Deploying Gradio With Disco","slug":"/guides/deploying-gradio-with-disco/","content":"Self-Hosting a Gradio app with Disco\nIntroduction\nGradio is a fantastic open-source Python library that allows you to build and share machine learning apps and demos with just a few lines of code. While Gradio offers free hosting on Hugging Face Spaces, you might want to deploy your app on your own server for more control, or to integrate it with other services.\nThis tutorial will guide you through deploying a Gradio application on your own server using Disco, an open-source platform that simplifies the deployment process. With Disco, you can enjoy the benefits of self-hosting without the usual complexities of server setup and maintenance. By the end, you'll have a working Gradio app deployed on your own server with automatic HTTPS and continuous deployment from GitHub.\nPrerequisites\nBefore you begin, make sure you have the following:\nA server with a fresh install of Ubuntu (4GB of RAM or more is recommended). You can get one from providers like DigitalOcean, Hetzner or AWS EC2.\nA domain name that you can configure.\nA GitHub account.\nBasic knowledge of the command line.\nStep 1: Create a Server\nFirst, you'll need a server to host your Gradio app. Choose a provider and create a new server with Ubuntu 24.04 as the operating system.\nOnce your server is up and running, take note of its IP address. You'll need it for the next step.\nStep 2: Configure DNS Settings\nBefore going further, you need to set up two domain names. Go to your domain registrar's DNS management panel and add these records:\nA domain for your Disco server (e.g., disco.example.com).\nA domain for your Gradio application (e.g., gradio.example.com).\nFor the server domain, create an A record pointing to your server's IP address:\nType: A\nName: disco\nValue: `\nFor the application domain, create a CNAME record pointing to your server domain:\nType: CNAME\nName: gradio\nValue: disco.example.com\nDNS changes can take a few minutes to propagate. You can verify that your server domain is resolving to the correct IP address by running ping disco.example.com\nStep 3: Test Your Server Connection\nNow that your DNS is set up, let's test the SSH connection to your server from your local machine. This ensures you can access it before we hand things over to Disco.\n`bash\nReplace with your server domain\nssh root@disco.example.com\n`\nIf the connection is successful, great! This is the last time you'll need to SSH into this server manually. Now, exit the SSH session to return to your local machine. This is a crucial step!\n`bash\nexit\n`\nStep 4: Install the Disco CLI on Your Local Machine\nImportant: From this point forward, all commands should be run from your local machine's terminal. You will not need to SSH into your server again.\nLet's install the Disco command-line interface (CLI) on your local machine. This is the tool you'll use to manage your deployments.\n`bash\ncurl https://cli-assets.letsdisco.dev/install.sh | sh\n`\nAfter the installation is complete, verify it's working by running:\n`bash\ndisco --version\n`\nStep 5: Initialize Your Server with Disco\nNow, from your local machine, let's set up Disco on your server using the domain you configured.\n`bash\nReplace with your server domain\ndisco init root@disco.example.com\n`\nThis command will:\nConnect to your server using SSH.\nInstall Docker.\nSet up the Disco server.\nConfigure the initial SSL certificate.\n            \n                \n                    \n                    \n                    \n                \n                Disco will automatically try to use your default SSH keys. If you use a non-standard key, you can specify the path with the -i flag, like so: disco init -i /path/to/your/ssh/key root@disco.example.com\n            \n                \nStep 6: Fork the Example Gradio App\nFor this tutorial, we'll use an example Gradio application. Go to this example Gradio app repository on GitHub and click the \"Fork\" button to create a copy of it in your own GitHub account.\nStep 7: Connect Disco to GitHub\nTo allow Disco to deploy your application from GitHub, you need to connect your GitHub account. Run the following command on your local machine:\n`bash\ndisco github:apps:add\n`\nThis command will open a browser window where you can authorize Disco with GitHub. You'll need to:\nGive the GitHub application a name (any name will do).\nSelect the repository you just forked (example-gradio-site).\nClick \"Install\".\nStep 8: Deploy Your Gradio App\nNow you're ready to deploy your Gradio app. We'll use the projects:add command on your local machine. Below, replace  with your GitHub username and gradio.example.com with the application domain you configured earlier.\n`bash\ndisco projects:add \\\n  --name gradio-app \\\n  --github /example-gradio-site \\\n  --domain gradio.example.com\n`\nDisco will automatically pull your code from GitHub, build the Docker container, deploy it to your server, and set up HTTPS with Let's Encrypt for your domain.\nStep 9: Test Your Deployed App\nOnce the deployment is complete, open your web browser and navigate to your application's domain: https://gradio.example.com. You should see your Gradio app running live!\nMaking Changes and Automatic Deployment\nOne of the best features of Disco is automatic deployment. Whenever you push changes to your GitHub repository, Disco will detect them, rebuild your application, and deploy it automatically.\nTo test this, modify the app.py` file in your forked repository, then commit and push the changes to GitHub. Within seconds, your deployed app will be updated.\nConclusion\nCongratulations! You have successfully deployed a Gradio application on your own server using Disco. You now have a fully managed deployment pipeline with automatic HTTPS, fast deployments triggered by Git pushes, and complete control over your server and application.\nThis setup provides the best of both worlds: the flexibility and cost-effectiveness of self-hosting combined with the convenience of a platform-as-a-service. For more advanced configurations and features, be sure to check out the Disco documentation and the Gradio documentation.","type":"GUIDE"},{"title":"Deploying Gradio With Docker","slug":"/guides/deploying-gradio-with-docker/","content":"Deploying a Gradio app with Docker\nIntroduction\nGradio is a powerful and intuitive Python library designed for creating web apps that showcase machine learning models. These web apps can be run locally, or deployed on Hugging Face Spaces for free. Or, you can deploy them on your servers in Docker containers. Dockerizing Gradio apps offers several benefits:\nConsistency: Docker ensures that your Gradio app runs the same way, irrespective of where it is deployed, by packaging the application and its environment together.\nPortability: Containers can be easily moved across different systems or cloud environments.\nScalability: Docker works well with orchestration systems like Kubernetes, allowing your app to scale up or down based on demand.\nHow to Dockerize a Gradio App\nLet's go through a simple example to understand how to containerize a Gradio app using Docker.\nStep 1: Create Your Gradio App\nFirst, we need a simple Gradio app. Let's create a Python file named app.py with the following content:\n``python\nimport gradio as gr\ndef greet(name):\n    return f\"Hello {name}!\"\niface = gr.Interface(fn=greet, inputs=\"text\", outputs=\"text\").launch()\n`\nThis app creates a simple interface that greets the user by name.\nStep 2: Create a Dockerfile\nNext, we'll create a Dockerfile to specify how our app should be built and run in a Docker container. Create a file named Dockerfile in the same directory as your app with the following content:\n`dockerfile\nFROM python:3.10-slim\nWORKDIR /usr/src/app\nCOPY . .\nRUN pip install --no-cache-dir gradio\nEXPOSE 7860\nENV GRADIOSERVERNAME=\"0.0.0.0\"\nCMD [\"python\", \"app.py\"]\n`\nThis Dockerfile performs the following steps:\nStarts from a Python 3.10 slim image.\nSets the working directory and copies the app into the container.\nInstalls Gradio (you should install all other requirements as well).\nExposes port 7860 (Gradio's default port).\nSets the GRADIOSERVERNAME environment variable to ensure Gradio listens on all network interfaces.\nSpecifies the command to run the app.\nStep 3: Build and Run Your Docker Container\nWith the Dockerfile in place, you can build and run your container:\n`bash\ndocker build -t gradio-app .\ndocker run -p 7860:7860 gradio-app\n`\nYour Gradio app should now be accessible at http://localhost:7860.\nImportant Considerations\nWhen running Gradio applications in Docker, there are a few important things to keep in mind:\nRunning the Gradio app on \"0.0.0.0\" and exposing port 7860\nIn the Docker environment, setting GRADIOSERVERNAME=\"0.0.0.0\" as an environment variable (or directly in your Gradio app's launch() function) is crucial for allowing connections from outside the container. And the EXPOSE 7860 directive in the Dockerfile tells Docker to expose Gradio's default port on the container to enable external access to the Gradio app. \nEnable Stickiness for Multiple Replicas\nWhen deploying Gradio apps with multiple replicas, such as on AWS ECS, it's important to enable stickiness with sessionAffinity: ClientIP`. This ensures that all requests from the same user are routed to the same instance. This is important because Gradio's communication protocol requires multiple separate connections from the frontend to the backend in order for events to be processed correctly. (If you use Terraform, you'll want to add a stickiness block into your target group definition.)\nDeploying Behind a Proxy\nIf you're deploying your Gradio app behind a proxy, like Nginx, it's essential to configure the proxy correctly. Gradio provides a Guide that walks through the necessary steps. This setup ensures your app is accessible and performs well in production environments.","type":"GUIDE"},{"title":"Deploying Gradio With Modal","slug":"/guides/deploying-gradio-with-modal/","content":"Deploying a Gradio app with Modal\nIntroduction\nGradio is a great way to test and demo your machine learning apps using a simple and intuitive Python API. When combined with Modal's developer-first cloud infrastructure, you can leverage powerful GPUs to run larger models faster. And you don't need an account with a cloud provider or any config files.\nIn this tutorial, we will walk you through setting up a Modal account, deploying a simple Gradio app on Modal, and discuss some of the nuance around Gradio's sticky session requirement and handling concurrency.\nDeploying a simple Gradio app on Modal\nLet's deploy a Gradio-style \"Hello, world\" app that lets a user input their name and then responds with a short greeting. We're not going to use this code as-is in our app, but it's useful to see what the initial Gradio version looks like.\n``python\nimport gradio as gr\nA simple Gradio interface for a greeting function\ndef greet(name):\n    return f\"Hello {name}!\"\ndemo = gr.Interface(fn=greet, inputs=\"text\", outputs=\"text\")\ndemo.launch()\n`\nTo deploy this app on Modal you'll need to\ndefine your container image,\nwrap the Gradio app in a Modal Function,\nand deploy it using Modal's CLI!\nPrerequisite: Install and set up Modal\nBefore you get started, you'll need to create a Modal account if you don't already have one. Then you can set up your environment by authenticating with those account credentials.\nSign up at modal.com. \nInstall the Modal client in your local development environment.\n`bash\npip install modal\n`\nAuthenticate your account.\n`\nmodal setup\n`\nGreat, now we can start building our app!\nStep 1: Define our  modal.Image\nTo start, let's make a new file named gradio_app.py, import modal, and define our image. Modal Images are defined by sequentially calling methods on our Image instance. \nFor this simple app, we'll \nstart with the debian_slim image,\nchoose a Python version (3.12),\nand install the dependencies - only fastapi and gradio.\n`python\nimport modal\napp = modal.App(\"gradio-app\")\nwebimage = modal.Image.debianslim(pythonversion=\"3.12\").uvpip_install(\n    \"fastapi[standard]\",\n    \"gradio\",\n)\n`\nNote, that you don't need to install gradio or fastapi in your local environement - only modal is required locally.\nStep 2: Wrap the Gradio app in a Modal-deployed FastAPI app\nLike many Gradio apps, the example above is run by calling launch() on our demo at the end of the script. However, Modal doesn't run scripts, it runs functions - serverless functions to be exact.\nTo get Modal to serve our demo, we can leverage Gradio and Modal's support for fastapi apps. We do this with the @modal.asgiapp() function decorator which deploys the web app returned by the function. And we use the mountgradio_app function to add our Gradio demo as a route in the web app.\n`python\nwith web_image.imports():\n\timport gradio as gr\n    from gradio.routes import mountgradioapp\n    from fastapi import FastAPI\n     \n@app.function(\n    image=web_image,\n    max_containers = 1, # we'll come to this later \n)\n@modal.concurrent(max_inputs=100) # allow multiple users at one time\n@modal.asgi_app()\ndef ui():\n    \"\"\"A simple Gradio interface for a greeting function.\"\"\"\n    def greet(name):\n\t    return f\"Hello {name}!\"\n\t\n\tdemo = gr.Interface(fn=greet, inputs=\"text\", outputs=\"text\")\n    return mountgradioapp(app=FastAPI(), blocks=demo, path=\"/\")\n`\nLet's quickly review what's going on here:\nWe use the Image.imports context manager to define our imports. These will be available when your function runs in the cloud.\nWe move our code inside a Python function, ui, and decorate it with @app.function which wraps it as a Modal serverless Function. We provide the image and other parameters (we'll cover this later) as inputs to the decorator.\nWe add the @modal.concurrent decorator which allows multiple requests per container to be processed at the same time.\nWe add the @modal.asgi_app decorator which tells Modal that this particular function is serving an ASGI app (here a fastapi app). To use this decorator, your ASGI app needs to be the return value from the function.\nStep 3: Deploying on Modal\nTo deploy the app, just run the following command:\n`bash\nmodal deploy \n`\nThe first time you run your app, Modal will build and cache the image which, takes about 30 seconds. As long as you don't change the image, subsequent deployments will only take a few seconds.\nAfter the image builds Modal will print the URL to your webapp and to your Modal dashboard. The webapp URL should look something like https://{workspace}-{environment}--gradio-app-ui.modal.run. Paste it into your web browser a try out your app!\nImportant Considerations\nSticky Sessions\nModal Functions are serverless which means that each client request is considered independent. While this facilitates autoscaling, it can also mean that extra care should be taken if your application requires any sort of server-side statefulness.\nGradio relies on a REST API, which is itself stateless. But it does require sticky sessions, meaning that every request from a particular client must be routed to the same container. However, Modal does not make any guarantees in this regard.\nA simple way to satisfy this constraint is to set maxcontainers = 1 in the @app.function decorator and setting the maxinputs argument of @modal.concurrent` to a fairly large number - as we did above. This means that Modal won't spin up more than one container to serve requests to your app which effectively satisfies the sticky session requirement.\nConcurrency and Queues\nBoth Gradio and Modal have concepts of concurrency and queues, and getting the most of out of your compute resources requires understanding how these interact.\nModal queues client requests to each deployed Function and simultaneously executes requests up to the concurrency limit for that Function. If requests come in and the concurrency limit is already satisfied, Modal will spin up a new container - up to the maximum set for the Function. In our case, our Gradio app is represented by one Modal Function, so all requests share one queue and concurrency limit. Therefore Modal constrains the total number of requests running at one time, regardless of what they are doing.\nGradio on the other hand, allows developers to utilize multiple queues each with its own concurrency limit. One or more event listeners can then be assigned to a queue which is useful to manage GPU resources for computationally expensive requests.\nThinking carefully about how these queues and limits interact can help you optimize your app's performance and resource optimization while avoiding unwanted results like shared or lost state.\nCreating a GPU Function\nAnother option to manage GPU utilization is to deploy your GPU computations in their own Modal Function and calling this remote Function from inside your Gradio app. This allows you to take full advantage of Modal's serverless autoscaling while routing all of the client HTTP requests to a single Gradio CPU container.","type":"GUIDE"},{"title":"Developing Faster With Reload Mode","slug":"/guides/developing-faster-with-reload-mode/","content":"Developing Faster with Reload Mode and Vibe Mode\nPrerequisite: This Guide requires you to know about Blocks. Make sure to read the Guide to Blocks first.\nThis guide covers hot reloading, reloading in a Python IDE, and using gradio with Jupyter Notebooks.\nWhy Hot Reloading?\nWhen you are building a Gradio demo, particularly out of Blocks, you may find it cumbersome to keep re-running your code to test your changes.\nTo make it faster and more convenient to write your code, we've made it easier to \"reload\" your Gradio apps instantly when you are developing in a Python IDE (like VS Code, Sublime Text, PyCharm, or so on) or generally running your Python code from the terminal. We've also developed an analogous \"magic command\" that allows you to re-run cells faster if you use Jupyter Notebooks (or any similar environment like Colab).\nThis short Guide will cover both of these methods, so no matter how you write Python, you'll leave knowing how to build Gradio apps faster.\nPython IDE Reload 🔥\nIf you are building Gradio Blocks using a Python IDE, your file of code (let's name it run.py) might look something like this:\n``python\nimport gradio as gr\nwith gr.Blocks() as demo:\n    gr.Markdown(\"# Greetings from Gradio!\")\n    inp = gr.Textbox(placeholder=\"What is your name?\")\n    out = gr.Textbox()\n    inp.change(fn=lambda x: f\"Welcome, {x}!\",\n               inputs=inp,\n               outputs=out)\nif name == \"main\":\n    demo.launch()\n`\nThe problem is that anytime that you want to make a change to your layout, events, or components, you have to close and rerun your app by writing python run.py.\nInstead of doing this, you can run your code in reload mode by changing 1 word: python to gradio:\nIn the terminal, run gradio run.py. That's it!\nNow, you'll see that after you'll see something like this:\n`bash\nWatching: '/Users/freddy/sources/gradio/gradio', '/Users/freddy/sources/gradio/demo/'\nRunning on local URL:  http://127.0.0.1:7860\n`\nThe important part here is the line that says Watching... What's happening here is that Gradio will be observing the directory where run.py file lives, and if the file changes, it will automatically rerun the file for you. So you can focus on writing your code, and your Gradio demo will refresh automatically 🥳\n            \n                \n                    \n                    \n                    \n                \n                the gradio command does not detect the parameters passed to the launch() methods because the launch() method is never called in reload mode. For example, setting auth, or show_error in launch() will not be reflected in the app.\n            \n                \nThere is one important thing to keep in mind when using the reload mode: Gradio specifically looks for a Gradio Blocks/Interface demo called demo in your code. If you have named your demo something else, you will need to pass in the name of your demo as the 2nd parameter in your code. So if your run.py file looked like this:\n`python\nimport gradio as gr\nwith gr.Blocks() as my_demo:\n    gr.Markdown(\"# Greetings from Gradio!\")\n    inp = gr.Textbox(placeholder=\"What is your name?\")\n    out = gr.Textbox()\n    inp.change(fn=lambda x: f\"Welcome, {x}!\",\n               inputs=inp,\n               outputs=out)\nif name == \"main\":\n    my_demo.launch()\n`\nThen you would launch it in reload mode like this: gradio run.py --demo-name=my_demo.\nBy default, the Gradio use UTF-8 encoding for scripts. For reload mode, If you are using encoding formats other than UTF-8 (such as cp1252), make sure you've done like this:\nConfigure encoding declaration of python script, for example: # -- coding: cp1252 --\nConfirm that your code editor has identified that encoding format. \nRun like this: gradio run.py --encoding cp1252\n🔥 If your application accepts command line arguments, you can pass them in as well. Here's an example:\n`python\nimport gradio as gr\nimport argparse\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--name\", type=str, default=\"User\")\nargs, unknown = parser.parseknownargs()\nwith gr.Blocks() as demo:\n    gr.Markdown(f\"# Greetings {args.name}!\")\n    inp = gr.Textbox()\n    out = gr.Textbox()\n    inp.change(fn=lambda x: x, inputs=inp, outputs=out)\nif name == \"main\":\n    demo.launch()\n`\nWhich you could run like this: gradio run.py -- --name Gretel\nEverything after the -- separator is passed straight through to your app, so your app's arguments are yours to name — including ones that happen to match a gradio option:\n`bash\ngradio run.py --demo-name my_demo -- --demo-name production\n`\nHere gradio reads the first --demo-name, and your app receives the second.\nAs a small aside, this auto-reloading happens if you change your run.py source code or the Gradio source code. Meaning that this can be useful if you decide to contribute to Gradio itself ✅\nControlling the Reload 🎛️\nBy default, reload mode will re-run your entire script for every change you make.\nBut there are some cases where this is not desirable.\nFor example, loading a machine learning model should probably only happen once to save time. There are also some Python libraries that use C or Rust extensions that throw errors when they are reloaded, like numpy and tiktoken.\nIn these situations, you can place code that you do not want to be re-run inside an if gr.NO_RELOAD:  codeblock. Here's an example of how you can use it to only load a transformers model once during the development process.\n            \n                \n                    \n                    \n                    \n                \n                The value of gr.NO_RELOAD is True. So you don't have to change your script when you are done developing and want to run it in production. Simply run the file with python instead of gradio.\n            \n                \n`python\nimport gradio as gr\nif gr.NO_RELOAD:\n\tfrom transformers import pipeline\n\tpipe = pipeline(\"text-classification\", model=\"cardiffnlp/twitter-roberta-base-sentiment-latest\")\ndemo = gr.Interface(lambda s: {d[\"label\"]: d[\"score\"] for d in pipe(s)}, gr.Textbox(), gr.Label())\nif name == \"main\":\n    demo.launch()\n`\nVibe Mode\nYou can also enable Gradio's Vibe Mode, which, which provides an in-browser chat that can be used to write or edit your Gradio app using natural language. To enable this, simply run use the --vibe flag with Gradio, e.g. gradio --vibe app.py.\nVibe Mode lets you describe commands using natural language and have an LLM write or edit the code in your Gradio app. The LLM is powered by Hugging Face's Inference Providers, so you must be logged into Hugging Face locally to use this. \nNote: When Vibe Mode is enabled, anyone who can access the Gradio endpoint can modify files and run arbitrary code on the host machine. Use only for local development.\nJupyter Notebook Magic 🔮\nWhat about if you use Jupyter Notebooks (or Colab Notebooks, etc.) to develop code? We got something for you too!\nWe've developed a magic command that will create and run a Blocks demo for you. To use this, load the gradio extension at the top of your notebook:\n%load_ext gradio\nThen, in the cell that you are developing your Gradio demo, simply write the magic command %%blocks at the top, and then write the layout and components like you would normally:\n`py\n%%blocks\nimport gradio as gr\nwith gr.Blocks() as demo:\n    gr.Markdown(f\"# Greetings {args.name}!\")\n    inp = gr.Textbox()\n    out = gr.Textbox()\n    inp.change(fn=lambda x: x, inputs=inp, outputs=out)\n``\nNotice that:\nYou do not need to launch your demo — Gradio does that for you automatically!\nEvery time you rerun the cell, Gradio will re-render your app on the same port and using the same underlying web server. This means you'll see your changes much, much faster than if you were rerunning the cell normally.\nHere's what it looks like in a jupyter notebook:\n🪄 This works in colab notebooks too! Here's a colab notebook where you can see the Blocks magic in action. Try making some changes and re-running the cell with the Gradio code!\n            \n                \n                    \n                    \n                    \n                \n                You may have to use %%blocks --share in Colab to get the demo to appear in the cell.\n            \n                \nThe Notebook Magic is now the author's preferred way of building Gradio demos. Regardless of how you write Python code, we hope either of these methods will give you a much better development experience using Gradio.\nNext Steps\nNow that you know how to develop quickly using Gradio, start building your own!\nIf you are looking for inspiration, try exploring demos other people have built with Gradio, browse public Hugging Face Spaces 🤗","type":"GUIDE"},{"title":"Documenting Custom Components","slug":"/guides/documenting-custom-components/","content":"Documenting Custom Components\nIn 4.15, we added a  new gradio cc docs command to the Gradio CLI to generate rich documentation for your custom component. This command will generate documentation for users automatically, but to get the most out of it, you need to do a few things.\nHow do I use it?\nThe documentation will be generated when running gradio cc build. You can pass the --no-generate-docs argument to turn off this behaviour.\nThere is also a standalone docs command that allows for greater customisation. If you are running this command manually it should be run after the version in your pyproject.toml has been bumped but before building the component.\nAll arguments are optional.\n``bash\ngradio cc docs\n  path # The directory of the custom component.\n  --demo-dir # Path to the demo directory.\n  --demo-name # Name of the demo file\n  --space-url # URL of the Hugging Face Space to link to\n  --generate-space # create a documentation space.\n  --no-generate-space # do not create a documentation space\n  --readme-path # Path to the README.md file.\n  --generate-readme # create a REAMDE.md file\n  --no-generate-readme # do not create a README.md file\n  --suppress-demo-check # suppress validation checks and warnings\n`\nWhat gets generated?\nThe gradio cc docs command will generate an interactive Gradio app and a static README file with various features. You can see an example here:\nGradio app deployed on Hugging Face Spaces\nREADME.md rendered by GitHub\nThe README.md and space both have the following features:\nA description.\nInstallation instructions.\nA fully functioning code snippet.\nOptional links to PyPi, GitHub, and Hugging Face Spaces.\nAPI documentation including:\nAn argument table for component initialisation showing types, defaults, and descriptions.\nA description of how the component affects the user's predict function.\nA table of events and their descriptions.\nAny additional interfaces or classes that may be used during initialisation or in the pre- or post- processors.\nAdditionally, the Gradio includes:\nA live demo.\nA richer, interactive version of the parameter tables.\nNicer styling!\nWhat do I need to do?\nThe documentation generator uses existing standards to extract the necessary information, namely Type Hints and Docstrings. There are no Gradio-specific APIs for documentation, so following best practices will generally yield the best results.\nIf you already use type hints and docstrings in your component source code, you don't need to do much to benefit from this feature, but there are some details that you should be aware of.\nPython version\nTo get the best documentation experience, you need to use Python 3.10 or greater when generating documentation. This is because some introspection features used to generate the documentation were only added in 3.10.\nType hints\nPython type hints are used extensively to provide helpful information for users. \n \n What are type hints?\nIf you need to become more familiar with type hints in Python, they are a simple way to express what Python types are expected for arguments and return values of functions and methods. They provide a helpful in-editor experience, aid in maintenance, and integrate with various other tools. These types can be simple primitives, like list str bool; they could be more compound types like liststr], str | None or tuple[str, float | int]; or they can be more complex types using utility classed like [TypedDict.\nRead more about type hints in Python.\nWhat do I need to add hints to?\nYou do not need to add type hints to every part of your code. For the documentation to work correctly, you will need to add type hints to the following component methods:\ninit parameters should be typed.\npostprocess parameters and return value should be typed.\npreprocess parameters and return value should be typed.\nIf you are using gradio cc create, these types should already exist, but you may need to tweak them based on any changes you make.\ninit\nHere, you only need to type the parameters. If you have cloned a template with gradio cc create, these should already be in place. You will only need to add new hints for anything you have added or changed:\n``py\ndef init(\n  self,\n  value: str | None = None,\n  *,\n  sources: Literal[\"upload\", \"microphone\"] = \"upload,\n  every: Timer | float | None = None,\n  ...\n):\n  ...\n`\npreprocess and postprocess\nThe preprocess and postprocess methods determine the value passed to the user function and the value that needs to be returned.\nEven if the design of your component is primarily as an input or an output, it is worth adding type hints to both the input parameters and the return values because Gradio has no way of limiting how components can be used.\nIn this case, we specifically care about:\nThe return type of preprocess.\nThe input type of postprocess.\n`py\ndef preprocess(\n  self, payload: FileData | None # input is optional\n) -> tuple[int, str] | str | None:\nuser function input  is the preprocess return ▲\nuser function output is the postprocess input ▼\ndef postprocess(\n  self, value: tuple[int, str] | None\n) -> FileData | bytes | None: # return is optional\n  ...\n`\nDocstrings\nDocstrings are also used extensively to extract more meaningful, human-readable descriptions of certain parts of the API.\n \n What are docstrings?\nIf you need to become more familiar with docstrings in Python, they are a way to annotate parts of your code with human-readable decisions and explanations. They offer a rich in-editor experience like type hints, but unlike type hints, they don't have any specific syntax requirements. They are simple strings and can take almost any form. The only requirement is where they appear. Docstrings should be \"a string literal that occurs as the first statement in a module, function, class, or method definition\".\nRead more about Python docstrings.\nWhile docstrings don't have any syntax requirements, we need a particular structure for documentation purposes.\nAs with type hint, the specific information we care about is as follows:\ninit parameter docstrings.\npreprocess return docstrings.\npostprocess input parameter docstrings.\nEverything else is optional.\nDocstrings should always take this format to be picked up by the documentation generator:\nClasses\n`py\n\"\"\"\nA description of the class.\nThis can span multiple lines and can contain markdown.\n\"\"\"\n`\nMethods and functions \nMarkdown in these descriptions will not be converted into formatted text.\n`py\n\"\"\"\nParameters:\n    param_one: A description for this parameter.\n    param_two: A description for this parameter.\nReturns:\n    A description for this return value.\n\"\"\"\n`\nEvents\nIn custom components, events are expressed as a list stored on the events field of the component class. While we do not need types for events, we do need a human-readable description so users can understand the behaviour of the event.\nTo facilitate this, we must create the event in a specific way.\nThere are two ways to add events to a custom component.\nBuilt-in events\nGradio comes with a variety of built-in events that may be enough for your component. If you are using built-in events, you do not need to do anything as they already have descriptions we can extract:\n`py\nfrom gradio.events import Events\nclass ParamViewer(Component):\n  ...\n  EVENTS = [\n    Events.change,\n    Events.upload,\n  ]\n`\nCustom events\nYou can define a custom event if the built-in events are unsuitable for your use case. This is a straightforward process, but you must create the event in this way for docstrings to work correctly:\n`py\nfrom gradio.events import Events, EventListener\nclass ParamViewer(Component):\n  ...\n  EVENTS = [\n    Events.change,\n    EventListener(\n        \"bingbong\",\n        doc=\"This listener is triggered when the user does a bingbong.\"\n      )\n  ]\n`\nDemo\nThe demo/app.py, often used for developing the component, generates the live demo and code snippet. The only strict rule here is that the demo.launch() command must be contained with a name == \"main\" conditional as below:\n`py\nif name == \"main\":\n  demo.launch()\n`\nThe documentation generator will scan for such a clause and error if absent. If you are not launching the demo inside the demo/app.py, then you can pass --suppress-demo-check to turn off this check.\nDemo recommendations\nAlthough there are no additional rules, there are some best practices you should bear in mind to get the best experience from the documentation generator.\nThese are only guidelines, and every situation is unique, but they are sound principles to remember.\nKeep the demo compact\nCompact demos look better and make it easier for users to understand what the demo does. Try to remove as many extraneous UI elements as possible to focus the users' attention on the core use case. \nSometimes, it might make sense to have a demo/app.py just for the docs and an additional, more complex app for your testing purposes. You can also create other spaces, showcasing more complex examples and linking to them from the main class docstring or the pyproject.toml description.\nKeep the code concise\nThe 'getting started' snippet utilises the demo code, which should be as short as possible to keep users engaged and avoid confusion.\nIt isn't the job of the sample snippet to demonstrate the whole API; this snippet should be the shortest path to success for a new user. It should be easy to type or copy-paste and easy to understand. Explanatory comments should be brief and to the point.\nAvoid external dependencies\nAs mentioned above, users should be able to copy-paste a snippet and have a fully working app. Try to avoid third-party library dependencies to facilitate this.\nYou should carefully consider any examples; avoiding examples that require additional files or that make assumptions about the environment is generally a good idea.\nEnsure the demo directory is self-contained\nOnly the demo directory will be uploaded to Hugging Face spaces in certain instances, as the component will be installed via PyPi if possible. It is essential that this directory is self-contained and any files needed for the correct running of the demo are present.\nAdditional URLs\nThe documentation generator will generate a few buttons, providing helpful information and links to users. They are obtained automatically in some cases, but some need to be explicitly included in the pyproject.yaml. \nPyPi Version and link - This is generated automatically.\nGitHub Repository - This is populated via the pyproject.toml's project.urls.repository.\nHugging Face Space - This is populated via the pyproject.toml's project.urls.space.\nAn example pyproject.toml urls section might look like this:\n`toml\n[project.urls]\nrepository = \"https://github.com/user/repo-name\"\nspace = \"https://huggingface.co/spaces/user/space-name\"\n``","type":"GUIDE"},{"title":"Dynamic Apps With Render Decorator","slug":"/guides/dynamic-apps-with-render-decorator/","content":"Dynamic Apps with the Render Decorator\nThe components and event listeners you define in a Blocks so far have been fixed - once the demo was launched, new components and listeners could not be added, and existing one could not be removed. \nThe @gr.render decorator introduces the ability to dynamically change this. Let's take a look. \nDynamic Number of Components\nIn the example below, we will create a variable number of Textboxes. When the user edits the input Textbox, we create a Textbox for each letter in the input. Try it out below:\n``python\nimport gradio as gr\nwith gr.Blocks() as demo:\n    input_text = gr.Textbox(label=\"input\")\n    @gr.render(inputs=input_text)\n    def show_split(text):\n        if len(text) == 0:\n            gr.Markdown(\"## No Input Provided\")\n        else:\n            for letter in text:\n                gr.Textbox(letter)\ndemo.launch()\n`\nSee how we can now create a variable number of Textboxes using our custom logic - in this case, a simple for loop. The @gr.render decorator enables this with the following steps:\nCreate a function and attach the @gr.render decorator to it.\nAdd the input components to the inputs= argument of @gr.render, and create a corresponding argument in your function for each component. This function will automatically re-run on any change to a component.\nAdd all components inside the function that you want to render based on the inputs.\nNow whenever the inputs change, the function re-runs, and replaces the components created from the previous function run with the latest run. Pretty straightforward! Let's add a little more complexity to this app:\n`python\nimport gradio as gr\nwith gr.Blocks() as demo:\n    input_text = gr.Textbox(label=\"input\")\n    mode = gr.Radio([\"textbox\", \"button\"], value=\"textbox\")\n    @gr.render(inputs=[inputtext, mode], triggers=[inputtext.submit])\n    def show_split(text, mode):\n        if len(text) == 0:\n            gr.Markdown(\"## No Input Provided\")\n        else:\n            for letter in text:\n                if mode == \"textbox\":\n                    gr.Textbox(letter)\n                else:\n                    gr.Button(letter)\ndemo.launch()\n`\nBy default, @gr.render re-runs are triggered by the .load listener to the app and the .change listener to any input component provided. We can override this by explicitly setting the triggers in the decorator, as we have in this app to only trigger on input_text.submit instead. \nIf you are setting custom triggers, and you also want an automatic render at the start of the app, make sure to add demo.load to your list of triggers.\nDynamic Event Listeners\nIf you're creating components, you probably want to attach event listeners to them as well. Let's take a look at an example that takes in a variable number of Textbox as input, and merges all the text into a single box.\n`python\nimport gradio as gr\nwith gr.Blocks() as demo:\n    text_count = gr.State(1)\n    add_btn = gr.Button(\"Add Box\")\n    addbtn.click(lambda x: x + 1, textcount, text_count)\n    @gr.render(inputs=text_count)\n    def render_count(count):\n        boxes = []\n        for i in range(count):\n            box = gr.Textbox(key=i, label=f\"Box {i}\")\n            boxes.append(box)\n        def merge(*args):\n            return \" \".join(args)\n        merge_btn.click(merge, boxes, output)\n    merge_btn = gr.Button(\"Merge\")\n    output = gr.Textbox(label=\"Merged Output\")\ndemo.launch()\n`\nLet's take a look at what's happening here:\nThe state variable textcount is keeping track of the number of Textboxes to create. By clicking on the Add button, we increase textcount which triggers the render decorator.\nNote that in every single Textbox we create in the render function, we explicitly set a key= argument. This key allows us to preserve the value of this Component between re-renders. If you type in a value in a textbox, and then click the Add button, all the Textboxes re-render, but their values aren't cleared because the key= maintains the the value of a Component across a render.\nWe've stored the Textboxes created in a list, and provide this list as input to the merge button event listener. Note that all event listeners that use Components created inside a render function must also be defined inside that render function. The event listener can still reference Components outside the render function, as we do here by referencing merge_btn and output which are both defined outside the render function.\nJust as with Components, whenever a function re-renders, the event listeners created from the previous render are cleared and the new event listeners from the latest run are attached. \nThis allows us to create highly customizable and complex interactions! \nCloser Look at keys= parameter\nThe key= argument tells Gradio that a component being created in a render function corresponds to the same logical component as in the previous render.\nThis allows Gradio to reuse the existing browser element instead of destroying and recreating it on every render. It also preserves the user's entered value across re-renders when the same keyed component is recreated.\nIf your component is nested inside layout items like gr.Row, make sure those containers are keyed consistently as well, because parent keys must also match.\nYou can also key event listeners, for example button.click(key=...), when the same listener is recreated with the same inputs and outputs across renders. This helps Gradio keep the listener associated with the correct component instances and can prevent issues when events finish processing after a re-render.\nPutting it Together\nLet's look at two examples that use all the features above. First, try out the to-do list app below: \n`python\nimport gradio as gr\nwith gr.Blocks() as demo:\n    tasks = gr.State([])\n    newtask = gr.Textbox(label=\"Task Name\", autofocus=True, maxlines=1)\n    def addtask(tasks, newtask_name):\n        return tasks + [{\"name\": newtaskname, \"complete\": False}], \"\"\n    newtask.submit(addtask, [tasks, newtask], [tasks, newtask])\n    @gr.render(inputs=tasks)\n    def rendertodos(tasklist):\n        complete = [task for task in task_list if task[\"complete\"]]\n        incomplete = [task for task in task_list if not task[\"complete\"]]\n        gr.Markdown(f\"### Incomplete Tasks ({len(incomplete)})\")\n        for task in incomplete:\n            with gr.Row():\n                gr.Textbox(task['name'], show_label=False, container=False)\n                done_btn = gr.Button(\"Done\", scale=0)\n                def mark_done(task=task):\n                    task[\"complete\"] = True\n                    return task_list\n                donebtn.click(markdone, None, [tasks])\n                delete_btn = gr.Button(\"Delete\", scale=0, variant=\"stop\")\n                def delete(task=task):\n                    task_list.remove(task)\n                    return task_list\n                delete_btn.click(delete, None, [tasks])\n        gr.Markdown(f\"### Complete Tasks ({len(complete)})\")\n        for task in complete:\n            gr.Textbox(task['name'], show_label=False, container=False)\ndemo.launch()\n`\nNote that almost the entire app is inside a single gr.render that reacts to the tasks gr.State variable. This variable is a nested list, which presents some complexity. If you design a gr.render to react to a list or dict structure, ensure you do the following:\nAny event listener that modifies a state variable in a manner that should trigger a re-render must set the state variable as an output. This lets Gradio know to check if the variable has changed behind the scenes. \nIn a gr.render, if a variable in a loop is used inside an event listener function, that variable should be \"frozen\" via setting it to itself as a default argument in the function header. See how we have task=task in both mark_done and delete. This freezes the variable to its \"loop-time\" value.\nLet's take a look at one last example that uses everything we learned. Below is an audio mixer. Provide multiple audio tracks and mix them together.\n`python\nimport gradio as gr\nwith gr.Blocks() as demo:\n    track_count = gr.State(1)\n    addtrackbtn = gr.Button(\"Add Track\")\n    addtrackbtn.click(lambda count: count + 1, trackcount, trackcount)\n    @gr.render(inputs=track_count)\n    def render_tracks(count):\n        audios = []\n        volumes = []\n        with gr.Row():\n            for i in range(count):\n                with gr.Column(variant=\"panel\", min_width=200):\n                    gr.Textbox(placeholder=\"Track Name\", key=f\"name-{i}\", show_label=False)\n                    track_audio = gr.Audio(label=f\"Track {i}\", key=f\"track-{i}\")\n                    track_volume = gr.Slider(0, 100, value=100, label=\"Volume\", key=f\"volume-{i}\")\n                    audios.append(track_audio)\n                    volumes.append(track_volume)\n            def merge(data):\n                sr, output = None, None\n                for audio, volume in zip(audios, volumes):\n                    sr, audio_val = data[audio]\n                    volume_val = data[volume]\n                    finaltrack = audioval * (volume_val / 100)\n                    if output is None:\n                        output = final_track\n                    else:\n                        minshape = tuple(min(s1, s2) for s1, s2 in zip(output.shape, finaltrack.shape))\n                        trimmedoutput = output[:minshape[0], ...][:, :minshape[1], ...] if output.ndim > 1 else output[:minshape[0]]\n                        trimmedfinal = finaltrack[:minshape[0], ...][:, :minshape[1], ...] if finaltrack.ndim > 1 else finaltrack[:min_shape[0]]\n                        output += trimmedoutput + trimmedfinal\n                return (sr, output)\n            mergebtn.click(merge, set(audios + volumes), outputaudio)\n    merge_btn = gr.Button(\"Merge Tracks\")\n    output_audio = gr.Audio(label=\"Output\", interactive=False)\ndemo.launch()\n`\nTwo things to note in this app:\nHere we provide key= to all the components! We need to do this so that if we add another track after setting the values for an existing track, our input values to the existing track do not get reset on re-render.\nWhen there are lots of components of different types and arbitrary counts passed to an event listener, it is easier to use the set and dictionary notation for inputs rather than list notation. Above, we make one large set of all the input gr.Audio and gr.Slider components when we pass the inputs to the merge function. In the function body we query the component values as a dict.\nThe gr.render` expands gradio capabilities extensively - see what you can make out of it!","type":"GUIDE"},{"title":"Environment Variables","slug":"/guides/environment-variables/","content":"Environment Variables\nEnvironment variables in Gradio provide a way to customize your applications and launch settings without changing the codebase. In this guide, we'll explore the key environment variables supported in Gradio and how to set them.\nKey Environment Variables\nGRADIOSERVERPORT\nDescription: Specifies the port on which the Gradio app will run.\nDefault: 7860\nExample:\n  ``bash\n  export GRADIOSERVERPORT=8000\n  `\nGRADIOSERVERNAME\nDescription: Defines the host name for the Gradio server. To make Gradio accessible from any IP address, set this to \"0.0.0.0\"\nDefault: \"127.0.0.1\" \nExample:\n  `bash\n  export GRADIOSERVERNAME=\"0.0.0.0\"\n  `\nGRADIONUMPORTS\nDescription: Defines the number of ports to try when starting the Gradio server.\nDefault: 100\nExample:\n  `bash\n  export GRADIONUMPORTS=200\n  `\nGRADIOANALYTICSENABLED\nDescription: Whether Gradio should provide \nDefault: \"True\"\nOptions: \"True\", \"False\"\nExample:\n  `sh\n  export GRADIOANALYTICSENABLED=\"True\"\n  `\nGRADIO_DEBUG\nDescription: Enables or disables debug mode in Gradio. If debug mode is enabled, the main thread does not terminate allowing error messages to be printed in environments such as Google Colab.\nDefault: 0\nExample:\n  `sh\n  export GRADIO_DEBUG=1\n  `\nGRADIOFLAGGINGMODE\nDescription: Controls whether users can flag inputs/outputs in the Gradio interface. See the Guide on flagging for more details.\nDefault: \"manual\"\nOptions: \"never\", \"manual\", \"auto\"\nExample:\n  `sh\n  export GRADIOFLAGGINGMODE=\"never\"\n  `\nGRADIOTEMPDIR\nDescription: Specifies the directory where temporary files created by Gradio are stored.\nDefault: System default temporary directory\nExample:\n  `sh\n  export GRADIOTEMPDIR=\"/path/to/temp\"\n  `\nGRADIOROOTPATH\nDescription: Sets the root path for the Gradio application. Useful if running Gradio behind a reverse proxy.\nDefault: \"\"\nExample:\n  `sh\n  export GRADIOROOTPATH=\"/myapp\"\n  `\nGRADIO_SHARE\nDescription: Enables or disables sharing the Gradio app.\nDefault: \"False\"\nOptions: \"True\", \"False\"\nExample:\n  `sh\n  export GRADIO_SHARE=\"True\"\n  `\nGRADIOALLOWEDPATHS\nDescription: Sets a list of complete filepaths or parent directories that gradio is allowed to serve. Must be absolute paths. Warning: if you provide directories, any files in these directories or their subdirectories are accessible to all users of your app. Multiple items can be specified by separating items with commas.\nDefault: \"\"\nExample:\n  `sh\n  export GRADIOALLOWEDPATHS=\"/mnt/sda1,/mnt/sda2\"\n  `\nGRADIOBLOCKEDPATHS\nDescription: Sets a list of complete filepaths or parent directories that gradio is not allowed to serve (i.e. users of your app are not allowed to access). Must be absolute paths. Warning: takes precedence over allowed_paths and all other directories exposed by Gradio by default. Multiple items can be specified by separating items with commas.\nDefault: \"\"\nExample:\n  `sh\n  export GRADIOBLOCKEDPATHS=\"/users/x/gradioapp/admin,/users/x/gradioapp/keys\"\n  `\nFORWARDEDALLOWIPS\nDescription: This is not a Gradio-specific environment variable, but rather one used in server configurations, specifically uvicorn which is used by Gradio internally. This environment variable is useful when deploying applications behind a reverse proxy. It defines a list of IP addresses that are trusted to forward traffic to your application. When set, the application will trust the X-Forwarded-For header from these IP addresses to determine the original IP address of the user making the request. This means that if you use the gr.Request object's client.host property, it will correctly get the user's IP address instead of the IP address of the reverse proxy server. Note that only trusted IP addresses (i.e. the IP addresses of your reverse proxy servers) should be added, as any server with these IP addresses can modify the X-Forwarded-For header and spoof the client's IP address.\nDefault: \"127.0.0.1\"\nExample:\n  `sh\n  export FORWARDEDALLOWIPS=\"127.0.0.1,192.168.1.100\"\n  `\nGRADIOCACHEEXAMPLES\nDescription: Whether or not to cache examples by default in gr.Interface(), gr.ChatInterface() or in gr.Examples() when no explicit argument is passed for the cache_examples parameter. You can set this environment variable to either the string \"true\" or \"false\".\nDefault: \"false\"\nExample:\n  `sh\n  export GRADIOCACHEEXAMPLES=\"true\"\n  `\nGRADIOCACHEMODE\nDescription: How to cache examples. Only applies if cacheexamples is set to True either via enviornment variable or by an explicit parameter, AND no no explicit argument is passed for the cachemode parameter in gr.Interface(), gr.ChatInterface() or in gr.Examples(). Can be set to either the strings \"lazy\" or \"eager.\" If \"lazy\", examples are cached after their first use for all users of the app. If \"eager\", all examples are cached at app launch.\nDefault: \"eager\"\nExample:\n  `sh\n  export GRADIOCACHEMODE=\"lazy\"\n  `\nGRADIOEXAMPLESCACHE\nDescription:  If you set cacheexamples=True in gr.Interface(), gr.ChatInterface() or in gr.Examples(), Gradio will run your prediction function and save the results to disk. By default, this is in the .gradio/cachedexamples// subdirectory within your app's working directory. You can customize the location of cached example files created by Gradio by setting the environment variable GRADIOEXAMPLESCACHE to an absolute path or a path relative to your working directory.\nDefault: \".gradio/cached_examples/\"\nExample:\n  `sh\n  export GRADIOEXAMPLESCACHE=\"customcachedexamples/\"\n  `\nGRADIOSSRMODE\nDescription: Controls whether server-side rendering (SSR) is enabled. When enabled, the initial HTML is rendered on the server rather than the client, which can improve initial page load performance and SEO.\nDefault: \"False\" (except on Hugging Face Spaces, where this environment variable sets it to True)\nOptions: \"True\", \"False\"\nExample:\n  `sh\n  export GRADIOSSRMODE=\"True\"\n  `\nGRADIONODESERVER_NAME\nDescription: Defines the host name for the Gradio node server. (Only applies if ssr_mode is set to True.)\nDefault: GRADIOSERVERNAME if it is set, otherwise \"127.0.0.1\"\nExample:\n  `sh\n  export GRADIONODESERVER_NAME=\"0.0.0.0\"\n  `\nGRADIONODENUM_PORTS\nDescription: Defines the number of ports to try when starting the Gradio node server. (Only applies if ssr_mode is set to True.)\nDefault: 100\nExample:\n  `sh\n  export GRADIONODENUM_PORTS=200\n  `\nGRADIORESETEXAMPLES_CACHE\nDescription: If set to \"True\", Gradio will delete and recreate the examples cache directory when the app starts instead of reusing the cached example if they already exist. \nDefault: \"False\"\nOptions: \"True\", \"False\"\nExample:\n  `sh\n  export GRADIORESETEXAMPLES_CACHE=\"True\"\n  `\nGRADIOCHATFLAGGING_MODE\nDescription: Controls whether users can flag messages in gr.ChatInterface applications. Similar to GRADIOFLAGGINGMODE but specifically for chat interfaces.\nDefault: \"never\"\nOptions: \"never\", \"manual\"\nExample:\n  `sh\n  export GRADIOCHATFLAGGING_MODE=\"manual\"\n  `\nGRADIOWATCHDIRS\nDescription: Specifies directories to watch for file changes when running Gradio in development mode. When files in these directories change, the Gradio app will automatically reload. Multiple directories can be specified by separating them with commas. This is primarily used by the gradio CLI command for development workflows.\nDefault: \"\"\nExample:\n  `sh\n  export GRADIOWATCHDIRS=\"/path/to/src,/path/to/templates\"\n  `\nGRADIOVIBEMODE\nDescription: Enables the Vibe editor mode, which provides an in-browser chat that can be used to write or edit your Gradio app using natural language. When enabled, anyone who can access the Gradio endpoint can modify files and run arbitrary code on the host machine. Use with extreme caution in production environments.\nDefault: \"\"\nOptions: Any non-empty string enables the mode\nExample:\n  `sh\n  export GRADIOVIBEMODE=\"1\"\n  `\nGRADIOMCPSERVER\nDescription: Enables the MCP (Model Context Protocol) server functionality in Gradio. When enabled, the Gradio app will be set up as an MCP server and documented functions will be added as MCP tools that can be used by LLMs. This allows LLMs to interact with your Gradio app's functionality through the MCP protocol.\nDefault: \"False\"\nOptions: \"True\", \"False\"\nExample:\n  `sh\n  export GRADIOMCPSERVER=\"True\"\n  `\nGRADIONUMWORKERS\nDescription: Number of multiple workers to launch in the background to offload traffic for file I/O and static assets from the main Gradio server. Only works when SSR mode is set.\nDefault: not set.\nOptions: Any positive integer.\nExample:\n  `sh\n  export GRADIONUMWORKERS=4\n  `\nGRADIOHEARTBEATINTERVAL\nDescription: Sets the interval, in seconds, between heartbeats that keep a client session alive. When a client disconnects, this heartbeat is used to trigger unload events and clean up session state. Lowering this value can help detect disconnections faster in environments such as Kubernetes, where the default interval can delay session cleanup.\nDefault: 15\nExample:\n  `sh\n  export GRADIOHEARTBEATINTERVAL=5\n  `\nHow to Set Environment Variables\nTo set environment variables in your terminal, use the export command followed by the variable name and its value. For example:\n`sh\nexport GRADIOSERVERPORT=8000\n`\nIf you're using a .env file to manage your environment variables, you can add them like this:\n`sh\nGRADIOSERVERPORT=8000\nGRADIOSERVERNAME=\"localhost\"\n`\nThen, use a tool like dotenv` to load these variables when running your application.","type":"GUIDE"},{"title":"Fastapi App With The Gradio Client","slug":"/guides/fastapi-app-with-the-gradio-client/","content":"Building a Web App with the Gradio Python Client\nIn this guide, we will demonstrate how to use the gradio_client Python library, which enables developers to make requests to a Gradio app programmatically, by creating an end-to-end example web app using FastAPI. The web app we will be building is called \"Acapellify,\" and it will allow users to upload video files as input and return a version of that video without instrumental music. It will also display a gallery of generated videos.\nPrerequisites\nBefore we begin, make sure you are running Python 3.9 or later, and have the following libraries installed:\ngradio_client\nfastapi\nuvicorn\nYou can install these libraries from pip:\n``bash\n$ pip install gradio_client fastapi uvicorn\n`\nYou will also need to have ffmpeg installed. You can check to see if you already have ffmpeg by running in your terminal:\n`bash\n$ ffmpeg version\n`\nOtherwise, install ffmpeg by following these instructions.\nStep 1: Write the Video Processing Function\nLet's start with what seems like the most complex bit -- using machine learning to remove the music from a video.\nLuckily for us, there's an existing Space we can use to make this process easier: https://huggingface.co/spaces/abidlabs/music-separation. This Space takes an audio file and produces two separate audio files: one with the instrumental music and one with all other sounds in the original clip. Perfect to use with our client!\nOpen a new Python file, say main.py, and start by importing the Client class from gradio_client and connecting it to this Space:\n`py\nfrom gradioclient import Client, handlefile\nclient = Client(\"abidlabs/music-separation\")\ndef acapellify(audio_path):\n    result = client.predict(handlefile(audiopath), api_name=\"/predict\")\n    return result[0]\n`\nThat's all the code that's needed -- notice that the API endpoints returns two audio files (one without the music, and one with just the music) in a list, and so we just return the first element of the list.\nNote: since this is a public Space, there might be other users using this Space as well, which might result in a slow experience. You can duplicate this Space with your own Hugging Face token and create a private Space that only you have will have access to and bypass the queue. To do that, simply replace the first two lines above with:\n`py\nfrom gradio_client import Client\nclient = Client.duplicate(\"abidlabs/music-separation\", token=YOURHFTOKEN)\n`\nEverything else remains the same!\nNow, of course, we are working with video files, so we first need to extract the audio from the video files. For this, we will be using the ffmpeg library, which does a lot of heavy lifting when it comes to working with audio and video files. The most common way to use ffmpeg is through the command line, which we'll call via Python's subprocess module:\nOur video processing workflow will consist of three steps:\nFirst, we start by taking in a video filepath and extracting the audio using ffmpeg.\nThen, we pass in the audio file through the acapellify() function above.\nFinally, we combine the new audio with the original video to produce a final acapellified video.\nHere's the complete code in Python, which you can add to your main.py file:\n`python\nimport subprocess\ndef processvideo(videopath):\n    oldaudio = os.path.basename(videopath).split(\".\")[0] + \".m4a\"\n    subprocess.run(['ffmpeg', '-y', '-i', videopath, '-vn', '-acodec', 'copy', oldaudio])\n    newaudio = acapellify(oldaudio)\n    newvideo = f\"acap{video_path}\"\n    subprocess.call(['ffmpeg', '-y', '-i', videopath, '-i', newaudio, '-map', '0:v', '-map', '1:a', '-c:v', 'copy', '-c:a', 'aac', '-strict', 'experimental', f\"static/{new_video}\"])\n    return new_video\n`\nYou can read up on ffmpeg documentation if you'd like to understand all of the command line parameters, as they are beyond the scope of this tutorial.\nStep 2: Create a FastAPI app (Backend Routes)\nNext up, we'll create a simple FastAPI app. If you haven't used FastAPI before, check out the great FastAPI docs. Otherwise, this basic template, which we add to main.py, will look pretty familiar:\n`python\nimport os\nfrom fastapi import FastAPI, File, UploadFile, Request\nfrom fastapi.responses import HTMLResponse, RedirectResponse\nfrom fastapi.staticfiles import StaticFiles\nfrom fastapi.templating import Jinja2Templates\napp = FastAPI()\nos.makedirs(\"static\", exist_ok=True)\napp.mount(\"/static\", StaticFiles(directory=\"static\"), name=\"static\")\ntemplates = Jinja2Templates(directory=\"templates\")\nvideos = []\n@app.get(\"/\", response_class=HTMLResponse)\nasync def home(request: Request):\n    return templates.TemplateResponse(\n        \"home.html\", {\"request\": request, \"videos\": videos})\n@app.post(\"/uploadvideo/\")\nasync def upload_video(video: UploadFile = File(...)):\n    video_path = video.filename\n    with open(video_path, \"wb+\") as fp:\n        fp.write(video.file.read())\n    newvideo = processvideo(video.filename)\n    videos.append(new_video)\n    return RedirectResponse(url='/', status_code=303)\n`\nIn this example, the FastAPI app has two routes: / and /uploadvideo/.\nThe / route returns an HTML template that displays a gallery of all uploaded videos.\nThe /uploadvideo/ route accepts a POST request with an UploadFile object, which represents the uploaded video file. The video file is \"acapellified\" via the process_video() method, and the output video is stored in a list which stores all of the uploaded videos in memory.\nNote that this is a very basic example and if this were a production app, you will need to add more logic to handle file storage, user authentication, and security considerations.\nStep 3: Create a FastAPI app (Frontend Template)\nFinally, we create the frontend of our web application. First, we create a folder called templates in the same directory as main.py. We then create a template, home.html inside the templates folder. Here is the resulting file structure:\n`csv\n├── main.py\n├── templates\n│   └── home.html\n`\nWrite the following as the contents of home.html:\n`html\n&lt;!DOCTYPE html> &lt;html> &lt;head> &lt;title>Video Gallery&lt;/title>\n&lt;style> body { font-family: sans-serif; margin: 0; padding: 0;\nbackground-color: #f5f5f5; } h1 { text-align: center; margin-top: 30px;\nmargin-bottom: 20px; } .gallery { display: flex; flex-wrap: wrap;\njustify-content: center; gap: 20px; padding: 20px; } .video { border: 2px solid\n#ccc; box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.2); border-radius: 5px; overflow:\nhidden; width: 300px; margin-bottom: 20px; } .video video { width: 100%; height:\n200px; } .video p { text-align: center; margin: 10px 0; } form { margin-top:\n20px; text-align: center; } input[type=\"file\"] { display: none; } .upload-btn {\ndisplay: inline-block; background-color: #3498db; color: #fff; padding: 10px\n20px; font-size: 16px; border: none; border-radius: 5px; cursor: pointer; }\n.upload-btn:hover { background-color: #2980b9; } .file-name { margin-left: 10px;\n} &lt;/style> &lt;/head> &lt;body> &lt;h1>Video Gallery&lt;/h1> {% if videos %}\n&lt;div class=\"gallery\"> {% for video in videos %} &lt;div class=\"video\">\n&lt;video controls> &lt;source src=\"{{ url_for('static', path=video) }}\"\ntype=\"video/mp4\"> Your browser does not support the video tag. &lt;/video>\n&lt;p>{{ video }}&lt;/p> &lt;/div> {% endfor %} &lt;/div> {% else %} &lt;p>No\nvideos uploaded yet.&lt;/p> {% endif %} &lt;form action=\"/uploadvideo/\"\nmethod=\"post\" enctype=\"multipart/form-data\"> &lt;label for=\"video-upload\"\nclass=\"upload-btn\">Choose video file&lt;/label> &lt;input type=\"file\"\nname=\"video\" id=\"video-upload\"> &lt;span class=\"file-name\">&lt;/span> &lt;button\ntype=\"submit\" class=\"upload-btn\">Upload&lt;/button> &lt;/form> &lt;script> //\nDisplay selected file name in the form const fileUpload =\ndocument.getElementById(\"video-upload\"); const fileName =\ndocument.querySelector(\".file-name\"); fileUpload.addEventListener(\"change\", (e)\n=> { fileName.textContent = e.target.files[0].name; }); &lt;/script> &lt;/body>\n&lt;/html>\n`\nStep 4: Run your FastAPI app\nFinally, we are ready to run our FastAPI app, powered by the Gradio Python Client!\nOpen up a terminal and navigate to the directory containing main.py. Then run the following command in the terminal:\n`bash\n$ uvicorn main:app\n`\nYou should see an output that looks like this:\n`csv\nLoaded as API: https://abidlabs-music-separation.hf.space ✔\nINFO:     Started server process [1360]\nINFO:     Waiting for application startup.\nINFO:     Application startup complete.\nINFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)\n``\nAnd that's it! Start uploading videos and you'll get some \"acapellified\" videos in response (might take seconds to minutes to process depending on the length of your videos). Here's how the UI looks after uploading two videos:\nIf you'd like to learn more about how to use the Gradio Python Client in your projects, read the dedicated Guide.","type":"GUIDE"},{"title":"File Access","slug":"/guides/file-access/","content":"Security and File Access\nSharing your Gradio app with others (by hosting it on Spaces, on your own server, or through temporary share links) exposes certain files on your machine to the internet. Files that are exposed can be accessed at a special URL:\n``bash\nhttp:///gradio_api/file=\n`\nThis guide explains which files are exposed as well as some best practices for making sure the files on your machine are secure.\nFiles Gradio allows users to access \nStatic files. You can designate static files or directories using the gr.setstaticpaths function. Static files  are not be copied to the Gradio cache (see below) and will be served directly from your computer. This can help save disk space and reduce the time your app takes to launch but be mindful of possible security implications as any static files are accessible to all useres of your Gradio app.\nFiles in the allowed_paths parameter in launch(). This parameter allows you to pass in a list of additional directories or exact filepaths you'd like to allow users to have access to. (By default, this parameter is an empty list).\nFiles in Gradio's cache. After you launch your Gradio app, Gradio copies certain files into a temporary cache and makes these files accessible to users. Let's unpack this in more detail below.\nThe Gradio cache\nFirst, it's important to understand why Gradio has a cache at all. Gradio copies files to a cache directory before returning them to the frontend. This prevents files from being overwritten by one user while they are still needed by another user of your application. For example, if your prediction function returns a video file, then Gradio will move that video to the cache after your prediction function runs and returns a URL the frontend can use to show the video. Any file in the cache is available via URL to all users of your running application.\n            \n                \n                    \n                    \n                    \n                \n                You can customize the location of the cache by setting the GRADIOTEMPDIR environment variable to an absolute path, such as /home/usr/scripts/project/temp/. \n            \n                \nFiles Gradio moves to the cache\nGradio moves three kinds of files into the cache\nFiles specified by the developer before runtime, e.g. cached examples, default values of components, or files passed into parameters such as the avatar_images of gr.Chatbot\nFile paths returned by a prediction function in your Gradio application, if they ALSO meet one of the conditions below:\nIt is in the allowed_paths parameter of the Blocks.launch method.\nIt is in the current working directory of the python interpreter.\nIt is in the temp directory obtained by tempfile.gettempdir().\nNote: files in the current working directory whose name starts with a period (.) will not be moved to the cache, even if they are returned from a prediction function, since they often contain sensitive information. \nIf none of these criteria are met, the prediction function that is returning that file will raise an exception instead of moving the file to cache. Gradio performs this check so that arbitrary files on your machine cannot be accessed.\nFiles uploaded by a user to your Gradio app (e.g. through the File or Image input components).\n            \n                \n                    \n                    \n                    \n                \n                If at any time Gradio blocks a file that you would like it to process, add its path to the allowed_paths parameter.\n            \n                \nThe files Gradio will not allow others to access\nWhile running, Gradio apps will NOT ALLOW users to access:\nFiles that you explicitly block via the blockedpaths parameter in launch(). You can pass in a list of additional directories or exact filepaths to the blockedpaths parameter in launch(). This parameter takes precedence over the files that Gradio exposes by default, or by the allowedpaths parameter or the gr.setstatic_paths function.\nAny other paths on the host machine. Users should NOT be able to access other arbitrary paths on the host.\nUploading Files\nSharing your Gradio application will also allow users to upload files to your computer or server. You can set a maximum file size for uploads to prevent abuse and to preserve disk space. You can do this with the maxfilesize parameter of .launch. For example, the following two code snippets limit file uploads to 5 megabytes per file.\n`python\nimport gradio as gr\ndemo = gr.Interface(lambda x: x, \"image\", \"image\")\ndemo.launch(maxfilesize=\"5mb\")\nor\ndemo.launch(maxfilesize=5 * gr.FileSize.MB)\n`\nBest Practices\nSet a maxfilesize for your application.\nDo not return arbitrary user input from a function that is connected to a file-based output component (gr.Image, gr.File, etc.). For example, the following interface would allow anyone to move an arbitrary file in your local directory to the cache: gr.Interface(lambda s: s, \"text\", \"file\"). This is because the user input is treated as an arbitrary file path. \nMake allowedpaths as small as possible. If a path in allowedpaths is a directory, any file within that directory can be accessed. Make sure the entires of allowed_paths only contains files related to your application.\nRun your gradio application from the same directory the application file is located in. This will narrow the scope of files Gradio will be allowed to move into the cache. For example, prefer python app.py to python Users/sources/project/app.py.\nExample: Accessing local files\nBoth gr.setstaticpaths and the allowed_paths parameter in launch expect absolute paths. Below is a minimal example to display a local .png image file in an HTML block.\n`txt\n├── assets\n│   └── logo.png\n└── app.py\n`\nFor the example directory structure, logo.png and any other files in the assets folder can be accessed from your Gradio app in app.py as follows:\n`python\nfrom pathlib import Path\nimport gradio as gr\ngr.setstaticpaths(paths=[Path.cwd().absolute()/\"assets\"])\nwith gr.Blocks() as demo:\n    gr.HTML(\"\")\ndemo.launch()\n``","type":"GUIDE"},{"title":"File Upload Mcp","slug":"/guides/file-upload-mcp/","content":"The File Upload MCP Server\nIf you've tried to to use a remote Gradio MCP server that takes a file as input (image, video, audio), you've probably run into this error:\nThe reason is that since the Gradio server is hosted on a different machine, any input files must be available via a public URL so that they can downloaded in the remote machine.\nThere are many ways to host files on the internet, but they all require adding a manual step to your workflow. In the age of LLM agents, shouldn't we expect them to handle this step for you?\nIn this post, we'll show how you can connect your LLM to the \"File Upload\" MCP server so that it can handle the file uploading for you when appropriate!\nUsing the File Upload MCP Server\nAs of version 5.36.0, Gradio now comes with a built-in MCP server that can upload files to a running Gradio application. In the View API page of the server, you should see the following code snippet if any of the tools require file inputs:\nThe command to start the MCP server takes two arguments:\nThe URL (or Hugging Face space id) of the gradio application to upload the files to. In this case, http://127.0.0.1:7860.\nThe local directory on your computer with which the server is allowed to upload files from (`). For security, please make this directory as narrow as possible to prevent unintended file uploads.\nAs stated in the image, you need to install uv (a python package manager that can run python scripts) before connecting from your MCP client. \nIf you have gradio installed locally and you don't want to install uv, you can replace the uvx command with the path to gradio binary. It should look like this:\n`json\n\"upload-files\": {\n    \"command\": \"\",\n    \"args\": [\n    \"upload-mcp\",\n    \"http://localhost:7860/\",\n    \"/Users/freddyboulton/Pictures\"\n    ]\n}\n`\nAfter connecting to the upload server, your LLM agent will know when to upload files for you automatically!\nConclusion\nIn this guide, we've covered how you can connect to the Upload File MCP Server so that your agent can upload files before using Gradio MCP servers. Remember to set the ` as small as possible to prevent unintended file uploads!","type":"GUIDE"},{"title":"Filters Tables And Stats","slug":"/guides/filters-tables-and-stats/","content":"Filters, Tables and Stats\nYour dashboard will likely consist of more than just plots. Let's take a look at some of the other common components of a dashboard.\nFilters\nUse 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:\n``python\nimport gradio as gr\nfrom data import df  \nwith gr.Blocks() as demo:\n    with gr.Row():\n        origin = gr.Dropdown([\"All\", \"DFW\", \"DAL\", \"HOU\"], value=\"All\", label=\"Origin\")\n        destination = gr.Dropdown([\"All\", \"JFK\", \"LGA\", \"EWR\"], value=\"All\", label=\"Destination\")\n        max_price = gr.Slider(0, 1000, value=1000, label=\"Max Price\")\n    plt = gr.ScatterPlot(df, x=\"time\", y=\"price\", inputs=[origin, destination, max_price])\n    @gr.on(inputs=[origin, destination, max_price], outputs=plt)\n    def filtereddata(origin, destination, maxprice):\n        _df = df[df[\"price\"] \nAnd this would be the function-as-value approach for the same demo.\n``python\nimport gradio as gr\nfrom data import df  \nwith gr.Blocks() as demo:\n    with gr.Row():\n        origin = gr.Dropdown([\"All\", \"DFW\", \"DAL\", \"HOU\"], value=\"All\", label=\"Origin\")\n        destination = gr.Dropdown([\"All\", \"JFK\", \"LGA\", \"EWR\"], value=\"All\", label=\"Destination\")\n        max_price = gr.Slider(0, 1000, value=1000, label=\"Max Price\")\n    def filtereddata(origin, destination, maxprice):\n        _df = df[df[\"price\"]","type":"GUIDE"},{"title":"Flagging","slug":"/guides/flagging/","content":"Flagging\nYou may have noticed the \"Flag\" button that appears by default in your Interface. When a user using your demo sees input with interesting output, such as erroneous or unexpected model behaviour, they can flag the input for you to review. Within the directory provided by the flagging_dir= argument to the Interface constructor, a CSV file will log the flagged inputs. If the interface involves file data, such as for Image and Audio components, folders will be created to store those flagged data as well.\nFor example, with the calculator interface shown above, we would have the flagged data stored in the flagged directory shown below:\n``directory\n+-- calculator.py\n+-- flagged/\n|   +-- logs.csv\n`\nflagged/logs.csv\n`csv\nnum1,operation,num2,Output\n5,add,7,12\n6,subtract,1.5,4.5\n`\nWith the sepia interface shown earlier, we would have the flagged data stored in the flagged directory shown below:\n`directory\n+-- sepia.py\n+-- flagged/\n|   +-- logs.csv\n|   +-- im/\n|   |   +-- 0.png\n|   |   +-- 1.png\n|   +-- Output/\n|   |   +-- 0.png\n|   |   +-- 1.png\n`\nflagged/logs.csv\n`csv\nim,Output\nim/0.png,Output/0.png\nim/1.png,Output/1.png\n`\nIf you wish for the user to provide a reason for flagging, you can pass a list of strings to the flagging_options` argument of Interface. Users will have to select one of the strings when flagging, which will be saved as an additional column to the CSV.","type":"GUIDE"},{"title":"Four Kinds Of Interfaces","slug":"/guides/four-kinds-of-interfaces/","content":"The 4 Kinds of Gradio Interfaces\nSo far, we've always assumed that in order to build an Gradio demo, you need both inputs and outputs. But this isn't always the case for machine learning demos: for example, unconditional image generation models don't take any input but produce an image as the output.\nIt turns out that the gradio.Interface class can actually handle 4 different kinds of demos:\nStandard demos: which have both separate inputs and outputs (e.g. an image classifier or speech-to-text model)\nOutput-only demos: which don't take any input but produce on output (e.g. an unconditional image generation model)\nInput-only demos: which don't produce any output but do take in some sort of input (e.g. a demo that saves images that you upload to a persistent external database)\nUnified demos: which have both input and output components, but the input and output components are the same. This means that the output produced overrides the input (e.g. a text autocomplete model)\nDepending on the kind of demo, the user interface (UI) looks slightly different:\nLet's see how to build each kind of demo using the Interface class, along with examples:\nStandard demos\nTo 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:\n``python\nimport numpy as np\nimport gradio as gr\ndef sepia(input_img):\n    sepia_filter = np.array([\n        [0.393, 0.769, 0.189],\n        [0.349, 0.686, 0.168],\n        [0.272, 0.534, 0.131]\n    ])\n    sepiaimg = inputimg.dot(sepia_filter.T)\n    sepiaimg /= sepiaimg.max()\n    return sepia_img\ndemo = gr.Interface(sepia, gr.Image(), \"image\", api_name=\"predict\")\ndemo.launch()\n`\nOutput-only demos\nWhat 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:\n`python\nimport time\nimport gradio as gr\ndef fake_gan():\n    time.sleep(1)\n    images = [\n            \"https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=387&q=80\",\n            \"https://images.unsplash.com/photo-1554151228-14d9def656e4?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=386&q=80\",\n            \"https://images.unsplash.com/photo-1542909168-82c3e7fdca5c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8aHVtYW4lMjBmYWNlfGVufDB8fDB8fA%3D%3D&w=1000&q=80\",\n    ]\n    return images\ndemo = gr.Interface(\n    fn=fake_gan,\n    inputs=None,\n    outputs=gr.Gallery(label=\"Generated Images\", columns=2),\n    title=\"FD-GAN\",\n    description=\"This is a fake demo of a GAN. In reality, the images are randomly chosen from Unsplash.\",\n    api_name=\"predict\",\n)\ndemo.launch()\n`\nInput-only demos\nSimilarly, 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:\n`python\nimport random\nimport string\nimport gradio as gr\ndef saveimagerandom_name(image):\n    randomstring = ''.join(random.choices(string.asciiletters, k=20)) + '.png'\n    image.save(random_string)\n    print(f\"Saved image to {random_string}!\")\ndemo = gr.Interface(\n    fn=saveimagerandom_name,\n    inputs=gr.Image(type=\"pil\"),\n    outputs=None,\n    api_name=\"predict\",\n)\ndemo.launch()\n`\nUnified demos\nA 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:\n`python\nimport gradio as gr\nfrom transformers import pipeline\ngenerator = pipeline('text-generation', model = 'gpt2')\ndef generatetext(textprompt):\n  response = generator(textprompt, maxlength = 30, numreturnsequences=5)\n  return response[0]['generated_text']  \ntextbox = gr.Textbox()\ndemo = gr.Interface(generatetext, textbox, textbox, apiname=\"predict\")\ndemo.launch()\n`\nIt 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!","type":"GUIDE"},{"title":"Frequently Asked Questions","slug":"/guides/frequently-asked-questions/","content":"Frequently Asked Questions\nWhat do I need to install before using Custom Components?\nBefore using Custom Components, make sure you have Python 3.10+, Node.js v18+, npm 9+, and Gradio 4.0+ (preferably Gradio 5.0+) installed.\nAre custom components compatible between Gradio 4.0 and 5.0?\nCustom components built with Gradio 5.0 should be compatible with Gradio 4.0. If you built your custom component in Gradio 4.0 you will have to rebuild your component to be compatible with Gradio 5.0. Simply follow these steps:\nUpdate the @gradio/preview package. cd into the frontend directory and run npm update.\nModify the dependencies key in pyproject.toml to pin the maximum allowed Gradio version at version 5, e.g. dependencies = [\"gradio>=4.0,.py, however the gradio command will hot reload so you can instantly see your changes. \nThe development server didn't work for me \nCheck your terminal and browser console\nMake sure there are no syntax errors or other obvious problems in your code. Exceptions triggered from python will be displayed in the terminal. Exceptions from javascript will be displayed in the browser console and/or the terminal.\nAre you developing on Windows?\nChrome on Windows will block the local compiled svelte files for security reasons. We recommend developing your custom component in the windows subsystem for linux (WSL) while the team looks at this issue.\nInspect the window.GRADIOCC_ variable\nIn the browser console, print the window.GRADIOCC variable (just type it into the console). If it is an empty object, that means\nthat the CLI could not find your custom component source code. Typically, this happens when the custom component is installed in a different virtual environment than the one used to run the dev command. Please use the --python-path and gradio-path CLI arguments to specify the path of the python and gradio executables for the environment your component is installed in. For example, if you are using a virtualenv located at /Users/mary/venv, pass in /Users/mary/bin/python and /Users/mary/bin/gradio respectively.\nIf the window.GRADIOCC variable is not empty (see below for an example), then the dev server should be working correctly. \nMake sure you are using a virtual environment\nIt is highly recommended you use a virtual environment to prevent conflicts with other python dependencies installed in your system.\nDo I always need to start my component from scratch?\nNo! You can start off from an existing gradio component as a template, see the five minute guide.\nYou can also start from an existing custom component if you'd like to tweak it further. Once you find the source code of a custom component you like, clone the code to your computer and run gradio cc install. Then you can run the development server to make changes.If you run into any issues, contact the author of the component by opening an issue in their repository. The gallery is a good place to look for published components. For example, to start from the PDF component, clone the space with git clone https://huggingface.co/spaces/freddyaboulton/gradiopdf, cd into the src directory, and run gradio cc install.\nDo I need to host my custom component on HuggingFace Spaces?\nYou can develop and build your custom component without hosting or connecting to HuggingFace.\nIf you would like to share your component with the gradio community, it is recommended to publish your package to PyPi and host a demo on HuggingFace so that anyone can install it or try it out.\nWhat methods are mandatory for implementing a custom component in Gradio?\nYou must implement the preprocess, postprocess, examplepayload, and examplevalue methods. If your component does not use a data model, you must also define the apiinfo, flag, and readfrom_flag methods. Read more in the backend guide.\nWhat is the purpose of a data_model in Gradio custom components?\nA data_model defines the expected data format for your component, simplifying the component development process and self-documenting your code. It streamlines API usage and example caching.\nWhy is it important to use FileData for components dealing with file uploads?\nUtilizing FileData is crucial for components that expect file uploads. It ensures secure file handling, automatic caching, and streamlined client library functionality.\nHow can I add event triggers to my custom Gradio component?\nYou can define event triggers in the EVENTS class attribute by listing the desired event names, which automatically adds corresponding methods to your component.\nCan I implement a custom Gradio component without defining a data_model?\nYes, it is possible to create custom components without a datamodel, but you are going to have to manually implement apiinfo, flag, and readfromflag methods.\nAre there sample custom components I can learn from?\nWe have prepared this collection of custom components on the HuggingFace Hub that you can use to get started!\nHow can I find custom components created by the Gradio community?\nWe're working on creating a gallery to make it really easy to discover new custom components.\nIn the meantime, you can search for HuggingFace Spaces that are tagged as a gradio-custom-component here","type":"GUIDE"},{"title":"From Openapi Spec","slug":"/guides/from-openapi-spec/","content":"Creating a Gradio app from an OpenAPI Spec\nIntroduction\nOpenAPI is a widely adopted standard for describing RESTful APIs in a machine-readable format, typically as a JSON  file. \nYou can create a Gradio UI from an OpenAPI Spec in 1 line of Python, instantly generating an interactive web interface for any API, making it accessible for demos, testing, or sharing with non-developers, without writing custom frontend code.\nHow it works\nGradio now provides a convenient function, gr.load_openapi, that can automatically generate a Gradio app from an OpenAPI v3 specification. This function parses the spec, creates UI components for each endpoint and parameter, and lets you interact with the API directly from your browser.\nHere's a minimal example:\n``python\nimport gradio as gr\ndemo = gr.load_openapi(\n    openapi_spec=\"https://petstore3.swagger.io/api/v3/openapi.json\",\n    base_url=\"https://petstore3.swagger.io/api/v3\",\n    paths=[\"/pet.*\"],\n    methods=[\"get\", \"post\"],\n)\ndemo.launch()\n`\nParameters:\nopenapi_spec: URL, file path, or Python dictionary containing the OpenAPI v3 spec (JSON format only).\nbase_url: The base URL for the API endpoints (e.g., https://api.example.com/v1).\npaths (optional): List of endpoint path patterns (supports regex) to include. If not set, all paths are included.\nmethods (optional): List of HTTP methods (e.g., [\"get\", \"post\"]`) to include. If not set, all methods are included.\nThe generated app will display a sidebar with available endpoints and create interactive forms for each operation, letting you make API calls and view responses in real time.\nNext steps\nOnce your Gradio app is running, you can share the URL with others so they can try out the API through a friendly web interface—no code required. For even more power, you can launch the app as an MCP (Model Control Protocol) server using Gradio's MCP integration, enabling programmatic access and orchestration of your API via the MCP ecosystem. This makes it easy to build, share, and automate API workflows with minimal effort.","type":"GUIDE"},{"title":"Frontend","slug":"/guides/frontend/","content":"The Frontend 🌐⭐️\nThis guide will cover everything you need to know to implement your custom component's frontend.\n            \n                \n                    \n                    \n                    \n                \n                Gradio components use Svelte. Writing Svelte is fun! If you're not familiar with it, we recommend checking out their interactive guide.\n            \n                \nThe directory structure \nThe frontend code should have, at minimum, three files:\nIndex.svelte: This is the main export and where your component's layout and logic should live.\nExample.svelte: This is where the example view of the component is defined.\nFeel free to add additional files and subdirectories. \nIf you want to export any additional modules, remember to modify the package.json file\n``json\n\"exports\": {\n    \".\": \"./Index.svelte\",\n    \"./example\": \"./Example.svelte\",\n    \"./package.json\": \"./package.json\"\n},\n`\nThe Index.svelte file\nYour component should expose the following props that will be passed down from the parent Gradio application.\n`typescript\nimport type { LoadingStatus } from \"@gradio/statustracker\";\nimport type { Gradio } from \"@gradio/utils\";\nexport let gradio: Gradio;\nexport let elem_id = \"\";\nexport let elem_classes: string[] = [];\nexport let scale: number | null = null;\nexport let min_width: number | undefined = undefined;\nexport let loading_status: LoadingStatus | undefined = undefined;\nexport let mode: \"static\" | \"interactive\";\n`\nelemid and elemclasses allow Gradio app developers to target your component with custom CSS and JavaScript from the Python Blocks class.\nscale and min_width allow Gradio app developers to control how much space your component takes up in the UI.\nloading_status is used to display a loading status over the component when it is the output of an event.\nmode is how the parent Gradio app tells your component whether the interactive or static version should be displayed.\ngradio: The gradio object is created by the parent Gradio app. It stores some application-level configuration that will be useful in your component, like internationalization. You must use it to dispatch events from your component.\nA minimal Index.svelte file would look like:\n`svelte\n\timport type { LoadingStatus } from \"@gradio/statustracker\";\n    import { Block } from \"@gradio/atoms\";\n\timport { StatusTracker } from \"@gradio/statustracker\";\n\timport type { Gradio } from \"@gradio/utils\";\n\texport let gradio: Gradio;\n    export let value = \"\";\n\texport let elem_id = \"\";\n\texport let elem_classes: string[] = [];\n\texport let scale: number | null = null;\n\texport let min_width: number | undefined = undefined;\n\texport let loading_status: LoadingStatus | undefined = undefined;\n    export let mode: \"static\" | \"interactive\";\n\t{#if loading_status}\n\t\t\n\t{/if}\n    {value}\n`\nThe Example.svelte file\nThe Example.svelte file should expose the following props:\n`typescript\n    export let value: string;\n    export let type: \"gallery\" | \"table\";\n    export let selected = false;\n    export let index: number;\n`\nvalue: The example value that should be displayed.\ntype: This is a variable that can be either \"gallery\" or \"table\" depending on how the examples are displayed. The \"gallery\" form is used when the examples correspond to a single input component, while the \"table\" form is used when a user has multiple input components, and the examples need to populate all of them. \nselected: You can also adjust how the examples are displayed if a user \"selects\" a particular example by using the selected variable.\nindex: The current index of the selected value.\nAny additional props your \"non-example\" component takes!\nThis is the Example.svelte file for the code Radio component:\n`svelte\n\texport let value: string;\n\texport let type: \"gallery\" | \"table\";\n\texport let selected = false;\n\t{value}\n\t.gallery {\n\t\tpadding: var(--size-1) var(--size-2);\n\t}\n`\nHandling Files\nIf your component deals with files, these files should be uploaded to the backend server. \nThe @gradio/client npm package provides the upload and prepare_files utility functions to help you do this.\nThe prepare_files function will convert the browser's File datatype to gradio's internal FileData type.\nYou should use the FileData data in your component to keep track of uploaded files.\nThe upload function will upload an array of FileData values to the server.\nHere's an example of loading files from an  element when its value changes.\n`svelte\n    import { upload, prepare_files, type FileData } from \"@gradio/client\";\n    export let root;\n    export let value;\n    let uploaded_files;\n    async function handleupload(filedata: FileData[]): Promise {\n        await tick();\n        uploadedfiles = await upload(filedata, root);\n    }\n    async function loadFiles(files: FileList): Promise {\n        let _files: File[] = Array.from(files);\n        if (!files.length) {\n            return;\n        }\n        if (file_count === \"single\") {\n            _files = [files[0]];\n        }\n        let filedata = await preparefiles(_files);\n        await handleupload(filedata);\n    }\n    async function loadFilesFromUpload(e: Event): Promise {\n\t\tconst target = e.target;\n\t\tif (!target.files) return;\n\t\tawait loadFiles(target.files);\n\t}\n`\nThe component exposes a prop named root. \nThis is passed down by the parent gradio app and it represents the base url that the files will be uploaded to and fetched from.\nFor WASM support, you should get the upload function from the Context and pass that as the third parameter of the upload function.\n`typescript\n    import { getContext } from \"svelte\";\n    const uploadfn = getContext(\"uploadfiles\");\n    async function handleupload(filedata: FileData[]): Promise {\n        await tick();\n        await upload(filedata, root, uploadfn);\n    }\n`\nLeveraging Existing Gradio Components\nMost of Gradio's frontend components are published on npm, the javascript package repository.\nThis means that you can use them to save yourself time while incorporating common patterns in your component, like uploading files.\nFor example, the @gradio/upload package has Upload and ModifyUpload components for properly uploading files to the Gradio server. \nHere is how you can use them to create a user interface to upload and display PDF files.\n`svelte\n\timport { type FileData, Upload, ModifyUpload } from \"@gradio/upload\";\n\timport { Empty, UploadText, BlockLabel } from \"@gradio/atoms\";\n{#if value === null && interactive}\n    \n        \n    \n{:else if value !== null}\n    {#if interactive}\n        \n    {/if}\n    \n{:else}\n      \t\n{/if}\n`\nYou can also combine existing Gradio components to create entirely unique experiences.\nLike rendering a gallery of chatbot conversations. \nThe possibilities are endless, please read the documentation on our javascript packages here.\nWe'll be adding more packages and documentation over the coming weeks!\nMatching Gradio Core's Design System\nYou can explore our component library via Storybook. You'll be able to interact with our components and see them in their various states.\nFor those interested in design customization, we provide the CSS variables consisting of our color palette, radii, spacing, and the icons we use - so you can easily match up your custom component with the style of our core components. This Storybook will be regularly updated with any new additions or changes.\nStorybook Link\nCustom configuration\nIf you want to make use of the vast vite ecosystem, you can use the gradio.config.js file to configure your component's build process. This allows you to make use of tools like tailwindcss, mdsvex, and more.\nCurrently, it is possible to configure the following:\nVite options:\nplugins: A list of vite plugins to use.\nSvelte options:\npreprocess: A list of svelte preprocessors to use.\nextensions: A list of file extensions to compile to .svelte files.\nbuild.target: The target to build for, this may be necessary to support newer javascript features. See the esbuild docs for more information.\nThe gradio.config.js file should be placed in the root of your component's frontend directory. A default config file is created for you when you create a new component. But you can also create your own config file, if one doesn't exist, and use it to customize your component's build process.\nExample for a Vite plugin\nCustom components can use Vite plugins to customize the build process. Check out the Vite Docs for more information. \nHere we configure TailwindCSS, a utility-first CSS framework. Setup is easiest using the version 4 prerelease. \n`\nnpm install tailwindcss@next @tailwindcss/vite@next\n`\nIn gradio.config.js:\n`typescript\nimport tailwindcss from \"@tailwindcss/vite\";\nexport default {\n    plugins: [tailwindcss()]\n};\n`\nThen create a style.css file with the following content:\n`css\n@import \"tailwindcss\";\n`\nImport this file into Index.svelte. Note, that you need to import the css file containing @import and cannot just use a  tag and use @import there. \n`svelte\n[...]\nimport \"./style.css\";\n[...]\n`\nExample for Svelte options\nIn gradio.config.js you can also specify a some Svelte options to apply to the Svelte compilation. In this example we will add support for mdsvex, a Markdown preprocessor for Svelte. \nIn order to do this we will need to add a Svelte Preprocessor to the svelte object in gradio.config.js and configure the extensions field. Other options are not currently supported.\nFirst, install the mdsvex plugin:\n`bash\nnpm install mdsvex\n`\nThen add the following to gradio.config.js:\n`typescript\nimport { mdsvex } from \"mdsvex\";\nexport default {\n    svelte: {\n        preprocess: [\n            mdsvex()\n        ],\n        extensions: [\".svelte\", \".svx\"]\n    }\n};\n`\nNow we can create mdsvex documents in our component's frontend directory and they will be compiled to .svelte files.\n`md\n    import { Block } from \"@gradio/atoms\";\n    export let title = \"Hello World\";\n{title}\nThis is a markdown file.\n`\nWe can then use the HelloWorld.svx file in our components:\n`svelte\n    import HelloWorld from \"./HelloWorld.svx\";\n``\nConclusion\nYou now know how to create delightful frontends for your components!","type":"GUIDE"},{"title":"Getting Started With The Js Client","slug":"/guides/getting-started-with-the-js-client/","content":"Getting Started with the Gradio JavaScript Client\nThe Gradio JavaScript Client makes it very easy to use any Gradio app as an API. As an example, consider this Hugging Face Space that transcribes audio files that are recorded from the microphone.\nUsing the @gradio/client library, we can easily use the Gradio as an API to transcribe audio files programmatically.\nHere's the entire code to do it:\n``js\nimport { Client, handle_file } from \"@gradio/client\";\nconst response = await fetch(\n\t\"https://github.com/audio-samples/audio-samples.github.io/raw/master/samples/wav/ted_speakers/SalmanKhan/sample-1.wav\"\n);\nconst audio_file = await response.blob();\nconst app = await Client.connect(\"abidlabs/whisper\");\nconst transcription = await app.predict(\"/predict\", [handlefile(audiofile)]);\nconsole.log(transcription.data);\n// [ \"I said the same phrase 30 times.\" ]\n`\nThe Gradio Client works with any hosted Gradio app, whether it be an image generator, a text summarizer, a stateful chatbot, a tax calculator, or anything else! The Gradio Client is mostly used with apps hosted on Hugging Face Spaces, but your app can be hosted anywhere, such as your own server.\nPrequisites: To use the Gradio client, you do not need to know the gradio library in great detail. However, it is helpful to have general familiarity with Gradio's concepts of input and output components.\nInstallation via npm\nInstall the @gradio/client package to interact with Gradio APIs using Node.js version >=18.0.0 or in browser-based projects. Use npm or any compatible package manager:\n`bash\nnpm i @gradio/client\n`\nThis command adds @gradio/client to your project dependencies, allowing you to import it in your JavaScript or TypeScript files.\nInstallation via CDN\nFor quick addition to your web project, you can use the jsDelivr CDN to load the latest version of @gradio/client directly into your HTML:\n`html\n\timport { Client } from \"https://cdn.jsdelivr.net/npm/@gradio/client/dist/index.min.js\";\n\t...\n`\nBe sure to add this to the  of your HTML. This will install the latest version but we advise hardcoding the version in production. You can find all available versions here. This approach is ideal for experimental or prototying purposes, though has some limitations. A complete example would look like this:\n`html\n    \n        import { Client } from \"https://cdn.jsdelivr.net/npm/@gradio/client/dist/index.min.js\";\n        const client = await Client.connect(\"abidlabs/en2fr\");\n        const result = await client.predict(\"/predict\", {\n            text: \"My name is Hannah\"\n        });\n        console.log(result);\n    \n`\nConnecting to a running Gradio App\nStart by connecting instantiating a client instance and connecting it to a Gradio app that is running on Hugging Face Spaces or generally anywhere on the web.\nConnecting to a Hugging Face Space\n`js\nimport { Client } from \"@gradio/client\";\nconst app = await Client.connect(\"abidlabs/en2fr\"); // a Space that translates from English to French\n`\nYou can also connect to private Spaces by passing in your HF token with the token property of the options parameter. You can get your HF token here: https://huggingface.co/settings/tokens\n`js\nimport { Client } from \"@gradio/client\";\nconst app = await Client.connect(\"abidlabs/my-private-space\", { token: \"hf_...\" })\n`\nDuplicating a Space for private use\nWhile you can use any public Space as an API, you may get rate limited by Hugging Face if you make too many requests. For unlimited usage of a Space, simply duplicate the Space to create a private Space, and then use it to make as many requests as you'd like! You'll need to pass in your Hugging Face token).\nClient.duplicate is almost identical to Client.connect, the only difference is under the hood:\n`js\nimport { Client, handle_file } from \"@gradio/client\";\nconst response = await fetch(\n\t\"https://audio-samples.github.io/samples/mp3/blizzard_unconditional/sample-0.mp3\"\n);\nconst audio_file = await response.blob();\nconst app = await Client.duplicate(\"abidlabs/whisper\", { token: \"hf_...\" });\nconst transcription = await app.predict(\"/predict\", [handlefile(audiofile)]);\n`\nIf you have previously duplicated a Space, re-running Client.duplicate will not create a new Space. Instead, the client will attach to the previously-created Space. So it is safe to re-run the Client.duplicate method multiple times with the same space.\nNote: if the original Space uses GPUs, your private Space will as well, and your Hugging Face account will get billed based on the price of the GPU. To minimize charges, your Space will automatically go to sleep after 5 minutes of inactivity. You can also set the hardware using the hardware and timeout properties of duplicate's options object like this:\n`js\nimport { Client } from \"@gradio/client\";\nconst app = await Client.duplicate(\"abidlabs/whisper\", {\n\ttoken: \"hf_...\",\n\ttimeout: 60,\n\thardware: \"a10g-small\"\n});\n`\nConnecting a general Gradio app\nIf your app is running somewhere else, just provide the full URL instead, including the \"http://\" or \"https://\". Here's an example of making predictions to a Gradio app that is running on a share URL:\n`js\nimport { Client } from \"@gradio/client\";\nconst app = Client.connect(\"https://bec81a83-5b5c-471e.gradio.live\");\n`\nConnecting to a Gradio app with auth\nIf the Gradio application you are connecting to requires a username and password, then provide them as a tuple to the auth argument of the Client class:\n`js\nimport { Client } from \"@gradio/client\";\nClient.connect(\n  space_name,\n  { auth: [username, password] }\n)\n`\nInspecting the API endpoints\nOnce you have connected to a Gradio app, you can view the APIs that are available to you by calling the Client's view_api method.\nFor the Whisper Space, we can do this:\n`js\nimport { Client } from \"@gradio/client\";\nconst app = await Client.connect(\"abidlabs/whisper\");\nconst appinfo = await app.viewapi();\nconsole.log(app_info);\n`\nAnd we will see the following:\n`json\n{\n\t\"named_endpoints\": {\n\t\t\"/predict\": {\n\t\t\t\"parameters\": [\n\t\t\t\t{\n\t\t\t\t\t\"label\": \"text\",\n\t\t\t\t\t\"component\": \"Textbox\",\n\t\t\t\t\t\"type\": \"string\"\n\t\t\t\t}\n\t\t\t],\n\t\t\t\"returns\": [\n\t\t\t\t{\n\t\t\t\t\t\"label\": \"output\",\n\t\t\t\t\t\"component\": \"Textbox\",\n\t\t\t\t\t\"type\": \"string\"\n\t\t\t\t}\n\t\t\t]\n\t\t}\n\t},\n\t\"unnamed_endpoints\": {}\n}\n`\nThis shows us that we have 1 API endpoint in this space, and shows us how to use the API endpoint to make a prediction: we should call the .predict() method (which we will explore below), providing a parameter input_audio of type string, which is a url to a file.\nWe should also provide the apiname='/predict' argument to the predict() method. Although this isn't necessary if a Gradio app has only 1 named endpoint, it does allow us to call different endpoints in a single app if they are available. If an app has unnamed API endpoints, these can also be displayed by running .viewapi(all_endpoints=True).\nThe \"View API\" Page\nAs an alternative to running the .view_api() method, you can click on the \"Use via API\" link in the footer of the Gradio app, which shows us the same information, along with example usage. \nThe View API page also includes an \"API Recorder\" that lets you interact with the Gradio UI normally and converts your interactions into the corresponding code to run with the JS Client.\nMaking a prediction\nThe simplest way to make a prediction is simply to call the .predict() method with the appropriate arguments:\n`js\nimport { Client } from \"@gradio/client\";\nconst app = await Client.connect(\"abidlabs/en2fr\");\nconst result = await app.predict(\"/predict\", [\"Hello\"]);\n`\nIf there are multiple parameters, then you should pass them as an array to .predict(), like this:\n`js\nimport { Client } from \"@gradio/client\";\nconst app = await Client.connect(\"gradio/calculator\");\nconst result = await app.predict(\"/predict\", [4, \"add\", 5]);\n`\nFor certain inputs, such as images, you should pass in a Buffer, Blob or File depending on what is most convenient. In node, this would be a Buffer or Blob; in a browser environment, this would be a Blob or File.\n`js\nimport { Client, handle_file } from \"@gradio/client\";\nconst response = await fetch(\n\t\"https://audio-samples.github.io/samples/mp3/blizzard_unconditional/sample-0.mp3\"\n);\nconst audio_file = await response.blob();\nconst app = await Client.connect(\"abidlabs/whisper\");\nconst result = await app.predict(\"/predict\", [handlefile(audiofile)]);\n`\nUsing events\nIf the API you are working with can return results over time, or you wish to access information about the status of a job, you can use the iterable interface for more flexibility. This is especially useful for iterative endpoints or generator endpoints that will produce a series of values over time as discrete responses.\n`js\nimport { Client } from \"@gradio/client\";\nfunction log_result(payload) {\n\tconst {\n\t\tdata: [translation]\n\t} = payload;\n\tconsole.log(The translated result is: ${translation});\n}\nconst app = await Client.connect(\"abidlabs/en2fr\");\nconst job = app.submit(\"/predict\", [\"Hello\"]);\nfor await (const message of job) {\n\tlog_result(message);\n}\n`\nStatus\nThe event interface also allows you to get the status of the running job by instantiating the client with the events options passing status and data as an array:\n`ts\nimport { Client } from \"@gradio/client\";\nconst app = await Client.connect(\"abidlabs/en2fr\", {\n\tevents: [\"status\", \"data\"]\n});\n`\nThis ensures that status messages are also reported to the client.\nstatuses are returned as an object with the following attributes: status (a human readbale status of the current job, \"pending\" | \"generating\" | \"complete\" | \"error\"), code (the detailed gradio code for the job), position (the current position of this job in the queue), queue_size (the total queue size), eta (estimated time this job will complete), success (a boolean representing whether the job completed successfully), and time ( as Date object detailing the time that the status was generated).\n`js\nimport { Client } from \"@gradio/client\";\nfunction log_status(status) {\n\tconsole.log(\n\t\tThe current status for this job is: ${JSON.stringify(status, null, 2)}.\n\t);\n}\nconst app = await Client.connect(\"abidlabs/en2fr\", {\n\tevents: [\"status\", \"data\"]\n});\nconst job = app.submit(\"/predict\", [\"Hello\"]);\nfor await (const message of job) {\n\tif (message.type === \"status\") {\n\t\tlog_status(message);\n\t}\n}\n`\nCancelling Jobs\nThe job instance also has a .cancel() method that cancels jobs that have been queued but not started. For example, if you run:\n`js\nimport { Client } from \"@gradio/client\";\nconst app = await Client.connect(\"abidlabs/en2fr\");\nconst job_one = app.submit(\"/predict\", [\"Hello\"]);\nconst job_two = app.submit(\"/predict\", [\"Friends\"]);\njob_one.cancel();\njob_two.cancel();\n`\nIf the first job has started processing, then it will not be canceled but the client will no longer listen for updates (throwing away the job). If the second job has not yet started, it will be successfully canceled and removed from the queue.\nGenerator Endpoints\nSome Gradio API endpoints do not return a single value, rather they return a series of values. You can listen for these values in real time using the iterable interface:\n`js\nimport { Client } from \"@gradio/client\";\nconst app = await Client.connect(\"gradio/count_generator\");\nconst job = app.submit(0, [9]);\nfor await (const message of job) {\n\tconsole.log(message.data);\n}\n`\nThis will log out the values as they are generated by the endpoint.\nYou can also cancel jobs that that have iterative outputs, in which case the job will finish immediately.\n`js\nimport { Client } from \"@gradio/client\";\nconst app = await Client.connect(\"gradio/count_generator\");\nconst job = app.submit(0, [9]);\nfor await (const message of job) {\n\tconsole.log(message.data);\n}\nsetTimeout(() => {\n\tjob.cancel();\n}, 3000);\n``","type":"GUIDE"},{"title":"Getting Started With The Python Client","slug":"/guides/getting-started-with-the-python-client/","content":"Getting Started with the Gradio Python client\nThe Gradio Python client makes it very easy to use any Gradio app as an API. As an example, consider this Hugging Face Space that transcribes audio files that are recorded from the microphone.\nUsing the gradio_client library, we can easily use the Gradio as an API to transcribe audio files programmatically.\nHere's the entire code to do it:\n``python\nfrom gradioclient import Client, handlefile\nclient = Client(\"abidlabs/whisper\")\nclient.predict(\n    audio=handlefile(\"audiosample.wav\")\n)\n>> \"This is a test of the whisper speech recognition model.\"\n`\nThe Gradio client works with any hosted Gradio app! Although the Client is mostly used with apps hosted on Hugging Face Spaces, your app can be hosted anywhere, such as your own server.\nPrerequisites: To use the Gradio client, you do not need to know the gradio library in great detail. However, it is helpful to have general familiarity with Gradio's concepts of input and output components.\nInstallation\nIf you already have a recent version of gradio, then the gradioclient is included as a dependency. But note that this documentation reflects the latest version of the gradioclient, so upgrade if you're not sure!\nThe lightweight gradio_client package can be installed from pip (or pip3) and is tested to work with Python versions 3.10 or higher:\n`bash\n$ pip install --upgrade gradio_client\n`\nConnecting to a Gradio App on Hugging Face Spaces\nStart by connecting instantiating a Client object and connecting it to a Gradio app that is running on Hugging Face Spaces.\n`python\nfrom gradio_client import Client\nclient = Client(\"abidlabs/en2fr\")  # a Space that translates from English to French\n`\nYou can also connect to private Spaces by passing in your HF token with the token parameter. You can get your HF token here: https://huggingface.co/settings/tokens\n`python\nfrom gradio_client import Client\nclient = Client(\"abidlabs/my-private-space\", token=\"...\")\n`\nDuplicating a Space for private use\nWhile you can use any public Space as an API, you may get rate limited by Hugging Face if you make too many requests. For unlimited usage of a Space, simply duplicate the Space to create a private Space,\nand then use it to make as many requests as you'd like!\nThe gradio_client includes a class method: Client.duplicate() to make this process simple (you'll need to pass in your Hugging Face token or be logged in using the Hugging Face CLI):\n`python\nimport os\nfrom gradioclient import Client, handlefile\nHFTOKEN = os.environ.get(\"HFTOKEN\")\nclient = Client.duplicate(\"abidlabs/whisper\", token=HF_TOKEN)\nclient.predict(handlefile(\"audiosample.wav\"))\n>> \"This is a test of the whisper speech recognition model.\"\n`\nIf you have previously duplicated a Space, re-running duplicate() will not create a new Space. Instead, the Client will attach to the previously-created Space. So it is safe to re-run the Client.duplicate() method multiple times.\nNote: if the original Space uses GPUs, your private Space will as well, and your Hugging Face account will get billed based on the price of the GPU. To minimize charges, your Space will automatically go to sleep after 1 hour of inactivity. You can also set the hardware using the hardware parameter of duplicate().\nConnecting a general Gradio app\nIf your app is running somewhere else, just provide the full URL instead, including the \"http://\" or \"https://\". Here's an example of making predictions to a Gradio app that is running on a share URL:\n`python\nfrom gradio_client import Client\nclient = Client(\"https://bec81a83-5b5c-471e.gradio.live\")\n`\nConnecting to a Gradio app with auth\nIf the Gradio application you are connecting to requires a username and password, then provide them as a tuple to the auth argument of the Client class:\n`python\nfrom gradio_client import Client\nClient(\n  space_name,\n  auth=[username, password]\n)\n`\nInspecting the API endpoints\nOnce you have connected to a Gradio app, you can view the APIs that are available to you by calling the Client.view_api() method. For the Whisper Space, we see the following:\n`bash\nClient.predict() Usage Info\n---------------------------\nNamed API endpoints: 1\npredict(audio, api_name=\"/predict\") -> output\n    Parameters:\n[Audio] audio: filepath (required)  \n    Returns:\n[Textbox] output: str \n`\nWe see  that we have 1 API endpoint in this space, and shows us how to use the API endpoint to make a prediction: we should call the .predict() method (which we will explore below), providing a parameter input_audio of type str, which is a filepath or URL.\nWe should also provide the api_name='/predict' argument to the predict() method. Although this isn't necessary if a Gradio app has only 1 named endpoint, it does allow us to call different endpoints in a single app if they are available.\nThe \"View API\" Page\nAs an alternative to running the .view_api() method, you can click on the \"Use via API\" link in the footer of the Gradio app, which shows us the same information, along with example usage. \nThe View API page also includes an \"API Recorder\" that lets you interact with the Gradio UI normally and converts your interactions into the corresponding code to run with the Python Client.\nMaking a prediction\nThe simplest way to make a prediction is simply to call the .predict() function with the appropriate arguments:\n`python\nfrom gradio_client import Client\nclient = Client(\"abidlabs/en2fr\")\nclient.predict(\"Hello\", api_name='/predict')\n>> Bonjour\n`\nIf there are multiple parameters, then you should pass them as separate arguments to .predict(), like this:\n`python\nfrom gradio_client import Client\nclient = Client(\"gradio/calculator\")\nclient.predict(4, \"add\", 5)\n>> 9.0\n`\nIt is recommended to provide key-word arguments instead of positional arguments:\n`python\nfrom gradio_client import Client\nclient = Client(\"gradio/calculator\")\nclient.predict(num1=4, operation=\"add\", num2=5)\n>> 9.0\n`\nThis allows you to take advantage of default arguments. For example, this Space includes the default value for the Slider component so you do not need to provide it when accessing it with the client.\n`python\nfrom gradio_client import Client\nclient = Client(\"abidlabs/image_generator\")\nclient.predict(text=\"an astronaut riding a camel\")\n`\nThe default value is the initial value of the corresponding Gradio component. If the component does not have an initial value, but if the corresponding argument in the predict function has a default value of None, then that parameter is also optional in the client. Of course, if you'd like to override it, you can include it as well:\n`python\nfrom gradio_client import Client\nclient = Client(\"abidlabs/image_generator\")\nclient.predict(text=\"an astronaut riding a camel\", steps=25)\n`\nFor providing files or URLs as inputs, you should pass in the filepath or URL to the file enclosed within gradioclient.handlefile(). This takes care of uploading the file to the Gradio server and ensures that the file is preprocessed correctly:\n`python\nfrom gradioclient import Client, handlefile\nclient = Client(\"abidlabs/whisper\")\nclient.predict(\n    audio=handlefile(\"https://audio-samples.github.io/samples/mp3/blizzardunconditional/sample-0.mp3\")\n)\n>> \"My thought I have nobody by a beauty and will as you poured. Mr. Rochester is serve in that so don't find simpus, and devoted abode, to at might in a r—\"\n`\nRunning jobs asynchronously\nOne should note that .predict() is a blocking operation as it waits for the operation to complete before returning the prediction.\nIn many cases, you may be better off letting the job run in the background until you need the results of the prediction. You can do this by creating a Job instance using the .submit() method, and then later calling .result() on the job to get the result. For example:\n`python\nfrom gradio_client import Client\nclient = Client(space=\"abidlabs/en2fr\")\njob = client.submit(\"Hello\", api_name=\"/predict\")  # This is not blocking\nDo something else\njob.result()  # This is blocking\n>> Bonjour\n`\nAdding callbacks\nAlternatively, one can add one or more callbacks to perform actions after the job has completed running, like this:\n`python\nfrom gradio_client import Client\ndef print_result(x):\n    print(\"The translated result is: {x}\")\nclient = Client(space=\"abidlabs/en2fr\")\njob = client.submit(\"Hello\", apiname=\"/predict\", resultcallbacks=[print_result])\nDo something else\n>> The translated result is: Bonjour\n`\nStatus\nThe Job object also allows you to get the status of the running job by calling the .status() method. This returns a StatusUpdate object with the following attributes: code (the status code, one of a set of defined strings representing the status. See the utils.Status class), rank (the current position of this job in the queue), queue_size (the total queue size), eta (estimated time this job will complete), success (a boolean representing whether the job completed successfully), and time (the time that the status was generated).\n`py\nfrom gradio_client import Client\nclient = Client(src=\"gradio/calculator\")\njob = client.submit(5, \"add\", 4, api_name=\"/predict\")\njob.status()\n>> \n`\nNote: The Job class also has a .done() instance method which returns a boolean indicating whether the job has completed.\nCancelling Jobs\nThe Job class also has a .cancel() instance method that cancels jobs that have been queued but not started. For example, if you run:\n`py\nclient = Client(\"abidlabs/whisper\")\njob1 = client.submit(handlefile(\"audiosample1.wav\"))\njob2 = client.submit(handlefile(\"audiosample2.wav\"))\njob1.cancel()  # will return False, assuming the job has started\njob2.cancel()  # will return True, indicating that the job has been canceled\n`\nIf the first job has started processing, then it will not be canceled. If the second job\nhas not yet started, it will be successfully canceled and removed from the queue.\nGenerator Endpoints\nSome Gradio API endpoints do not return a single value, rather they return a series of values. You can get the series of values that have been returned at any time from such a generator endpoint by running job.outputs():\n`py\nfrom gradio_client import Client\nclient = Client(src=\"gradio/count_generator\")\njob = client.submit(3, api_name=\"/count\")\nwhile not job.done():\n    time.sleep(0.1)\njob.outputs()\n>> ['0', '1', '2']\n`\nNote that running job.result() on a generator endpoint only gives you the first value returned by the endpoint.\nThe Job object is also iterable, which means you can use it to display the results of a generator function as they are returned from the endpoint. Here's the equivalent example using the Job as a generator:\n`py\nfrom gradio_client import Client\nclient = Client(src=\"gradio/count_generator\")\njob = client.submit(3, api_name=\"/count\")\nfor o in job:\n    print(o)\n>> 0\n>> 1\n>> 2\n`\nYou can also cancel jobs that that have iterative outputs, in which case the job will finish as soon as the current iteration finishes running.\n`py\nfrom gradio_client import Client\nimport time\nclient = Client(\"abidlabs/test-yield\")\njob = client.submit(\"abcdef\")\ntime.sleep(3)\njob.cancel()  # job cancels after 2 iterations\n`\nDemos with Session State\nGradio demos can include session state, which provides a way for demos to persist information from user interactions within a page session.\nFor example, consider the following demo, which maintains a list of words that a user has submitted in a gr.State component. When a user submits a new word, it is added to the state, and the number of previous occurrences of that word is displayed:\n`python\nimport gradio as gr\ndef count(word, listofwords):\n    return listofwords.count(word), listofwords + [word]\nwith gr.Blocks() as demo:\n    words = gr.State([])\n    textbox = gr.Textbox()\n    number = gr.Number()\n    textbox.submit(count, inputs=[textbox, words], outputs=[number, words])\n    \ndemo.launch()\n`\nIf you were to connect this this Gradio app using the Python Client, you would notice that the API information only shows a single input and output:\n`csv\nClient.predict() Usage Info\n---------------------------\nNamed API endpoints: 1\npredict(word, apiname=\"/count\") -> value31\n    Parameters:\n[Textbox] word: str (required)  \n    Returns:\n[Number] value_31: float \n`\nThat is because the Python client handles state automatically for you -- as you make a series of requests, the returned state from one request is stored internally and automatically supplied for the subsequent request. If you'd like to reset the state, you can do that by calling Client.reset_session()`.","type":"GUIDE"},{"title":"Gradio 6 Migration Guide","slug":"/guides/gradio-6-migration-guide/","content":"Gradio 6 Migration Guide\nWe are excited to release Gradio 6, the latest major version of the Gradio library. Gradio 6 is significantly more performant, lighter, and easier to customize than previous versions of Gradio. The Gradio team is only planning on maintaining future versions of Gradio 6 so we encourage all developers to migrate to Gradio 6.x.\nGradio 6 includes several breaking changes that were made in order to standardize the Python API. This migration guide lists the breaking changes and the specific code changes needed in order to migrate. The easiest way to know whether you need to make changes is to upgrade your Gradio app to 5.50 (pip install --upgrade gradio==5.50). Gradio 5.50 emits deprecation warnings for any parameters removed in Gradio 6, allowing you to know whether your Gradio app will be compatible with Gradio 6.\nHere, we walk through the breaking changes that were introduced in Gradio 6. Code snippets are provided, allowing you to migrate your code easily to Gradio 6. You can also copy-paste this document as Markdown if you are using an LLM to help migrate your code. \nApp-level Changes\nApp-level parameters have been moved from Blocks to launch()\nThe gr.Blocks class constructor previously contained several parameters that applied to your entire Gradio app, specifically:\ntheme: The theme for your Gradio app\ncss: Custom CSS code as a string\ncss_paths: Paths to custom CSS files\njs: Custom JavaScript code\nhead: Custom HTML code to insert in the head of the page\nhead_paths: Paths to custom HTML files to insert in the head\nSince gr.Blocks can be nested and are not necessarily unique to a Gradio app, these parameters have now been moved to Blocks.launch(), which can only be called once for your entire Gradio app.\nBefore (Gradio 5.x):\n``python\nimport gradio as gr\nwith gr.Blocks(\n    theme=gr.themes.Soft(),\n    css=\".my-class { color: red; }\",\n) as demo:\n    gr.Textbox(label=\"Input\")\ndemo.launch()\n`\nAfter (Gradio 6.x):\n`python\nimport gradio as gr\nwith gr.Blocks() as demo:\n    gr.Textbox(label=\"Input\")\ndemo.launch(\n    theme=gr.themes.Soft(),\n    css=\".my-class { color: red; }\",\n)\n`\nThis change makes it clearer that these parameters apply to the entire app and not to individual Blocks instances.\nshowapi parameter replaced with footerlinks\nThe showapi parameter in launch() has been replaced with a more flexible footerlinks parameter that allows you to control which links appear in the footer of your Gradio app.\nIn Gradio 5.x:\nshow_api=True (default) showed the API documentation link in the footer\nshow_api=False hid the API documentation link\nIn Gradio 6.x:\nfooter_links accepts a list of strings: [\"api\", \"gradio\", \"settings\"]\nYou can now control precisely which footer links are shown:\n\"api\": Shows the API documentation link\n\"gradio\": Shows the \"Built with Gradio\" link\n\"settings\": Shows the settings link\nBefore (Gradio 5.x):\n`python\nimport gradio as gr\nwith gr.Blocks() as demo:\n    gr.Textbox(label=\"Input\")\ndemo.launch(show_api=False)\n`\nAfter (Gradio 6.x):\n`python\nimport gradio as gr\nwith gr.Blocks() as demo:\n    gr.Textbox(label=\"Input\")\ndemo.launch(footer_links=[\"gradio\", \"settings\"])\n`\nTo replicate the old behavior:\nshowapi=True → footerlinks=[\"api\", \"gradio\", \"settings\"] (or just omit the parameter, as this is the default)\nshowapi=False → footerlinks=[\"gradio\", \"settings\"]\nEvent listener parameters: showapi removed and apiname=False no longer supported\nIn event listeners (such as .click(), .change(), etc.), the showapi parameter has been removed, and apiname no longer accepts False as a valid value. These have been replaced with a new api_visibility parameter that provides more fine-grained control.\nIn Gradio 5.x:\nshow_api=True (default) showed the endpoint in the API documentation\nshow_api=False hid the endpoint from API docs but still allowed downstream apps to use it\napi_name=False completely disabled the API endpoint (no downstream apps could use it)\nIn Gradio 6.x:\napi_visibility accepts one of three string values:\n\"public\": The endpoint is shown in API docs and accessible to all (equivalent to old show_api=True)\n\"undocumented\": The endpoint is hidden from API docs but still accessible to downstream apps (equivalent to old show_api=False)\n\"private\": The endpoint is hidden from API docs and not callable by the Gradio client libraries (equivalent to old api_name=False). Note: direct HTTP requests to the endpoint are still possible.\nBefore (Gradio 5.x):\n`python\nimport gradio as gr\nwith gr.Blocks() as demo:\n    btn = gr.Button(\"Click me\")\n    output = gr.Textbox()\n    \n    btn.click(fn=lambda: \"Hello\", outputs=output, show_api=False)\n    \ndemo.launch()\n`\nOr to completely disable the API:\n`python\nbtn.click(fn=lambda: \"Hello\", outputs=output, api_name=False)\n`\nAfter (Gradio 6.x):\n`python\nimport gradio as gr\nwith gr.Blocks() as demo:\n    btn = gr.Button(\"Click me\")\n    output = gr.Textbox()\n    \n    btn.click(fn=lambda: \"Hello\", outputs=output, api_visibility=\"undocumented\")\n    \ndemo.launch()\n`\nOr to completely disable the API:\n`python\nbtn.click(fn=lambda: \"Hello\", outputs=output, api_visibility=\"private\")\n`\nTo replicate the old behavior:\nshowapi=True → apivisibility=\"public\" (or just omit the parameter, as this is the default)\nshowapi=False → apivisibility=\"undocumented\"\napiname=False → apivisibility=\"private\"\nlikeusermessage moved from .like() event to constructor \nThe likeusermessage parameter has been moved from the .like() event listener to the Chatbot constructor.\nBefore (Gradio 5.x):\n`python\nchatbot = gr.Chatbot()\nchatbot.like(printlikedislike, None, None, likeusermessage=True)\n`\nAfter (Gradio 6.x):\n`python\nchatbot = gr.Chatbot(likeusermessage=True)\nchatbot.like(printlikedislike, None, None)\n`\nDefault API names for Interface and ChatInterface now use function names\nThe default API endpoint names for gr.Interface and gr.ChatInterface have changed to be consistent with how gr.Blocks events work and to better support MCP (Model Context Protocol) tools.\nIn Gradio 5.x:\ngr.Interface had a default API name of /predict\ngr.ChatInterface had a default API name of /chat\nIn Gradio 6.x:\nBoth gr.Interface and gr.ChatInterface now use the name of the function you pass in as the default API endpoint name\nThis makes the API more descriptive and consistent with gr.Blocks behavior\nE.g. if your Gradio app is:\n`python\nimport gradio as gr\ndef generate_text(prompt):\n    return f\"Generated: {prompt}\"\ndemo = gr.Interface(fn=generate_text, inputs=\"text\", outputs=\"text\")\ndemo.launch()\n`\nPreviously, the API endpoint that Gradio generated would be: /predict. Now, the API endpoint will be: /generate_text\nTo maintain the old endpoint names:\nIf you need to keep the old endpoint names for backward compatibility (e.g., if you have external services calling these endpoints), you can explicitly set the api_name parameter:\n`python\ndemo = gr.Interface(fn=generatetext, inputs=\"text\", outputs=\"text\", apiname=\"predict\")\n`\nSimilarly for ChatInterface:\n`python\ndemo = gr.ChatInterface(fn=chatfunction, apiname=\"chat\")\n`\ngr.Chatbot and gr.ChatInterface tuple format removed\nThe tuple format for chatbot messages has been removed in Gradio 6.0. You must now use the messages format with dictionaries containing \"role\" and \"content\" keys.\nIn Gradio 5.x:\nYou could use type=\"tuples\" or the default tuple format: [[\"user message\", \"assistant message\"], ...]\nThe tuple format was a list of lists where each inner list had two elements: [usermessage, assistantmessage]\nIn Gradio 6.x:\nOnly the messages format is supported: type=\"messages\"\nMessages must be dictionaries with \"role\" and \"content\" keys: [{\"role\": \"user\", \"content\": \"Hello\"}, {\"role\": \"assistant\", \"content\": \"Hi there!\"}]\nBefore (Gradio 5.x):\n`python\nimport gradio as gr\nUsing tuple format\nchatbot = gr.Chatbot(value=[[\"Hello\", \"Hi there!\"]])\n`\nOr with type=\"tuples\":\n`python\nchatbot = gr.Chatbot(value=[[\"Hello\", \"Hi there!\"]], type=\"tuples\")\n`\nAfter (Gradio 6.x):\n`python\nimport gradio as gr\nMust use messages format\nchatbot = gr.Chatbot(\n    value=[\n        {\"role\": \"user\", \"content\": \"Hello\"},\n        {\"role\": \"assistant\", \"content\": \"Hi there!\"}\n    ],\n    type=\"messages\"\n)\n`\nSimilarly for gr.ChatInterface, if you were manually setting the chat history:\n`python\nBefore (Gradio 5.x)\ndemo = gr.ChatInterface(\n    fn=chat_function,\n    examples=[[\"Hello\", \"Hi there!\"]]\n)\nAfter (Gradio 6.x)\ndemo = gr.ChatInterface(\n    fn=chat_function,\n    examples=[{\"role\": \"user\", \"content\": \"Hello\"}, {\"role\": \"assistant\", \"content\": \"Hi there!\"}]\n)\n`\nNote: If you're using gr.ChatInterface with a function that returns messages, the function should return messages in the new format. The tuple format is no longer supported.\ngr.ChatInterface history format now uses structured content\nThe history format in gr.ChatInterface has been updated to consistently use OpenAI-style structured content format. Content is now always a list of content blocks, even for simple text messages.\nIn Gradio 5.x:\nContent could be a simple string: {\"role\": \"user\", \"content\": \"Hello\"}\nSimple text messages used a string directly\nIn Gradio 6.x:\nContent is always a list of content blocks: {\"role\": \"user\", \"content\": [{\"type\": \"text\", \"text\": \"Hello\"}]}\nThis format is consistent with OpenAI's message format and supports multimodal content (text, images, etc.)\nBefore (Gradio 5.x):\n`python\nhistory = [\n    {\"role\": \"user\", \"content\": \"What is the capital of France?\"},\n    {\"role\": \"assistant\", \"content\": \"Paris\"}\n]\n`\nAfter (Gradio 6.x):\n`python\nhistory = [\n    {\"role\": \"user\", \"content\": [{\"type\": \"text\", \"text\": \"What is the capital of France?\"}]},\n    {\"role\": \"assistant\", \"content\": [{\"type\": \"text\", \"text\": \"Paris\"}]}\n]\n`\nWith files:\nWhen files are uploaded in the chat, they are represented as content blocks with \"type\": \"file\". All content blocks (files and text) are grouped together in the same message's content array:\n`python\nhistory = [\n    {\n        \"role\": \"user\",\n        \"content\": [\n            {\"type\": \"file\", \"file\": {\"path\": \"cat1.png\"}},\n            {\"type\": \"file\", \"file\": {\"path\": \"cat2.png\"}},\n            {\"type\": \"text\", \"text\": \"What's the difference between these two images?\"}\n        ]\n    }\n]\n`\nThis structured format allows for multimodal content (text, images, files, etc.) in chat messages, making it consistent with OpenAI's API format. All files uploaded in a single message are grouped together in the content array along with any text content.\ncacheexamples parameter updated and cachemode introduced\nThe cacheexamples parameter (used in Interface, ChatInterface, and Examples) no longer accepts the string value \"lazy\". It now strictly accepts boolean values (True or False). To control the caching strategy, a new cachemode parameter has been introduced.\nIn Gradio 5.x:\ncache_examples accepted True, False, or \"lazy\".\nIn Gradio 6.x:\ncache_examples only accepts True or False.\ncache_mode accepts \"eager\" (default) or \"lazy\".\nBefore (Gradio 5.x):\n`python\nimport gradio as gr\ndemo = gr.Interface(\n    fn=predict, \n    inputs=\"text\", \n    outputs=\"text\", \n    examples=[\"Hello\", \"World\"],\n    cache_examples=\"lazy\"\n)\n`\nAfter (Gradio 6.x):\nYou must now set cache_examples=True and specify the mode separately:\n`python\nimport gradio as gr\ndemo = gr.Interface(\n    fn=predict, \n    inputs=\"text\", \n    outputs=\"text\", \n    examples=[\"Hello\", \"World\"],\n    cache_examples=True,\n    cache_mode=\"lazy\"\n)\n`\nIf you previously used cacheexamples=True (which implied eager caching), no changes are required, as cachemode defaults to \"eager\".\nComponent-level Changes\ngr.Video no longer accepts tuple values for video and subtitles\nThe tuple format for returning video with subtitles has been deprecated. Instead of returning a tuple (videopath, subtitlepath), you should now use the gr.Video component directly with the subtitles parameter.\nIn Gradio 5.x:\nYou could return a tuple of (videopath, subtitlepath) from a function\nThe tuple format was (str | Path, str | Path | None)\nIn Gradio 6.x:\nReturn a gr.Video component instance with the subtitles parameter\nThis provides more flexibility and consistency with other components\nBefore (Gradio 5.x):\n`python\nimport gradio as gr\ndef generatevideowith_subtitles(input):\n    video_path = \"output.mp4\"\n    subtitle_path = \"subtitles.srt\"\n    return (videopath, subtitlepath)\ndemo = gr.Interface(\n    fn=generatevideowith_subtitles,\n    inputs=\"text\",\n    outputs=gr.Video()\n)\ndemo.launch()\n`\nAfter (Gradio 6.x):\n`python\nimport gradio as gr\ndef generatevideowith_subtitles(input):\n    video_path = \"output.mp4\"\n    subtitle_path = \"subtitles.srt\"\n    return gr.Video(value=videopath, subtitles=subtitlepath)\ndemo = gr.Interface(\n    fn=generatevideowith_subtitles,\n    inputs=\"text\",\n    outputs=gr.Video()\n)\ndemo.launch()\n`\ngr.HTML padding parameter default changed to False\nThe default value of the padding parameter in gr.HTML has been changed from True to False for consistency with gr.Markdown.\nIn Gradio 5.x:\npadding=True was the default for gr.HTML\nHTML components had padding by default\nIn Gradio 6.x:\npadding=False is the default for gr.HTML\nThis matches the default behavior of gr.Markdown for consistency\nTo maintain the old behavior:\nIf you want to keep the padding that was present in Gradio 5.x, explicitly set padding=True:\n`python\nhtml = gr.HTML(\"Content\", padding=True)\n`\ngr.Dataframe rowcount and colcount parameters restructured\nThe rowcount and colcount parameters in gr.Dataframe have been restructured to provide more flexibility and clarity. The tuple format for specifying fixed/dynamic behavior has been replaced with separate parameters for initial counts and limits.\nIn Gradio 5.x:\nrow_count: int | tuple[int, str] - Could be an int or tuple like (5, \"fixed\") or (5, \"dynamic\")\ncol_count: int | tuple[int, str] | None - Could be an int or tuple like (3, \"fixed\") or (3, \"dynamic\")\nIn Gradio 6.x:\nrow_count: int | None - Just the initial number of rows to display\nrowlimits: tuple[int | None, int | None] | None - Tuple specifying (minrows, max_rows) constraints\ncolumn_count: int | None - The initial number of columns to display\ncolumnlimits: tuple[int | None, int | None] | None - Tuple specifying (mincolumns, max_columns) constraints\nBefore (Gradio 5.x):\n`python\nimport gradio as gr\nFixed number of rows (users can't add/remove rows)\ndf = gr.Dataframe(rowcount=(5, \"fixed\"), colcount=(3, \"dynamic\"))\n`\nOr with dynamic rows:\n`python\nDynamic rows (users can add/remove rows)\ndf = gr.Dataframe(rowcount=(5, \"dynamic\"), colcount=(3, \"fixed\"))\n`\nOr with just integers (defaults to dynamic):\n`python\ndf = gr.Dataframe(rowcount=5, colcount=3)\n`\nAfter (Gradio 6.x):\n`python\nimport gradio as gr\nFixed number of rows (users can't add/remove rows)\ndf = gr.Dataframe(rowcount=5, rowlimits=(5, 5), columncount=3, columnlimits=None)\n`\nOr with dynamic rows (users can add/remove rows):\n`python\nDynamic rows with no limits\ndf = gr.Dataframe(rowcount=5, rowlimits=None, columncount=3, columnlimits=None)\n`\nOr with min/max constraints:\n`python\nRows between 3 and 10, columns between 2 and 5\ndf = gr.Dataframe(rowcount=5, rowlimits=(3, 10), columncount=3, columnlimits=(2, 5))\n`\nMigration examples:\nrowcount=(5, \"fixed\") → rowcount=5, row_limits=(5, 5)\nrowcount=(5, \"dynamic\") → rowcount=5, row_limits=None\nrowcount=5 → rowcount=5, row_limits=None (same behavior)\ncolcount=(3, \"fixed\") → columncount=3, column_limits=(3, 3)\ncolcount=(3, \"dynamic\") → columncount=3, column_limits=None\ncolcount=3 → columncount=3, column_limits=None (same behavior)\nallow_tags=True is now the default for gr.Chatbot\nDue to the rise in LLMs returning HTML, markdown tags, and custom tags (such as  tags), the default value of allow_tags in gr.Chatbot has changed from False to True in Gradio 6.\nIn Gradio 5.x:\nallow_tags=False was the default\nAll HTML and custom tags were sanitized/removed from chatbot messages (unless explicitly allowed)\nIn Gradio 6.x:\nallow_tags=True is the default\nAll custom tags (non-standard HTML tags) are preserved in chatbot messages\nStandard HTML tags are still sanitized for security unless sanitize_html=False\nBefore (Gradio 5.x):\n`python\nimport gradio as gr\nchatbot = gr.Chatbot()\n`\nThis would remove all tags from messages, including custom tags like .\nAfter (Gradio 6.x):\n`python\nimport gradio as gr\nchatbot = gr.Chatbot()\n`\nThis will now preserve custom tags like  in the messages.\nTo maintain the old behavior:\nIf you want to continue removing all tags from chatbot messages (the old default behavior), explicitly set allow_tags=False:\n`python\nimport gradio as gr\nchatbot = gr.Chatbot(allow_tags=False)\n`\nNote: You can also specify a list of specific tags to allow:\n`python\nchatbot = gr.Chatbot(allowtags=[\"thinking\", \"toolcall\"])\n`\nThis will only preserve  and  tags while removing all other custom tags.\nOther removed component parameters\nSeveral component parameters have been removed in Gradio 6.0. These parameters were previously deprecated and have now been fully removed.\ngr.Chatbot removed parameters\nbubblefullwidth - This parameter has been removed as it no longer has any effect.\nresizeable - This parameter (with the typo) has been removed. Use resizable instead.\nBefore (Gradio 5.x):\n`python\nchatbot = gr.Chatbot(resizeable=True)\n`\nAfter (Gradio 6.x):\n`python\nchatbot = gr.Chatbot(resizable=True)\n`\nshowcopybutton, showcopyallbutton, showshare_button - These parameters have been removed. Use the buttons parameter instead.\nBefore (Gradio 5.x):\n`python\nchatbot = gr.Chatbot(showcopybutton=True, showcopyallbutton=True, showshare_button=True)\n`\nAfter (Gradio 6.x):\n`python\nchatbot = gr.Chatbot(buttons=[\"copy\", \"copy_all\", \"share\"])\n`\ngr.Audio / WaveformOptions removed parameters\nshowcontrols - This parameter in WaveformOptions has been removed. Use showrecording_waveform instead.\nBefore (Gradio 5.x):\n`python\naudio = gr.Audio(\n    waveformoptions=gr.WaveformOptions(showcontrols=False)\n)\n`\nAfter (Gradio 6.x):\n`python\naudio = gr.Audio(\n    waveformoptions=gr.WaveformOptions(showrecording_waveform=False)\n)\n`\nminlength and maxlength - These parameters have been removed. Use validators on event listeners instead.\nBefore (Gradio 5.x):\n`python\naudio = gr.Audio(minlength=1, maxlength=10)\n`\nAfter (Gradio 6.x):\n`python\naudio = gr.Audio()\naudio.upload(\n    fn=process_audio,\n    validator=lambda audio: gr.validators.isaudiocorrectlength(audio, minlength=1, max_length=10),\n    inputs=audio\n)\n`\nshowdownloadbutton, showsharebutton - These parameters have been removed. Use the buttons parameter instead.\nBefore (Gradio 5.x):\n`python\naudio = gr.Audio(showdownloadbutton=True, showsharebutton=True)\n`\nAfter (Gradio 6.x):\n`python\naudio = gr.Audio(buttons=[\"download\", \"share\"])\n`\nNote: For components where showsharebutton had a default of None (which would show the button on Spaces), you can use buttons=[\"share\"] to always show it, or omit it from the list to hide it.\ngr.Image removed parameters\nmirrorwebcam - This parameter has been removed. Use webcamoptions with gr.WebcamOptions instead.\nBefore (Gradio 5.x):\n`python\nimage = gr.Image(mirror_webcam=True)\n`\nAfter (Gradio 6.x):\n`python\nimage = gr.Image(webcam_options=gr.WebcamOptions(mirror=True))\n`\nwebcamconstraints - This parameter has been removed. Use webcamoptions with gr.WebcamOptions instead.\nBefore (Gradio 5.x):\n`python\nimage = gr.Image(webcam_constraints={\"facingMode\": \"user\"})\n`\nAfter (Gradio 6.x):\n`python\nimage = gr.Image(webcam_options=gr.WebcamOptions(constraints={\"facingMode\": \"user\"}))\n`\nshowdownloadbutton, showsharebutton, showfullscreenbutton - These parameters have been removed. Use the buttons parameter instead.\nBefore (Gradio 5.x):\n`python\nimage = gr.Image(showdownloadbutton=True, showsharebutton=True, showfullscreenbutton=True)\n`\nAfter (Gradio 6.x):\n`python\nimage = gr.Image(buttons=[\"download\", \"share\", \"fullscreen\"])\n`\ngr.Video removed parameters\nmirrorwebcam - This parameter has been removed. Use webcamoptions with gr.WebcamOptions instead.\nBefore (Gradio 5.x):\n`python\nvideo = gr.Video(mirror_webcam=True)\n`\nAfter (Gradio 6.x):\n`python\nvideo = gr.Video(webcam_options=gr.WebcamOptions(mirror=True))\n`\nwebcamconstraints - This parameter has been removed. Use webcamoptions with gr.WebcamOptions instead.\nBefore (Gradio 5.x):\n`python\nvideo = gr.Video(webcam_constraints={\"facingMode\": \"user\"})\n`\nAfter (Gradio 6.x):\n`python\nvideo = gr.Video(webcam_options=gr.WebcamOptions(constraints={\"facingMode\": \"user\"}))\n`\nminlength and maxlength - These parameters have been removed. Use validators on event listeners instead.\nBefore (Gradio 5.x):\n`python\nvideo = gr.Video(minlength=1, maxlength=10)\n`\nAfter (Gradio 6.x):\n`python\nvideo = gr.Video()\nvideo.upload(\n    fn=process_video,\n    validator=lambda video: gr.validators.isvideocorrectlength(video, minlength=1, max_length=10),\n    inputs=video\n)\n`\nshowdownloadbutton, showsharebutton - These parameters have been removed. Use the buttons parameter instead.\nBefore (Gradio 5.x):\n`python\nvideo = gr.Video(showdownloadbutton=True, showsharebutton=True)\n`\nAfter (Gradio 6.x):\n`python\nvideo = gr.Video(buttons=[\"download\", \"share\"])\n`\ngr.ImageEditor removed parameters\ncropsize - This parameter has been removed. Use canvassize instead.\nBefore (Gradio 5.x):\n`python\neditor = gr.ImageEditor(crop_size=(512, 512))\n`\nAfter (Gradio 6.x):\n`python\neditor = gr.ImageEditor(canvas_size=(512, 512))\n`\nRemoved components\ngr.LogoutButton - This component has been removed. Use gr.LoginButton instead, which handles both login and logout processes.\nBefore (Gradio 5.x):\n`python\nlogout_btn = gr.LogoutButton()\n`\nAfter (Gradio 6.x):\n`python\nlogin_btn = gr.LoginButton()\n`\nNative plot components removed parameters\nThe following parameters have been removed from gr.LinePlot, gr.BarPlot, and gr.ScatterPlot:\noverlay_point - This parameter has been removed.\nwidth - This parameter has been removed. Use CSS styling or container width instead.\nstroke_dash - This parameter has been removed.\ninteractive - This parameter has been removed.\nshowactionsbutton - This parameter has been removed.\ncolorlegendtitle - This parameter has been removed. Use color_title instead.\nshowfullscreenbutton, showexportbutton - These parameters have been removed. Use the buttons parameter instead.\nBefore (Gradio 5.x):\n`python\nplot = gr.LinePlot(\n    value=data,\n    x=\"date\",\n    y=\"downloads\",\n    overlay_point=True,\n    width=900,\n    showfullscreenbutton=True,\n    showexportbutton=True\n)\n`\nAfter (Gradio 6.x):\n`python\nplot = gr.LinePlot(\n    value=data,\n    x=\"date\",\n    y=\"downloads\",\n    buttons=[\"fullscreen\", \"export\"]\n)\n`\nNote: For colorlegendtitle, use color_title instead:\nBefore (Gradio 5.x):\n`python\nplot = gr.ScatterPlot(colorlegendtitle=\"Category\")\n`\nAfter (Gradio 6.x):\n`python\nplot = gr.ScatterPlot(color_title=\"Category\")\n`\ngr.Textbox removed parameters\nshowcopybutton - This parameter has been removed. Use the buttons parameter instead.\nBefore (Gradio 5.x):\n`python\ntext = gr.Textbox(showcopybutton=True)\n`\nAfter (Gradio 6.x):\n`python\ntext = gr.Textbox(buttons=[\"copy\"])\n`\ngr.Markdown removed parameters\nshowcopybutton - This parameter has been removed. Use the buttons parameter instead.\nBefore (Gradio 5.x):\n`python\nmarkdown = gr.Markdown(showcopybutton=True)\n`\nAfter (Gradio 6.x):\n`python\nmarkdown = gr.Markdown(buttons=[\"copy\"])\n`\ngr.Dataframe removed parameters\nshowcopybutton, showfullscreenbutton - These parameters have been removed. Use the buttons parameter instead.\nBefore (Gradio 5.x):\n`python\ndf = gr.Dataframe(showcopybutton=True, showfullscreenbutton=True)\n`\nAfter (Gradio 6.x):\n`python\ndf = gr.Dataframe(buttons=[\"copy\", \"fullscreen\"])\n`\ngr.Slider removed parameters\nshowresetbutton - This parameter has been removed. Use the buttons parameter instead.\nBefore (Gradio 5.x):\n`python\nslider = gr.Slider(showresetbutton=True)\n`\nAfter (Gradio 6.x):\n`python\nslider = gr.Slider(buttons=[\"reset\"])\n`\nCLI Changes\ngradio sketch command removed\nThe gradio sketch command-line tool has been deprecated and completely removed in Gradio 6. This tool was used to create Gradio apps through a visual interface.\nIn Gradio 5.x:\nYou could run gradio sketch to launch an interactive GUI for building Gradio apps\nThe tool would generate Python code visually\nIn Gradio 6.x:\nThe gradio sketch command has been removed\nRunning gradio sketch will raise a DeprecationWarning\nPython Client Changes\nhf_token parameter renamed to token in Client\nThe hf_token parameter in the Client class has been renamed to token for consistency and simplicity.\nBefore (Gradio 5.x):\n`python\nfrom gradio_client import Client\nclient = Client(\"abidlabs/my-private-space\", hftoken=\"hf...\")\n`\nAfter (Gradio 6.x):\n`python\nfrom gradio_client import Client\nclient = Client(\"abidlabs/my-private-space\", token=\"hf_...\")\n`\ndeploy_discord method deprecated\nThe deploy_discord method in the Client class has been deprecated and will be removed in Gradio 6.0. This method was used to deploy Gradio apps as Discord bots.\nBefore (Gradio 5.x):\n`python\nfrom gradio_client import Client\nclient = Client(\"username/space-name\")\nclient.deploydiscord(discordbot_token=\"...\")\n`\nAfter (Gradio 6.x):\nThe deploy_discord method is no longer available. Please see the documentation on creating a Discord bot with Gradio for alternative approaches.\nAppError now subclasses Exception instead of ValueError\nThe AppError exception class in the Python client now subclasses Exception directly instead of ValueError. This is a breaking change if you have code that specifically catches ValueError to handle AppError instances.\nBefore (Gradio 5.x):\n`python\nfrom gradio_client import Client\nfrom gradio_client.exceptions import AppError\ntry:\n    client = Client(\"username/space-name\")\n    result = client.predict(\"/predict\", inputs)\nexcept ValueError as e:\n    # This would catch AppError in Gradio 5.x\n    print(f\"Error: {e}\")\n`\nAfter (Gradio 6.x):\n`python\nfrom gradio_client import Client\nfrom gradio_client.exceptions import AppError\ntry:\n    client = Client(\"username/space-name\")\n    result = client.predict(\"/predict\", inputs)\nexcept AppError as e:\n    # Explicitly catch AppError\n    print(f\"App error: {e}\")\nexcept ValueError as e:\n    # This will no longer catch AppError\n    print(f\"Value error: {e}\")\n``","type":"GUIDE"},{"title":"Gradio And Llm Agents","slug":"/guides/gradio-and-llm-agents/","content":"Gradio & LLM Agents 🤝\nLarge Language Models (LLMs) are very impressive but they can be made even more powerful if we could give them skills to accomplish specialized tasks.\nThe gradio_tools library can turn any Gradio application into a tool that an agent can use to complete its task. For example, an LLM could use a Gradio tool to transcribe a voice recording it finds online and then summarize it for you. Or it could use a different Gradio tool to apply OCR to a document on your Google Drive and then answer questions about it.\nThis guide will show how you can use gradiotools to grant your LLM Agent access to the cutting edge Gradio applications hosted in the world. Although gradiotools are compatible with more than one agent framework, we will focus on Langchain Agents in this guide.\nSome background\nWhat are agents?\nA LangChain agent is a Large Language Model (LLM) that takes user input and reports an output based on using one of many tools at its disposal.\nWhat is Gradio?\nGradio is the defacto standard framework for building Machine Learning Web Applications and sharing them with the world - all with just python! 🐍\ngradio_tools - An end-to-end example\nTo get started with gradio_tools, all you need to do is import and initialize your tools and pass them to the langchain agent!\nIn the following example, we import the StableDiffusionPromptGeneratorTool to create a good prompt for stable diffusion, the\nStableDiffusionTool to create an image with our improved prompt, the ImageCaptioningTool to caption the generated image, and\nthe TextToVideoTool to create a video from a prompt.\nWe then tell our agent to create an image of a dog riding a skateboard, but to please improve our prompt ahead of time. We also ask\nit to caption the generated image and create a video for it. The agent can decide which tool to use without us explicitly telling it.\n``python\nimport os\nif not os.getenv(\"OPENAIAPIKEY\"):\n    raise ValueError(\"OPENAIAPIKEY must be set\")\nfrom langchain.agents import initialize_agent\nfrom langchain.llms import OpenAI\nfrom gradio_tools import (StableDiffusionTool, ImageCaptioningTool, StableDiffusionPromptGeneratorTool,\n                          TextToVideoTool)\nfrom langchain.memory import ConversationBufferMemory\nllm = OpenAI(temperature=0)\nmemory = ConversationBufferMemory(memorykey=\"chathistory\")\ntools = [StableDiffusionTool().langchain, ImageCaptioningTool().langchain,\n         StableDiffusionPromptGeneratorTool().langchain, TextToVideoTool().langchain]\nagent = initialize_agent(tools, llm, memory=memory, agent=\"conversational-react-description\", verbose=True)\noutput = agent.run(input=(\"Please create a photo of a dog riding a skateboard \"\n                          \"but improve my prompt prior to using an image generator.\"\n                          \"Please caption the generated image and create a video for it using the improved prompt.\"))\n`\nYou'll note that we are using some pre-built tools that come with gradiotools. Please see this doc for a complete list of the tools that come with gradiotools.\nIf you would like to use a tool that's not currently in gradio_tools, it is very easy to add your own. That's what the next section will cover.\ngradio_tools - creating your own tool\nThe core abstraction is the GradioTool, which lets you define a new tool for your LLM as long as you implement a standard interface:\n`python\nclass GradioTool(BaseTool):\n    def init(self, name: str, description: str, src: str) -> None:\n    @abstractmethod\n    def create_job(self, query: str) -> Job:\n        pass\n    @abstractmethod\n    def postprocess(self, output: Tuple[Any] | Any) -> str:\n        pass\n`\nThe requirements are:\nThe name for your tool\nThe description for your tool. This is crucial! Agents decide which tool to use based on their description. Be precise and be sure to include example of what the input and the output of the tool should look like.\nThe url or space id, e.g. freddyaboulton/calculator, of the Gradio application. Based on this value, gradio_tool will create a gradio client instance to query the upstream application via API. Be sure to click the link and learn more about the gradio client library if you are not familiar with it.\ncreate_job - Given a string, this method should parse that string and return a job from the client. Most times, this is as simple as passing the string to the submit function of the client. More info on creating jobs here\npostprocess - Given the result of the job, convert it to a string the LLM can display to the user.\nOptional - Some libraries, e.g. MiniChain, may need some info about the underlying gradio input and output types used by the tool. By default, this will return gr.Textbox() but\n   if you'd like to provide more accurate info, implement the blockinput(self, gr) and blockoutput(self, gr) methods of the tool. The gr variable is the gradio module (the result of import gradio as gr). It will be\n   automatically imported by the GradiTool parent class and passed to the blockinput and blockoutput methods.\nAnd that's it!\nOnce you have created your tool, open a pull request to the gradio_tools repo! We welcome all contributions.\nExample tool - Stable Diffusion\nHere is the code for the StableDiffusion tool as an example:\n`python\nfrom gradio_tool import GradioTool\nimport os\nclass StableDiffusionTool(GradioTool):\n    \"\"\"Tool for calling stable diffusion from llm\"\"\"\n    def init(\n        self,\n        name=\"StableDiffusion\",\n        description=(\n            \"An image generator. Use this to generate images based on \"\n            \"text input. Input should be a description of what the image should \"\n            \"look like. The output will be a path to an image file.\"\n        ),\n        src=\"gradio-client-demos/stable-diffusion\",\n        token=None,\n    ) -> None:\n        super().init(name, description, src, token)\n    def create_job(self, query: str) -> Job:\n        return self.client.submit(query, \"\", 9, fn_index=1)\n    def postprocess(self, output: str) -> str:\n        return [os.path.join(output, i) for i in os.listdir(output) if not i.endswith(\"json\")][0]\n    def blockinput(self, gr) -> \"gr.components.Component\":\n        return gr.Textbox()\n    def blockoutput(self, gr) -> \"gr.components.Component\":\n        return gr.Image()\n`\nSome notes on this implementation:\nAll instances of GradioTool have an attribute called client that is a pointed to the underlying gradio client. That is what you should use\n   in the create_job method.\ncreate_job just passes the query string to the submit function of the client with some other parameters hardcoded, i.e. the negative prompt string and the guidance scale. We could modify our tool to also accept these values from the input string in a subsequent version.\nThe postprocess method simply returns the first image from the gallery of images created by the stable diffusion space. We use the os` module to get the full path of the image.\nConclusion\nYou now know how to extend the abilities of your LLM with the 1000s of gradio spaces running in the wild!\nAgain, we welcome any contributions to the gradio_tools library.\nWe're excited to see the tools you all build!","type":"GUIDE"},{"title":"Gradio Workflows Vs N8n Vs Comfyui","slug":"/guides/gradio-workflows-vs-n8n-vs-comfyui/","content":"gradio workflows vs n8n vs comfyui\nnode graphs! three tools everyone lumps together because they all look like boxes with wires between them. but they can do completely different jobs.\nquick version if you're skimming:\ncomfyui → you want control over how the image gets made\nn8n → you want it running on its own at 4am\ngr.Workflow → you want the thing you built to be an app with a url and an api\nwhat gr.Workflow actually is\nit's a gradio app that reads a graph out of a json file and gives you a canvas. the whole thing is this:\n``python\nimport gradio as gr\ndef reverse(text: str) -> str:\n    return (text or \"\")[::-1]\ndemo = gr.Workflow(graph=\"workflow.json\", bind={\"reverse\": reverse})\ndemo.launch()\n`\nbind is you handing the canvas a list of your own python functions and going \"you can call these.\"\nno graph yet? pass your functions in a list, tell it what connects to what, and gradio writes the json file the first time you hit save.\nnodes come in three flavours. stuff going in, stuff coming out, and the interesting bit in the middle. that middle bit can be a hugging face space, a model running through hf inference, a dataset, or one of your own functions.\nthe hub is the node library\nhere's the bit that actually changes how you work.\nthe sidebar ships with a curated set of spaces and models so it isn't an empty search box on day one, and searching it searches that set. everything else on the hub you reach by pasting: drop owner/repo or a url into the sidebar's space box, or into the picker on a node, and it resolves the repo and adds it. spaces, models, datasets.\nyou don't install anything. you don't write a wrapper. drag a space on and gradio fetches its /info, reads the endpoints, and draws the ports for you. if it has more than one endpoint you pick which one you want from the node itself. models work slightly differently — they're typed off the pipeline tag, so a text-to-image model gets a prompt in and an image out, no api call needed to work that out.\nso you type \"background removal\" in, drag the first thing that looks good, wire it to your image input. thirty seconds.\none gotcha: adding a space needs the space to actually answer. if it's asleep or it isn't a gradio app with an api, you get an error at drag time, not at run time.\nmodels let you pin an inference provider too (together, replicate, whoever) or leave it on auto and let hf route it.\nthe workflow is an api\nthe execution logic that runs when you click through the canvas also exists in python, so your graph runs fine with nobody watching it.\nwhich means the thing you dragged together is also an api.\nbuild a graph where a text box feeds a local function, a model, and a space, all landing on outputs. gradio knows they're connected and gives you one endpoint that takes your text and returns all three results together. call it with gradio_client, or call it over http. it shows up in the view api panel like any other gradio app, documented, typed, ready to drop into someone else's code.\nso you never have to choose between the canvas and the app. the graph is the app. wire up boxes for two minutes, and what you've actually built is a hugging face space with a ui people can click and an endpoint you can use wherever you like.\nvs n8n\nn8n is automation. cron jobs. webhooks. it watches your inbox. it has a credentials store hooked into a few hundred services, it replays failed runs, it has fallback workflows for when something dies at 4am and you're asleep.\n\"when a stripe charge goes through, write a row to postgres and post in #sales\" — n8n solved that years ago. gr.Workflow hasn't, because nothing here runs on a timer, fires on its own, or holds your third party logins for you.\nwhat gr.Workflow gives you instead is a link. you deploy to a space, you send someone a url, they use it. or they call it from code. n8n can sort of get there with a webhook node but you're building toward it, whereas here it's the only mode there is.\nthe other difference is what's in the sidebar. n8n's integration list is huge and hand-built, one node per service, maintained by people. gradio's is the hugging face hub, which is a lot more stuff and a lot less curation.\nuse n8n if it needs to run on a schedule.\nuse gr.Workflow if a person needs to click it.\nvs comfyui\ncomfy lives a floor below this.\nits nodes are the guts of image generation, samplers and schedulers and loras and all of it. you want to change how one step of a twenty step generation behaves? comfy. and that custom node ecosystem is genuinely wild, people have built insane things in there.\nbut getting a new node into comfy means installing it, and getting a new model means downloading weights. in gradio you paste a repo id. the tradeoff is obvious: comfy's node runs on your gpu and you own every knob on it, gradio's node is someone else's space and you get whatever they exposed.\na gr.Workflow node can't reach inside flux. it calls the space, sends a prompt, gets an image.\nfor \"caption this photo, turn the caption into a marketing prompt, generate from it\" that's the right level. you don't want to be picking samplers for that. for dialling in one specific look across forty generations? nah. open comfy.\nbefore you start\neverything flows one way. no cycles, no while loops, no loop-until-it's-good-enough.\nin the canvas, independent branches run at the same time. called as an api, the python executor walks the graph one node at a time — same results, no parallelism.\nsaving is gated. locally you need the write-access link gradio prints at launch; on a space you need to be signed in as the owner. share-link visitors get read-only.\nand when a remote space blows up three hops downstream, you might have to duplicate it and fix it yourself, or change to another space.\nNote! It's in beta. gr.Workflow is still in beta, may have bugs, and its API and UX may change in future releases. \nquick answers to stuff people ask\ncan i use any hugging face model?\nyes, any model you can run through hf inference. it's in the sidebar if it's curated, otherwise paste the repo id into a node's picker. ports come from the model's pipeline tag.\ndoes every gradio space work as a node?\nmost do. it needs to be awake and it needs an api endpoint with types the canvas can read. if it's asleep or has no api, adding it fails.\nis this a comfyui replacement?\nonly if you treat the model as a black box. if you care how the image gets made, go to comfy.\ncan it replace n8n?\nno. nothing runs on a schedule, and that's n8n's job.\ndo i really get an api?\nyeah. every output node becomes a normal gradio endpoint. connected ones come back together in one response.\ncan i run my own python in it?\nyep, that's what bind` is for. pass your functions, they show up as nodes.\nwhere does it actually run?\nyour app's python process does the calling: it hits the space over the gradio client, or hf inference for models, and runs your bound functions in-process. the browser drives the graph and renders it, and streams text generation directly for the token-by-token effect. it all goes against an hf token, so locally that's your quota, and if you deploy with oauth it's each visitor's own.","type":"GUIDE"},{"title":"How To Use 3D Model Component","slug":"/guides/how-to-use-3D-model-component/","content":"How to Use the 3D Model Component\nIntroduction\n3D models are becoming more popular in machine learning and make for some of the most fun demos to experiment with. Using gradio, you can easily build a demo of your 3D image model and share it with anyone. The Gradio 3D Model component accepts 3 file types including: .obj, .glb, & .gltf.\nThis guide will show you how to build a demo for your 3D image model in a few lines of code; like the one below. Play around with 3D object by clicking around, dragging and zooming:\n \nPrerequisites\nMake sure you have the gradio Python package already installed.\nTaking a Look at the Code\nLet's take a look at how to create the minimal interface above. The prediction function in this case will just return the original 3D model mesh, but you can change this function to run inference on your machine learning model. We'll take a look at more complex examples below.\n``python\nimport gradio as gr\nimport os\ndef loadmesh(meshfile_name):\n    return meshfilename\ndemo = gr.Interface(\n    fn=load_mesh,\n    inputs=gr.Model3D(),\n    outputs=gr.Model3D(\n            clear_color=[0.0, 0.0, 0.0, 0.0],  label=\"3D Model\"),\n    examples=[\n        [os.path.join(os.path.dirname(file), \"files/Bunny.obj\")],\n        [os.path.join(os.path.dirname(file), \"files/Duck.glb\")],\n        [os.path.join(os.path.dirname(file), \"files/Fox.gltf\")],\n        [os.path.join(os.path.dirname(file), \"files/face.obj\")],\n    ],\n)\nif name == \"main\":\n    demo.launch()\n`\nLet's break down the code above:\nload_mesh: This is our 'prediction' function and for simplicity, this function will take in the 3D model mesh and return it.\nCreating the Interface:\nfn: the prediction function that is used when the user clicks submit. In our case this is the load_mesh function.\ninputs: create a model3D input component. The input expects an uploaded file as a {str} filepath.\noutputs: create a model3D output component. The output component also expects a file as a {str} filepath.\nclear_color: this is the background color of the 3D model canvas. Expects RGBa values.\nlabel: the label that appears on the top left of the component.\nexamples: list of 3D model files. The 3D model component can accept .obj, .glb, & .gltf file types.\ncache_examples`: saves the predicted output for the examples, to save time on inference.\nExploring a more complex Model3D Demo:\nBelow is a demo that uses the DPT model to predict the depth of an image and then uses 3D Point Cloud to create a 3D object. Take a look at the app.py file for a peek into the code and the model prediction function.\n \nAnd you're done! That's all the code you need to build an interface for your Model3D model. Here are some references that you may find useful:\nGradio's \"Getting Started\" guide\nThe first 3D Model Demo and complete code (on Hugging Face Spaces)","type":"GUIDE"},{"title":"Image Classification In Pytorch","slug":"/guides/image-classification-in-pytorch/","content":"Image Classification in PyTorch\nIntroduction\nImage classification is a central task in computer vision. Building better classifiers to classify what object is present in a picture is an active area of research, as it has applications stretching from autonomous vehicles to medical imaging.\nSuch models are perfect to use with Gradio's image input component, so in this tutorial we will build a web demo to classify images using Gradio. We will be able to build the whole web application in Python, and it will look like the demo on the bottom of the page.\nLet's get started!\nPrerequisites\nMake sure you have the gradio Python package already installed. We will be using a pretrained image classification model, so you should also have torch installed.\nStep 1 — Setting up the Image Classification Model\nFirst, we will need an image classification model. For this tutorial, we will use a pretrained Resnet-18 model, as it is easily downloadable from PyTorch Hub. You can use a different pretrained model or train your own.\n``python\nimport torch\nmodel = torch.hub.load('pytorch/vision:v0.6.0', 'resnet18', pretrained=True).eval()\n`\nBecause we will be using the model for inference, we have called the .eval() method.\nStep 2 — Defining a predict function\nNext, we will need to define a function that takes in the user input, which in this case is an image, and returns the prediction. The prediction should be returned as a dictionary whose keys are class name and values are confidence probabilities. We will load the class names from this text file.\nIn the case of our pretrained model, it will look like this:\n`python\nimport requests\nfrom PIL import Image\nfrom torchvision import transforms\nDownload human-readable labels for ImageNet.\nresponse = requests.get(\"https://git.io/JJkYN\")\nlabels = response.text.split(\"\\n\")\ndef predict(inp):\n  inp = transforms.ToTensor()(inp).unsqueeze(0)\n  with torch.no_grad():\n    prediction = torch.nn.functional.softmax(model(inp)[0], dim=0)\n    confidences = {labels[i]: float(prediction[i]) for i in range(1000)}\n  return confidences\n`\nLet's break this down. The function takes one parameter:\ninp: the input image as a PIL image\nThen, the function converts the image to a PIL Image and then eventually a PyTorch tensor, passes it through the model, and returns:\nconfidences: the predictions, as a dictionary whose keys are class labels and whose values are confidence probabilities\nStep 3 — Creating a Gradio Interface\nNow that we have our predictive function set up, we can create a Gradio Interface around it.\nIn this case, the input component is a drag-and-drop image component. To create this input, we use Image(type=\"pil\") which creates the component and handles the preprocessing to convert that to a PIL image.\nThe output component will be a Label, which displays the top labels in a nice form. Since we don't want to show all 1,000 class labels, we will customize it to show only the top 3 images by constructing it as Label(numtopclasses=3).\nFinally, we'll add one more parameter, the examples, which allows us to prepopulate our interfaces with a few predefined examples. The code for Gradio looks like this:\n`python\nimport gradio as gr\ngr.Interface(fn=predict,\n             inputs=gr.Image(type=\"pil\"),\n             outputs=gr.Label(numtopclasses=3),\n             examples=[\"lion.jpg\", \"cheetah.jpg\"]).launch()\n`\nThis produces the following interface, which you can try right here in your browser (try uploading your own examples!):\nAnd you're done! That's all the code you need to build a web demo for an image classifier. If you'd like to share with others, try setting share=True when you launch()` the Interface!","type":"GUIDE"},{"title":"Image Classification With Vision Transformers","slug":"/guides/image-classification-with-vision-transformers/","content":"Image Classification with Vision Transformers\nIntroduction\nImage classification is a central task in computer vision. Building better classifiers to classify what object is present in a picture is an active area of research, as it has applications stretching from facial recognition to manufacturing quality control.\nState-of-the-art image classifiers are based on the transformers architectures, originally popularized for NLP tasks. Such architectures are typically called vision transformers (ViT). Such models are perfect to use with Gradio's image input component, so in this tutorial we will build a web demo to classify images using Gradio. We will be able to build the whole web application in a single line of Python, and it will look like the demo on the bottom of the page.\nLet's get started!\nPrerequisites\nMake sure you have the gradio Python package already installed.\nStep 1 — Choosing a Vision Image Classification Model\nFirst, we will need an image classification model. For this tutorial, we will use a model from the Hugging Face Model Hub. The Hub contains thousands of models covering dozens of different machine learning tasks.\nExpand the Tasks category on the left sidebar and select \"Image Classification\" as our task of interest. You will then see all of the models on the Hub that are designed to classify images.\nAt the time of writing, the most popular one is google/vit-base-patch16-224, which has been trained on ImageNet images at a resolution of 224x224 pixels. We will use this model for our demo.\nStep 2 — Loading the Vision Transformer Model with Gradio\nWhen using a model from the Hugging Face Hub, we do not need to define the input or output components for the demo. Similarly, we do not need to be concerned with the details of preprocessing or postprocessing.\nAll of these are automatically inferred from the model tags.\nBesides the import statement, it only takes a single line of Python to load and launch the demo.\nWe use the gr.Interface.load() method and pass in the path to the model including the huggingface/ to designate that it is from the Hugging Face Hub.\n``python\nimport gradio as gr\ngr.Interface.load(\n             \"huggingface/google/vit-base-patch16-224\",\n             examples=[\"alligator.jpg\", \"laptop.jpg\"]).launch()\n`\nNotice that we have added one more parameter, the examples, which allows us to prepopulate our interfaces with a few predefined examples.\nThis produces the following interface, which you can try right here in your browser. When you input an image, it is automatically preprocessed and sent to the Hugging Face Hub API, where it is passed through the model and returned as a human-interpretable prediction. Try uploading your own image!\nAnd you're done! In one line of code, you have built a web demo for an image classifier. If you'd like to share with others, try setting share=True when you launch()` the Interface!","type":"GUIDE"},{"title":"Installing Gradio In A Virtual Environment","slug":"/guides/installing-gradio-in-a-virtual-environment/","content":"Installing Gradio in a Virtual Environment\nIn this guide, we will describe step-by-step how to install gradio within a virtual environment. This guide will cover both Windows and MacOS/Linux systems.\nVirtual Environments\nA virtual environment in Python is a self-contained directory that holds a Python installation for a particular version of Python, along with a number of additional packages. This environment is isolated from the main Python installation and other virtual environments. Each environment can have its own independent set of installed Python packages, which allows you to maintain different versions of libraries for different projects without conflicts.\nUsing virtual environments ensures that you can work on multiple Python projects on the same machine without any conflicts. This is particularly useful when different projects require different versions of the same library. It also simplifies dependency management and enhances reproducibility, as you can easily share the requirements of your project with others.\nInstalling Gradio on Windows\nTo install Gradio on a Windows system in a virtual environment, follow these steps:\nInstall Python: Ensure you have Python 3.10 or higher installed. You can download it from python.org. You can verify the installation by running python --version or python3 --version in Command Prompt.\nCreate a Virtual Environment:\n   Open Command Prompt and navigate to your project directory. Then create a virtual environment using the following command:\n   ``bash\n   python -m venv gradio-env\n   `\n   This command creates a new directory gradio-env in your project folder, containing a fresh Python installation.\nActivate the Virtual Environment:\n   To activate the virtual environment, run:\n   `bash\n   .\\gradio-env\\Scripts\\activate\n   `\n   Your command prompt should now indicate that you are working inside gradio-env. Note: you can choose a different name than gradio-env for your virtual environment in this step.\nInstall Gradio:\n   Now, you can install Gradio using pip:\n   `bash\n   pip install gradio\n   `\nVerification:\n   To verify the installation, run python and then type:\n   `python\n   import gradio as gr\n   print(gr.version)\n   `\n   This will display the installed version of Gradio.\nInstalling Gradio on MacOS/Linux\nThe installation steps on MacOS and Linux are similar to Windows but with some differences in commands.\nInstall Python:\n   Python usually comes pre-installed on MacOS and most Linux distributions. You can verify the installation by running python --version in the terminal (note that depending on how Python is installed, you might have to use python3 instead of python throughout these steps). \n   \n   Ensure you have Python 3.10 or higher installed. If you do not have it installed, you can download it from python.org. \nCreate a Virtual Environment:\n   Open Terminal and navigate to your project directory. Then create a virtual environment using:\n   `bash\n   python -m venv gradio-env\n   `\n   Note: you can choose a different name than gradio-env for your virtual environment in this step.\nActivate the Virtual Environment:\n   To activate the virtual environment on MacOS/Linux, use:\n   `bash\n   source gradio-env/bin/activate\n   `\nInstall Gradio:\n   With the virtual environment activated, install Gradio using pip:\n   `bash\n   pip install gradio\n   `\nVerification:\n   To verify the installation, run python and then type:\n   `python\n   import gradio as gr\n   print(gr.version)\n   ``\n   This will display the installed version of Gradio.\nBy following these steps, you can successfully install Gradio in a virtual environment on your operating system, ensuring a clean and managed workspace for your Python projects.","type":"GUIDE"},{"title":"Interface State","slug":"/guides/interface-state/","content":"Interface State\nSo far, we've assumed that your demos are stateless: that they do not persist information beyond a single function call. What if you want to modify the behavior of your demo based on previous interactions with the demo? There are two approaches in Gradio: global state and session state.\nGlobal State\nIf 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.\n``python\nimport gradio as gr\nscores = []\ndef track_score(score):\n    scores.append(score)\n    top_scores = sorted(scores, reverse=True)[:3]\n    return top_scores\ndemo = gr.Interface(\n    track_score,\n    gr.Number(label=\"Score\"),\n    gr.JSON(label=\"Top Scores\"),\n    api_name=\"predict\"\n)\ndemo.launch()\n`\nIn 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.\nSession State\nAnother 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:\nPass in an extra parameter into your function, which represents the state of the interface.\nAt the end of the function, return the updated value of the state as an extra return value.\nAdd the 'state' input and 'state' output components when creating your Interface\nHere's a simple app to illustrate session state - this app simply stores users previous submissions and displays them back to the user:\n`python\nimport gradio as gr\ndef store_message(message: str, history: list[str]):  \n    output = {\n        \"Current messages\": message,\n        \"Previous messages\": history[::-1]\n    }\n    history.append(message)\n    return output, history\ndemo = gr.Interface(fn=store_message,\n                    inputs=[\"textbox\", gr.State(value=[])],\n                    outputs=[\"json\", gr.State()],\n                    api_name=\"predict\"\n                    )\ndemo.launch()\n`\nNotice 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.\nThe 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. \nNote: 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. Alternatively, if you are building a chatbot that maintains user state, consider using the ChatInterface` abstraction, which manages state automatically.","type":"GUIDE"},{"title":"Internationalization","slug":"/guides/internationalization/","content":"Related spaces:\nInternationalization (i18n)\nGradio comes with ready-to-use internationalization (i18n) support:\nBuilt-in translations: Gradio automatically translates standard UI elements (like \"Submit\", \"Clear\", \"Cancel\") in more than 40 languages based on the user's browser locale.\nCustom translations: For app-specific text, Gradio provides the I18n class that lets you extend the built-in system with your own translations.\nSetting Up Translations\nYou can initialize the I18n class with multiple language dictionaries to add custom translations:\n``python\nimport gradio as gr\nCreate an I18n instance with translations for multiple languages\ni18n = gr.I18n(\n    en={\"greeting\": \"Hello, welcome to my app!\", \"submit\": \"Submit\"},\n    es={\"greeting\": \"¡Hola, bienvenido a mi aplicación!\", \"submit\": \"Enviar\"},\n    fr={\"greeting\": \"Bonjour, bienvenue dans mon application!\", \"submit\": \"Soumettre\"}\n)\nwith gr.Blocks() as demo:\n    # Use the i18n method to translate the greeting\n    gr.Markdown(i18n(\"greeting\"))\n    with gr.Row():\n        input_text = gr.Textbox(label=\"Input\")\n        output_text = gr.Textbox(label=\"Output\")\n    \n    submit_btn = gr.Button(i18n(\"submit\"))\nPass the i18n instance to the launch method\ndemo.launch(i18n=i18n)\n`\nHow It Works\nWhen you use the i18n instance with a translation key, Gradio will show the corresponding translation to users based on their browser's language settings or the language they've selected in your app.\nIf a translation isn't available for the user's locale, the system will fall back to English (if available) or display the key itself.\nValid Locale Codes\nLocale codes should follow the BCP 47 format (e.g., 'en', 'en-US', 'zh-CN'). The I18n class will warn you if you use an invalid locale code.\nSupported Component Properties\nThe following component properties typically support internationalization:\ndescription\ninfo\ntitle\nplaceholder\nvalue\nlabel\nNote that support may vary depending on the component, and some properties might have exceptions where internationalization is not applicable. You can check this by referring to the typehint for the parameter and if it contains I18nData`, then it supports internationalization.","type":"GUIDE"},{"title":"Key Component Concepts","slug":"/guides/key-component-concepts/","content":"Gradio Components: The Key Concepts\nIn this section, we discuss a few important concepts when it comes to components in Gradio.\nIt's important to understand these concepts when developing your own component.\nOtherwise, your component may behave very different to other Gradio components!\n            \n                \n                    \n                    \n                    \n                \n                You can skip this section if you are familiar with the internals of the Gradio library, such as each component's preprocess and postprocess methods.\n            \n                \nInteractive vs Static\nEvery component in Gradio comes in a static variant, and most come in an interactive version as well.\nThe static version is used when a component is displaying a value, and the user can NOT change that value by interacting with it. \nThe interactive version is used when the user is able to change the value by interacting with the Gradio UI.\nLet's see some examples:\n``python\nimport gradio as gr\nwith gr.Blocks() as demo:\n   gr.Textbox(value=\"Hello\", interactive=True)\n   gr.Textbox(value=\"Hello\", interactive=False)\ndemo.launch()\n`\nThis will display two textboxes.\nThe only difference: you'll be able to edit the value of the Gradio component on top, and you won't be able to edit the variant on the bottom (i.e. the textbox will be disabled).\nPerhaps a more interesting example is with the Image component:\n`python\nimport gradio as gr\nwith gr.Blocks() as demo:\n   gr.Image(interactive=True)\n   gr.Image(interactive=False)\ndemo.launch()\n`\nThe interactive version of the component is much more complex -- you can upload images or snap a picture from your webcam -- while the static version can only be used to display images.\nNot every component has a distinct interactive version. For example, the gr.AnnotatedImage only appears as a static version since there's no way to interactively change the value of the annotations or the image.\nWhat you need to remember\nGradio will use the interactive version (if available) of a component if that component is used as the input to any event; otherwise, the static version will be used.\nWhen you design custom components, you must accept the boolean interactive keyword in the constructor of your Python class. In the frontend, you may accept the interactive property, a bool which represents whether the component should be static or interactive. If you do not use this property in the frontend, the component will appear the same in interactive or static mode.\nThe value and how it is preprocessed/postprocessed\nThe most important attribute of a component is its value.\nEvery component has a value.\nThe value that is typically set by the user in the frontend (if the component is interactive) or displayed to the user (if it is static). \nIt is also this value that is sent to the backend function when a user triggers an event, or returned by the user's function e.g. at the end of a prediction.\nSo this value is passed around quite a bit, but sometimes the format of the value needs to change between the frontend and backend. \nTake a look at this example:\n`python\nimport numpy as np\nimport gradio as gr\ndef sepia(input_img):\n    sepia_filter = np.array([\n        [0.393, 0.769, 0.189], \n        [0.349, 0.686, 0.168], \n        [0.272, 0.534, 0.131]\n    ])\n    sepiaimg = inputimg.dot(sepia_filter.T)\n    sepiaimg /= sepiaimg.max()\n    return sepia_img\ndemo = gr.Interface(sepia, gr.Image(width=200, height=200), \"image\")\ndemo.launch()\n`\nThis will create a Gradio app which has an Image component as the input and the output. \nIn the frontend, the Image component will actually upload the file to the server and send the filepath but this is converted to a numpy array before it is sent to a user's function. \nConversely, when the user returns a numpy array from their function, the numpy array is converted to a file so that it can be sent to the frontend and displayed by the Image component.\n            \n                \n                    \n                    \n                    \n                \n                By default, the Image component sends numpy arrays to the python function because it is a common choice for machine learning engineers, though the Image component also supports other formats using the type parameter.  Read the Image docs here to learn more.\n            \n                \nEach component does two conversions:\npreprocess: Converts the value from the format sent by the frontend to the format expected by the python function. This usually involves going from a web-friendly JSON structure to a python-native data structure, like a numpy array or PIL image. The Audio, Image components are good examples of preprocess methods.\npostprocess: Converts the value returned by the python function to the format expected by the frontend. This usually involves going from a python-native data-structure, like a PIL image to a JSON structure.\nWhat you need to remember\nEvery component must implement preprocess and postprocess methods. In the rare event that no conversion needs to happen, simply return the value as-is. Textbox and Number are examples of this. \nAs a component author, YOU control the format of the data displayed in the frontend as well as the format of the data someone using your component will receive. Think of an ergonomic data-structure a python developer will find intuitive, and control the conversion from a Web-friendly JSON data structure (and vice-versa) with preprocess and postprocess.\nThe \"Example Version\" of a Component\nGradio apps support providing example inputs -- and these are very useful in helping users get started using your Gradio app. \nIn gr.Interface, you can provide examples using the examples keyword, and in Blocks, you can provide examples using the special gr.Examples component.\nAt the bottom of this screenshot, we show a miniature example image of a cheetah that, when clicked, will populate the same image in the input Image component:\nTo enable the example view, you must have the following two files in the top of the frontend directory:\nExample.svelte: this corresponds to the \"example version\" of your component\nIndex.svelte: this corresponds to the \"regular version\"\nIn the backend, you typically don't need to do anything. The user-provided example value is processed using the same .postprocess() method described earlier. If you'd like to do process the data differently (for example, if the .postprocess() method is computationally expensive), then you can write your own .process_example() method for your custom component, which will be used instead. \nThe Example.svelte file and process_example()` method will be covered in greater depth in the dedicated frontend and backend guides respectively.\nWhat you need to remember\nIf you expect your component to be used as input, it is important to define an \"Example\" view.\nIf you don't, Gradio will use a default one but it won't be as informative as it can be!\nConclusion\nNow that you know the most important pieces to remember about Gradio components, you can start to design and build your own!","type":"GUIDE"},{"title":"More Blocks Features","slug":"/guides/more-blocks-features/","content":"More Blocks Features\nExamples\nJust like with gr.Interface, you can also add examples for your functions when you are working with gr.Blocks. In this case, instantiate a gr.Examples similar to how you would instantiate any other component. The constructor of gr.Examples takes two required arguments:\nexamples: a nested list of examples, in which the outer list consists of examples and each inner list consists of an input corresponding to each input component\ninputs: the component or list of components that should be populated when the examples are clicked\nYou can also set cacheexamples=True or cacheexamples='lazy', similar to the caching API in gr.Interface, in which case two additional arguments must be provided:\noutputs: the component or list of components corresponding to the output of the examples\nfn: the function to run to generate the outputs corresponding to the examples\nHere's an example showing how to use gr.Examples in a gr.Blocks app:\n``python\nimport gradio as gr\ndef calculator(num1, operation, num2):\n    if operation == \"add\":\n        return num1 + num2\n    elif operation == \"subtract\":\n        return num1 - num2\n    elif operation == \"multiply\":\n        return num1 * num2\n    elif operation == \"divide\":\n        return num1 / num2\nwith gr.Blocks() as demo:\n    with gr.Row():\n        with gr.Column():\n            num_1 = gr.Number(value=4)\n            operation = gr.Radio([\"add\", \"subtract\", \"multiply\", \"divide\"])\n            num_2 = gr.Number(value=0)\n            submit_btn = gr.Button(value=\"Calculate\")\n        with gr.Column():\n            result = gr.Number()\n    submit_btn.click(\n        calculator, inputs=[num1, operation, num2], outputs=[result], api_visibility=\"private\"\n    )\n    examples = gr.Examples(\n        examples=[\n            [5, \"add\", 3],\n            [4, \"divide\", 2],\n            [-4, \"multiply\", 2.5],\n            [0, \"subtract\", 1.2],\n        ],\n        inputs=[num1, operation, num2],\n    )\nif name == \"main\":\n    demo.launch(footer_links=[\"gradio\"])\n`\nNote: When you click on examples, not only does the value of the input component update to the example value, but the component's configuration also reverts to the properties with which you constructed the component. This ensures that the examples are compatible with the component even if its configuration has been changed.\nRunning Events Continuously\nYou can run events on a fixed schedule using gr.Timer() object. This will run the event when the timer's tick event fires. See the code below:\n`python\nwith gr.Blocks as demo:\n    timer = gr.Timer(5)\n    textbox = gr.Textbox()\n    textbox2 = gr.Textbox()\n    timer.tick(settextboxfn, textbox, textbox2)\n`\nThis can also be used directly with a Component's every= parameter, if the value of the Component is a function:\n`python\nwith gr.Blocks as demo:\n    timer = gr.Timer(5)\n    textbox = gr.Textbox()\n    textbox2 = gr.Textbox(settextboxfn, inputs=[textbox], every=timer)\n`\nHere is an example of a demo that print the current timestamp, and also prints random numbers regularly!\n`python\nimport gradio as gr\nimport random\nimport time\nwith gr.Blocks() as demo:\n  timer = gr.Timer(1)\n  timestamp = gr.Number(label=\"Time\")\n  timer.tick(lambda: round(time.time()), outputs=timestamp, api_name=\"timestamp\")\n  number = gr.Number(lambda: random.randint(1, 10), every=timer, label=\"Random Number\")\n  with gr.Row():\n    gr.Button(\"Start\").click(lambda: gr.Timer(active=True), None, timer)\n    gr.Button(\"Stop\").click(lambda: gr.Timer(active=False), None, timer)\n    gr.Button(\"Go Fast\").click(lambda: 0.2, None, timer)\nif name == \"main\":\n  demo.launch()\n`\nGathering Event Data\nYou can gather specific data about an event by adding the associated event data class as a type hint to an argument in the event listener function.\nFor example, event data for .select() can be type hinted by a gradio.SelectData argument. This event is triggered when a user selects some part of the triggering component, and the event data includes information about what the user specifically selected. For example, if a user selected a specific word in a Textbox, a specific pixel in an Image, a specific image in a Gallery, or a specific cell in a DataFrame, the event data argument would contain information about the specific selection.\nThe SelectData includes the value that was selected, and the index where the selection occurred. A simple example that shows what text was selected in a Textbox.\n`python\nimport gradio as gr\nwith gr.Blocks() as demo:\n    textbox = gr.Textbox(\"The quick brown fox jumped.\")\n    selection = gr.Textbox()\n    def getselection(selectevt: gr.SelectData):\n        return select_evt.value\n    textbox.select(get_selection, None, selection)\n`\nIn the 2 player tic-tac-toe demo below, a user can select a cell in the DataFrame to make a move. The event data argument contains information about the specific cell that was selected. We can first check to see if the cell is empty, and then update the cell with the user's move.\n`python\nimport gradio as gr\nwith gr.Blocks() as demo:\n    turn = gr.Textbox(\"X\", interactive=False, label=\"Turn\")\n    board = gr.Dataframe(value=[[\"\", \"\", \"\"]] * 3, interactive=False, type=\"array\")\n    def place(board: list[list[int]], turn, evt: gr.SelectData):  \n        if evt.value:\n            return board, turn\n        board[evt.index[0]][evt.index[1]] = turn\n        turn = \"O\" if turn == \"X\" else \"X\"\n        return board, turn\n    board.select(place, [board, turn], [board, turn], show_progress=\"hidden\")\ndemo.launch()\n`\nAccessing Component Properties\nEvent data tells you about the event. Sometimes you want the other half of the picture: the current state of the component itself. You can get that by type hinting an argument with the component's own class.\nWhen a parameter is annotated with a component type, the argument you receive is not the component's value but an object carrying all of its current properties, exactly as they are in the browser at the moment the event fires.\n`python\nimport gradio as gr\nwith gr.Blocks() as demo:\n    number = gr.Number(value=5, minimum=0, maximum=10)\n    output = gr.Textbox()\n    def describe(x: gr.Number):\n        return f\"{x.value} (allowed range: {x.minimum} to {x.maximum})\"\n    gr.Button(\"Describe\").click(describe, number, output)\n`\nThe component must still be passed in as an input, and the annotation has to be a component class such as gr.Number or gr.Model3D — layout classes like gr.Accordion do not carry properties this way.\nThis is most useful for properties the user can change without triggering an event, which the backend would otherwise have no way of knowing about. gr.Model3D is a good example: camera_position tracks the camera as the user orbits and zooms, so you can read the view someone is actually looking at.\nThe demo below is a gr.Interface taking a gr.Model3D and returning a gr.Image. Orbit and zoom the model, press Submit, and the function reads camera_position off its annotated argument and photographs the model from that same viewpoint. Nothing else is wired up: the viewpoint arrives purely because the parameter is annotated gr.Model3D.\n`python\nimport gradio as gr\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom gradio.media import get_model3d\nMODEL = get_model3d(\"Bunny.obj\")\nDEFAULT_VIEW = (90.0, 60.0, 0.4)\nPOINTS = np.array(\n    [[float(n) for n in ln.split()[1:4]] for ln in open(MODEL) if ln.startswith(\"v \")]\n)[:, [0, 2, 1]] * np.array([1, -1, 1])\ndef snapshot(viewer: gr.Model3D):\n    alpha, beta, radius = (\n        current if current is not None else default\n        for current, default in zip(viewer.cameraposition, DEFAULTVIEW)\n    )\n    fig = plt.figure(figsize=(4, 4))\n    ax = fig.add_subplot(projection=\"3d\")\n    ax.scatter(*POINTS.T, s=1, c=POINTS[:, 2], cmap=\"viridis\")\n    ax.view_init(elev=90 - beta, azim=-alpha)\n    center, half = POINTS.mean(axis=0), radius / 4\n    ax.set(\n        xlim=(center[0] - half, center[0] + half),\n        ylim=(center[1] - half, center[1] + half),\n        zlim=(center[2] - half, center[2] + half),\n    )\n    ax.setboxaspect(None, zoom=1.4)\n    ax.setaxisoff()\n    fig.canvas.draw()\n    return np.asarray(fig.canvas.buffer_rgba())  \ndemo = gr.Interface(\n    snapshot,\n    gr.Model3D(\n        MODEL,\n        cameraposition=DEFAULTVIEW,\n        interactive=False,\n        label=\"Orbit and zoom me\",\n    ),\n    gr.Image(label=\"Snapshot from your viewpoint\"),\n    description=\"Orbit the model, then hit Submit to photograph it from the view you are looking at.\",\n    clear_btn=None,\n    flagging_mode=\"never\",\n)\ndemo.launch()\n`\nOther properties that follow the user this way include sliderposition on gr.ImageSlider, selectedindex on gr.Gallery, and playback_position on gr.Audio and gr.Video.\nValidation\nFor certain apps, it is important to validate inputs prior to using them. While this can be done in the main event function, events also support a validator function dedicated to this task.\nThis feature allows for a far better user experience than placing this logic in your main function for the following reasons:\nInput validation is performed immediately, bypassing the queue, giving the end user almost instant feedback.\nValidation errors returned from the validator function are displayed differently in the UI.\nThe validator function allows for greater granularity. Rather than raising a generic exception, you can return a validation message and status for each input individually.\nThe validator kwarg should be a function that returns a gr.validate object for each input. gr.validate takes two arguments:\nis_valid - whether or not the input is valid\nmessage - the message to display if validation fails.\nIn the demo below you can see that by returning a validation status for each input, we have more granular information that we can display to the user.\n`python\nimport gradio as gr\ndef validate_input(age, location):\n    return [\n        gr.validate(not age or age > 3, \"Age must be at least 3\"),\n        gr.validate(\"london\" not in location.lower(), \"Location must not be in London\"),\n    ]\ndef process_text(age, location):\n    return f\"Processed: {age} -- {location.upper()}\"\nwith gr.Blocks() as demo:\n    gr.Markdown(\"# Validator Parameter Test Demo\")\n    with gr.Row():\n        with gr.Column():\n            age = gr.Number(\n                label=\"Enter age\",\n                placeholder=\"Enter age\",\n            )\n            location = gr.Textbox(\n                max_lines=3,\n                label=\"Enter location\",\n                placeholder=\"Enter location\",\n            )\n    validate_btn = gr.Button(\"Process with Validation\", variant=\"primary\")\n    outputwithvalidation = gr.Textbox(\n        label=\"Output (with validation)\", interactive=False\n    )\n    validate_btn.click(\n        fn=process_text,\n        validator=validate_input,\n        inputs=[age, location],\n        outputs=outputwithvalidation,\n    )\ndemo.launch()\n``","type":"GUIDE"},{"title":"More On Examples","slug":"/guides/more-on-examples/","content":"More on Examples\nIn the previous Guide, we discussed how to provide example inputs for your demo to make it easier for users to try it out. Here, we dive into more details.\nProviding Examples\nAdding examples to an Interface is as easy as providing a list of lists to the examples\nkeyword argument.\nEach sublist is a data sample, where each element corresponds to an input of the prediction function.\nThe inputs must be ordered in the same order as the prediction function expects them.\nIf your interface only has one input component, then you can provide your examples as a regular list instead of a list of lists.\nLoading Examples from a Directory\nYou 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.\nIn the case of multiple inputs, this directory must\ncontain a log.csv file with the example values.\nIn the context of the calculator demo, we can set examples='/demo/calculator/examples' and in that directory we include the following log.csv file:\n``csv\nnum,operation,num2\n5,\"add\",3\n4,\"divide\",2\n5,\"multiply\",3\n`\nThis can be helpful when browsing flagged data. Simply point to the flagged directory and the Interface will load the examples from the flagged data.\nProviding Partial Examples\nSometimes 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.\nCaching examples\nYou 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.\nIf cacheexamples=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 gradiocachedexamples in your working directory by default. You can also set this directory with the GRADIOEXAMPLES_CACHE environment variable, which can be either an absolute path or a relative path to your working directory.\nWhenever 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!\nAlternatively, 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.\nKeep 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()`.","type":"GUIDE"},{"title":"Multimodal Chatbot Part1","slug":"/guides/multimodal-chatbot-part1/","content":"Build a Custom Multimodal Chatbot - Part 1\nThis is the first in a two part series where we build a custom Multimodal Chatbot component.\nIn part 1, we will modify the Gradio Chatbot component to display text and media files (video, audio, image) in the same message.\nIn part 2, we will build a custom Textbox component that will be able to send multimodal messages (text and media files) to the chatbot.\nYou can follow along with the author of this post as he implements the chatbot component in the following YouTube video!\nHere's a preview of what our multimodal chatbot component will look like:\nPart 1 - Creating our project\nFor this demo we will be tweaking the existing Gradio Chatbot component to display text and media files in the same message.\nLet's create a new custom component directory by templating off of the Chatbot component source code.\n``bash\ngradio cc create MultimodalChatbot --template Chatbot\n`\nAnd we're ready to go!\n            \n                \n                    \n                    \n                    \n                \n                Make sure to modify the Author key in the pyproject.toml file.\n            \n                \nPart 2a - The backend data_model\nOpen up the multimodalchatbot.py file in your favorite code editor and let's get started modifying the backend of our component.\nThe first thing we will do is create the data_model of our component.\nThe data_model is the data format that your python component will receive and send to the javascript client running the UI.\nYou can read more about the data_model in the backend guide.\nFor our component, each chatbot message will consist of two keys: a text key that displays the text message and an optional list of media files that can be displayed underneath the text.\nImport the FileData and GradioModel classes from gradio.data_classes and modify the existing ChatbotData class to look like the following:\n`python\nclass FileMessage(GradioModel):\n    file: FileData\n    alt_text: Optional[str] = None\nclass MultimodalMessage(GradioModel):\n    text: Optional[str] = None\n    files: Optional[List[FileMessage]] = None\nclass ChatbotData(GradioRootModel):\n    root: List[Tuple[Optional[MultimodalMessage], Optional[MultimodalMessage]]]\nclass MultimodalChatbot(Component):\n    ...\n    data_model = ChatbotData\n`\n            \n                \n                    \n                    \n                    \n                \n                The data_models are implemented using Pydantic V2. Read the documentation here.\n            \n                \nWe've done the hardest part already!\nPart 2b - The pre and postprocess methods\nFor the preprocess method, we will keep it simple and pass a list of MultimodalMessages to the python functions that use this component as input. \nThis will let users of our component access the chatbot data with .text and .files attributes.\nThis is a design choice that you can modify in your implementation!\nWe can return the list of messages with the root property of the ChatbotData like so:\n`python\ndef preprocess(\n    self,\n    payload: ChatbotData | None,\n) -> List[MultimodalMessage] | None:\n    if payload is None:\n        return payload\n    return payload.root\n`\n            \n                \n                    \n                    \n                    \n                \n                Learn about the reasoning behind the preprocess and postprocess methods in the key concepts guide\n            \n                \nIn the postprocess method we will coerce each message returned by the python function to be a MultimodalMessage class. \nWe will also clean up any indentation in the text field so that it can be properly displayed as markdown in the frontend.\nWe can leave the postprocess method as is and modify the postprocesschat_messages\n`python\ndef postprocesschat_messages(\n    self, chat_message: MultimodalMessage | dict | None\n) -> MultimodalMessage | None:\n    if chat_message is None:\n        return None\n    if isinstance(chat_message, dict):\n        chatmessage = MultimodalMessage(**chatmessage)\n    chatmessage.text = inspect.cleandoc(chatmessage.text or \"\")\n    for file in chatmessage.files:\n        file.file.mimetype = clientutils.getmimetype(file_.file.path)\n    return chat_message\n`\nBefore we wrap up with the backend code, let's modify the examplevalue and examplepayload method to return a valid dictionary representation of the ChatbotData:\n`python\ndef example_value(self) -> Any:\n    return [[{\"text\": \"Hello!\", \"files\": []}, None]]\ndef example_payload(self) -> Any:\n    return [[{\"text\": \"Hello!\", \"files\": []}, None]]\n`\nCongrats - the backend is complete!\nPart 3a - The Index.svelte file\nThe frontend for the Chatbot component is divided into two parts - the Index.svelte file and the shared/Chatbot.svelte file.\nThe Index.svelte file applies some processing to the data received from the server and then delegates the rendering of the conversation to the shared/Chatbot.svelte file.\nFirst we will modify the Index.svelte file to apply processing to the new data type the backend will return.\nLet's begin by porting our custom types  from our python data_model to typescript.\nOpen frontend/shared/utils.ts and add the following type definitions at the top of the file:\n`ts\nexport type FileMessage = {\n\tfile: FileData;\n\talt_text?: string;\n};\nexport type MultimodalMessage = {\n\ttext: string;\n\tfiles?: FileMessage[];\n}\n`\nNow let's import them in Index.svelte and modify the type annotations for value and _value.\n`ts\nimport type { FileMessage, MultimodalMessage } from \"./shared/utils\";\nexport let value: [\n    MultimodalMessage | null,\n    MultimodalMessage | null\n][] = [];\nlet _value: [\n    MultimodalMessage | null,\n    MultimodalMessage | null\n][];\n`\nWe need to normalize each message to make sure each file has a proper URL to fetch its contents from.\nWe also need to format any embedded file links in the text key.\nLet's add a process_message utility function and apply it whenever the value changes.\n`ts\nfunction process_message(msg: MultimodalMessage | null): MultimodalMessage | null {\n    if (msg === null) {\n        return msg;\n    }\n    msg.text = redirectsrcurl(msg.text);\n    msg.files = msg.files.map(normalize_messages);\n    return msg;\n}\n$: _value = value\n    ? value.map(([usermsg, botmsg]) => [\n            processmessage(usermsg),\n            processmessage(botmsg)\n        ])\n    : [];\n`\nPart 3b - the Chatbot.svelte file\nLet's begin similarly to the Index.svelte file and let's first modify the type annotations.\nImport Mulimodal message at the top of the  section and use it to type the value and old_value variables.\n`ts\nimport type { MultimodalMessage } from \"./utils\";\nexport let value:\n    | [\n            MultimodalMessage | null,\n            MultimodalMessage | null\n        ][]\n    | null;\nlet old_value:\n    | [\n            MultimodalMessage | null,\n            MultimodalMessage | null\n        ][]\n    | null = null;\n`\nWe also need to modify the handleselect and handlelike functions:\n`ts\nfunction handle_select(\n    i: number,\n    j: number,\n    message: MultimodalMessage | null\n): void {\n    dispatch(\"select\", {\n        index: [i, j],\n        value: message\n    });\n}\nfunction handle_like(\n    i: number,\n    j: number,\n    message: MultimodalMessage | null,\n    liked: boolean\n): void {\n    dispatch(\"like\", {\n        index: [i, j],\n        value: message,\n        liked: liked\n    });\n}\n`\nNow for the fun part, actually rendering the text and files in the same message!\nYou should see some code like the following that determines whether a file or a markdown message should be displayed depending on the type of the message:\n`svelte\n{#if typeof message === \"string\"}\n    \n{:else if message !== null && message.file?.mime_type?.includes(\"audio\")}\n    \n{#each message.files as file, k}\n    {#if file !== null && file.file.mime_type?.includes(\"audio\")}\n        \n    {:else if message !== null && file.file?.mime_type?.includes(\"video\")}\n        \n            \n        \n    {:else if message !== null && file.file?.mime_type?.includes(\"image\")}\n        \n    {:else if message !== null && file.file?.url !== null}\n        \n            {file.file?.orig_name || file.file?.path}\n        \n    {:else if pending_message && j === 1}\n        \n    {/if}\n{/each}\n`\nWe did it! 🎉\nPart 4 - The demo\nFor this tutorial, let's keep the demo simple and just display a static conversation between a hypothetical user and a bot.\nThis demo will show how both the user and the bot can send files. \nIn part 2 of this tutorial series we will build a fully functional chatbot demo!\nThe demo code will look like the following:\n`python\nimport gradio as gr\nfrom gradio_multimodalchatbot import MultimodalChatbot\nfrom gradio.data_classes import FileData\nuser_msg1 = {\"text\": \"Hello, what is in this image?\",\n             \"files\": [{\"file\": FileData(path=\"https://gradio-builds.s3.amazonaws.com/diffusionimage/cutedog.jpg\")}]\n             }\nbot_msg1 = {\"text\": \"It is a very cute dog\",\n            \"files\": []}\nuser_msg2 = {\"text\": \"Describe this audio clip please.\",\n             \"files\": [{\"file\": FileData(path=\"cantina.wav\")}]}\nbot_msg2 = {\"text\": \"It is the cantina song from Star Wars\",\n            \"files\": []}\nuser_msg3 = {\"text\": \"Give me a video clip please.\",\n             \"files\": []}\nbot_msg3 = {\"text\": \"Here is a video clip of the world\",\n            \"files\": [{\"file\": FileData(path=\"world.mp4\")},\n                      {\"file\": FileData(path=\"cantina.wav\")}]}\nconversation = [[usermsg1, botmsg1], [usermsg2, botmsg2], [usermsg3, botmsg3]]\nwith gr.Blocks() as demo:\n    MultimodalChatbot(value=conversation, height=800)\ndemo.launch()\n`\n            \n                \n                    \n                    \n                    \n                \n                Change the filepaths so that they correspond to files on your machine. Also, if you are running in development mode, make sure the files are located in the top level of your custom component directory.\n            \n                \nPart 5 - Deploying and Conclusion\nLet's build and deploy our demo with gradio cc build and gradio cc deploy`!\nYou can check out our component deployed to HuggingFace Spaces and all of the source code is available here.\nSee you in the next installment of this series!","type":"GUIDE"},{"title":"Multipage Apps","slug":"/guides/multipage-apps/","content":"Multipage Apps\nYour Gradio app can support multiple pages with the Blocks.route() method. Here's what a multipage Gradio app generally looks like:\n``python\nwith gr.Blocks() as demo:  # Main page\n    name = gr.Textbox(label=\"Name\")\n    ...\nwith demo.route(\"Second page\", \"/second\"):\n    num = gr.Number()\n    ...\ndemo.launch()\n`\nThis allows you to define links to separate pages, each with a separate URL, which are  linked to the top of the Gradio app in an automatically-generated navbar. \nHere's a complete example:\n`python\nimport gradio as gr\nimport random\nimport time\nwith gr.Blocks() as demo:\n    name = gr.Textbox(label=\"Name\")\n    output = gr.Textbox(label=\"Output Box\")\n    greet_btn = gr.Button(\"Greet\")\n    @gr.on([greet_btn.click, name.submit], inputs=name, outputs=output)\n    def greet(name):\n        return \"Hello \" + name + \"!\"\n    \n    @gr.render(inputs=name, triggers=[output.change])\n    def spell_out(name):\n        with gr.Row():\n            for letter in name:\n                gr.Textbox(letter)\nwith demo.route(\"Up\") as incrementer_demo:\n    num = gr.Number()\n    incrementer_demo.load(lambda: time.sleep(1) or random.randint(10, 40), None, num)\n    with gr.Row():\n        inc_btn = gr.Button(\"Increase\")\n        dec_btn = gr.Button(\"Decrease\")\n    incbtn.click(fn=lambda x: x + 1, inputs=num, outputs=num, apiname=\"increment\")\n    decbtn.click(fn=lambda x: x - 1, inputs=num, outputs=num, apiname=\"decrement\")\n    for i in range(100):\n        gr.Textbox()\ndef wait(x):\n    time.sleep(2)\n    return x\nidentityiface = gr.Interface(wait, \"image\", \"image\", apiname=\"predict\")\nwith demo.route(\"Interface\") as incrementer_demo:\n    identity_iface.render()\n    gr.Interface(lambda x, y: x * y, [\"number\", \"number\"], \"number\", api_name=\"predict\")\ndemo.launch()\n`\nAll of these pages will share the same backend, including the same queue.\nNote: multipage apps do not support interactions between pages, e.g. an event listener on one page cannot output to a component on another page. Use gr.Tabs() for this type of functionality instead of pages.\nSeparate Files\nFor maintainability, you may want to write the code for different pages in different files. Because any Gradio Blocks can be imported and rendered inside another Blocks using the .render() method, you can do this as follows.\nCreate one main file, say app.py and create separate Python files for each page:\n`\napp.py\nmain_page.py\nsecond_page.py\n`\nThe Python file corresponding to each page should consist of a regular Gradio Blocks, Interface, or ChatInterface application, e.g.\nmain_page.py\n`py\nimport gradio as gr\nwith gr.Blocks() as demo:\n    gr.Image()\nif name == \"main\":\n    demo.launch()\n`\nsecond_page.py\n`py\nimport gradio as gr\nwith gr.Blocks() as demo:\n    t = gr.Textbox()\n    demo.load(lambda : \"Loaded\", None, t)\nif name == \"main\":\n    demo.launch()\n`\nIn your main app.py file, simply import the Gradio demos from the page files and .render() them:\napp.py\n`py\nimport gradio as gr\nimport mainpage, secondpage\nwith gr.Blocks() as demo:\n    main_page.demo.render()\nwith demo.route(\"Second Page\"):\n    second_page.demo.render()\nif name == \"main\":\n    demo.launch()\n`\nThis allows you to run each page as an independent Gradio app for testing, while also creating a single file app.py that serves as the entrypoint for the complete multipage app.\nCustomizing the Navbar\nBy default, Gradio automatically generates a navigation bar for multipage apps that displays all your pages with \"Home\" as the title for the main page. You can customize the navbar behavior using the gr.Navbar component.\nPer-Page Navbar Configuration\nYou can have different navbar configurations for each page of your app:\n`python\nimport gradio as gr\nwith gr.Blocks() as demo:\n    # Navbar for the main page\n    navbar = gr.Navbar(\n        visible=True,\n        mainpagename=\"Dashboard\",\n        value=[(\"About\", \"https://example.com/about\")]\n    )\n    \n    gr.Textbox(label=\"Main page content\")\nwith demo.route(\"Settings\"):\n    # Different navbar for the Settings page\n    navbar = gr.Navbar(\n        visible=True,\n        mainpagename=\"Home\",\n        value=[(\"Documentation\", \"https://docs.example.com\")]\n    )\n    gr.Textbox(label=\"Settings page\")\ndemo.launch()\n`\nImportant Notes:\nYou can have one gr.Navbar component per page. Each page's navbar configuration is independent.\nThe mainpagename parameter customizes the title of the home page link in the navbar.\nThe value parameter allows you to add additional links to the navbar, which can be internal pages or external URLs.\nIf no gr.Navbar component is present on a page, the default navbar behavior is used (visible with \"Home\" as the home page title).\nYou can update the navbar properties using standard Gradio event handling, just like with any other component.\nHere's an example that demonstrates the last point:\n`python\nimport gradio as gr\nwith gr.Blocks(title=\"Navbar Demo\") as demo:\n    navbar = gr.Navbar(value=[(\"About Me\", \"https://x.com/abidlabs\")], visible=True, mainpagename=\"Dashboard\")\n    gr.Markdown(\"# Dashboard Page\")\n    hide_btn = gr.Button(\"Hide Navbar\")\n    hide_btn.click(fn=lambda : gr.Navbar(visible=False), outputs=navbar)\n    show_btn = gr.Button(\"Show Navbar\")\n    showbtn.click(fn=lambda : gr.Navbar(visible=True, mainpage_name=\"Dashboard is Back!\"), outputs=navbar)\nwith demo.route(\"Settings\", \"/settings\"):\n    gr.Markdown(\"# Settings Page\")\ndemo.launch()\n``","type":"GUIDE"},{"title":"Named Entity Recognition","slug":"/guides/named-entity-recognition/","content":"Named-Entity Recognition\nIntroduction\nNamed-entity recognition (NER), also known as token classification or text tagging, is the task of taking a sentence and classifying every word (or \"token\") into different categories, such as names of people or names of locations, or different parts of speech.\nFor example, given the sentence:\nDoes Chicago have any Pakistani restaurants?\nA named-entity recognition algorithm may identify:\n\"Chicago\" as a location\n\"Pakistani\" as an ethnicity\nand so on.\nUsing gradio (specifically the HighlightedText component), you can easily build a web demo of your NER model and share that with the rest of your team.\nHere is an example of a demo that you'll be able to build:\nThis tutorial will show how to take a pretrained NER model and deploy it with a Gradio interface. We will show two different ways to use the HighlightedText component -- depending on your NER model, either of these two ways may be easier to learn!\nPrerequisites\nMake sure you have the gradio Python package already installed. You will also need a pretrained named-entity recognition model. You can use your own, while in this tutorial, we will use one from the transformers library.\nApproach 1: List of Entity Dictionaries\nMany named-entity recognition models output a list of dictionaries. Each dictionary consists of an entity, a \"start\" index, and an \"end\" index. This is, for example, how NER models in the transformers library operate:\n``py\nfrom transformers import pipeline\nner_pipeline = pipeline(\"ner\")\nner_pipeline(\"Does Chicago have any Pakistani restaurants\")\n`\nOutput:\n`bash\n[{'entity': 'I-LOC',\n  'score': 0.9988978,\n  'index': 2,\n  'word': 'Chicago',\n  'start': 5,\n  'end': 12},\n {'entity': 'I-MISC',\n  'score': 0.9958592,\n  'index': 5,\n  'word': 'Pakistani',\n  'start': 22,\n  'end': 31}]\n`\nIf you have such a model, it is very easy to hook it up to Gradio's HighlightedText component. All you need to do is pass in this list of entities, along with the original text to the model, together as dictionary, with the keys being \"entities\" and \"text\" respectively.\nHere is a complete example:\n`python\nfrom transformers import pipeline\nimport gradio as gr\nner_pipeline = pipeline(\"ner\")  \nexamples = [\n    \"Does Chicago have any stores and does Joe live here?\",\n]\ndef ner(text):\n    output = ner_pipeline(text)\n    return {\"text\": text, \"entities\": output}\ndemo = gr.Interface(ner,\n             gr.Textbox(placeholder=\"Enter sentence here...\"),\n             gr.HighlightedText(),\n             examples=examples,\n             api_name=\"predict\")\ndemo.launch()\n`\nApproach 2: List of Tuples\nAn alternative way to pass data into the HighlightedText component is a list of tuples. The first element of each tuple should be the word or words that are being classified into a particular entity. The second element should be the entity label (or None if they should be unlabeled). The HighlightedText component automatically strings together the words and labels to display the entities.\nIn some cases, this can be easier than the first approach. Here is a demo showing this approach using Spacy's parts-of-speech tagger:\n`python\nimport gradio as gr\nimport os\nos.system('python -m spacy download encoreweb_sm')\nimport spacy  \nfrom spacy import displacy  \nnlp = spacy.load(\"encoreweb_sm\")\ndef text_analysis(text):\n    doc = nlp(text)\n    html = displacy.render(doc, style=\"dep\", page=True)\n    html = (\n        \"\"\nhtml\n\"\"\n    )\n    pos_count = {\n        \"char_count\": len(text),\n        \"token_count\": 0,\n    }\n    pos_tokens = []\n    for token in doc:\n        postokens.extend([(token.text, token.pos), (\" \", None)])\n    return postokens, poscount, html\ndemo = gr.Interface(\n    text_analysis,\n    gr.Textbox(placeholder=\"Enter sentence here...\"),\n    [\"highlight\", \"json\", \"html\"],\n    examples=[\n        [\"What a beautiful morning for a walk!\"],\n        [\"It was the best of times, it was the worst of times.\"],\n    ],\n    api_name=\"predict\",\n)\ndemo.launch()\n`\nAnd you're done! That's all you need to know to build a web-based GUI for your NER model.\nFun tip: you can share your NER demo instantly with others simply by setting share=True in launch()`.","type":"GUIDE"},{"title":"Object Detection From Video","slug":"/guides/object-detection-from-video/","content":"Streaming Object Detection from Video\nIn this guide we'll use the RT-DETR model to detect objects in a user uploaded video. We'll stream the results from the server using the new video streaming features introduced in Gradio 5.0.\nSetting up the Model\nFirst, we'll install the following requirements in our system:\n``\nopencv-python\ntorch\ntransformers>=4.43.0\nspaces\n`\nThen, we'll download the model from the Hugging Face Hub:\n`python\nfrom transformers import RTDetrForObjectDetection, RTDetrImageProcessor\nimageprocessor = RTDetrImageProcessor.frompretrained(\"PekingU/rtdetr_r50vd\")\nmodel = RTDetrForObjectDetection.frompretrained(\"PekingU/rtdetrr50vd\").to(\"cuda\")\n`\nWe're moving the model to the GPU. We'll be deploying our model to Hugging Face Spaces and running the inference in the free ZeroGPU cluster. \nThe Inference Function\nOur inference function will accept a video and a desired confidence threshold.\nObject detection models identify many objects and assign a confidence score to each object. The lower the confidence, the higher the chance of a false positive. So we will let our users set the confidence threshold.\nOur function will iterate over the frames in the video and run the RT-DETR model over each frame.\nWe will then draw the bounding boxes for each detected object in the frame and save the frame to a new output video.\nThe function will yield each output video in chunks of two seconds.\nIn order to keep inference times as low as possible on ZeroGPU (there is a time-based quota),\nwe will halve the original frames-per-second in the output video and resize the input frames to be half the original \nsize before running the model.\nThe code for the inference function is below - we'll go over it piece by piece.\n`python\nimport spaces\nimport cv2\nfrom PIL import Image\nimport torch\nimport time\nimport numpy as np\nimport uuid\nfrom drawboxes import drawbounding_boxes\nSUBSAMPLE = 2\n@spaces.GPU\ndef streamobjectdetection(video, conf_threshold):\n    cap = cv2.VideoCapture(video)\n    # This means we will output mp4 videos\n    videocodec = cv2.VideoWriterfourcc(*\"mp4v\") # type: ignore\n    fps = int(cap.get(cv2.CAPPROPFPS))\n    desired_fps = fps // SUBSAMPLE\n    width  = int(cap.get(cv2.CAPPROPFRAME_WIDTH)) // 2\n    height = int(cap.get(cv2.CAPPROPFRAME_HEIGHT)) // 2\n    iterating, frame = cap.read()\n    n_frames = 0\n    # Use UUID to create a unique video file\n    outputvideoname = f\"output_{uuid.uuid4()}.mp4\"\n    # Output Video\n    outputvideo = cv2.VideoWriter(outputvideoname, videocodec, desired_fps, (width, height)) # type: ignore\n    batch = []\n    while iterating:\n        frame = cv2.resize( frame, (0,0), fx=0.5, fy=0.5)\n        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n        if n_frames % SUBSAMPLE == 0:\n            batch.append(frame)\n        if len(batch) == 2 * desired_fps:\n            inputs = imageprocessor(images=batch, returntensors=\"pt\").to(\"cuda\")\n            with torch.no_grad():\n                outputs = model(inputs)\n            boxes = imageprocessor.postprocessobjectdetection(\n                outputs,\n                target_sizes=torch.tensor([(height, width)] * len(batch)),\n                threshold=conf_threshold)\n            \n            for i, (array, box) in enumerate(zip(batch, boxes)):\n                pilimage = drawboundingboxes(Image.fromarray(array), box, model, confthreshold)\n                frame = np.array(pil_image)\n                # Convert RGB to BGR\n                frame = frame[:, :, ::-1].copy()\n                output_video.write(frame)\n            batch = []\n            output_video.release()\n            yield outputvideoname\n            outputvideoname = f\"output_{uuid.uuid4()}.mp4\"\n            outputvideo = cv2.VideoWriter(outputvideoname, videocodec, desired_fps, (width, height)) # type: ignore\n        iterating, frame = cap.read()\n        n_frames += 1\n`\nReading from the Video\nOne of the industry standards for creating videos in python is OpenCV so we will use it in this app.\nThe cap variable is how we will read from the input video. Whenever we call cap.read(), we are reading the next frame in the video.\nIn order to stream video in Gradio, we need to yield a different video file for each \"chunk\" of the output video.\nWe create the next video file to write to with the outputvideo = cv2.VideoWriter(outputvideoname, videocodec, desiredfps, (width, height)) line. The videocodec is how we specify the type of video file. Only \"mp4\" and \"ts\" files are supported for video sreaming at the moment.\nThe Inference Loop\nFor each frame in the video, we will resize it to be half the size. OpenCV reads files in BGR format, so will convert to the expected RGB format of transfomers. That's what the first two lines of the while loop are doing. \nWe take every other frame and add it to a batch list so that the output video is half the original FPS. When the batch covers two seconds of video, we will run the model. The two second threshold was chosen to keep the processing time of each batch small enough so that video is smoothly displayed in the server while not requiring too many separate forward passes. In order for video streaming to work properly in Gradio, the batch size should be at least 1 second. \nWe run the forward pass of the model and then use the postprocessobject_detection method of the model to scale the detected bounding boxes to the size of the input frame.\nWe make use of a custom function to draw the bounding boxes (source here). We then have to convert from RGB to BGR before writing back to the output video.\nOnce we have finished processing the batch, we create a new output video file for the next batch.\nThe Gradio Demo\nThe UI code is pretty similar to other kinds of Gradio apps. \nWe'll use a standard two-column layout so that users can see the input and output videos side by side.\nIn order for streaming to work, we have to set streaming=True in the output video. Setting the video\nto autoplay is not necessary but it's a better experience for users.\n`python\nimport gradio as gr\nwith gr.Blocks() as app:\n    gr.HTML(\n        \"\"\"\n    \n    Video Object Detection with RT-DETR\n    \n    \"\"\")\n    with gr.Row():\n        with gr.Column():\n            video = gr.Video(label=\"Video Source\")\n            conf_threshold = gr.Slider(\n                label=\"Confidence Threshold\",\n                minimum=0.0,\n                maximum=1.0,\n                step=0.05,\n                value=0.30,\n            )\n        with gr.Column():\n            output_video = gr.Video(label=\"Processed Video\", streaming=True, autoplay=True)\n    video.upload(\n        fn=streamobjectdetection,\n        inputs=[video, conf_threshold],\n        outputs=[output_video],\n    )\n``\nConclusion\nYou can check out our demo hosted on Hugging Face Spaces here. \nIt is also embedded on this page below","type":"GUIDE"},{"title":"Object Detection From Webcam With Webrtc","slug":"/guides/object-detection-from-webcam-with-webrtc/","content":"Real Time Object Detection from a Webcam Stream with FastRTC\nIn this guide, we'll use YOLOv10 to perform real-time object detection in Gradio from a user's webcam feed. We'll utilize FastRTC a companion library from the gradio team for building low latency streaming web applications. You can see the finished product in action below:\nSetting up\nStart by installing all the dependencies. Add the following lines to a requirements.txt file and run pip install -r requirements.txt:\n``bash\nopencv-python\nfastrtc\nonnxruntime-gpu\n`\nWe'll use the ONNX runtime to speed up YOLOv10 inference. This guide assumes you have access to a GPU. If you don't, change onnxruntime-gpu to onnxruntime. Without a GPU, the model will run slower, resulting in a laggy demo.\nWe'll use OpenCV for image manipulation and the WebRTC protocol to achieve near-zero latency.\nNote: If you want to deploy this app on any cloud provider, you'll need to use your Hugging Face token to connect to a TURN server. Learn more in this guide. If you're not familiar with TURN servers, consult this guide.\nThe Inference Function\nWe'll download the YOLOv10 model from the Hugging Face hub and instantiate a custom inference class to use this model. \nThe implementation of the inference class isn't covered in this guide, but you can find the source code here if you're interested. This implementation borrows heavily from this github repository.\nWe're using the yolov10-n variant because it has the lowest latency. See the Performance section of the README in the YOLOv10 GitHub repository.\n`python\nfrom huggingfacehub import hfhub_download\nfrom inference import YOLOv10\nmodelfile = hfhub_download(\n    repo_id=\"onnx-community/yolov10n\", filename=\"onnx/model.onnx\"\n)\nmodel = YOLOv10(model_file)\ndef detection(image, conf_threshold=0.3):\n    image = cv2.resize(image, (model.inputwidth, model.inputheight))\n    newimage = model.detectobjects(image, conf_threshold)\n    return new_image\n`\nOur inference function, detection, accepts a numpy array from the webcam and a desired confidence threshold. Object detection models like YOLO identify many objects and assign a confidence score to each. The lower the confidence, the higher the chance of a false positive. We'll let users adjust the confidence threshold.\nThe function returns a numpy array corresponding to the same input image with all detected objects in bounding boxes.\nThe Gradio Demo\nThe Gradio demo is straightforward, but we'll implement a few specific features:\nUse the WebRTC custom component to ensure input and output are sent to/from the server with WebRTC. \nThe WebRTC component will serve as both an input and output component.\nUtilize the time_limit parameter of the stream event. This parameter sets a processing time for each user's stream. In a multi-user setting, such as on Spaces, we'll stop processing the current user's stream after this period and move on to the next. \nWe'll also apply custom CSS to center the webcam and slider on the page.\n`python\nimport gradio as gr\nfrom fastrtc import WebRTC\ncss = \"\"\".my-group {max-width: 600px !important; max-height: 600px !important;}\n         .my-column {display: flex !important; justify-content: center !important; align-items: center !important;}\"\"\"\nwith gr.Blocks(css=css) as demo:\n    gr.HTML(\n        \"\"\"\n        \n        YOLOv10 Webcam Stream (Powered by WebRTC ⚡️)\n        \n        \"\"\"\n    )\n    with gr.Column(elem_classes=[\"my-column\"]):\n        with gr.Group(elem_classes=[\"my-group\"]):\n            image = WebRTC(label=\"Stream\", rtcconfiguration=rtcconfiguration)\n            conf_threshold = gr.Slider(\n                label=\"Confidence Threshold\",\n                minimum=0.0,\n                maximum=1.0,\n                step=0.05,\n                value=0.30,\n            )\n        image.stream(\n            fn=detection, inputs=[image, confthreshold], outputs=[image], timelimit=10\n        )\nif name == \"main\":\n    demo.launch()\n``\nConclusion\nOur app is hosted on Hugging Face Spaces here. \nYou can use this app as a starting point to build real-time image applications with Gradio. Don't hesitate to open issues in the space or in the FastRTC GitHub repo if you have any questions or encounter problems.","type":"GUIDE"},{"title":"Pdf Component Example","slug":"/guides/pdf-component-example/","content":"Case Study: A Component to Display PDFs\nLet's work through an example of building a custom gradio component for displaying PDF files.\nThis component will come in handy for showcasing document question answering models, which typically work on PDF input.\nThis is a sneak preview of what our finished component will look like:\nStep 0: Prerequisites\nMake sure you have gradio 5.0 or higher installed as well as node 20+.\nAs of the time of publication, the latest release is 4.1.1.\nAlso, please read the Five Minute Tour of custom components and the Key Concepts guide before starting.\nStep 1: Creating the custom component\nNavigate to a directory of your choosing and run the following command:\n``bash\ngradio cc create PDF\n`\nTip: You should change the name of the component.\nSome of the screenshots assume the component is called PDF but the concepts are the same!\nThis will create a subdirectory called pdf in your current working directory.\nThere are three main subdirectories in pdf: frontend, backend, and demo.\nIf you open pdf in your code editor, it will look like this:\n            \n                \n                    \n                    \n                    \n                \n                For this demo we are not templating off a current gradio component. But you can see the list of available templates with gradio cc show and then pass the template name to the --template option, e.g. gradio cc create &lt;Name&gt; --template &lt;foo&gt;\n            \n                \nStep 2: Frontend - modify javascript dependencies\nWe're going to use the pdfjs javascript library to display the pdfs in the frontend. \nLet's start off by adding it to our frontend project's dependencies, as well as adding a couple of other projects we'll need.\nFrom within the frontend directory, run npm install @gradio/client @gradio/upload @gradio/icons @gradio/button and npm install --save-dev pdfjs-dist@3.11.174.\nAlso, let's uninstall the @zerodevx/svelte-json-view dependency by running npm uninstall @zerodevx/svelte-json-view.\nThe complete package.json should look like this:\n`json\n{\n  \"name\": \"gradio_pdf\",\n  \"version\": \"0.2.0\",\n  \"description\": \"Gradio component for displaying PDFs\",\n  \"type\": \"module\",\n  \"author\": \"\",\n  \"license\": \"ISC\",\n  \"private\": false,\n  \"main_changeset\": true,\n  \"exports\": {\n    \".\": \"./Index.svelte\",\n    \"./example\": \"./Example.svelte\",\n    \"./package.json\": \"./package.json\"\n  },\n  \"devDependencies\": {\n    \"pdfjs-dist\": \"3.11.174\"\n  },\n  \"dependencies\": {\n    \"@gradio/atoms\": \"0.2.0\",\n    \"@gradio/statustracker\": \"0.3.0\",\n    \"@gradio/utils\": \"0.2.0\",\n    \"@gradio/client\": \"0.7.1\",\n    \"@gradio/upload\": \"0.3.2\",\n    \"@gradio/icons\": \"0.2.0\",\n    \"@gradio/button\": \"0.2.3\",\n    \"pdfjs-dist\": \"3.11.174\"\n  }\n}\n`\n            \n                \n                    \n                    \n                    \n                \n                Running npm install will install the latest version of the package available. You can install a specific version with npm install package@&lt;version&gt;.  You can find all of the gradio javascript package documentation here. It is recommended you use the same versions as me as the API can change.\n            \n                \nNavigate to Index.svelte and delete mentions of JSONView\n`ts\nimport { JsonView } from \"@zerodevx/svelte-json-view\";\n`\n`svelte\n`\nStep 3: Frontend - Launching the Dev Server\nRun the dev command to launch the development server.\nThis will open the demo in demo/app.py in an environment where changes to the frontend and backend directories will reflect instantaneously in the launched app.\nAfter launching the dev server, you should see a link printed to your console that says Frontend Server (Go here): ... .\n \nYou should see the following:\nIts not impressive yet but we're ready to start coding!\nStep 4: Frontend - The basic skeleton\nWe're going to start off by first writing the skeleton of our frontend and then adding the pdf rendering logic.\nAdd the following imports and expose the following properties to the top of your file in the  tag.\nYou may get some warnings from your code editor that some props are not used.\nThat's ok.\n`ts\n    import { tick } from \"svelte\";\n    import type { Gradio } from \"@gradio/utils\";\n    import { Block, BlockLabel } from \"@gradio/atoms\";\n    import { File } from \"@gradio/icons\";\n    import { StatusTracker } from \"@gradio/statustracker\";\n    import type { LoadingStatus } from \"@gradio/statustracker\";\n    import type { FileData } from \"@gradio/client\";\n    import { Upload, ModifyUpload } from \"@gradio/upload\";\n\texport let elem_id = \"\";\n\texport let elem_classes: string[] = [];\n\texport let visible = true;\n\texport let value: FileData | null = null;\n\texport let container = true;\n\texport let scale: number | null = null;\n\texport let root: string;\n\texport let height: number | null = 500;\n\texport let label: string;\n\texport let proxy_url: string;\n\texport let min_width: number | undefined = undefined;\n\texport let loading_status: LoadingStatus;\n\texport let gradio: Gradio;\n    let _value = value;\n    let oldvalue = value;\n`\n            \n                \n                    \n                    \n                    \n                \n                The gradio` object passed in here contains some metadata about the application as well as some utility methods. One of these utilities is a dispatch method. We want to dispatch change and upload events whenever our PDF is changed or updated. This line provides type hints that these are the only events we will be dispatching.\n            \n                \nWe want our frontend component to let users upload a PDF document if there isn't one already loaded.\nIf it is loaded, we want to display it underneath a \"clear\" button that lets our users upload a new document. \nWe're going to use the Upload and ModifyUpload components that come with the @gradio/upload package to do this.\nUnderneath the  tag, delete all the current code and add the following:\n`svelte\n    {#if loading_status}\n        \n    {/if}\n    \n    {#if _value}\n        \n    {:else}\n        \n            Upload your PDF\n        \n    {/if}\n`\nYou should see the following when you navigate to your app after saving your current changes:\nStep 5: Frontend - Nicer Upload Text\nThe Upload your PDF text looks a bit small and barebones. \nLets customize it!\nCreate a new file called PdfUploadText.svelte and copy the following code.\nIts creating a new div to display our \"upload text\" with some custom styling.\n            \n                \n                    \n                    \n                    \n                \n                Notice that we're leveraging Gradio core's existing css variables here: var(--size-60) and var(--body-text-color-subdued). This allows our component to work nicely in light mode and dark mode, as well as with Gradio's built-in themes.\n            \n                \n`svelte\n\timport { Upload as UploadIcon } from \"@gradio/icons\";\n\texport let hovered = false;\n\t \n    Drop PDF\nor -\n    Click to Upload\n\t.wrap {\n\t\tdisplay: flex;\n\t\tflex-direction: column;\n\t\tjustify-content: center;\n\t\talign-items: center;\n\t\tmin-height: var(--size-60);\n\t\tcolor: var(--block-label-text-color);\n\t\tline-height: var(--line-md);\n\t\theight: 100%;\n\t\tpadding-top: var(--size-3);\n\t}\n\t.or {\n\t\tcolor: var(--body-text-color-subdued);\n\t\tdisplay: flex;\n\t}\n\t.icon-wrap {\n\t\twidth: 30px;\n\t\tmargin-bottom: var(--spacing-lg);\n\t}\n\t@media (--screen-md) {\n\t\t.wrap {\n\t\t\tfont-size: var(--text-lg);\n\t\t}\n\t}\n\t.hovered {\n\t\tcolor: var(--color-accent);\n\t}\n`\nNow import PdfUploadText.svelte in your  and pass it to the Upload component!\n`svelte\n\timport PdfUploadText from \"./PdfUploadText.svelte\";\n...\n    \n        \n    \n`\nAfter saving your code, the frontend should now look like this:\nStep 6: PDF Rendering logic\nThis is the most advanced javascript part.\nIt took me a while to figure it out!\nDo not worry if you have trouble, the important thing is to not be discouraged 💪\nAsk for help in the gradio discord if you need and ask for help.\nWith that out of the way, let's start off by importing pdfjs and loading the code of the pdf worker from the mozilla cdn.\n`ts\n\timport pdfjsLib from \"pdfjs-dist\";\n    ...\n    pdfjsLib.GlobalWorkerOptions.workerSrc =  \"https://cdn.bootcss.com/pdf.js/3.11.174/pdf.worker.js\";\n`\nAlso create the following variables:\n`ts\n    let pdfDoc;\n    let numPages = 1;\n    let currentPage = 1;\n    let canvasRef;\n`\nNow, we will use pdfjs to render a given page of the PDF onto an html document.\nAdd the following code to Index.svelte:\n`ts\n    async function get_doc(value: FileData) {\n        const loadingTask = pdfjsLib.getDocument(value.url);\n        pdfDoc = await loadingTask.promise;\n        numPages = pdfDoc.numPages;\n        render_page();\n    }\n    function render_page() {\n    // Render a specific page of the PDF onto the canvas\n        pdfDoc.getPage(currentPage).then(page => {\n            const ctx  = canvasRef.getContext('2d')\n            ctx.clearRect(0, 0, canvasRef.width, canvasRef.height);\n            let viewport = page.getViewport({ scale: 1 });\n            let scale = height / viewport.height;\n            viewport = page.getViewport({ scale: scale });\n            const renderContext = {\n                canvasContext: ctx,\n                viewport,\n            };\n            canvasRef.width = viewport.width;\n            canvasRef.height = viewport.height;\n            page.render(renderContext);\n        });\n    }\n    // If the value changes, render the PDF of the currentPage\n    $: if(JSON.stringify(oldvalue) != JSON.stringify(value)) {\n        if (_value){\n            getdoc(value);\n        }\n        oldvalue = value;\n        gradio.dispatch(\"change\");\n    }\n`\n            \n                \n                    \n                    \n                    \n                \n                The $: syntax in svelte is how you declare statements to be reactive. Whenever any of the inputs of the statement change, svelte will automatically re-run that statement.\n            \n                \nNow place the canvas underneath the ModifyUpload component:\n`svelte\n    \n`\nAnd add the following styles to the  tag:\n`svelte\n    .pdf-canvas {\n        display: flex;\n        justify-content: center;\n        align-items: center;\n    }\n`\nStep 7: Handling The File Upload And Clear\nNow for the fun part - actually rendering the PDF when the file is uploaded!\nAdd the following functions to the  tag:\n`ts\n    async function handle_clear() {\n        _value = null;\n        await tick();\n        gradio.dispatch(\"change\");\n    }\n    async function handle_upload({detail}: CustomEvent): Promise {\n        value = detail;\n        await tick();\n        gradio.dispatch(\"change\");\n        gradio.dispatch(\"upload\");\n    }\n`\n            \n                \n                    \n                    \n                    \n                \n                The gradio.dispatch method is actually what is triggering the change or upload events in the backend. For every event defined in the component's backend, we will explain how to do this in Step 9, there must be at least one gradio.dispatch(\"&lt;event-name&gt;\") call. These are called gradio events and they can be listended from the entire Gradio application. You can dispatch a built-in svelte event with the dispatch function. These events can only be listened to from the component's direct parent. Learn about svelte events from the official documentation.\n            \n                \nNow we will run these functions whenever the Upload component uploads a file and whenever the ModifyUpload component clears the current file. The  component dispatches a load event with a payload of type FileData corresponding to the uploaded file. The on:load syntax tells Svelte to automatically run this function in response to the event.\n`svelte\n    \n    \n    ...\n    \n    \n        \n    \n`\nCongratulations! You have a working pdf uploader!\nStep 8: Adding buttons to navigate pages\nIf a user uploads a PDF document with multiple pages, they will only be able to see the first one.\nLet's add some buttons to help them navigate the page.\nWe will use the BaseButton from @gradio/button so that they look like regular Gradio buttons.\nImport the BaseButton and add the following functions that will render the next and previous page of the PDF.\n`ts\n    import { BaseButton } from \"@gradio/button\";\n    ...\n    function next_page() {\n        if (currentPage >= numPages) {\n            return;\n        }\n        currentPage++;\n        render_page();\n    }\n    function prev_page() {\n        if (currentPage == 1) {\n            return;\n        }\n        currentPage--;\n        render_page();\n    }\n`\nNow we will add them underneath the canvas in a separate \n`svelte\n    ...\n    \n    \n        \n    \n    \n        \n            ⬅️\n        \n         {currentPage} / {numPages} \n        \n            ➡️\n        \n    \n    \n    ...\n    .button-row {\n        display: flex;\n        flex-direction: row;\n        width: 100%;\n        justify-content: center;\n        align-items: center;\n    }\n    .page-count {\n        margin: 0 10px;\n        font-family: var(--font-mono);\n    }\n`\nCongratulations! The frontend is almost complete 🎉\nStep 8.5: The Example view\nWe're going to want users of our component to get a preview of the PDF if its used as an example in a gr.Interface or gr.Examples.\nTo do so, we're going to add some of the pdf rendering logic in Index.svelte to Example.svelte.\n`svelte\n\texport let value: string;\n\texport let type: \"gallery\" | \"table\";\n\texport let selected = false;\n\timport pdfjsLib from \"pdfjs-dist\";\n\tpdfjsLib.GlobalWorkerOptions.workerSrc =  \"https://cdn.bootcss.com/pdf.js/3.11.174/pdf.worker.js\";\n\t\n\tlet pdfDoc;\n\tlet canvasRef;\n\tasync function get_doc(url: string) {\n\t\tconst loadingTask = pdfjsLib.getDocument(url);\n\t\tpdfDoc = await loadingTask.promise;\n\t\trenderPage();\n\t\t}\n\tfunction renderPage() {\n\t\t// Render a specific page of the PDF onto the canvas\n\t\t\tpdfDoc.getPage(1).then(page => {\n\t\t\t\tconst ctx  = canvasRef.getContext('2d')\n\t\t\t\tctx.clearRect(0, 0, canvasRef.width, canvasRef.height);\n\t\t\t\t\n\t\t\t\tconst viewport = page.getViewport({ scale: 0.2 });\n\t\t\t\t\n\t\t\t\tconst renderContext = {\n\t\t\t\t\tcanvasContext: ctx,\n\t\t\t\t\tviewport\n\t\t\t\t};\n\t\t\t\tcanvasRef.width = viewport.width;\n\t\t\t\tcanvasRef.height = viewport.height;\n\t\t\t\tpage.render(renderContext);\n\t\t\t});\n\t\t}\n\t\n\t$: get_doc(value);\n\t\n\t.gallery {\n\t\tpadding: var(--size-1) var(--size-2);\n\t}\n`\n            \n                \n                    \n                    \n                    \n                \n                Exercise for the reader - reduce the code duplication between Index.svelte and Example.svelte 😊\n            \n                \nYou will not be able to render examples until we make some changes to the backend code in the next step!\nStep 9: The backend\nThe backend changes needed are smaller.\nWe're almost done!\nWhat we're going to do is:\nAdd change and upload events to our component.\nAdd a height property to let users control the height of the PDF.\nSet the data_model of our component to be FileData. This is so that Gradio can automatically cache and safely serve any files that are processed by our component.\nModify the preprocess method to return a string corresponding to the path of our uploaded PDF.\nModify the postprocess to turn a path to a PDF created in an event handler to a FileData.\nWhen all is said an done, your component's backend code should look like this:\n`python\nfrom future import annotations\nfrom typing import Any, Callable, TYPE_CHECKING\nfrom gradio.components.base import Component\nfrom gradio.data_classes import FileData\nfrom gradio import processing_utils\nif TYPE_CHECKING:\n    from gradio.components import Timer\nclass PDF(Component):\n    EVENTS = [\"change\", \"upload\"]\n    data_model = FileData\n    def init(self, value: Any = None, *,\n                 height: int | None = None,\n                 label: str | I18nData | None = None,\n                 info: str | I18nData | None = None,\n                 show_label: bool | None = None,\n                 container: bool = True,\n                 scale: int | None = None,\n                 min_width: int | None = None,\n                 interactive: bool | None = None,\n                 visible: bool = True,\n                 elem_id: str | None = None,\n                 elem_classes: list[str] | str | None = None,\n                 render: bool = True,\n                 load_fn: Callable[..., Any] | None = None,\n                 every: Timer | float | None = None):\n        super().init(value, label=label, info=info,\n                         showlabel=showlabel, container=container,\n                         scale=scale, minwidth=minwidth,\n                         interactive=interactive, visible=visible,\n                         elemid=elemid, elemclasses=elemclasses,\n                         render=render, loadfn=loadfn, every=every)\n        self.height = height\n    def preprocess(self, payload: FileData) -> str:\n        return payload.path\n    def postprocess(self, value: str | None) -> FileData:\n        if not value:\n            return None\n        return FileData(path=value)\n    def example_payload(self):\n        return \"https://gradio-builds.s3.amazonaws.com/assets/pdf-guide/fw9.pdf\"\n    def example_value(self):\n        return \"https://gradio-builds.s3.amazonaws.com/assets/pdf-guide/fw9.pdf\"\n`\nStep 10: Add a demo and publish!\nTo test our backend code, let's add a more complex demo that performs Document Question and Answering with huggingface transformers.\nIn our demo directory, create a requirements.txt file with the following packages\n`\ntorch\ntransformers\npdf2image\npytesseract\n`\n            \n                \n                    \n                    \n                    \n                \n                Remember to install these yourself and restart the dev server! You may need to install extra non-python dependencies for pdf2image. See here. Feel free to write your own demo if you have trouble.\n            \n                \n`python\nimport gradio as gr\nfrom gradio_pdf import PDF\nfrom pdf2image import convertfrompath\nfrom transformers import pipeline\nfrom pathlib import Path\ndir_ = Path(file).parent\np = pipeline(\n    \"document-question-answering\",\n    model=\"impira/layoutlm-document-qa\",\n)\ndef qa(question: str, doc: str) -> str:\n    img = convertfrompath(doc)[0]\n    output = p(img, question)\n    return sorted(output, key=lambda x: x[\"score\"], reverse=True)[0]['answer']\ndemo = gr.Interface(\n    qa,\n    [gr.Textbox(label=\"Question\"), PDF(label=\"Document\")],\n    gr.Textbox(),\n)\ndemo.launch()\n`\nSee our demo in action below!\n  \nFinally lets build our component with gradio cc build and publish it with the gradio cc publish command!\nThis will guide you through the process of uploading your component to PyPi and HuggingFace Spaces.\n            \n                \n                    \n                    \n                    \n                \n                You may need to add the following lines to the Dockerfile of your HuggingFace Space.\n            \n                \n`Dockerfile\nRUN mkdir -p /tmp/cache/\nRUN chmod a+rwx -R /tmp/cache/\nRUN apt-get update && apt-get install -y poppler-utils tesseract-ocr\nENV TRANSFORMERS_CACHE=/tmp/cache/\n`\nConclusion\nIn order to use our new component in any gradio 4.0 app, simply install it with pip, e.g. pip install gradio-pdf. Then you can use it like the built-in gr.File() component (except that it will only accept and display PDF files).\nHere is a simple demo with the Blocks api:\n`python\nimport gradio as gr\nfrom gradio_pdf import PDF\nwith gr.Blocks() as demo:\n    pdf = PDF(label=\"Upload a PDF\", interactive=True)\n    name = gr.Textbox()\n    pdf.upload(lambda f: f, pdf, name)\ndemo.launch()\n``\nI hope you enjoyed this tutorial!\nThe complete source code for our component is here.\nPlease don't hesitate to reach out to the gradio community on the HuggingFace Discord if you get stuck.","type":"GUIDE"},{"title":"Plot Component For Maps","slug":"/guides/plot-component-for-maps/","content":"How to Use the Plot Component for Maps\nIntroduction\nThis guide explains how you can use Gradio to plot geographical data on a map using the gradio.Plot component. The Gradio Plot component works with Matplotlib, Bokeh and Plotly. Plotly is what we will be working with in this guide. Plotly allows developers to easily create all sorts of maps with their geographical data. Take a look here for some examples.\nOverview\nWe will be using the New York City Airbnb dataset, which is hosted on kaggle here. I've uploaded it to the Hugging Face Hub as a dataset here for easier use and download. Using this data we will plot Airbnb locations on a map output and allow filtering based on price and location. Below is the demo that we will be building. ⚡️\nStep 1 - Loading CSV data 💾\nLet's start by loading the Airbnb NYC data from the Hugging Face Hub.\n``python\nfrom datasets import load_dataset\ndataset = load_dataset(\"gradio/NYC-Airbnb-Open-Data\", split=\"train\")\ndf = dataset.to_pandas()\ndef filtermap(minprice, max_price, boroughs):\n    newdf = df[(df['neighbourhoodgroup'].isin(boroughs)) &\n            (df['price'] > min_price) & (df['price'] Name: %{customdata[0]}Price: $%{customdata[1]}'\n        ))\nfig.update_layout(\n    mapbox_style=\"open-street-map\",\n    hovermode='closest',\n    mapbox=dict(\n        bearing=0,\n        center=go.layout.mapbox.Center(\n            lat=40.67,\n            lon=-73.90\n        ),\n        pitch=0,\n        zoom=9\n    ),\n)\n`\nAbove, we create a scatter plot on mapbox by passing it our list of latitudes and longitudes to plot markers. We also pass in our custom data of names and prices for additional info to appear on every marker we hover over. Next we use update_layout to specify other map settings such as zoom, and centering.\nMore info here on scatter plots using Mapbox and Plotly.\nStep 3 - Gradio App ⚡️\nWe will use two gr.Number components and a gr.CheckboxGroup to allow users of our app to specify price ranges and borough locations. We will then use the gr.Plot component as an output for our Plotly + Mapbox map we created earlier.\n`python\nwith gr.Blocks() as demo:\n    with gr.Column():\n        with gr.Row():\n            min_price = gr.Number(value=250, label=\"Minimum Price\")\n            max_price = gr.Number(value=1000, label=\"Maximum Price\")\n        boroughs = gr.CheckboxGroup(choices=[\"Queens\", \"Brooklyn\", \"Manhattan\", \"Bronx\", \"Staten Island\"], value=[\"Queens\", \"Brooklyn\"], label=\"Select Boroughs:\")\n        btn = gr.Button(value=\"Update Filter\")\n        map = gr.Plot()\n    demo.load(filtermap, [minprice, max_price, boroughs], map)\n    btn.click(filtermap, [minprice, max_price, boroughs], map)\n`\nWe layout these components using the gr.Column and gr.Row and we'll also add event triggers for when the demo first loads and when our \"Update Filter\" button is clicked in order to trigger the map to update with our new filters.\nThis is what the full demo code looks like:\n`python\nimport gradio as gr\nimport plotly.graph_objects as go\nfrom datasets import load_dataset\ndataset = load_dataset(\"gradio/NYC-Airbnb-Open-Data\", split=\"train\")\ndf = dataset.to_pandas()\ndef filtermap(minprice, max_price, boroughs):\n    filtereddf = df[(df['neighbourhoodgroup'].isin(boroughs)) &\n          (df['price'] > min_price) & (df['price'] Name: %{customdata[0]}Price: $%{customdata[1]}'\n        ))\n    fig.update_layout(\n        mapbox_style=\"open-street-map\",\n        hovermode='closest',\n        mapbox=dict(\n            bearing=0,\n            center=go.layout.mapbox.Center(\n                lat=40.67,\n                lon=-73.90\n            ),\n            pitch=0,\n            zoom=9\n        ),\n    )\n    return fig\nwith gr.Blocks() as demo:\n    with gr.Column():\n        with gr.Row():\n            min_price = gr.Number(value=250, label=\"Minimum Price\")\n            max_price = gr.Number(value=1000, label=\"Maximum Price\")\n        boroughs = gr.CheckboxGroup(choices=[\"Queens\", \"Brooklyn\", \"Manhattan\", \"Bronx\", \"Staten Island\"], value=[\"Queens\", \"Brooklyn\"], label=\"Select Boroughs:\")\n        btn = gr.Button(value=\"Update Filter\")\n        map = gr.Plot()\n    demo.load(filtermap, [minprice, max_price, boroughs], map)\n    btn.click(filtermap, [minprice, max_price, boroughs], map)\ndemo.launch()\n`\nStep 4 - Deployment 🤗\nIf you run the code above, your app will start running locally.\nYou can even get a temporary shareable link by passing the share=True parameter to launch`.\nBut what if you want to a permanent deployment solution?\nLet's deploy our Gradio app to the free HuggingFace Spaces platform.\nIf you haven't used Spaces before, follow the previous guide here.\nConclusion 🎉\nAnd you're all done! That's all the code you need to build a map demo.\nHere's a link to the demo Map demo and complete code (on Hugging Face Spaces)","type":"GUIDE"},{"title":"Progress Bars","slug":"/guides/progress-bars/","content":"Progress Bars\nGradio supports the ability to create custom Progress Bars so that you have customizability and control over the progress update that you show to the user. In order to enable this, simply add an argument to your method that has a default value of a gr.Progress instance. Then you can update the progress levels by calling this instance directly with a float between 0 and 1, or using the tqdm() method of the Progress instance to track progress over an iterable, as shown below.\n``python\nimport gradio as gr\nimport time\ndef slowly_reverse(word, progress=gr.Progress()):\n    progress(0, desc=\"Starting\")\n    time.sleep(1)\n    progress(0.05)\n    new_string = \"\"\n    for letter in progress.tqdm(word, desc=\"Reversing\"):\n        time.sleep(0.25)\n        newstring = letter + newstring  \n    return new_string\ndemo = gr.Interface(slowlyreverse, gr.Text(), gr.Text(), apiname=\"predict\")\ndemo.launch()\n`\nIf you use the tqdm library, you can even report progress updates automatically from any tqdm.tqdm that already exists within your function by setting the default argument as gr.Progress(track_tqdm=True)`!","type":"GUIDE"},{"title":"Querying Gradio Apps With Curl","slug":"/guides/querying-gradio-apps-with-curl/","content":"Querying Gradio Apps with Curl\nIt is possible to use any Gradio app as an API using cURL, the command-line tool that is pre-installed on many operating systems. This is particularly useful if you are trying to query a Gradio app from an environment other than Python or Javascript (since specialized Gradio clients exist for both Python and Javascript).\nAs an example, consider this Gradio demo that translates text from English to French: https://abidlabs-en2fr.hf.space/.\nUsing curl, we can translate text programmatically.\nHere's the code to do it:\n``bash\n$ curl -X POST https://abidlabs-en2fr.hf.space/call/predict -H \"Content-Type: application/json\" -d '{\n  \"data\": [\"Hello, my friend.\"] \n}'\n>> {\"eventid\": $EVENTID}   \n`\n`bash\n$ curl -N https://abidlabs-en2fr.hf.space/call/predict/$EVENT_ID\n>> event: complete\n>> data: [\"Bonjour, mon ami.\"]\n`\nNote: making a prediction and getting a result requires two curl requests: a POST and a GET. The POST request returns an EVENT_ID and prints  it to the console, which is used in the second GET request to fetch the results. You can combine these into a single command using awk and read to parse the results of the first command and pipe into the second, like this:\n`bash\n$ curl -X POST https://abidlabs-en2fr.hf.space/call/predict -H \"Content-Type: application/json\" -d '{\n  \"data\": [\"Hello, my friend.\"] \n}' \\\n  | awk -F'\"' '{ print $4}'  \\\n  | read EVENTID; curl -N https://abidlabs-en2fr.hf.space/call/predict/$EVENTID\n>> event: complete\n>> data: [\"Bonjour, mon ami.\"]\n`\nIn the rest of this Guide, we'll explain these two steps in more detail and provide additional examples of querying Gradio apps with curl.\nPrerequisites: For this Guide, you do not need to know how to build Gradio apps in great detail. However, it is helpful to have general familiarity with Gradio's concepts of input and output components.\nInstallation\nYou generally don't need to install cURL, as it comes pre-installed on many operating systems. Run:\n`bash\ncurl --version\n`\nto confirm that curl is installed. If it is not already installed, you can install it by visiting https://curl.se/download.html. \nStep 0: Get the URL for your Gradio App \nTo query a Gradio app, you'll need its full URL. This is usually just the URL that the Gradio app is hosted on, for example: https://bec81a83-5b5c-471e.gradio.live\nHugging Face Spaces\nHowever, if you are querying a Gradio on Hugging Face Spaces, you will need to use the URL of the embedded Gradio app, not the URL of the Space webpage. For example:\n`bash\n❌ Space URL: https://huggingface.co/spaces/abidlabs/en2fr\n✅ Gradio app URL: https://abidlabs-en2fr.hf.space/\n`\nYou can get the Gradio app URL by clicking the \"view API\" link at the bottom of the page. Or, you can right-click on the page and then click on \"View Frame Source\" or the equivalent in your browser to view the URL of the embedded Gradio app.\nWhile you can use any public Space as an API, you may get rate limited by Hugging Face if you make too many requests. For unlimited usage of a Space, simply duplicate the Space to create a private Space,\nand then use it to make as many requests as you'd like!\nNote: to query private Spaces, you will need to pass in your Hugging Face (HF) token. You can get your HF token here: https://huggingface.co/settings/tokens. In this case, you will need to include an additional header in both of your curl calls that we'll discuss below:\n`bash\n-H \"Authorization: Bearer $HF_TOKEN\"\n`\nNow, we are ready to make the two curl requests.\nStep 1: Make a Prediction (POST)\nThe first of the two curl requests is POST request that submits the input payload to the Gradio app. \nThe syntax of the POST request is as follows:\n`bash\n$ curl -X POST $URL/call/$API_NAME -H \"Content-Type: application/json\" -d '{\n  \"data\": $PAYLOAD\n}'\n`\nHere:\n$URL is the URL of the Gradio app as obtained in Step 0\n$API_NAME is the name of the API endpoint for the event that you are running. You can get the API endpoint names by clicking the \"view API\" link at the bottom of the page.\n$PAYLOAD is a valid JSON data list containing the input payload, one element for each input component.\nWhen you make this POST request successfully, you will get an event id that is printed to the terminal in this format:\n`bash\n>> {\"eventid\": $EVENTID}   \n`\nThis EVENT_ID will be needed in the subsequent curl request to fetch the results of the prediction. \nHere are some examples of how to make the POST request\nBasic Example\nRevisiting the example at the beginning of the page, here is how to make the POST request for a simple Gradio application that takes in a single input text component:\n`bash\n$ curl -X POST https://abidlabs-en2fr.hf.space/call/predict -H \"Content-Type: application/json\" -d '{\n  \"data\": [\"Hello, my friend.\"] \n}'\n`\nMultiple Input Components\nThis Gradio demo accepts three inputs: a string corresponding to the gr.Textbox, a boolean value corresponding to the gr.Checkbox, and a numerical value corresponding to the gr.Slider. Here is the POST request:\n`bash\ncurl -X POST https://gradio-hello-world-3.hf.space/call/predict -H \"Content-Type: application/json\" -d '{\n  \"data\": [\"Hello\", true, 5]\n}'\n`\nPrivate Spaces\nAs mentioned earlier, if you are making a request to a private Space, you will need to pass in a Hugging Face token that has read access to the Space. The request will look like this:\n`bash\n$ curl -X POST https://private-space.hf.space/call/predict -H \"Content-Type: application/json\" -H \"Authorization: Bearer $HF_TOKEN\" -d '{\n  \"data\": [\"Hello, my friend.\"] \n}'\n`\nFiles\nIf you are using curl to query a Gradio application that requires file inputs, the files need to be provided as URLs, and The URL needs to be enclosed in a dictionary in this format:\n`bash\n{\"path\": $URL}\n`\nHere is an example POST request:\n`bash\n$ curl -X POST https://gradio-image-mod.hf.space/call/predict -H \"Content-Type: application/json\" -d '{\n  \"data\": [{\"path\": \"https://raw.githubusercontent.com/gradio-app/gradio/main/test/test_files/bus.png\"}] \n}'\n`\nStateful Demos\nIf your Gradio demo persists user state across multiple interactions (e.g. is a chatbot), you can pass in a sessionhash alongside the data. Requests with the same sessionhash are assumed to be part of the same user session. Here's how that might look:\n`bash\nThese two requests will share a session\ncurl -X POST https://gradio-chatinterface-random-response.hf.space/call/chat -H \"Content-Type: application/json\" -d '{\n  \"data\": [\"Are you sentient?\"],\n  \"session_hash\": \"randomsequence1234\"\n}'\ncurl -X POST https://gradio-chatinterface-random-response.hf.space/call/chat -H \"Content-Type: application/json\" -d '{\n  \"data\": [\"Really?\"],\n  \"session_hash\": \"randomsequence1234\"\n}'\nThis request will be treated as a new session\ncurl -X POST https://gradio-chatinterface-random-response.hf.space/call/chat -H \"Content-Type: application/json\" -d '{\n  \"data\": [\"Are you sentient?\"],\n  \"session_hash\": \"newsequence5678\"\n}'\n`\nStep 2: GET the result\nOnce you have received the EVENT_ID corresponding to your prediction, you can stream the results. Gradio stores these results  in a least-recently-used cache in the Gradio app. By default, the cache can store 2,000 results (across all users and endpoints of the app). \nTo stream the results for your prediction, make a GET request with the following syntax:\n`bash\n$ curl -N $URL/call/$APINAME/$EVENTID\n`\n            \n                \n                    \n                    \n                    \n                \n                If you are fetching results from a private Space, include a header with your HF token like this: -H \"Authorization: Bearer $HF_TOKEN\" in the GET request.\n            \n                \nThis should produce a stream of responses in this format:\n`bash\nevent: ... \ndata: ...\nevent: ... \ndata: ...\n...\n`\nHere: event can be one of the following:\ngenerating: indicating an intermediate result\ncomplete: indicating that the prediction is complete and the final result \nerror: indicating that the prediction was not completed successfully\nheartbeat: sent every 15 seconds to keep the request alive\nThe data is in the same format as the input payload: valid JSON data list containing the output result, one element for each output component.\nHere are some examples of what results you should expect if a request is completed successfully:\nBasic Example\nRevisiting the example at the beginning of the page, we would expect the result to look like this:\n`bash\nevent: complete\ndata: [\"Bonjour, mon ami.\"]\n`\nMultiple Outputs\nIf your endpoint returns multiple values, they will appear as elements of the data list:\n`bash\nevent: complete\ndata: [\"Good morning Hello. It is 5 degrees today\", -15.0]\n`\nStreaming Example\nIf your Gradio app streams a sequence of values, then they will be streamed directly to your terminal, like this:\n`bash\nevent: generating\ndata: [\"Hello, w!\"]\nevent: generating\ndata: [\"Hello, wo!\"]\nevent: generating\ndata: [\"Hello, wor!\"]\nevent: generating\ndata: [\"Hello, worl!\"]\nevent: generating\ndata: [\"Hello, world!\"]\nevent: complete\ndata: [\"Hello, world!\"]\n`\nFile Example\nIf your Gradio app returns a file, the file will be represented as a dictionary in this format (including potentially some additional keys):\n`python\n{\n    \"orig_name\": \"example.jpg\",\n    \"path\": \"/path/in/server.jpg\",\n    \"url\": \"https:/example.com/example.jpg\",\n    \"meta\": {\"_type\": \"gradio.FileData\"}\n}\n`\nIn your terminal, it may appear like this:\n`bash\nevent: complete\ndata: [{\"path\": \"/tmp/gradio/359933dc8d6cfe1b022f35e2c639e6e42c97a003/image.webp\", \"url\": \"https://gradio-image-mod.hf.space/c/file=/tmp/gradio/359933dc8d6cfe1b022f35e2c639e6e42c97a003/image.webp\", \"size\": null, \"origname\": \"image.webp\", \"mimetype\": null, \"isstream\": false, \"meta\": {\"type\": \"gradio.FileData\"}}]\n`\nAuthentication\nWhat if your Gradio application has authentication enabled? In that case, you'll need to make an additional POST request with cURL to authenticate yourself before you make any queries. Here are the complete steps:\nFirst, login with a POST request supplying a valid username and password:\n`bash\ncurl -X POST $URL/login \\\n     -d \"username=$USERNAME&password=$PASSWORD\" \\\n     -c cookies.txt\n`\nIf the credentials are correct, you'll get {\"success\":true} in response and the cookies will be saved in cookies.txt.\nNext, you'll need to include these cookies when you make the original POST request, like this:\n`bash\n$ curl -X POST $URL/call/$API_NAME -b cookies.txt -H \"Content-Type: application/json\" -d '{\n  \"data\": $PAYLOAD\n}'\n`\nFinally, you'll need to GET the results, again supplying the cookies from the file:\n`bash\ncurl -N $URL/call/$APINAME/$EVENTID -b cookies.txt\n``","type":"GUIDE"},{"title":"Queuing","slug":"/guides/queuing/","content":"Queuing\nEvery Gradio app comes with a built-in queuing system that can scale to thousands of concurrent users. Because many of your event listeners may involve heavy processing, Gradio automatically creates a queue to handle every event listener in the backend. Every event listener in your app automatically has a queue to process incoming events.\nConfiguring the Queue\nBy default, each event listener has its own queue, which handles one request at a time. This can be configured via two arguments:\nconcurrency_limit: This sets the maximum number of concurrent executions for an event listener. By default, the limit is 1 unless configured otherwise in Blocks.queue(). You can also set it to None for no limit (i.e., an unlimited number of concurrent executions). For example:\n``python\nimport gradio as gr\nwith gr.Blocks() as demo:\n    prompt = gr.Textbox()\n    image = gr.Image()\n    generate_btn = gr.Button(\"Generate Image\")\n    generatebtn.click(imagegen, prompt, image, concurrency_limit=5)\n`\nIn the code above, up to 5 requests can be processed simultaneously for this event listener. Additional requests will be queued until a slot becomes available.\nIf you want to manage multiple event listeners using a shared queue, you can use the concurrency_id argument:\nconcurrency_id: This allows event listeners to share a queue by assigning them the same ID. For example, if your setup has only 2 GPUs but multiple functions require GPU access, you can create a shared queue for all those functions. Here's how that might look:\n`python\nimport gradio as gr\nwith gr.Blocks() as demo:\n    prompt = gr.Textbox()\n    image = gr.Image()\n    generatebtn1 = gr.Button(\"Generate Image via model 1\")\n    generatebtn2 = gr.Button(\"Generate Image via model 2\")\n    generatebtn3 = gr.Button(\"Generate Image via model 3\")\n    generatebtn1.click(imagegen1, prompt, image, concurrencylimit=2, concurrencyid=\"gpu_queue\")\n    generatebtn2.click(imagegen2, prompt, image, concurrencyid=\"gpuqueue\")\n    generatebtn3.click(imagegen3, prompt, image, concurrencyid=\"gpuqueue\")\n`\nIn this example, all three event listeners share a queue identified by \"gpuqueue\". The queue can handle up to 2 concurrent requests at a time, as defined by the concurrencylimit.\nNotes\nTo ensure unlimited concurrency for an event listener, set concurrency_limit=None.  This is useful if your function is calling e.g. an external API which handles the rate limiting of requests itself.\nThe default concurrency limit for all queues can be set globally using the defaultconcurrencylimit parameter in Blocks.queue()`. \nThese configurations make it easy to manage the queuing behavior of your Gradio app.","type":"GUIDE"},{"title":"Quickstart","slug":"/guides/quickstart/","content":"Quickstart\nGradio is an open-source Python package that allows you to quickly build a demo or web application for your machine learning model, API, or any arbitrary Python function. You can then share a link to your demo or web application in just a few seconds using Gradio's built-in sharing features. No JavaScript, CSS, or web hosting experience needed!\nIt just takes a few lines of Python to create your own demo, so let's get started 💫\nInstallation\nPrerequisite: Gradio requires Python 3.10 or higher.\nWe recommend installing Gradio using pip, which is included by default in Python. Run this in your terminal or command prompt:\n``bash\npip install --upgrade gradio\n`\n            \n                \n                    \n                    \n                    \n                \n                It is best to install Gradio in a virtual environment. Detailed installation instructions for all common operating systems are provided here. \n            \n                \nBuilding Your First Demo\nYou can run Gradio in your favorite code editor, Jupyter notebook, Google Colab, or anywhere else you write Python. Let's write your first Gradio app:\n`python\nimport gradio as gr\ndef greet(name, intensity):\n    return \"Hello, \" + name + \"!\" * int(intensity)\ndemo = gr.Interface(\n    fn=greet,\n    inputs=[\"text\", \"slider\"],\n    outputs=[\"text\"],\n    api_name=\"predict\"\n)\ndemo.launch()\n`\n            \n                \n                    \n                    \n                    \n                \n                We shorten the imported name from gradio to gr. This is a widely adopted convention for better readability of code. \n            \n                \nNow, run your code. If you've written the Python code in a file named app.py, then you would run python app.py from the terminal.\nThe demo below will open in a browser on http://localhost:7860 if running from a file. If you are running within a notebook, the demo will appear embedded within the notebook.\nType your name in the textbox on the left, drag the slider, and then press the Submit button. You should see a friendly greeting on the right.\n            \n                \n                    \n                    \n                    \n                \n                When developing locally, you can run your Gradio app in hot reload mode, which automatically reloads the Gradio app whenever you make changes to the file. To do this, simply type in gradio before the name of the file instead of python. In the example above, you would type: gradio app.py in your terminal. You can also enable vibe mode by using the --vibe flag, e.g. gradio --vibe app.py, which provides an in-browser chat that can be used to write or edit your Gradio app using natural language. Learn more in the Hot Reloading Guide.\n            \n                \nUnderstanding the Interface Class\nYou'll notice that in order to make your first demo, you created an instance of the gr.Interface class. The Interface class is designed to create demos for machine learning models which accept one or more inputs, and return one or more outputs. \nThe Interface class has three core arguments:\nfn: the function to wrap a user interface (UI) around\ninputs: the Gradio component(s) to use for the input. The number of components should match the number of arguments in your function.\noutputs: the Gradio component(s) to use for the output. The number of components should match the number of return values from your function.\nThe fn argument is very flexible -- you can pass any Python function that you want to wrap with a UI. In the example above, we saw a relatively simple function, but the function could be anything from a music generator to a tax calculator to the prediction function of a pretrained machine learning model.\nThe inputs and outputs arguments take one or more Gradio components. As we'll see, Gradio includes more than 30 built-in components (such as the gr.Textbox(), gr.Image(), and gr.HTML() components) that are designed for machine learning applications. \n            \n                \n                    \n                    \n                    \n                \n                For the inputs and outputs arguments, you can pass in the name of these components as a string (\"textbox\") or an instance of the class (gr.Textbox()).\n            \n                \nIf your function accepts more than one argument, as is the case above, pass a list of input components to inputs, with each input component corresponding to one of the arguments of the function, in order. The same holds true if your function returns more than one value: simply pass in a list of components to outputs. This flexibility makes the Interface class a very powerful way to create demos.\nWe'll dive deeper into the gr.Interface on our series on building Interfaces.\nSharing Your Demo\nWhat good is a beautiful demo if you can't share it? Gradio lets you easily share a machine learning demo without having to worry about the hassle of hosting on a web server. Simply set share=True in launch(), and a publicly accessible URL will be created for your demo. Let's revisit our example demo,  but change the last line as follows:\n`python\nimport gradio as gr\ndef greet(name):\n    return \"Hello \" + name + \"!\"\ndemo = gr.Interface(fn=greet, inputs=\"textbox\", outputs=\"textbox\")\n    \ndemo.launch(share=True)  # Share your demo with just 1 extra parameter 🚀\n`\nWhen you run this code, a public URL will be generated for your demo in a matter of seconds, something like:\n👉 &nbsp; https://a23dsf231adb.gradio.live\nNow, anyone around the world can try your Gradio demo from their browser, while the machine learning model and all computation continues to run locally on your computer.\nTo learn more about sharing your demo, read our dedicated guide on sharing your Gradio application.\nAn Overview of Gradio\nSo far, we've been discussing the Interface class, which is a high-level class that lets you build demos quickly with Gradio. But what else does Gradio include?\nCustom Demos with gr.Blocks\nGradio offers a low-level approach for designing web apps with more customizable layouts and data flows with the gr.Blocks class. Blocks supports things like controlling where components appear on the page, handling multiple data flows and more complex interactions (e.g. outputs can serve as inputs to other functions), and updating properties/visibility of components based on user interaction — still all in Python. \nYou can build very custom and complex applications using gr.Blocks(). For example, the popular image generation Automatic1111 Web UI is built using Gradio Blocks. We dive deeper into the gr.Blocks on our series on building with Blocks.\nChatbots with gr.ChatInterface\nGradio includes another high-level class, gr.ChatInterface, which is specifically designed to create Chatbot UIs. Similar to Interface, you supply a function and Gradio creates a fully working Chatbot UI. If you're interested in creating a chatbot, you can jump straight to our dedicated guide on gr.ChatInterface.\nThe Gradio Python & JavaScript Ecosystem\nThat's the gist of the core gradio Python library, but Gradio is actually so much more! It's an entire ecosystem of Python and JavaScript libraries that let you build machine learning applications, or query them programmatically, in Python or JavaScript. Here are other related parts of the Gradio ecosystem:\nGradio Python Client (gradio_client): query any Gradio app programmatically in Python.\nGradio JavaScript Client (@gradio/client): query any Gradio app programmatically in JavaScript.\nHugging Face Spaces: the most popular place to host Gradio applications — for free!\nServer mode (gradio.Server`): build a completely custom frontend using only Gradio's backend (queue, streaming, MCP, ZeroGPU, and Spaces hosting included).\nWhat's Next?\nKeep learning about Gradio sequentially using the Gradio Guides, which include explanations as well as example code and embedded interactive demos. Next up: let's dive deeper into the Interface class.\nOr, if you already know the basics and are looking for something specific, you can search the more technical API documentation.","type":"GUIDE"},{"title":"Reactive Interfaces","slug":"/guides/reactive-interfaces/","content":"Reactive Interfaces\nFinally, we cover how to get Gradio demos to refresh automatically or continuously stream data.\nLive Interfaces\nYou can make interfaces automatically refresh by setting live=True in the interface. Now the interface will recalculate as soon as the user input changes.\n``python\nimport gradio as gr\ndef calculator(num1, operation, num2):\n    if operation == \"add\":\n        return num1 + num2\n    elif operation == \"subtract\":\n        return num1 - num2\n    elif operation == \"multiply\":\n        return num1 * num2\n    elif operation == \"divide\":\n        return num1 / num2\ndemo = gr.Interface(\n    calculator,\n    [\n        \"number\",\n        gr.Radio([\"add\", \"subtract\", \"multiply\", \"divide\"]),\n        \"number\"\n    ],\n    \"number\",\n    live=True,\n)\ndemo.launch()\n`\nNote there is no submit button, because the interface resubmits automatically on change.\nStreaming Components\nSome 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.\nThe 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.\nHere is example code of streaming images from the webcam.\n`python\nimport gradio as gr\nimport numpy as np\ndef flip(im):\n    return np.flipud(im)\ndemo = gr.Interface(\n    flip,\n    gr.Image(sources=[\"webcam\"], streaming=True),\n    \"image\",\n    live=True,\n    api_name=\"predict\",\n)\ndemo.launch()\n`\nStreaming 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 with Gradio.","type":"GUIDE"},{"title":"Real Time Speech Recognition","slug":"/guides/real-time-speech-recognition/","content":"Real Time Speech Recognition\nIntroduction\nAutomatic speech recognition (ASR), the conversion of spoken speech to text, is a very important and thriving area of machine learning. ASR algorithms run on practically every smartphone, and are becoming increasingly embedded in professional workflows, such as digital assistants for nurses and doctors. Because ASR algorithms are designed to be used directly by customers and end users, it is important to validate that they are behaving as expected when confronted with a wide variety of speech patterns (different accents, pitches, and background audio conditions).\nUsing gradio, you can easily build a demo of your ASR model and share that with a testing team, or test it yourself by speaking through the microphone on your device.\nThis tutorial will show how to take a pretrained speech-to-text model and deploy it with a Gradio interface. We will start with a full-context model, in which the user speaks the entire audio before the prediction runs. Then we will adapt the demo to make it streaming, meaning that the audio model will convert speech as you speak. \nPrerequisites\nMake sure you have the gradio Python package already installed. You will also need a pretrained speech recognition model. In this tutorial, we will build demos from 2 ASR libraries:\nTransformers (for this, pip install torch transformers torchaudio)\nMake sure you have at least one of these installed so that you can follow along the tutorial. You will also need ffmpeg installed on your system, if you do not already have it, to process files from the microphone.\nHere's how to build a real time speech recognition (ASR) app:\nSet up the Transformers ASR Model\nCreate a Full-Context ASR Demo with Transformers\nCreate a Streaming ASR Demo with Transformers\nSet up the Transformers ASR Model\nFirst, you will need to have an ASR model that you have either trained yourself or you will need to download a pretrained model. In this tutorial, we will start by using a pretrained ASR model from the model, whisper.\nHere is the code to load whisper from Hugging Face transformers.\n``python\nfrom transformers import pipeline\np = pipeline(\"automatic-speech-recognition\", model=\"openai/whisper-base.en\")\n`\nThat's it!\nCreate a Full-Context ASR Demo with Transformers\nWe will start by creating a full-context ASR demo, in which the user speaks the full audio before using the ASR model to run inference. This is very easy with Gradio -- we simply create a function around the pipeline object above.\nWe will use gradio's built in Audio component, configured to take input from the user's microphone and return a filepath for the recorded audio. The output component will be a plain Textbox.\n`python\nimport gradio as gr\nfrom transformers import pipeline\nimport numpy as np\ntranscriber = pipeline(\"automatic-speech-recognition\", model=\"openai/whisper-base.en\")\ndef transcribe(audio):\n    sr, y = audio\n    \n    # Convert to mono if stereo\n    if y.ndim > 1:\n        y = y.mean(axis=1)\n        \n    y = y.astype(np.float32)\n    y /= np.max(np.abs(y))\n    return transcriber({\"sampling_rate\": sr, \"raw\": y})[\"text\"]  \ndemo = gr.Interface(\n    transcribe,\n    gr.Audio(sources=\"microphone\"),\n    \"text\",\n    api_name=\"predict\",\n)\ndemo.launch()\n`\nThe transcribe function takes a single parameter, audio, which is a numpy array of the audio the user recorded. The pipeline object expects this in float32 format, so we convert it first to float32, and then extract the transcribed text.\nCreate a Streaming ASR Demo with Transformers\nTo make this a streaming demo, we need to make these changes:\nSet streaming=True in the Audio component\nSet live=True in the Interface\nAdd a state to the interface to store the recorded audio of a user\n            \n                \n                    \n                    \n                    \n                \n                You can also set timelimit and streamevery parameters in the interface. The timelimit caps the amount of time each user's stream can take. The default is 30 seconds so users won't be able to stream audio for more than 30 seconds. The streamevery parameter controls how frequently data is sent to your function. By default it is 0.5 seconds.\n            \n                \nTake a look below.\n`python\nimport gradio as gr\nfrom transformers import pipeline\nimport numpy as np\ntranscriber = pipeline(\"automatic-speech-recognition\", model=\"openai/whisper-base.en\")\ndef transcribe(stream, new_chunk):\n    sr, y = new_chunk\n    \n    # Convert to mono if stereo\n    if y.ndim > 1:\n        y = y.mean(axis=1)\n        \n    y = y.astype(np.float32)\n    y /= np.max(np.abs(y))\n    if stream is not None:\n        stream = np.concatenate([stream, y])\n    else:\n        stream = y\n    return stream, transcriber({\"sampling_rate\": sr, \"raw\": stream})[\"text\"]  \ndemo = gr.Interface(\n    transcribe,\n    [\"state\", gr.Audio(sources=[\"microphone\"], streaming=True)],\n    [\"state\", \"text\"],\n    live=True,\n    api_name=\"predict\"\n)\ndemo.launch()\n`\nNotice that we now have a state variable because we need to track all the audio history. transcribe gets called whenever there is a new small chunk of audio, but we also need to keep track of all the audio spoken so far in the state. As the interface runs, the transcribe function gets called, with a record of all the previously spoken audio in the stream and the new chunk of audio as new_chunk. We return the new full audio to be stored back in its current state, and we also return the transcription. Here, we naively append the audio together and call the transcriber` object on the entire audio. You can imagine more efficient ways of handling this, such as re-processing only the last 5 seconds of audio whenever a new chunk of audio is received. \nNow the ASR model will run inference as you speak!","type":"GUIDE"},{"title":"Resource Cleanup","slug":"/guides/resource-cleanup/","content":"Resource Cleanup\nYour Gradio application may create resources during its lifetime.\nExamples of resources are gr.State variables, any variables you create and explicitly hold in memory, or files you save to disk. \nOver time, these resources can use up all of your server's RAM or disk space and crash your application.\nGradio provides some tools for you to clean up the resources created by your app:\nAutomatic deletion of gr.State variables.\nAutomatic cache cleanup with the delete_cache parameter.\nThe Blocks.unload event.\nLet's take a look at each of them individually.\nAutomatic deletion of gr.State\nWhen a user closes their browser tab, Gradio will automatically delete any gr.State variables associated with that user session after 60 minutes. If the user connects again within those 60 minutes, no state will be deleted.\nYou can control the deletion behavior further with the following two parameters of gr.State:\ndelete_callback - An arbitrary function that will be called when the variable is deleted. This function must take the state value as input. This function is useful for deleting variables from GPU memory.\ntimetolive - The number of seconds the state should be stored for after it is created or updated. This will delete variables before the session is closed, so it's useful for clearing state for potentially long running sessions.\nAutomatic cache cleanup via delete_cache\nYour Gradio application will save uploaded and generated files to a special directory called the cache directory. Gradio uses a hashing scheme to ensure that duplicate files are not saved to the cache but over time the size of the cache will grow (especially if your app goes viral 😉).\nGradio can periodically clean up the cache for you if you specify the delete_cache parameter of gr.Blocks(), gr.Interface(), or gr.ChatInterface(). \nThis parameter is a tuple of the form [frequency, age] both expressed in number of seconds.\nEvery frequency seconds, the temporary files created by this Blocks instance will be deleted if more than age seconds have passed since the file was created. \nFor example, setting this to (86400, 86400) will delete temporary files every day if they are older than a day old.\nAdditionally, the cache will be deleted entirely when the server restarts.\nThe unload event\nAdditionally, Gradio now includes a Blocks.unload() event, allowing you to run arbitrary cleanup functions when users disconnect (this does not have a 60 minute delay).\nUnlike other gradio events, this event does not accept inputs or outptus.\nYou can think of the unload event as the opposite of the load event.\nPutting it all together\nThe following demo uses all of these features. When a user visits the page, a special unique directory is created for that user.\nAs the user interacts with the app, images are saved to disk in that special directory.\nWhen the user closes the page, the images created in that session are deleted via the unload event.\nThe state and files in the cache are cleaned up automatically as well.\n``python\nfrom future import annotations\nimport gradio as gr\nimport numpy as np\nfrom PIL import Image\nfrom pathlib import Path\nimport secrets\nimport shutil\ncurrent_dir = Path(file).parent\ndef generaterandomimg(history: list[Image.Image], request: gr.Request):\n    \"\"\"Generate a random red, green, blue, orange, yellor or purple image.\"\"\"\n    colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 165, 0), (255, 255, 0), (128, 0, 128)]\n    color = colors[np.random.randint(0, len(colors))]\n    img = Image.new('RGB', (100, 100), color)\n    userdir: Path = currentdir / str(request.session_hash)\n    userdir.mkdir(existok=True)\n    path = userdir / f\"{secrets.tokenurlsafe(8)}.webp\"\n    img.save(path)\n    history.append(img)\n    return img, history, history\ndef delete_directory(req: gr.Request):\n    if not req.username:\n        return\n    userdir: Path = currentdir / req.username\n    shutil.rmtree(str(user_dir))\nwith gr.Blocks(delete_cache=(60, 3600)) as demo:\n    gr.Markdown(\"\"\"# State Cleanup Demo\n                🖼️ Images are saved in a user-specific directory and deleted when the users closes the page via demo.unload.\n                \"\"\")\n    with gr.Row():\n        with gr.Column(scale=1):\n            with gr.Row():\n                img = gr.Image(label=\"Generated Image\", height=300, width=300)\n            with gr.Row():\n                gen = gr.Button(value=\"Generate\")\n            with gr.Row():\n                history = gr.Gallery(label=\"Previous Generations\", height=500, columns=10)\n                state = gr.State(value=[], delete_callback=lambda v: print(\"STATE DELETED\"))\n    demo.load(generaterandomimg, [state], [img, state, history])\n    gen.click(generaterandomimg, [state], [img, state, history])\n    demo.unload(delete_directory)\ndemo.launch()\n``","type":"GUIDE"},{"title":"Running Background Tasks","slug":"/guides/running-background-tasks/","content":"Running Background Tasks\nIntroduction\nThis guide explains how you can run background tasks from your gradio app.\nBackground tasks are operations that you'd like to perform outside the request-response\nlifecycle of your app either once or on a periodic schedule.\nExamples of background tasks include periodically synchronizing data to an external database or\nsending a report of model predictions via email.\nOverview\nWe will be creating a simple \"Google-forms-style\" application to gather feedback from users of the gradio library.\nWe will use a local sqlite database to store our data, but we will periodically synchronize the state of the database\nwith a HuggingFace Dataset so that our user reviews are always backed up.\nThe synchronization will happen in a background task running every 60 seconds.\nAt the end of the demo, you'll have a fully working application like this one:\n \nStep 1 - Write your database logic 💾\nOur application will store the name of the reviewer, their rating of gradio on a scale of 1 to 5, as well as\nany comments they want to share about the library. Let's write some code that creates a database table to\nstore this data. We'll also write some functions to insert a review into that table and fetch the latest 10 reviews.\nWe're going to use the sqlite3 library to connect to our sqlite database but gradio will work with any library.\nThe code will look like this:\n``python\nDB_FILE = \"./reviews.db\"\ndb = sqlite3.connect(DB_FILE)\nCreate table if it doesn't already exist\ntry:\n    db.execute(\"SELECT * FROM reviews\").fetchall()\n    db.close()\nexcept sqlite3.OperationalError:\n    db.execute(\n        '''\n        CREATE TABLE reviews (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\n                              createdat TIMESTAMP DEFAULT CURRENTTIMESTAMP NOT NULL,\n                              name TEXT, review INTEGER, comments TEXT)\n        ''')\n    db.commit()\n    db.close()\ndef getlatestreviews(db: sqlite3.Connection):\n    reviews = db.execute(\"SELECT * FROM reviews ORDER BY id DESC limit 10\").fetchall()\n    total_reviews = db.execute(\"Select COUNT(id) from reviews\").fetchone()[0]\n    reviews = pd.DataFrame(reviews, columns=[\"id\", \"date_created\", \"name\", \"review\", \"comments\"])\n    return reviews, total_reviews\ndef add_review(name: str, review: int, comments: str):\n    db = sqlite3.connect(DB_FILE)\n    cursor = db.cursor()\n    cursor.execute(\"INSERT INTO reviews(name, review, comments) VALUES(?,?,?)\", [name, review, comments])\n    db.commit()\n    reviews, totalreviews = getlatest_reviews(db)\n    db.close()\n    return reviews, total_reviews\n`\nLet's also write a function to load the latest reviews when the gradio application loads:\n`python\ndef load_data():\n    db = sqlite3.connect(DB_FILE)\n    reviews, totalreviews = getlatest_reviews(db)\n    db.close()\n    return reviews, total_reviews\n`\nStep 2 - Create a gradio app ⚡\nNow that we have our database logic defined, we can use gradio create a dynamic web page to ask our users for feedback!\n`python\nwith gr.Blocks() as demo:\n    with gr.Row():\n        with gr.Column():\n            name = gr.Textbox(label=\"Name\", placeholder=\"What is your name?\")\n            review = gr.Radio(label=\"How satisfied are you with using gradio?\", choices=[1, 2, 3, 4, 5])\n            comments = gr.Textbox(label=\"Comments\", lines=10, placeholder=\"Do you have any feedback on gradio?\")\n            submit = gr.Button(value=\"Submit Feedback\")\n        with gr.Column():\n            data = gr.Dataframe(label=\"Most recently created 10 rows\")\n            count = gr.Number(label=\"Total number of reviews\")\n    submit.click(add_review, [name, review, comments], [data, count])\n    demo.load(load_data, None, [data, count])\n`\nStep 3 - Synchronize with HuggingFace Datasets 🤗\nWe could call demo.launch() after step 2 and have a fully functioning application. However,\nour data would be stored locally on our machine. If the sqlite file were accidentally deleted, we'd lose all of our reviews!\nLet's back up our data to a dataset on the HuggingFace hub.\nCreate a dataset here before proceeding.\nNow at the top of our script, we'll use the huggingface hub client library\nto connect to our dataset and pull the latest backup.\n`python\nTOKEN = os.environ.get('HUB_TOKEN')\nrepo = huggingface_hub.Repository(\n    local_dir=\"data\",\n    repo_type=\"dataset\",\n    clone_from=\"\",\n    useauthtoken=TOKEN\n)\nrepo.git_pull()\nshutil.copyfile(\"./data/reviews.db\", DB_FILE)\n`\nNote that you'll have to get an access token from the \"Settings\" tab of your HuggingFace for the above code to work.\nIn the script, the token is securely accessed via an environment variable.\nNow we will create a background task to synch our local database to the dataset hub every 60 seconds.\nWe will use the AdvancedPythonScheduler to handle the scheduling.\nHowever, this is not the only task scheduling library available. Feel free to use whatever you are comfortable with.\nThe function to back up our data will look like this:\n`python\nfrom apscheduler.schedulers.background import BackgroundScheduler\ndef backup_db():\n    shutil.copyfile(DB_FILE, \"./data/reviews.db\")\n    db = sqlite3.connect(DB_FILE)\n    reviews = db.execute(\"SELECT * FROM reviews\").fetchall()\n    pd.DataFrame(reviews).to_csv(\"./data/reviews.csv\", index=False)\n    print(\"updating db\")\n    repo.pushtohub(blocking=False, commit_message=f\"Updating data at {datetime.datetime.now()}\")\nscheduler = BackgroundScheduler()\nscheduler.addjob(func=backupdb, trigger=\"interval\", seconds=60)\nscheduler.start()\n`\nStep 4 (Bonus) - Deployment to HuggingFace Spaces\nYou can use the HuggingFace Spaces platform to deploy this application for free ✨\nIf you haven't used Spaces before, follow the previous guide here.\nYou will have to use the HUB_TOKEN` environment variable as a secret in the Guides.\nConclusion\nCongratulations! You know how to run background tasks from your gradio app on a schedule ⏲️.\nCheckout the application running on Spaces here.\nThe complete code is here","type":"GUIDE"},{"title":"Running Gradio On Your Web Server With Nginx","slug":"/guides/running-gradio-on-your-web-server-with-nginx/","content":"Running a Gradio App on your Web Server with Nginx\nIntroduction\nGradio is a Python library that allows you to quickly create customizable web apps for your machine learning models and data processing pipelines. Gradio apps can be deployed on Hugging Face Spaces for free.\nIn some cases though, you might want to deploy a Gradio app on your own web server. You might already be using Nginx, a highly performant web server, to serve your website (say https://www.example.com), and you want to attach Gradio to a specific subpath on your website (e.g. https://www.example.com/gradio-demo).\nIn this Guide, we will guide you through the process of running a Gradio app behind Nginx on your own web server to achieve this.\nPrerequisites\nA Linux web server with Nginx installed and Gradio installed\nA working Gradio app saved as a python file on your web server\nEditing your Nginx configuration file\nStart by editing the Nginx configuration file on your web server. By default, this is located at: /etc/nginx/nginx.conf\nIn the http block, add the following line to include server block configurations from a separate file:\n``bash\ninclude /etc/nginx/sites-enabled/*;\n`\nCreate a new file in the /etc/nginx/sites-available directory (create the directory if it does not already exist), using a filename that represents your app, for example: sudo nano /etc/nginx/sites-available/mygradioapp\nPaste the following into your file editor:\n`bash\nserver {\n    listen 80;\n    server_name example.com www.example.com;  # Change this to your domain name\n    location /gradio-demo/ {  # Change this if you'd like to server your Gradio app on a different path\n        proxy_pass http://127.0.0.1:7860/; # Change this if your Gradio app will be running on a different port\n        proxy_buffering off;\n        proxy_redirect off;\n        proxyhttpversion 1.1;\n        proxysetheader Upgrade $http_upgrade;\n        proxysetheader Connection \"upgrade\";\n        proxysetheader Host $host;\n        proxysetheader X-Forwarded-Host $host;\n        proxysetheader X-Forwarded-Proto $scheme;\n    }\n}\n`\n            \n                \n                    \n                    \n                    \n                \n                Setting the X-Forwarded-Host and X-Forwarded-Proto headers is important as Gradio uses these, in conjunction with the root_path parameter discussed below, to construct the public URL that your app is being served on. Gradio uses the public URL to fetch various static assets. If these headers are not set, your Gradio app may load in a broken state.\n            \n                \nNote: The $host variable does not include the host port. If you are serving your Gradio application on a raw IP address and port, you should use the $http_host variable instead, in these lines:\n`bash\n        proxysetheader Host $host;\n        proxysetheader X-Forwarded-Host $host;\n`\nRun your Gradio app on your web server\nBefore you launch your Gradio app, you'll need to set the root_path to be the same as the subpath that you specified in your nginx configuration. This is necessary for Gradio to run on any subpath besides the root of the domain.\n    Note: Instead of a subpath, you can also provide a complete URL for rootpath (beginning with http or https) in which case the rootpath is treated as an absolute URL instead of a URL suffix (but in this case, you'll need to update the root_path if the domain changes).\nHere's a simple example of a Gradio app with a custom root_path corresponding to the Nginx configuration above.\n`python\nimport gradio as gr\nimport time\ndef test(x):\ntime.sleep(4)\nreturn x\ngr.Interface(test, \"textbox\", \"textbox\").queue().launch(root_path=\"/gradio-demo\")\n`\nStart a tmux session by typing tmux and pressing enter (optional)\nIt's recommended that you run your Gradio app in a tmux session so that you can keep it running in the background easily\nThen, start your Gradio app. Simply type in python followed by the name of your Gradio python file. By default, your app will run on localhost:7860, but if it starts on a different port, you will need to update the nginx configuration file above.\nRestart Nginx\nIf you are in a tmux session, exit by typing CTRL+B (or CMD+B), followed by the \"D\" key.\nFinally, restart nginx by running sudo systemctl restart nginx.\nAnd that's it! If you visit https://example.com/gradio-demo` on your browser, you should see your Gradio app running there","type":"GUIDE"},{"title":"Server Mode","slug":"/guides/server-mode/","content":"Server mode\nIn this post, we will demonstrate how to build a completely custom frontend for your Gradio application, while still utilizing Gradio's backend, which means you still get an API server with queuing and streaming, MCP tool support, ZeroGPU support, and hosting on Hugging Face Spaces.\nTo do this, you use Server mode: instantiate gradio.Server directly. The gradio.Server class is a FastAPI server with Gradio's API engine built in, so you get all the backend benefits with complete flexibility on what kind of frontend (e.g. a React app, a simple HTML page, or any vibe-coded frontend), if any, you'd like to launch alongside the backend server.\nWhen to use gradio.Server\nUse gradio.Server instead of gr.Blocks when any of the following apply:\nYou want a completely custom (potentially vibe-coded) UI (your own HTML, React, Svelte, etc.) powered by Gradio's backend\nYou want full FastAPI control (custom GET/POST routes, middleware, dependency injection) alongside Gradio API endpoints\nYou're building a service to host on Spaces with or without ZeroGPU but don't need Gradio components\nIf you're happy with Gradio's built-in UI components, use gr.Blocks, gr.ChatInterface, or gr.Interface instead.\nInstallation\ngradio.Server is included in the main Gradio package. If you want MCP support, install the extra:\n``bash\npip install \"gradio[mcp]\"\n`\nA Minimal Example\nHere's the simplest possible Server mode app — a single API endpoint with no UI:\n`python\nfrom gradio import Server\napp = Server()\n@app.api(name=\"hello\")\ndef hello(name: str) -> str:\n    return f\"Hello, {name}!\"\napp.launch()\n`\nThat's it. When you run this script, you get:\nA Gradio API endpoint at /gradio_api/call/hello with queuing and SSE streaming\nAuto-generated API docs at /gradio_api/info\nA Python and JavaScript client that can call /hello by name\nYou can test it with the Gradio Python client:\n`python\nfrom gradio_client import Client\nclient = Client(\"http://localhost:7860\")\nresult = client.predict(\"World\", api_name=\"/hello\")\nprint(result)  # \"Hello, World!\"\n`\nCustom Routes\nSince gradio.Server inherits from FastAPI, you can add any route directly:\n`python\nfrom gradio import Server\nfrom fastapi.responses import HTMLResponse\napp = Server()\n@app.api(name=\"hello\")\ndef hello(name: str) -> str:\n    return f\"Hello, {name}!\"\n@app.get(\"/\", response_class=HTMLResponse)\nasync def homepage():\n    return \"Welcome to my API\"\n@app.get(\"/health\")\nasync def health():\n    return {\"status\": \"ok\"}\napp.launch()\n`\nYour custom routes take priority over Gradio's default routes. For example, your GET / replaces Gradio's default UI page.\nYou can also use all standard FastAPI features — app.addmiddleware(), app.includerouter(), dependency injection, exception handlers, and so on.\nMCP Tools\nTo expose your API endpoints as MCP tools, add the @app.mcp.tool() decorator and pass mcp_server=True to launch():\n`python\nfrom gradio import Server\napp = Server()\n@app.mcp.tool(name=\"hello\")\n@app.api(name=\"hello\")\ndef hello(name: str) -> str:\n    \"\"\"Greet someone by name.\"\"\"\n    return f\"Hello, {name}!\"\napp.launch(mcp_server=True)\n`\nThe @app.mcp.tool() and @app.api() decorators are independent — you can have API-only endpoints or MCP-only tools. Stack both when you want a function available through both.\nA Complete Example with the JavaScript Client\nThis example combines everything: custom HTML served at /, Gradio API endpoints with concurrency limits, MCP tools, and a custom REST endpoint, and two connected via the Gradio JavaScript client.\n`python\nfrom gradio import Server\nfrom fastapi.responses import HTMLResponse\napp = Server()\n@app.mcp.tool(name=\"add\")\n@app.api(name=\"add\")\ndef add(a: int, b: int) -> int:\n    \"\"\"Add two numbers together.\"\"\"\n    return a + b\n@app.mcp.tool(name=\"multiply\")\n@app.api(name=\"multiply\")\ndef multiply(a: int, b: int) -> int:\n    \"\"\"Multiply two numbers together.\"\"\"\n    return a * b\n@app.get(\"/\", response_class=HTMLResponse)\nasync def homepage():\n    return \"\"\"\nCalculator\n{ margin: 0; box-sizing: border-box; font-family: 'Courier New', monospace; }\n  body { min-height: 100vh; display: flex; align-items: center; justify-content: center; background: #1a1a2e; color: #fff;}\n  .calc { background: #16213e; padding: 2rem; border-radius: 1rem; box-shadow: 0 8px 32px rgba(0,0,0,.4); width: 320px; }\n  #out { background: #0f3460; color: #0f0; font-size: 2rem; text-align: right; padding: .75rem 1rem; border-radius: .5rem; min-height: 3rem; margin-bottom: 1rem; }\n  .row { display: flex; gap: .5rem; margin-bottom: .5rem; }\n  input { flex: 1; min-width: 0; padding: .6rem; font-size: 1.2rem; border: none; border-radius: .5rem; background: #e2e2e2; text-align: center; }\n  button { flex: 1; padding: .6rem; font-size: 1rem; border: none; border-radius: .5rem; cursor: pointer; font-weight: bold; color: #fff; }\n  .add { background: #e94560; } .mul { background: #533483; }\n  button:hover { opacity: .85; }\n  \n    0\n    Operands\n    \n    Operation\n    +&times;\n  \n  \n    import { client } from \"https://cdn.jsdelivr.net/npm/@gradio/client/dist/index.min.js\";\n    const app = await client(location.origin);\n    window.run = async (ep) => {\n      const a = parseInt(document.getElementById(\"a\").value), b = parseInt(document.getElementById(\"b\").value);\n      document.getElementById(\"out\").textContent = (await app.predict(\"/\" + ep, { a, b })).data;\n    };\n  \n\"\"\"\nif name == \"main\":\n    app.launch(mcp_server=True)\n`\nRun it with:\n`bash\npython run.py\n`\nThen open http://localhost:7860 in your browser. The custom HTML page uses the @gradio/client JavaScript library to call the Gradio API endpoints. Meanwhile, the same endpoints are available as MCP tools and through the REST API at /gradioapi/call/add and /gradioapi/call/multiply.\nNote: if your Server app uses ZeroGPU, you must call Gradio API endpoints through @gradio/client from the browser. The JavaScript client forwards the Hugging Face iframe auth headers needed for ZeroGPU quota handling.\nConcurrency and Streaming\napp.api() supports all of the same concurrency and streaming options as gr.api():\n`python\n@app.api(name=\"generate\", concurrencylimit=2, streamevery=0.5)\nasync def generate(prompt: str):\n    for token in model.generate(prompt):\n        yield token\n`\nGenerator functions automatically stream results via SSE, just like in a regular Gradio app. The concurrency_limit parameter controls how many concurrent calls to this endpoint are allowed. By default, this is set to 1, since many ML workloads that run on GPU can only support a single user at a time. However, you can increase this, or set to None to use FastAPI defaults, if you are e.g. calling an external API.\nFor the full API reference, see the Server` documentation.","type":"GUIDE"},{"title":"Setting Up A Demo For Maximum Performance","slug":"/guides/setting-up-a-demo-for-maximum-performance/","content":"Setting Up a Demo for Maximum Performance\nLet's say that your Gradio demo goes viral on social media -- you have lots of users trying it out simultaneously, and you want to provide your users with the best possible experience or, in other words, minimize the amount of time that each user has to wait in the queue to see their prediction.\nHow can you configure your Gradio demo to handle the most traffic? In this Guide, we dive into some of the parameters of Gradio's .queue() method as well as some other related parameters, and discuss how to set these parameters in a way that allows you to serve lots of users simultaneously with minimal latency.\nThis is an advanced guide, so make sure you know the basics of Gradio already, such as how to create and launch a Gradio Interface. Most of the information in this Guide is relevant whether you are hosting your demo on Hugging Face Spaces or on your own server.\nOverview of Gradio's Queueing System\nBy default, every Gradio demo includes a built-in queuing system that scales to thousands of requests. When a user of your app submits a request (i.e. submits an input to your function), Gradio adds the request to the queue, and requests are processed in order, generally speaking (this is not exactly true, as discussed below). When the user's request has finished processing, the Gradio server returns the result back to the user using server-side events (SSE). The SSE protocol has several advantages over simply using HTTP POST requests: \n(1) They do not time out -- most browsers raise a timeout error if they do not get a response to a POST request after a short period of time (e.g. 1 min). This can be a problem if your inference function takes longer than 1 minute to run or if many people are trying out your demo at the same time, resulting in increased latency.\n(2) They allow the server to send multiple updates to the frontend. This means, for example, that the server can send a real-time ETA of how long your prediction will take to complete.\nTo configure the queue, simply call the .queue() method before launching an Interface, TabbedInterface, ChatInterface or any Blocks. Here's an example:\n``py\nimport gradio as gr\napp = gr.Interface(lambda x:x, \"image\", \"image\")\napp.queue()  # \n                \n                    \n                    \n                    \n                \n                You should use async functions whenever possible to increase the number of concurrent requests your app can handle. Quick functions that are not CPU-bound are good candidates to be written as async. This guide is a good primer on the concept.\n            \n                \nThe max_size parameter in queue()\nA more blunt way to reduce the wait times is simply to prevent too many people from joining the queue in the first place. You can set the maximum number of requests that the queue processes using the maxsize parameter of queue(). If a request arrives when the queue is already of the maximum size, it will not be allowed to join the queue and instead, the user will receive an error saying that the queue is full and to try again. By default, maxsize=None, meaning that there is no limit to the number of users that can join the queue.\nParadoxically, setting a max_size can often improve user experience because it prevents users from being dissuaded by very long queue wait times. Users who are more interested and invested in your demo will keep trying to join the queue, and will be able to get their results faster.\nRecommendation: For a better user experience, set a max_size that is reasonable given your expectations of how long users might be willing to wait for a prediction.\nThe maxbatchsize parameter in events\nAnother way to increase the parallelism of your Gradio demo is to write your function so that it can accept batches of inputs. Most deep learning models can process batches of samples more efficiently than processing individual samples.\nIf you write your function to process a batch of samples, Gradio will automatically batch incoming requests together and pass them into your function as a batch of samples. You need to set batch to True (by default it is False) and set a maxbatchsize (by default it is 4) based on the maximum number of samples your function is able to handle. These two parameters can be passed into gr.Interface() or to an event in Blocks such as .click().\nWhile setting a batch is conceptually similar to having workers process requests in parallel, it is often faster than setting defaultconcurrencylimit for deep learning models. The downside is that you might need to adapt your function a little bit to accept batches of samples instead of individual samples.\nHere's an example of a function that does not accept a batch of inputs -- it processes a single input at a time:\n`py\nimport time\ndef trim_words(word, length):\n    return word[:int(length)]\n`\nHere's the same function rewritten to take in a batch of samples:\n`py\nimport time\ndef trim_words(words, lengths):\n    trimmed_words = []\n    for w, l in zip(words, lengths):\n        trimmed_words.append(w[:int(l)])\n    return [trimmed_words]\n`\nThe second function can be used with batch=True and an appropriate maxbatchsize parameter.\nRecommendation: If possible, write your function to accept batches of samples, and then set batch to True and the maxbatchsize as high as possible based on your machine's memory limits.\nUpgrading your Hardware (GPUs, TPUs, etc.)\nIf you have done everything above, and your demo is still not fast enough, you can upgrade the hardware that your model is running on. Changing the model from running on CPUs to running on GPUs will usually provide a 10x-50x increase in inference time for deep learning models.\nIt is particularly straightforward to upgrade your Hardware on Hugging Face Spaces. Simply click on the \"Settings\" tab in your Space and choose the Space Hardware you'd like.\nWhile you might need to adapt portions of your machine learning inference code to run on a GPU (here's a handy guide if you are using PyTorch), Gradio is completely agnostic to the choice of hardware and will work completely fine if you use it with CPUs, GPUs, TPUs, or any other hardware!\nNote: your GPU memory is different than your CPU memory, so if you upgrade your hardware,\nyou might need to adjust the value of the defaultconcurrencylimit` parameter described above.\nConclusion\nCongratulations! You know how to set up a Gradio demo for maximum performance. Good luck on your next viral demo!","type":"GUIDE"},{"title":"Sharing Your App","slug":"/guides/sharing-your-app/","content":"Sharing Your App\nIn this Guide, we dive more deeply into the various aspects of sharing a Gradio app with others. We will cover:\nSharing demos with the share parameter\nHosting on HF Spaces\nSharing Deep Links\nEmbedding hosted spaces\nUsing the API page\nAccessing network requests\nMounting within FastAPI\nAuthentication\nMCP Servers\nRate Limits\nAnalytics\nProgressive Web Apps (PWAs)\nSharing Demos\nGradio demos can be easily shared publicly by setting share=True in the launch() method. Like this:\n``python\nimport gradio as gr\ndef greet(name):\n    return \"Hello \" + name + \"!\"\ndemo = gr.Interface(fn=greet, inputs=\"textbox\", outputs=\"textbox\")\ndemo.launch(share=True)  # Share your demo with just 1 extra parameter 🚀\n`\nThis 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.\nA 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 on your own cloud server to overcome this restriction.)\n            \n                \n                    \n                    \n                    \n                \n                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 as discussed below.\n            \n                \nNote 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 to share your local server with specific users.\nHosting on HF Spaces\nIf you'd like to have a permanent link to your Gradio demo on the internet, use Hugging Face Spaces. Hugging Face Spaces provides the infrastructure to permanently host your machine learning model for free!\nAfter you have created a free Hugging Face account, you have two methods to deploy your Gradio app to Hugging Face Spaces:\nFrom 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.\nFrom your browser: Drag and drop a folder containing your Gradio model and all related files here. See this guide how to host on Hugging Face Spaces for more information, or watch the embedded video:\n  \nSharing Deep Links\nYou can add a button to your Gradio app that creates a unique URL you can use to share your app and all components as they currently are with others. This is useful for sharing unique and interesting generations from your application , or for saving a snapshot of your app at a particular point in time.\nTo add a deep link button to your app, place the gr.DeepLinkButton component anywhere in your app.\nFor the URL to be accessible to others, your app must be available at a public URL. So be sure to host your app like Hugging Face Spaces or use the share=True parameter when launching your app.\nLet's see an example of how this works. Here's a simple Gradio chat ap that uses the gr.DeepLinkButton component. After a couple of messages, click the deep link button and paste it into a new browser tab to see the app as it is at that point in time.\n`python\nimport gradio as gr\nimport random\ndef random_response(message, history):\n    return random.choice([\"Hi!\", \"Hello!\", \"Greetings!\"])\nwith gr.Blocks() as demo:\n    gr.ChatInterface(\n        random_response,\n        title=\"Greeting Bot\",\n        description=\"Ask anything and receive a nice greeting!\",\n        api_name=\"chat\",\n    )\n    gr.DeepLinkButton()\nif name == \"main\":\n    demo.launch(share=True)\n`\nEmbedding Hosted Spaces\nOnce you have hosted your app on Hugging Face Spaces (or on your own server), you may want to embed the demo on a different website, such as your blog or your portfolio. Embedding an interactive demo allows people to try out the machine learning model that you have built, without needing to download or install anything — right in their browser! The best part is that you can embed interactive demos even in static websites, such as GitHub pages.\nThere are two ways to embed your Gradio demos. You can find quick links to both options directly on the Hugging Face Space page, in the \"Embed this Space\" dropdown option:\nEmbedding with Web Components\nWeb components typically offer a better experience to users than IFrames. Web components load lazily, meaning that they won't slow down the loading time of your website, and they automatically adjust their height based on the size of the Gradio app.\nTo embed with Web Components:\nImport the gradio JS library into into your site by adding the script below in your site (replace {GRADIO_VERSION} in the URL with the library version of Gradio you are using).\n`html\n`\nAdd\n`html\n`\nelement where you want to place the app. Set the src= attribute to your Space's embed URL, which you can find in the \"Embed this Space\" button. For example:\n`html\n`\nfetch(\"https://pypi.org/pypi/gradio/json\"\n).then(r => r.json()\n).then(obj => {\n    let v = obj.info.version;\n    content = document.querySelector('.prose');\n    content.innerHTML = content.innerHTML.replaceAll(\"{GRADIO_VERSION}\", v);\n});\nYou can see examples of how web components look on the Gradio landing page.\nYou can also customize the appearance and behavior of your web component with attributes that you pass into the  tag:\nsrc: as we've seen, the src attributes links to the URL of the hosted Gradio demo that you would like to embed\nspace: an optional shorthand if your Gradio demo is hosted on Hugging Face Space. Accepts a username/space_name instead of a full URL. Example: gradio/Echocardiogram-Segmentation. If this attribute attribute is provided, then src does not need to be provided.\ncontrolpagetitle: a boolean designating whether the html title of the page should be set to the title of the Gradio app (by default \"false\")\ninitial_height: the initial height of the web component while it is loading the Gradio app, (by default \"300px\"). Note that the final height is set based on the size of the Gradio app.\ncontainer: whether to show the border frame and information about where the Space is hosted (by default \"true\")\ninfo: whether to show just the information about where the Space is hosted underneath the embedded app (by default \"true\")\nautoscroll: whether to autoscroll to the output when prediction has finished (by default \"false\")\neager: whether to load the Gradio app as soon as the page loads (by default \"false\")\ntheme_mode: whether to use the dark, light, or default system theme mode (by default \"system\")\nrender: an event that is triggered once the embedded space has finished rendering.\nHere's an example of how to use these attributes to create a Gradio app that does not lazy load and has an initial height of 0px.\n`html\n`\nHere's another example of how to use the render event. An event listener is used to capture the render event and will call the handleLoadComplete() function once rendering is complete.\n`html\n\tfunction handleLoadComplete() {\n\t\tconsole.log(\"Embedded space has finished rendering\");\n\t}\n\tconst gradioApp = document.querySelector(\"gradio-app\");\n\tgradioApp.addEventListener(\"render\", handleLoadComplete);\n`\nNote: While Gradio's CSS will never impact the embedding page, the embedding page can affect the style of the embedded Gradio app. Make sure that any CSS in the parent page isn't so general that it could also apply to the embedded Gradio app and cause the styling to break. Element selectors such as header { ... } and footer { ... } will be the most likely to cause issues.\nEmbedding with IFrames\nTo embed with IFrames instead (if you cannot add javascript to your website, for example), add this element:\n`html\n`\nAgain, you can find the src= attribute to your Space's embed URL, which you can find in the \"Embed this Space\" button.\nNote: if you use IFrames, you'll probably want to add a fixed height attribute and set style=\"border:0;\" to remove the border. In addition, if your app requires permissions such as access to the webcam or the microphone, you'll need to provide that as well using the allow attribute.\nAPI Page\nYou can use almost any Gradio app as an API! In the footer of a Gradio app like this one, you'll see a \"Use via API\" link.\nThis is a page that lists the endpoints that can be used to query the Gradio app, via our supported clients: either the Python client, or the JavaScript client. For each endpoint, Gradio automatically generates the parameters and their types, as well as example inputs, like this.\nThe endpoints are automatically created when you launch a Gradio application. If you are using Gradio Blocks, you can also name each event listener, such as\n`python\nbtn.click(add, [num1, num2], output, api_name=\"addition\")\n`\nThis will add and document the endpoint /addition/ to the automatically generated API page. Read more about the API page here.\nAccessing the Network Request Directly\nWhen a user makes a prediction to your app, you may need the underlying network request, in order to get the request headers (e.g. for advanced authentication), log the client's IP address, getting the query parameters, or for other reasons. Gradio supports this in a similar manner to FastAPI: simply add a function parameter whose type hint is gr.Request and Gradio will pass in the network request as that parameter. Here is an example:\n`python\nimport gradio as gr\ndef echo(text, request: gr.Request):\n    if request:\n        print(\"Request headers dictionary:\", request.headers)\n        print(\"IP address:\", request.client.host)\n        print(\"Query parameters:\", dict(request.query_params))\n    return text\nio = gr.Interface(echo, \"textbox\", \"textbox\").launch()\n`\nNote: if your function is called directly instead of through the UI (this happens, for\nexample, when examples are cached, or when the Gradio app is called via API), then request will be None.\nYou should handle this case explicitly to ensure that your app does not throw any errors. That is why\nwe have the explicit check if request.\nMounting Within Another FastAPI App\nIn some cases, you might have an existing FastAPI app, and you'd like to add a path for a Gradio demo.\nYou can easily do this with gradio.mountgradioapp().\nHere's a complete example:\n`python\n\"\"\"\nTest script for https://github.com/gradio-app/gradio/issues/11848\nGradio does not show media when FastAPI is behind a reverse proxy (root_path).\nSimulates a reverse proxy by wrapping the FastAPI app in an outer\nStarlette app mounted at /myapp. Gradio is mounted at /gradio inside.\nOpen http://localhost:8000/myapp/gradio/ to test.\n\"\"\"\nimport os\nfrom contextlib import asynccontextmanager\nfrom fastapi import FastAPI\nfrom starlette.applications import Starlette\nfrom starlette.routing import Mount\nimport gradio as gr\nCUSTOM_PATH = \"/gradio\"\nPROXY_PREFIX = \"/myapp\"\napp = FastAPI()\n@app.get(\"/\")\ndef read_main():\n    return {\"message\": \"This is your main app\"}\ndef identity(image):\n    return image\ndemo = gr.Interface(\n    fn=identity,\n    inputs=gr.Image(type=\"filepath\"),\n    outputs=gr.Image(label=\"Output Image\"),\n)\napp = gr.mountgradioapp(app, demo, path=CUSTOMPATH, rootpath=f\"{PROXYPREFIX}{CUSTOMPATH}\")\n@asynccontextmanager\nasync def lifespan(outer_app):\n    async with app.router.lifespan_context(app):\n        yield\nouter_app = Starlette(\n    routes=[Mount(PROXY_PREFIX, app=app)],\n    lifespan=lifespan,\n)\nif name == \"main\":\n    import uvicorn\n    port = int(os.environ.get(\"GRADIOSERVERPORT\", 8000))\n    print(f\"\\nOpen http://localhost:{port}{PROXYPREFIX}{CUSTOMPATH}/\\n\")\n    uvicorn.run(outer_app, host=\"0.0.0.0\", port=port)\n`\nNote that this approach also allows you run your Gradio apps on custom paths (http://localhost:8000/gradio in the example above).\nAuthentication\nPassword-protected app\nYou may wish to put an authentication page in front of your app to limit who can open your app. With the auth= keyword argument in the launch() method, you can provide a tuple with a username and password, or a list of acceptable username/password tuples; Here's an example that provides password-based authentication for a single user named \"admin\":\n`python\ndemo.launch(auth=(\"admin\", \"pass1234\"))\n`\nFor more complex authentication handling, you can even pass a function that takes a username and password as arguments, and returns True to allow access, False otherwise.\nHere's an example of a function that accepts any login where the username and password are the same:\n`python\ndef same_auth(username, password):\n    return username == password\ndemo.launch(auth=same_auth)\n`\nIf you have multiple users, you may wish to customize the content that is shown depending on the user that is logged in. You can retrieve the logged in user by accessing the network request directly as discussed above, and then reading the .username attribute of the request. Here's an example:\n`python\nimport gradio as gr\ndef update_message(request: gr.Request):\n    return f\"Welcome, {request.username}\"\nwith gr.Blocks() as demo:\n    m = gr.Markdown()\n    demo.load(update_message, None, m)\ndemo.launch(auth=[(\"Abubakar\", \"Abubakar\"), (\"Ali\", \"Ali\")])\n`\nNote: For authentication to work properly, third party cookies must be enabled in your browser. This is not the case by default for Safari or for Chrome Incognito Mode.\nIf users visit the /logout page of your Gradio app, they will automatically be logged out and session cookies deleted. This allows you to add logout functionality to your Gradio app as well. Let's update the previous example to include a log out button:\n`python\nimport gradio as gr\ndef update_message(request: gr.Request):\n    return f\"Welcome, {request.username}\"\nwith gr.Blocks() as demo:\n    m = gr.Markdown()\n    logout_button = gr.Button(\"Logout\", link=\"/logout\")\n    demo.load(update_message, None, m)\ndemo.launch(auth=[(\"Pete\", \"Pete\"), (\"Dawood\", \"Dawood\")])\n`\nBy default, visiting /logout logs the user out from all sessions (e.g. if they are logged in from multiple browsers or devices, all will be signed out). If you want to log out only from the current session, add the query parameter allsession=false (i.e. /logout?allsession=false).\nNote: Gradio's built-in authentication provides a straightforward and basic layer of access control but does not offer robust security features for applications that require stringent access controls (e.g.  multi-factor authentication, rate limiting, or automatic lockout policies).\nOAuth (Login via Hugging Face)\nGradio natively supports OAuth login via Hugging Face. In other words, you can easily add a \"Sign in with Hugging Face\" button to your demo, which allows you to get a user's HF username as well as other information from their HF profile. Check out this Space for a live demo.\nTo enable OAuth, you must set hf_oauth: true as a Space metadata in your README.md file. This will register your Space\nas an OAuth application on Hugging Face. Next, you can use gr.LoginButton to add a login button to\nyour Gradio app. Once a user is logged in with their HF account, you can retrieve their profile by adding a parameter of type\ngr.OAuthProfile to any Gradio function. The user profile will be automatically injected as a parameter value. If you want\nto perform actions on behalf of the user (e.g. list user's private repos, create repo, etc.), you can retrieve the user\ntoken by adding a parameter of type gr.OAuthToken. You must define which scopes you will use in your Space metadata\n(see documentation for more details).\nHere is a short example:\n`python\nfrom future import annotations\nimport gradio as gr\nfrom huggingface_hub import whoami\ndef hello(profile: gr.OAuthProfile | None) -> str:\n    if profile is None:\n        return \"I don't know you.\"\n    return f\"Hello {profile.name}\"\ndef listorganizations(oauthtoken: gr.OAuthToken | None) -> str:\n    if oauth_token is None:\n        return \"Please deploy this on Spaces and log in to list organizations.\"\n    orgnames = [org[\"name\"] for org in whoami(oauthtoken.token)[\"orgs\"]]\n    return f\"You belong to {', '.join(org_names)}.\"\nwith gr.Blocks() as demo:\n    gr.LoginButton()\n    m1 = gr.Markdown()\n    m2 = gr.Markdown()\n    demo.load(hello, inputs=None, outputs=m1)\n    demo.load(list_organizations, inputs=None, outputs=m2)\ndemo.launch()\n`\nWhen the user clicks on the login button, they get redirected in a new page to authorize your Space.\nUsers can revoke access to their profile at any time in their settings.\nAs seen above, OAuth features are available only when your app runs in a Space. However, you often need to test your app\nlocally before deploying it. To test OAuth features locally, your machine must be logged in to Hugging Face. Please run huggingface-cli login or set HF_TOKEN as environment variable with one of your access token. You can generate a new token in your settings page (https://huggingface.co/settings/tokens). Then, clicking on the gr.LoginButton will log in to your local Hugging Face profile, allowing you to debug your app with your Hugging Face account before deploying it to a Space.\nSecurity Note: It is important to note that adding a gr.LoginButton does not restrict users from using your app, in the same way that adding username-password authentication does. This means that users of your app who have not logged in with Hugging Face can still access and run events in your Gradio app -- the difference is that the gr.OAuthProfile or gr.OAuthToken will be None in the corresponding functions.\nOAuth (with external providers)\nIt is also possible to authenticate with external OAuth providers (e.g. Google OAuth) in your Gradio apps. To do this, first mount your Gradio app within a FastAPI app (as discussed above). Then, you must write an authentication function, which gets the user's username from the OAuth provider and returns it. This function should be passed to the authdependency parameter in gr.mountgradio_app.\nSimilar to FastAPI dependency functions, the function specified by auth_dependency will run before any Gradio-related route in your FastAPI app. The function should accept a single parameter: the FastAPI Request and return either a string (representing a user's username) or None. If a string is returned, the user will be able to access the Gradio-related routes in your FastAPI app.\nFirst, let's show a simplistic example to illustrate the auth_dependency parameter:\n`python\nfrom fastapi import FastAPI, Request\nimport gradio as gr\napp = FastAPI()\ndef get_user(request: Request):\n    return request.headers.get(\"user\")\ndemo = gr.Interface(lambda s: f\"Hello {s}!\", \"textbox\", \"textbox\")\napp = gr.mountgradioapp(app, demo, path=\"/demo\", authdependency=getuser)\nif name == 'main':\n    uvicorn.run(app)\n`\nIn this example, only requests that include a \"user\" header will be allowed to access the Gradio app. Of course, this does not add much security, since any user can add this header in their request.\nHere's a more complete example showing how to add Google OAuth to a Gradio app (assuming you've already created OAuth Credentials on the Google Developer Console):\n`python\nimport os\nfrom authlib.integrations.starlette_client import OAuth, OAuthError\nfrom fastapi import FastAPI, Depends, Request\nfrom starlette.config import Config\nfrom starlette.responses import RedirectResponse\nfrom starlette.middleware.sessions import SessionMiddleware\nimport uvicorn\nimport gradio as gr\napp = FastAPI()\nReplace these with your own OAuth settings\nGOOGLECLIENTID = \"...\"\nGOOGLECLIENTSECRET = \"...\"\nSECRET_KEY = \"...\"\nconfigdata = {'GOOGLECLIENTID': GOOGLECLIENTID, 'GOOGLECLIENTSECRET': GOOGLECLIENT_SECRET}\nstarletteconfig = Config(environ=configdata)\noauth = OAuth(starlette_config)\noauth.register(\n    name='google',\n    servermetadataurl='https://accounts.google.com/.well-known/openid-configuration',\n    client_kwargs={'scope': 'openid email profile'},\n)\nSECRETKEY = os.environ.get('SECRETKEY') or \"averysecret_key\"\napp.addmiddleware(SessionMiddleware, secretkey=SECRET_KEY)\nDependency to get the current user\ndef get_user(request: Request):\n    user = request.session.get('user')\n    if user:\n        return user['name']\n    return None\n@app.get('/')\ndef public(user: dict = Depends(get_user)):\n    if user:\n        return RedirectResponse(url='/gradio')\n    else:\n        return RedirectResponse(url='/login-demo')\n@app.route('/logout')\nasync def logout(request: Request):\n    request.session.pop('user', None)\n    return RedirectResponse(url='/')\n@app.route('/login')\nasync def login(request: Request):\n    redirecturi = request.urlfor('auth')\n    # If your app is running on https, you should ensure that the\n    # redirect_uri is https, e.g. uncomment the following lines:\n    #\n    # from urllib.parse import urlparse, urlunparse\n    # redirecturi = urlunparse(urlparse(str(redirecturi))._replace(scheme='https'))\n    return await oauth.google.authorizeredirect(request, redirecturi)\n@app.route('/auth')\nasync def auth(request: Request):\n    try:\n        accesstoken = await oauth.google.authorizeaccess_token(request)\n    except OAuthError:\n        return RedirectResponse(url='/')\n    request.session['user'] = dict(access_token)[\"userinfo\"]\n    return RedirectResponse(url='/')\nwith gr.Blocks() as login_demo:\n    gr.Button(\"Login\", link=\"/login\")\napp = gr.mountgradioapp(app, login_demo, path=\"/login-demo\")\ndef greet(request: gr.Request):\n    return f\"Welcome to Gradio, {request.username}\"\nwith gr.Blocks() as main_demo:\n    m = gr.Markdown(\"Welcome to Gradio!\")\n    gr.Button(\"Logout\", link=\"/logout\")\n    main_demo.load(greet, None, m)\napp = gr.mountgradioapp(app, maindemo, path=\"/gradio\", authdependency=get_user)\nif name == 'main':\n    uvicorn.run(app)\n`\nThere are actually two separate Gradio apps in this example! One that simply displays a log in button (this demo is accessible to any user), while the other main demo is only accessible to users that are logged in. You can try this example out on this Space.\nMCP Servers\nGradio apps can function as MCP (Model Context Protocol) servers, allowing LLMs to use your app's functions as tools. By simply setting mcp_server=True in the .launch() method, Gradio automatically converts your app's functions into MCP tools that can be called by MCP clients like Claude Desktop, Cursor, or Cline. The server exposes tools based on your function names, docstrings, and type hints, and can handle file uploads, authentication headers, and progress updates. You can also create MCP-only functions using gr.api and expose resources and prompts using decorators. For a comprehensive guide on building MCP servers with Gradio, see Building an MCP Server with Gradio.\nRate Limits\nWhen publishing your app publicly, and making it available via API or via MCP server, you might want to set rate limits to prevent users from abusing your app. You can identify users using their IP address (using the gr.Request object as discussed above) or, if they are logged in via Hugging Face OAuth, using their username. To see a complete example of how to set rate limits, please see this Gradio app.\nAnalytics\nBy default, Gradio collects certain analytics to help us better understand the usage of the gradio library. This includes the following information:\nWhat environment the Gradio app is running on (e.g. Colab Notebook, Hugging Face Spaces)\nWhat input/output components are being used in the Gradio app\nWhether the Gradio app is utilizing certain advanced features, such as auth or show_error\nThe IP address which is used solely to measure the number of unique developers using Gradio\nThe version of Gradio that is running\nNo information is collected from users of your Gradio app. If you'd like to disable analytics altogether, you can do so by setting the analyticsenabled parameter to False in gr.Blocks, gr.Interface, or gr.ChatInterface. Or, you can set the GRADIOANALYTICS_ENABLED environment variable to \"False\" to apply this to all Gradio apps created across your system.\nNote: this reflects the analytics policy as of gradio>=4.32.0.\nProgressive Web App (PWA)\nProgressive Web Apps (PWAs) are web applications that are regular web pages or websites, but can appear to the user like installable platform-specific applications.\nGradio apps can be easily served as PWAs by setting the pwa=True parameter in the launch() method. Here's an example:\n`python\nimport gradio as gr\ndef greet(name):\n    return \"Hello \" + name + \"!\"\ndemo = gr.Interface(fn=greet, inputs=\"textbox\", outputs=\"textbox\")\ndemo.launch(pwa=True)  # Launch your app as a PWA\n`\nThis will generate a PWA that can be installed on your device. Here's how it looks:\nWhen you specify favicon_path in the launch() method, the icon will be used as the app's icon. Here's an example:\n`python\ndemo.launch(pwa=True, favicon_path=\"./hf-logo.svg\")  # Use a custom icon for your PWA\n``","type":"GUIDE"},{"title":"State In Blocks","slug":"/guides/state-in-blocks/","content":"Managing State\nWhen building a Gradio application with gr.Blocks(), you may want to share certain values between users (e.g. a count of visitors to your page), or persist values for a single user across certain interactions (e.g. a chat history). This referred to as state and there are three general ways to manage state in a Gradio application:\nGlobal state: persist and share values among all users of your Gradio application while your Gradio application is running\nSession state: persist values for each user of your Gradio application while they are using your Gradio application in a single session. If they refresh the page, session state will be reset.\nBrowser state: persist values for each user of your Gradio application in the browser's localStorage, allowing data to persist even after the page is refreshed or closed.\nGlobal State\nGlobal state in Gradio apps is very simple: any variable created outside of a function is shared globally between all users.\nThis makes managing global state very simple and without the need for external services. For example, in this application, the visitor_count variable is shared between all users\n``py\nimport gradio as gr\nShared between all users\nvisitor_count = 0\ndef increment_counter():\n    global visitor_count\n    visitor_count += 1\n    return visitor_count\nwith gr.Blocks() as demo:    \n    number = gr.Textbox(label=\"Total Visitors\", value=\"Counting...\")\n    demo.load(increment_counter, inputs=None, outputs=number)\ndemo.launch()\n`\nThis means that any time you do not want to share a value between users, you should declare it within a function. But what if you need to share values between function calls, e.g. a chat history? In that case, you should use one of the subsequent approaches to manage state.\nSession State\nGradio supports session state, where data persists across multiple submits within a page session. To reiterate, session data is not shared between different users of your model, and does not persist if a user refreshes the page to reload the Gradio app. To store data in a session state, you need to do three things:\nCreate a gr.State() object. If there is a default value to this stateful object, pass that into the constructor. Note that gr.State objects must be deepcopy-able, otherwise you will need to use a different approach as described below.\nIn the event listener, put the State object as an input and output as needed.\nIn the event listener function, add the variable to the input parameters and the return value.\nLet's take a look at a simple example. We have a simple checkout app below where you add items to a cart. You can also see the size of the cart.\n`python\nimport gradio as gr\nwith gr.Blocks() as demo:\n    cart = gr.State([])\n    itemstoadd = gr.CheckboxGroup([\"Cereal\", \"Milk\", \"Orange Juice\", \"Water\"])\n    def additems(newitems, previous_cart):\n        cart = previouscart + newitems\n        return cart\n    gr.Button(\"Add Items\").click(additems, [itemsto_add, cart], cart)\n    cart_size = gr.Number(label=\"Cart Size\")\n    cart.change(lambda cart: len(cart), cart, cart_size)\ndemo.launch()\n`\nNotice how we do this with state:\nWe store the cart items in a gr.State() object, initialized here to be an empty list.\nWhen adding items to the cart, the event listener uses the cart as both input and output - it returns the updated cart with all the items inside. \nWe can attach a .change listener to cart, that uses the state variable as input as well.\nYou can think of gr.State as an invisible Gradio component that can store any kind of value. Here, cart is not visible in the frontend but is used for calculations.\nThe .change listener for a state variable triggers after any event listener changes the value of a state variable. If the state variable holds a sequence (like a list, set, or dict), a change is triggered if any of the elements inside change. If it holds an object or primitive, a change is triggered if the hash of the  value changes. So if you define a custom class and create a gr.State variable that is an instance of that class, make sure that the the class includes a sensible hash implementation.\nThe value of a session State variable is cleared when the user refreshes the page. The value is stored on in the app backend for 60 minutes after the user closes the tab (this can be configured by the delete_cache parameter in gr.Blocks).\nLearn more about State in the docs.\nWhat about objects that cannot be deepcopied?\nAs mentioned earlier, the value stored in gr.State must be deepcopy-able. If you are working with a complex object that cannot be deepcopied, you can take a different approach to manually read the user's session_hash and store a global dictionary with instances of your object for each user. Here's how you would do that:\n`py\nimport gradio as gr\nclass NonDeepCopyable:\n    def init(self):\n        from threading import Lock\n        self.counter = 0\n        self.lock = Lock()  # Lock objects cannot be deepcopied\n    \n    def increment(self):\n        with self.lock:\n            self.counter += 1\n            return self.counter\nGlobal dictionary to store user-specific instances\ninstances = {}\ndef initialize_instance(request: gr.Request):\n    instances[request.session_hash] = NonDeepCopyable()\n    return \"Session initialized!\"\ndef cleanup_instance(request: gr.Request):\n    if request.session_hash in instances:\n        del instances[request.session_hash]\ndef increment_counter(request: gr.Request):\n    if request.session_hash in instances:\n        instance = instances[request.session_hash]\n        return instance.increment()\n    return \"Error: Session not initialized\"\nwith gr.Blocks() as demo:\n    output = gr.Textbox(label=\"Status\")\n    counter = gr.Number(label=\"Counter Value\")\n    increment_btn = gr.Button(\"Increment Counter\")\n    incrementbtn.click(incrementcounter, inputs=None, outputs=counter)\n    \n    # Initialize instance when page loads\n    demo.load(initialize_instance, inputs=None, outputs=output)    \n    # Clean up instance when page is closed/refreshed\n    demo.unload(cleanup_instance)    \ndemo.launch()\n`\nBrowser State\nGradio also supports browser state, where data persists in the browser's localStorage even after the page is refreshed or closed. This is useful for storing user preferences, settings, API keys, or other data that should persist across sessions. To use local state:\nCreate a gr.BrowserState object. You can optionally provide an initial default value and a key to identify the data in the browser's localStorage.\nUse it like a regular gr.State component in event listeners as inputs and outputs.\nHere's a simple example that saves a user's username and password across sessions:\n`python\nimport random\nimport string\nimport gradio as gr\nimport time\nwith gr.Blocks() as demo:\n    gr.Markdown(\"Your Username and Password will get saved in the browser's local storage. \"\n                \"If you refresh the page, the values will be retained.\")\n    username = gr.Textbox(label=\"Username\")\n    password = gr.Textbox(label=\"Password\", type=\"password\")\n    btn = gr.Button(\"Generate Randomly\")\n    local_storage = gr.BrowserState([\"\", \"\"])\n    saved_message = gr.Markdown(\"✅ Saved to local storage\", visible=False)\n    @btn.click(outputs=[username, password])\n    def generate_randomly():\n        u = \"\".join(random.choices(string.ascii_letters + string.digits, k=10))\n        p = \"\".join(random.choices(string.ascii_letters + string.digits, k=10))\n        return u, p\n    @demo.load(inputs=[local_storage], outputs=[username, password])\n    def loadfromlocalstorage(savedvalues):\n        print(\"loading from local storage\", saved_values)\n        return savedvalues[0], savedvalues[1]\n    @gr.on([username.change, password.change], inputs=[username, password], outputs=[local_storage])\n    def savetolocal_storage(username, password):\n        return [username, password]\n    @gr.on(localstorage.change, outputs=[savedmessage])\n    def showsavedmessage():\n        timestamp = time.strftime(\"%I:%M:%S %p\")\n        return gr.Markdown(\n            f\"✅ Saved to local storage at {timestamp}\",\n            visible=True\n        )\ndemo.launch()\n`\nNote: The value stored in gr.BrowserState does not persist if the Grado app is restarted. To persist it, you can hardcode specific values of storage_key and secret in the gr.BrowserState` component and restart the Gradio app on the same server name and server port. However, this should only be done if you are running trusted Gradio apps, as in principle, this can allow one Gradio app to access localStorage data that was created by a different Gradio app.","type":"GUIDE"},{"title":"Streaming Ai Generated Audio","slug":"/guides/streaming-ai-generated-audio/","content":"Streaming AI Generated Audio\nIn this guide, we'll build a novel AI application to showcase Gradio's audio output streaming. We're going to a build a talking Magic 8 Ball 🎱\nA Magic 8 Ball is a toy that answers any question after you shake it. Our application will do the same but it will also speak its response!\nWe won't cover all the implementation details in this blog post but the code is freely available on Hugging Face Spaces.\nThe Overview\nJust like the classic Magic 8 Ball, a user should ask it a question orally and then wait for a response. Under the hood, we'll use Whisper to transcribe the audio and then use an LLM to generate a magic-8-ball-style answer. Finally, we'll use Parler TTS to read the response aloud.\nThe UI\nFirst let's define the UI and put placeholders for all the python logic.\n``python\nimport gradio as gr\nwith gr.Blocks() as block:\n    gr.HTML(\n        f\"\"\"\n         Magic 8 Ball 🎱 \n         Ask a question and receive wisdom \n         Powered by  Parler-TTS\n        \"\"\"\n    )\n    with gr.Group():\n        with gr.Row():\n            audio_out = gr.Audio(label=\"Spoken Answer\", streaming=True, autoplay=True)\n            answer = gr.Textbox(label=\"Answer\")\n            state = gr.State()\n        with gr.Row():\n            audio_in = gr.Audio(label=\"Speak your question\", sources=\"microphone\", type=\"filepath\")\n    audioin.stoprecording(generateresponse, audioin, [state, answer, audio_out])\\\n        .then(fn=readresponse, inputs=state, outputs=[answer, audioout])\nblock.launch()\n`\nWe're placing the output Audio and Textbox components and the input Audio component in separate rows. In order to stream the audio from the server, we'll set streaming=True in the output Audio component. We'll also set autoplay=True so that the audio plays as soon as it's ready.\nWe'll be using the Audio input component's stop_recording event to trigger our application's logic when a user stops recording from their microphone.\nWe're separating the logic into two parts. First, generateresponse will take the recorded audio, transcribe it and generate a response with an LLM. We're going to store the response in a gr.State variable that then gets passed to the readresponse function that generates the audio.\nWe're doing this in two parts because only read_response will require a GPU. Our app will run on Hugging Faces ZeroGPU which has time-based quotas. Since generating the response can be done with Hugging Face's Inference API, we shouldn't include that code in our GPU function as it will needlessly use our GPU quota.\nThe Logic\nAs mentioned above, we'll use Hugging Face's Inference API to transcribe the audio and generate a response from an LLM. After instantiating the client, I use the automaticspeech_recognition method (this automatically uses Whisper running on Hugging Face's Inference Servers) to transcribe the audio. Then I pass the question to an LLM (Mistal-7B-Instruct) to generate a response. We are prompting the LLM to act like a magic 8 ball with the system message.\nOur generate_response function will also send empty updates to the output textbox and audio components (returning None). \nThis is because I want the Gradio progress tracker to be displayed over the components but I don't want to display the answer until the audio is ready.\n`python\nfrom huggingface_hub import InferenceClient\nclient = InferenceClient(token=os.getenv(\"HF_TOKEN\"))\ndef generate_response(audio):\n    gr.Info(\"Transcribing Audio\", duration=5)\n    question = client.automaticspeechrecognition(audio).text\n    messages = [{\"role\": \"system\", \"content\": (\"You are a magic 8 ball.\"\n                                              \"Someone will present to you a situation or question and your job \"\n                                              \"is to answer with a cryptic adage or proverb such as \"\n                                              \"'curiosity killed the cat' or 'The early bird gets the worm'.\"\n                                              \"Keep your answers short and do not include the phrase 'Magic 8 Ball' in your response. If the question does not make sense or is off-topic, say 'Foolish questions get foolish answers.'\"\n                                              \"For example, 'Magic 8 Ball, should I get a dog?', 'A dog is ready for you but are you ready for the dog?'\")},\n                {\"role\": \"user\", \"content\": f\"Magic 8 Ball please answer this question -  {question}\"}]\n    \n    response = client.chatcompletion(messages, maxtokens=64, seed=random.randint(1, 5000),\n                                      model=\"mistralai/Mistral-7B-Instruct-v0.3\")\n    response = response.choices[0].message.content.replace(\"Magic 8 Ball\", \"\").replace(\":\", \"\")\n    return response, None, None\n`\nNow that we have our text response, we'll read it aloud with Parler TTS. The read_response function will be a python generator that yields the next chunk of audio as it's ready.\nWe'll be using the Mini v0.1 for the feature extraction but the Jenny fine tuned version for the voice. This is so that the voice is consistent across generations.\nStreaming audio with transformers requires a custom Streamer class. You can see the implementation here. Additionally, we'll convert the output to bytes so that it can be streamed faster from the backend. \n`python\nfrom streamer import ParlerTTSStreamer\nfrom transformers import AutoTokenizer, AutoFeatureExtractor, set_seed\nimport numpy as np\nimport spaces\nimport torch\nfrom threading import Thread\ndevice = \"cuda:0\" if torch.cuda.isavailable() else \"mps\" if torch.backends.mps.isavailable() else \"cpu\"\ntorch_dtype = torch.float16 if device != \"cpu\" else torch.float32\nrepoid = \"parler-tts/parlerttsminiv0.1\"\njennyrepoid = \"ylacombe/parler-tts-mini-jenny-30H\"\nmodel = ParlerTTSForConditionalGeneration.from_pretrained(\n    jennyrepoid, torchdtype=torchdtype, lowcpumem_usage=True\n).to(device)\ntokenizer = AutoTokenizer.frompretrained(repoid)\nfeatureextractor = AutoFeatureExtractor.frompretrained(repo_id)\nsamplingrate = model.audioencoder.config.sampling_rate\nframerate = model.audioencoder.config.frame_rate\n@spaces.GPU\ndef read_response(answer):\n    playstepsin_s = 2.0\n    playsteps = int(framerate * playstepsin_s)\n    description = \"Jenny speaks at an average pace with a calm delivery in a very confined sounding environment with clear audio quality.\"\n    descriptiontokens = tokenizer(description, returntensors=\"pt\").to(device)\n    streamer = ParlerTTSStreamer(model, device=device, playsteps=playsteps)\n    prompt = tokenizer(answer, return_tensors=\"pt\").to(device)\n    generation_kwargs = dict(\n        inputids=descriptiontokens.input_ids,\n        promptinputids=prompt.input_ids,\n        streamer=streamer,\n        do_sample=True,\n        temperature=1.0,\n        minnewtokens=10,\n    )\n    set_seed(42)\n    thread = Thread(target=model.generate, kwargs=generation_kwargs)\n    thread.start()\n    for new_audio in streamer:\n        print(f\"Sample of length: {round(newaudio.shape[0] / samplingrate, 2)} seconds\")\n        yield answer, numpytomp3(newaudio, samplingrate=sampling_rate)\n``\nConclusion\nYou can see our final application here!","type":"GUIDE"},{"title":"Streaming Inputs","slug":"/guides/streaming-inputs/","content":"Streaming inputs\n            \n                \n                    \n                    \n                    \n                \n                Check out FastRTC, our companion library for building low latency streaming web apps with a familiar Gradio syntax. \n            \n                \nIn the previous guide, we covered how to stream a sequence of outputs from an event handler. Gradio also allows you to stream images from a user's camera or audio chunks from their microphone into your event handler. This can be used to create real-time object detection apps or conversational chat applications with Gradio.\nCurrently, the gr.Image and the gr.Audio components support input streaming via the stream event.\nLet's create the simplest streaming app possible, which simply returns the webcam stream unmodified.\n``python\nimport gradio as gr\nwith gr.Blocks() as demo:\n    with gr.Row():\n        with gr.Column():\n            input_img = gr.Image(label=\"Input\", sources=\"webcam\")\n        with gr.Column():\n            output_img = gr.Image(label=\"Output\")\n        inputimg.stream(lambda s: s, inputimg, outputimg, timelimit=15, streamevery=0.1, concurrencylimit=30)\nif name == \"main\":\n    demo.launch()\n`\nTry it out! The streaming event is triggered when the user starts recording. Under the hood, the webcam will take a photo every 0.1 seconds and send it to the server. The server will then return that image.\nThere are two unique keyword arguments for the stream event:\ntime_limit - This is the amount of time the gradio server will spend processing the event. Media streams are naturally unbounded so it's important to set a time limit so that one user does not hog the Gradio queue. The time limit only counts the time spent processing the stream, not the time spent waiting in the queue. The orange bar displayed at the bottom of the input image represents the remaining time. When the time limit expires, the user will automatically rejoin the queue.\nstream_every - This is the frequency (in seconds) with which the stream will capture input and send it to the server. For demos like image detection or manipulation, setting a smaller value is desired to get a \"real-time\" effect. For demos like speech transcription, a higher value is useful so that the transcription algorithm has more context of what's being said.\nA Realistic Image Demo\nLet's create a demo where a user can choose a filter to apply to their webcam stream. Users can choose from an edge-detection filter, a cartoon filter, or simply flipping the stream vertically.\n`python\nimport gradio as gr\nimport numpy as np\nimport cv2  \ndef transform_cv2(frame, transform):\n    if transform == \"cartoon\":\n        # prepare color\n        img_color = cv2.pyrDown(cv2.pyrDown(frame))\n        for _ in range(6):\n            imgcolor = cv2.bilateralFilter(imgcolor, 9, 9, 7)\n        imgcolor = cv2.pyrUp(cv2.pyrUp(imgcolor))\n        # prepare edges\n        imgedges = cv2.cvtColor(frame, cv2.COLORRGB2GRAY)\n        img_edges = cv2.adaptiveThreshold(\n            cv2.medianBlur(img_edges, 7),\n            255,\n            cv2.ADAPTIVETHRESHMEAN_C,\n            cv2.THRESH_BINARY,\n            9,\n            2,\n        )\n        imgedges = cv2.cvtColor(imgedges, cv2.COLOR_GRAY2RGB)\n        # combine color and edges\n        img = cv2.bitwiseand(imgcolor, img_edges)\n        return img\n    elif transform == \"edges\":\n        # perform edge detection\n        img = cv2.cvtColor(cv2.Canny(frame, 100, 200), cv2.COLOR_GRAY2BGR)\n        return img\n    else:\n        return np.flipud(frame)\nwith gr.Blocks() as demo:\n    with gr.Row():\n        with gr.Column():\n            transform = gr.Dropdown(\n                choices=[\"cartoon\", \"edges\", \"flip\"],\n                value=\"flip\",\n                label=\"Transformation\",\n            )\n            input_img = gr.Image(sources=[\"webcam\"], type=\"numpy\")\n        with gr.Column():\n            output_img = gr.Image(streaming=True)\n        dep = input_img.stream(\n            transform_cv2,\n            [input_img, transform],\n            [output_img],\n            time_limit=30,\n            stream_every=0.1,\n            concurrency_limit=30,\n        )\ndemo.launch()\n`\nYou will notice that if you change the filter value it will immediately take effect in the output stream. That is an important difference of stream events in comparison to other Gradio events. The input values of the stream can be changed while the stream is being processed. \n            \n                \n                    \n                    \n                    \n                \n                We set the \"streaming\" parameter of the image output component to be \"True\". Doing so lets the server automatically convert our output images into base64 format, a format that is efficient for streaming.\n            \n                \nUnified Image Demos\nFor some image streaming demos, like the one above, we don't need to display separate input and output components. Our app would look cleaner if we could just display the modified output stream.\nWe can do so by just specifying the input image component as the output of the stream event.\n`python\nimport gradio as gr\nimport numpy as np\nimport cv2  \ndef transform_cv2(frame, transform):\n    if transform == \"cartoon\":\n        # prepare color\n        img_color = cv2.pyrDown(cv2.pyrDown(frame))\n        for _ in range(6):\n            imgcolor = cv2.bilateralFilter(imgcolor, 9, 9, 7)\n        imgcolor = cv2.pyrUp(cv2.pyrUp(imgcolor))\n        # prepare edges\n        imgedges = cv2.cvtColor(frame, cv2.COLORRGB2GRAY)\n        img_edges = cv2.adaptiveThreshold(\n            cv2.medianBlur(img_edges, 7),\n            255,\n            cv2.ADAPTIVETHRESHMEAN_C,\n            cv2.THRESH_BINARY,\n            9,\n            2,\n        )\n        imgedges = cv2.cvtColor(imgedges, cv2.COLOR_GRAY2RGB)\n        # combine color and edges\n        img = cv2.bitwiseand(imgcolor, img_edges)\n        return img\n    elif transform == \"edges\":\n        # perform edge detection\n        img = cv2.cvtColor(cv2.Canny(frame, 100, 200), cv2.COLOR_GRAY2BGR)\n        return img\n    else:\n        return np.flipud(frame)\ncss=\"\"\".my-group {max-width: 500px !important; max-height: 500px !important;}\n            .my-column {display: flex !important; justify-content: center !important; align-items: center !important};\"\"\"\nwith gr.Blocks() as demo:\n    with gr.Column(elem_classes=[\"my-column\"]):\n        with gr.Group(elem_classes=[\"my-group\"]):\n            transform = gr.Dropdown(choices=[\"cartoon\", \"edges\", \"flip\"],\n                                    value=\"flip\", label=\"Transformation\")\n            input_img = gr.Image(sources=[\"webcam\"], type=\"numpy\", streaming=True)\n    inputimg.stream(transformcv2, [inputimg, transform], [inputimg], timelimit=30, streamevery=0.1)\nif name == \"main\":\n    demo.launch(css=css)\n`\nKeeping track of past inputs or outputs\nYour streaming function should be stateless. It should take the current input and return its corresponding output. However, there are cases where you may want to keep track of past inputs or outputs. For example, you may want to keep a buffer of the previous k inputs to improve the accuracy of your transcription demo. You can do this with Gradio's gr.State() component.\nLet's showcase this with a sample demo:\n`python\ndef transcribehandler(currentaudio, state, transcript):\n    nexttext = transcribe(currentaudio, history=state)\n    state.append(current_audio)\n    state = state[-3:]\n    return state, transcript + next_text\nwith gr.Blocks() as demo:\n    with gr.Row():\n        with gr.Column():\n            mic = gr.Audio(sources=\"microphone\")\n            state = gr.State(value=[])\n        with gr.Column():\n            transcript = gr.Textbox(label=\"Transcript\")\n    mic.stream(transcribe_handler, [mic, state, transcript], [state, transcript],\n               timelimit=10, streamevery=1)\ndemo.launch()\n``\nEnd-to-End Examples\nFor an end-to-end example of streaming from the webcam, see the object detection from webcam guide.","type":"GUIDE"},{"title":"Streaming Outputs","slug":"/guides/streaming-outputs/","content":"Streaming outputs\nIn some cases, you may want to stream a sequence of outputs rather than show a single output at once. For example, you might have an image generation model and you want to show the image that is generated at each step, leading up to the final image. Or you might have a chatbot which streams its response one token at a time instead of returning it all at once.\nIn such cases, you can supply a generator function into Gradio instead of a regular function. Creating generators in Python is very simple: instead of a single return value, a function should yield a series of values instead. Usually the yield statement is put in some kind of loop. Here's an example of an generator that simply counts up to a given number:\n``python\ndef my_generator(x):\n    for i in range(x):\n        yield i\n`\nYou supply a generator into Gradio the same way as you would a regular function. For example, here's a a (fake) image generation model that generates noise for several steps before outputting an image using the gr.Interface class:\n`python\nimport gradio as gr\nimport numpy as np\nimport time\ndef fake_diffusion(steps):\n    rng = np.random.default_rng()\n    for i in range(steps):\n        time.sleep(1)\n        image = rng.random(size=(600, 600, 3))\n        yield image\n    image = np.ones((1000,1000,3), np.uint8)\n    image[:] = [255, 124, 0]\n    yield image\ndemo = gr.Interface(fake_diffusion,\n                    inputs=gr.Slider(1, 10, 3, step=1),\n                    outputs=\"image\",\n                    api_name=\"predict\")\ndemo.launch()\n`\nNote that we've added a time.sleep(1) in the iterator to create an artificial pause between steps so that you are able to observe the steps of the iterator (in a real image generation model, this probably wouldn't be necessary).\nSimilarly, Gradio can handle streaming inputs, e.g. an image generation model that reruns every time a user types a letter in a textbox. This is covered in more details in our guide on building reactive Interfaces. \nStreaming Media\nGradio can stream audio and video directly from your generator function.\nThis lets your user hear your audio or see your video nearly as soon as it's yielded by your function.\nAll you have to do is \nSet streaming=True in your gr.Audio or gr.Video output component.\nWrite a python generator that yields the next \"chunk\" of audio or video.\nSet autoplay=True so that the media starts playing automatically.\nFor audio, the next \"chunk\" can be either an .mp3 or .wav file or a bytes sequence of audio.\nFor video, the next \"chunk\" has to be either .mp4 file or a file with h.264 codec with a .ts extension.\nFor smooth playback, make sure chunks are consistent lengths and larger than 1 second.\nWe'll finish with some simple examples illustrating these points.\nStreaming Audio\n`python\nimport gradio as gr\nfrom time import sleep\ndef keeprepeating(audiofile):\n    for _ in range(10):\n        sleep(0.5)\n        yield audio_file\ngr.Interface(keep_repeating,\n             gr.Audio(sources=[\"microphone\"], type=\"filepath\"),\n             gr.Audio(streaming=True, autoplay=True)\n).launch()\n`\nStreaming Video\n`python\nimport gradio as gr\nfrom time import sleep\ndef keeprepeating(videofile):\n    for _ in range(10):\n        sleep(0.5)\n        yield video_file\ngr.Interface(keep_repeating,\n             gr.Video(sources=[\"webcam\"], format=\"mp4\"),\n             gr.Video(streaming=True, autoplay=True)\n).launch()\n``\nEnd-to-End Examples\nFor an end-to-end example of streaming media, see the object detection from video guide or the streaming AI-generated audio with transformers guide.","type":"GUIDE"},{"title":"Styling The Gradio Dataframe","slug":"/guides/styling-the-gradio-dataframe/","content":"How to Style the Gradio Dataframe\nIntroduction\nData visualization is a crucial aspect of data analysis and machine learning. The Gradio DataFrame component is a popular way to display tabular data within a web application. \nBut what if you want to stylize the table of data? What if you want to add background colors, partially highlight cells, or change the display precision of numbers? This Guide is for you!\nLet's dive in!\nPrerequisites: We'll be using the gradio.Blocks class in our examples.\nYou can read the Guide to Blocks first if you are not already familiar with it. Also please make sure you are using the latest version version of Gradio: pip install --upgrade gradio.\nThe Pandas Styler\nThe Gradio DataFrame component now supports values of the type Styler from the pandas class. This allows us to reuse the rich existing API and documentation of the Styler class instead of inventing a new style format on our own. Here's a complete example of how it looks:\n``python\nimport pandas as pd \nimport gradio as gr\nCreating a sample dataframe\ndf = pd.DataFrame({\n    \"A\" : [14, 4, 5, 4, 1], \n    \"B\" : [5, 2, 54, 3, 2], \n    \"C\" : [20, 20, 7, 3, 8], \n    \"D\" : [14, 3, 6, 2, 6], \n    \"E\" : [23, 45, 64, 32, 23]\n}) \nApplying style to highlight the maximum value in each row\nstyler = df.style.highlight_max(color = 'lightgreen', axis = 0)\nDisplaying the styled dataframe in Gradio\nwith gr.Blocks() as demo:\n    gr.DataFrame(styler)\n    \ndemo.launch()\n`\nThe Styler class can be used to apply conditional formatting and styling to dataframes, making them more visually appealing and interpretable. You can highlight certain values, apply gradients, or even use custom CSS to style the DataFrame. The Styler object is applied to a DataFrame and it returns a new object with the relevant styling properties, which can then be previewed directly, or rendered dynamically in a Gradio interface.\nTo read more about the Styler object, read the official pandas documentation at: https://pandas.pydata.org/docs/user_guide/style.html\nBelow, we'll explore a few examples:\nHighlighting Cells\nOk, so let's revisit the previous example. We start by creating a pd.DataFrame object and then highlight the highest value in each row with a light green color:\n`python\nimport pandas as pd \nCreating a sample dataframe\ndf = pd.DataFrame({\n    \"A\" : [14, 4, 5, 4, 1], \n    \"B\" : [5, 2, 54, 3, 2], \n    \"C\" : [20, 20, 7, 3, 8], \n    \"D\" : [14, 3, 6, 2, 6], \n    \"E\" : [23, 45, 64, 32, 23]\n}) \nApplying style to highlight the maximum value in each row\nstyler = df.style.highlight_max(color = 'lightgreen', axis = 0)\n`\nNow, we simply pass this object into the Gradio DataFrame and we can visualize our colorful table of data in 4 lines of python:\n`python\nimport gradio as gr\nwith gr.Blocks() as demo:\n    gr.Dataframe(styler)\n    \ndemo.launch()\n`\nHere's how it looks:\nFont Colors\nApart from highlighting cells, you might want to color specific text within the cells. Here's how you can change text colors for certain columns:\n`python\nimport pandas as pd \nimport gradio as gr\nCreating a sample dataframe\ndf = pd.DataFrame({\n    \"A\" : [14, 4, 5, 4, 1], \n    \"B\" : [5, 2, 54, 3, 2], \n    \"C\" : [20, 20, 7, 3, 8], \n    \"D\" : [14, 3, 6, 2, 6], \n    \"E\" : [23, 45, 64, 32, 23]\n}) \nFunction to apply text color\ndef highlight_cols(x): \n    df = x.copy() \n    df.loc[:, :] = 'color: purple'\n    df[['B', 'C', 'E']] = 'color: green'\n    return df \nApplying the style function\ns = df.style.apply(highlight_cols, axis = None)\nDisplaying the styled dataframe in Gradio\nwith gr.Blocks() as demo:\n    gr.DataFrame(s)\n    \ndemo.launch()\n`\nIn this script, we define a custom function highlight_cols that changes the text color to purple for all cells, but overrides this for columns B, C, and E with green. Here's how it looks:\nDisplay Precision \nSometimes, the data you are dealing with might have long floating numbers, and you may want to display only a fixed number of decimals for simplicity. The pandas Styler object allows you to format the precision of numbers displayed. Here's how you can do this:\n`python\nimport pandas as pd\nimport gradio as gr\nCreating a sample dataframe with floating numbers\ndf = pd.DataFrame({\n    \"A\" : [14.12345, 4.23456, 5.34567, 4.45678, 1.56789], \n    \"B\" : [5.67891, 2.78912, 54.89123, 3.91234, 2.12345], \n    # ... other columns\n}) \nSetting the precision of numbers to 2 decimal places\ns = df.style.format(\"{:.2f}\")\nDisplaying the styled dataframe in Gradio\nwith gr.Blocks() as demo:\n    gr.DataFrame(s)\n    \ndemo.launch()\n`\nIn this script, the format method of the Styler object is used to set the precision of numbers to two decimal places. Much cleaner now:\nCustom Styling\nSo far, we've been restricting ourselves to styling that is supported by the Pandas Styler class. But what if you want to create custom styles like partially highlighting cells based on their values:\nThis isn't possible with Styler, but you can do this by creating your own styling array, which is a 2D array the same size and shape as your data. Each element in this list should be a CSS style string (e.g. \"background-color: green\") that applies to the  element containing the cell value (or an empty string if no custom CSS should be applied). Similarly, you can create a display_value array which controls the value that is displayed in each cell (which can be different the underlying value which is the one that is used for searching/sorting).\nHere's the complete code for how to can use custom styling with gr.Dataframe as in the screenshot above:\n``python\nimport gradio as gr\ndata = [\n    [\"DeepSeek Coder\", 79.3],\n    [\"Llama 3.3\", 68.9],\n    [\"Qwen 2.5\", 61.9],\n    [\"Gemma 2\", 59.5],\n    [\"GPT 2\", 18.3],\n]\nheaders = [\"Model\", \"% Correct (LeetCode Hard)\"]\ndef get_styling(values):\n    return [[\"\", f\"background: linear-gradient(90deg, rgba(220, 242, 220) {row[1]}%, transparent {row[1]}%)\"] for row in values]\ndef getdisplayvalue(values):\n    display_values = []\n    medals = [\"🥇\", \"🥈\", \"🥉\"]\n    for i, row in enumerate(values):\n        if i","type":"GUIDE"},{"title":"The Interface Class","slug":"/guides/the-interface-class/","content":"The Interface class\nAs mentioned in the Quickstart, the gr.Interface class is a high-level abstraction in Gradio that allows you to quickly create a demo for any Python function simply by specifying the input types and the output types. Revisiting our first demo:\n``python\nimport gradio as gr\ndef greet(name, intensity):\n    return \"Hello, \" + name + \"!\" * int(intensity)\ndemo = gr.Interface(\n    fn=greet,\n    inputs=[\"text\", \"slider\"],\n    outputs=[\"text\"],\n    api_name=\"predict\"\n)\ndemo.launch()\n`\nWe see that the Interface class is initialized with three required parameters:\nfn: the function to wrap a user interface (UI) around\ninputs: which Gradio component(s) to use for the input. The number of components should match the number of arguments in your function.\noutputs: which Gradio component(s) to use for the output. The number of components should match the number of return values from your function.\nIn this Guide, we'll dive into gr.Interface and the various ways it can be customized, but before we do that, let's get a better understanding of Gradio components.\nGradio Components\nGradio includes more than 30 pre-built components (as well as many community-built custom components) 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. \nComponents Attributes\nWe 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?\nLet'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.\nIf 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.\n`python\nimport gradio as gr\ndef greet(name, intensity):\n    return \"Hello, \" + name + \"!\" * intensity\ndemo = gr.Interface(\n    fn=greet,\n    inputs=[\"text\", gr.Slider(value=2, minimum=1, maximum=10, step=1)],\n    outputs=[gr.Textbox(label=\"greeting\", lines=3)],\n    api_name=\"predict\"\n)\ndemo.launch()\n`\nMultiple Input and Output Components\nSuppose 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. \n`python\nimport gradio as gr\ndef greet(name, is_morning, temperature):\n    salutation = \"Good morning\" if is_morning else \"Good evening\"\n    greeting = f\"{salutation} {name}. It is {temperature} degrees today\"\n    celsius = (temperature - 32) * 5 / 9\n    return greeting, round(celsius, 2)\ndemo = gr.Interface(\n    fn=greet,\n    inputs=[\"text\", \"checkbox\", gr.Slider(0, 100)],\n    outputs=[\"text\", \"number\"],\n    api_name=\"predict\"\n)\ndemo.launch()\n`\nJust 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.\nAn Image Example\nGradio 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!\n`python\nimport numpy as np\nimport gradio as gr\ndef sepia(input_img):\n    sepia_filter = np.array([\n        [0.393, 0.769, 0.189],\n        [0.349, 0.686, 0.168],\n        [0.272, 0.534, 0.131]\n    ])\n    sepiaimg = inputimg.dot(sepia_filter.T)\n    sepiaimg /= sepiaimg.max()\n    return sepia_img\ndemo = gr.Interface(sepia, gr.Image(), \"image\", api_name=\"predict\")\ndemo.launch()\n`\nWhen 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. \nGradio 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:\n`python\ngr.Image(type=\"filepath\")\n`\nYou can read more about the built-in Gradio components and how to customize them in the Gradio docs.\nExample Inputs\nYou 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.\n`python\nimport gradio as gr\ndef calculator(num1, operation, num2):\n    if operation == \"add\":\n        return num1 + num2\n    elif operation == \"subtract\":\n        return num1 - num2\n    elif operation == \"multiply\":\n        return num1 * num2\n    elif operation == \"divide\":\n        if num2 == 0:\n            raise gr.Error(\"Cannot divide by zero!\")\n        return num1 / num2\ndemo = gr.Interface(\n    calculator,\n    [\n        \"number\",\n        gr.Radio([\"add\", \"subtract\", \"multiply\", \"divide\"]),\n        \"number\"\n    ],\n    \"number\",\n    examples=[\n        [45, \"add\", 3],\n        [3.14, \"divide\", 2],\n        [144, \"multiply\", 2.5],\n        [0, \"subtract\", 1.2],\n    ],\n    title=\"Toy Calculator\",\n    description=\"Here's a sample toy calculator.\",\n    api_name=\"predict\"\n)\ndemo.launch()\n`\nYou 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 examplesperpage argument of Interface).\nContinue learning about examples in the More On Examples guide.\nDescriptive Content\nIn the previous example, you may have noticed the title= and description= keyword arguments in the Interface constructor that helps users understand your app.\nThere are three arguments in the Interface constructor to specify where this content should go:\ntitle: which accepts text and can display it at the very top of interface, and also becomes the page title.\ndescription: which accepts text, markdown or HTML and places it right under the title.\narticle: which also accepts text, markdown or HTML and places it below the interface.\nAnother 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.\n`python\ngr.Number(label='Age', info='In years, must be greater than 0')\n`\nAdditional Inputs within an Accordion\nIf 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.\nYou can customize the appearance of the accordion by using the optional additionalinputsaccordion 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).\nHere's an example:\n`python\nimport gradio as gr\ndef generatefakeimage(prompt, seed, initial_image=None):\n    return f\"Used seed: {seed}\", \"https://dummyimage.com/300/09f.png\"\ndemo = gr.Interface(\n    generatefakeimage,\n    inputs=[\"textbox\"],\n    outputs=[\"textbox\", \"image\"],\n    additional_inputs=[\n        gr.Slider(0, 1000),\n        \"image\"\n    ],\n    api_name=\"predict\",\n)\ndemo.launch()\n``","type":"GUIDE"},{"title":"Themes","slug":"/guides/themes/","content":"Gradio Themes\nGradio themes are the easiest way to customize the look and feel of your app. You can choose from a variety of themes, or create your own. To do so, pass the theme= kwarg to the launch() method of Interface, ChatInterface, or Blocks. For example:\n``python\ndemo = gr.Interface()\ndemo.launch(theme=gr.themes.Monochrome())\n`\nor\n`python\nwith gr.Blocks() as demo:\n    ... # your code here\ndemo.launch(theme=gr.themes.Soft())\n    ...\n`\nGradio comes with a set of prebuilt themes which you can load from gr.themes.*`. You can extend these themes or create your own themes from scratch - see the theming guide for more details.\nFor additional styling ability, you can pass any CSS (as well as custom JavaScript) to your Gradio application. This is discussed in more detail in our custom JS and CSS guide.","type":"GUIDE"},{"title":"Theming Guide","slug":"/guides/theming-guide/","content":"Theming\nIntroduction\nGradio features a built-in theming engine that lets you customize the look and feel of your app. You can choose from a variety of themes, or create your own. To do so, pass the theme= kwarg to the launch() method of Blocks or Interface. For example:\n``python\nwith gr.Blocks() as demo:\n    ... # your code here\ndemo.launch(theme=gr.themes.Soft())\n    ...\n`\nGradio comes with a set of prebuilt themes which you can load from gr.themes.*. These are:\ngr.themes.Base() - the \"base\" theme sets the primary color to blue but otherwise has minimal styling, making it particularly useful as a base for creating new, custom themes.\ngr.themes.Default() - the \"default\" Gradio 5 theme, with a vibrant orange primary color and gray secondary color.\ngr.themes.Origin() - the \"origin\" theme is most similar to Gradio 4 styling. Colors, especially in light mode, are more subdued than the Gradio 5 default theme.\ngr.themes.Citrus() - the \"citrus\" theme uses a yellow primary color, highlights form elements that are in focus, and includes fun 3D effects when buttons are clicked.\ngr.themes.Monochrome() - the \"monochrome\" theme uses a black primary and white secondary color, and uses serif-style fonts, giving the appearance of a black-and-white newspaper. \ngr.themes.Soft() - the \"soft\" theme uses a purple primary color and white secondary color. It also increases the border radius around buttons and form elements and highlights labels.\ngr.themes.Glass() - the \"glass\" theme has a blue primary color and a transclucent gray secondary color. The theme also uses vertical gradients to create a glassy effect.\ngr.themes.Ocean() - the \"ocean\" theme has a blue-green primary color and gray secondary color. The theme also uses horizontal gradients, especially for buttons and some form elements.\nEach of these themes set values for hundreds of CSS variables. You can use prebuilt themes as a starting point for your own custom themes, or you can create your own themes from scratch. Let's take a look at each approach.\nUsing the Theme Builder\nThe easiest way to build a theme is using the Theme Builder. To launch the Theme Builder locally, run the following code:\n`python\nimport gradio as gr\ngr.themes.builder()\n`\nYou can use the Theme Builder running on Spaces above, though it runs much faster when you launch it locally via gr.themes.builder().\nAs you edit the values in the Theme Builder, the app will preview updates in real time. You can download the code to generate the theme you've created so you can use it in any Gradio app.\nIn the rest of the guide, we will cover building themes programmatically.\nExtending Themes via the Constructor\nAlthough each theme has hundreds of CSS variables, the values for most these variables are drawn from 8 core variables which can be set through the constructor of each prebuilt theme. Modifying these 8 arguments allows you to quickly change the look and feel of your app.\nCore Colors\nThe first 3 constructor arguments set the colors of the theme and are gradio.themes.Color objects. Internally, these Color objects hold brightness values for the palette of a single hue, ranging from 50, 100, 200..., 800, 900, 950. Other CSS variables are derived from these 3 colors.\nThe 3 color constructor arguments are:\nprimary_hue: This is the color draws attention in your theme. In the default theme, this is set to gradio.themes.colors.orange.\nsecondary_hue: This is the color that is used for secondary elements in your theme. In the default theme, this is set to gradio.themes.colors.blue.\nneutral_hue: This is the color that is used for text and other neutral elements in your theme. In the default theme, this is set to gradio.themes.colors.gray.\nYou could modify these values using their string shortcuts, such as\n`python\nwith gr.Blocks() as demo:\n    ... # your code here\ndemo.launch(theme=gr.themes.Default(primaryhue=\"red\", secondaryhue=\"pink\"))\n    ...\n`\nor you could use the Color objects directly, like this:\n`python\nwith gr.Blocks() as demo:\n    ... # your code here\ndemo.launch(theme=gr.themes.Default(primaryhue=gr.themes.colors.red, secondaryhue=gr.themes.colors.pink))\n`\nPredefined colors are:\nslate\ngray\nzinc\nneutral\nstone\nred\norange\namber\nyellow\nlime\ngreen\nemerald\nteal\ncyan\nsky\nblue\nindigo\nviolet\npurple\nfuchsia\npink\nrose\nYou could also create your own custom Color objects and pass them in.\nCore Sizing\nThe next 3 constructor arguments set the sizing of the theme and are gradio.themes.Size objects. Internally, these Size objects hold pixel size values that range from xxs to xxl. Other CSS variables are derived from these 3 sizes.\nspacingsize: This sets the padding within and spacing between elements. In the default theme, this is set to gradio.themes.sizes.spacingmd.\nradiussize: This sets the roundedness of corners of elements. In the default theme, this is set to gradio.themes.sizes.radiusmd.\ntextsize: This sets the font size of text. In the default theme, this is set to gradio.themes.sizes.textmd.\nYou could modify these values using their string shortcuts, such as\n`python\nwith gr.Blocks() as demo:\n    ... # your code here\ndemo.launch(theme=gr.themes.Default(spacingsize=\"sm\", radiussize=\"none\"))\n    ...\n`\nor you could use the Size objects directly, like this:\n`python\nwith gr.Blocks() as demo:\n    ... # your code here\ndemo.launch(theme=gr.themes.Default(spacingsize=gr.themes.sizes.spacingsm, radiussize=gr.themes.sizes.radiusnone))\n    ...\n`\nThe predefined size objects are:\nradius_none\nradius_sm\nradius_md\nradius_lg\nspacing_sm\nspacing_md\nspacing_lg\ntext_sm\ntext_md\ntext_lg\nYou could also create your own custom Size objects and pass them in.\nCore Fonts\nThe final 2 constructor arguments set the fonts of the theme. You can pass a list of fonts to each of these arguments to specify fallbacks. If you provide a string, it will be loaded as a system font. If you provide a gradio.themes.GoogleFont, the font will be loaded from Google Fonts.\nfont: This sets the primary font of the theme. In the default theme, this is set to gradio.themes.GoogleFont(\"IBM Plex Sans\").\nfont_mono: This sets the monospace font of the theme. In the default theme, this is set to gradio.themes.GoogleFont(\"IBM Plex Mono\").\nYou could modify these values such as the following:\n`python\nwith gr.Blocks() as demo:\n    ... # your code here\ndemo.launch(theme=gr.themes.Default(font=[gr.themes.GoogleFont(\"Inconsolata\"), \"Arial\", \"sans-serif\"]))\n    ...\n`\nCustom CSS\nFor styling beyond what theme variables provide, you can add custom CSS via the custom_css attribute. This CSS is bundled with the theme, so it will be included when you upload or download themes from the Hub.\n`python\ntheme = gr.themes.Default()\ntheme.custom_css = \"\"\"\nbutton.primary {\n    background: linear-gradient(135deg, var(--primary-400), var(--primary-600));\n    transition: transform 0.15s ease, box-shadow 0.15s ease;\n}\nbutton.primary:hover {\n    transform: translateY(-2px);\n    box-shadow: 0 4px 12px color-mix(in srgb, var(--primary-500) 40%, transparent);\n}\n\"\"\"\nwith gr.Blocks(theme=theme) as demo:\n    gr.Textbox(label=\"Input\")\n    gr.Button(\"Submit\", variant=\"primary\")\ndemo.launch()\n`\nExtending Themes via .set()\nYou can also modify the values of CSS variables after the theme has been loaded. To do so, use the .set() method of the theme object to get access to the CSS variables. For example:\n`python\ntheme = gr.themes.Default(primary_hue=\"blue\").set(\n    loader_color=\"#FF0000\",\n    slider_color=\"#FF0000\",\n)\nwith gr.Blocks() as demo:\n    ... # your code here\ndemo.launch(theme=theme)\n`\nIn the example above, we've set the loadercolor and slidercolor variables to #FF0000, despite the overall primary_color using the blue color palette. You can set any CSS variable that is defined in the theme in this manner.\nYour IDE type hinting should help you navigate these variables. Since there are so many CSS variables, let's take a look at how these variables are named and organized.\nCSS Variable Naming Conventions\nCSS variable names can get quite long, like buttonprimarybackgroundfillhover_dark! However they follow a common naming convention that makes it easy to understand what they do and to find the variable you're looking for. Separated by underscores, the variable name is made up of:\nThe target element, such as button, slider, or block.\nThe target element type or sub-element, such as buttonprimary, or blocklabel.\nThe property, such as buttonprimarybackgroundfill, or blocklabelborderwidth.\nAny relevant state, such as buttonprimarybackgroundfillhover.\nIf the value is different in dark mode, the suffix dark. For example, inputbordercolorfocus_dark.\nOf course, many CSS variable names are shorter than this, such as tablebordercolor, or input_shadow.\nCSS Variable Organization\nThough there are hundreds of CSS variables, they do not all have to have individual values. They draw their values by referencing a set of core variables and referencing each other. This allows us to only have to modify a few variables to change the look and feel of the entire theme, while also getting finer control of individual elements that we may want to modify.\nReferencing Core Variables\nTo reference one of the core constructor variables, precede the variable name with an asterisk. To reference a core color, use the primary_, secondary, or *neutral prefix, followed by the brightness value. For example:\n`python\ntheme = gr.themes.Default(primary_hue=\"blue\").set(\n    buttonprimarybackgroundfill=\"*primary200\",\n    buttonprimarybackgroundfillhover=\"*primary_300\",\n)\n`\nIn the example above, we've set the buttonprimarybackgroundfill and buttonprimarybackgroundfillhover variables to *primary200 and *primary_300. These variables will be set to the 200 and 300 brightness values of the blue primary color palette, respectively.\nSimilarly, to reference a core size, use the spacing_, radius, or *text prefix, followed by the size value. For example:\n`python\ntheme = gr.themes.Default(radius_size=\"md\").set(\n    buttonprimaryborderradius=\"*radiusxl\",\n)\n`\nIn the example above, we've set the buttonprimaryborderradius variable to *radiusxl. This variable will be set to the xl setting of the medium radius size range.\nReferencing Other Variables\nVariables can also reference each other. For example, look at the example below:\n`python\ntheme = gr.themes.Default().set(\n    buttonprimarybackground_fill=\"#FF0000\",\n    buttonprimarybackgroundfillhover=\"#FF0000\",\n    buttonprimaryborder=\"#FF0000\",\n)\n`\nHaving to set these values to a common color is a bit tedious. Instead, we can reference the buttonprimarybackgroundfill variable in the buttonprimarybackgroundfillhover and buttonprimary_border variables, using a * prefix.\n`python\ntheme = gr.themes.Default().set(\n    buttonprimarybackground_fill=\"#FF0000\",\n    buttonprimarybackgroundfillhover=\"*buttonprimarybackground_fill\",\n    buttonprimaryborder=\"*buttonprimarybackground_fill\",\n)\n`\nNow, if we change the buttonprimarybackgroundfill variable, the buttonprimarybackgroundfillhover and buttonprimary_border variables will automatically update as well.\nThis is particularly useful if you intend to share your theme - it makes it easy to modify the theme without having to change every variable.\nNote that dark mode variables automatically reference each other. For example:\n`python\ntheme = gr.themes.Default().set(\n    buttonprimarybackground_fill=\"#FF0000\",\n    buttonprimarybackgroundfilldark=\"#AAAAAA\",\n    buttonprimaryborder=\"*buttonprimarybackground_fill\",\n    buttonprimaryborderdark=\"*buttonprimarybackgroundfill_dark\",\n)\n`\nbuttonprimaryborderdark will draw its value from buttonprimarybackgroundfill_dark, because dark mode always draw from the dark version of the variable.\nCSS Variables Reference\nFor a full list of all available CSS variables, see the CSS Variables Reference.\nCreating a Full Theme\nLet's say you want to create a theme from scratch! We'll go through it step by step - you can also see the source of prebuilt themes in the gradio source repo for reference - here's the source for the Monochrome theme.\nOur new theme class will inherit from gradio.themes.Base, a theme that sets a lot of convenient defaults. Let's make a simple demo that creates a dummy theme called Seafoam, and make a simple app that uses it.\n`python\nimport gradio as gr\nfrom gradio.themes.base import Base\nimport time\nclass Seafoam(Base):\n    pass\nseafoam = Seafoam()\nwith gr.Blocks() as demo:\n    textbox = gr.Textbox(label=\"Name\")\n    slider = gr.Slider(label=\"Count\", minimum=0, maximum=100, step=1)\n    with gr.Row():\n        button = gr.Button(\"Submit\", variant=\"primary\")\n        clear = gr.Button(\"Clear\")\n    output = gr.Textbox(label=\"Output\")\n    def repeat(name, count):\n        time.sleep(3)\n        return name * count\n    button.click(repeat, [textbox, slider], output)\nif name == \"main\":\n    demo.launch(theme=seafoam)\n`\nThe Base theme is very barebones, and uses gr.themes.Blue as it primary color - you'll note the primary button and the loading animation are both blue as a result. Let's change the defaults core arguments of our app. We'll overwrite the constructor and pass new defaults for the core constructor arguments.\nWe'll use gr.themes.Emerald as our primary color, and set secondary and neutral hues to gr.themes.Blue. We'll make our text larger using text_lg. We'll use Quicksand as our default font, loaded from Google Fonts.\n`python\nfrom future import annotations\nfrom typing import Iterable\nimport gradio as gr\nfrom gradio.themes.base import Base\nfrom gradio.themes.utils import colors, fonts, sizes\nimport time\nclass Seafoam(Base):\n    def init(\n        self,\n        *,\n        primary_hue: colors.Color | str = colors.emerald,\n        secondary_hue: colors.Color | str = colors.blue,\n        neutral_hue: colors.Color | str = colors.gray,\n        spacingsize: sizes.Size | str = sizes.spacingmd,\n        radiussize: sizes.Size | str = sizes.radiusmd,\n        textsize: sizes.Size | str = sizes.textlg,\n        font: fonts.Font\n        | str\n        | Iterable[fonts.Font | str] = (\n            fonts.GoogleFont(\"Quicksand\"),\n            \"ui-sans-serif\",\n            \"sans-serif\",\n        ),\n        font_mono: fonts.Font\n        | str\n        | Iterable[fonts.Font | str] = (\n            fonts.GoogleFont(\"IBM Plex Mono\"),\n            \"ui-monospace\",\n            \"monospace\",\n        ),\n    ):\n        super().init(\n            primaryhue=primaryhue,\n            secondaryhue=secondaryhue,\n            neutralhue=neutralhue,\n            spacingsize=spacingsize,\n            radiussize=radiussize,\n            textsize=textsize,\n            font=font,\n            fontmono=fontmono,\n        )\nseafoam = Seafoam()\nwith gr.Blocks() as demo:\n    textbox = gr.Textbox(label=\"Name\")\n    slider = gr.Slider(label=\"Count\", minimum=0, maximum=100, step=1)\n    with gr.Row():\n        button = gr.Button(\"Submit\", variant=\"primary\")\n        clear = gr.Button(\"Clear\")\n    output = gr.Textbox(label=\"Output\")\n    def repeat(name, count):\n        time.sleep(3)\n        return name * count\n    button.click(repeat, [textbox, slider], output)\nif name == \"main\":\n    demo.launch(theme=seafoam)\n`\nSee how the primary button and the loading animation are now green? These CSS variables are tied to the primary_hue variable.\nLet's modify the theme a bit more directly. We'll call the set() method to overwrite CSS variable values explicitly. We can use any CSS logic, and reference our core constructor arguments using the * prefix.\n`python\nfrom future import annotations\nfrom typing import Iterable\nimport gradio as gr\nfrom gradio.themes.base import Base\nfrom gradio.themes.utils import colors, fonts, sizes\nimport time\nclass Seafoam(Base):\n    def init(\n        self,\n        *,\n        primary_hue: colors.Color | str = colors.emerald,\n        secondary_hue: colors.Color | str = colors.blue,\n        neutral_hue: colors.Color | str = colors.blue,\n        spacingsize: sizes.Size | str = sizes.spacingmd,\n        radiussize: sizes.Size | str = sizes.radiusmd,\n        textsize: sizes.Size | str = sizes.textlg,\n        font: fonts.Font\n        | str\n        | Iterable[fonts.Font | str] = (\n            fonts.GoogleFont(\"Quicksand\"),\n            \"ui-sans-serif\",\n            \"sans-serif\",\n        ),\n        font_mono: fonts.Font\n        | str\n        | Iterable[fonts.Font | str] = (\n            fonts.GoogleFont(\"IBM Plex Mono\"),\n            \"ui-monospace\",\n            \"monospace\",\n        ),\n    ):\n        super().init(\n            primaryhue=primaryhue,\n            secondaryhue=secondaryhue,\n            neutralhue=neutralhue,\n            spacingsize=spacingsize,\n            radiussize=radiussize,\n            textsize=textsize,\n            font=font,\n            fontmono=fontmono,\n        )\n        super().set(\n            bodybackgroundfill=\"repeating-linear-gradient(45deg, primary_200, primary200 10px, *primary50 10px, *primary_50 20px)\",\n            bodybackgroundfilldark=\"repeating-linear-gradient(45deg, *primary800, primary_800 10px, primary900 10px, *primary900 20px)\",\n            buttonprimarybackgroundfill=\"linear-gradient(90deg, *primary300, *secondary_400)\",\n            buttonprimarybackgroundfillhover=\"linear-gradient(90deg, primary_200, secondary_300)\",\n            buttonprimarytext_color=\"white\",\n            buttonprimarybackgroundfilldark=\"linear-gradient(90deg, primary_600, secondary_800)\",\n            slidercolor=\"*secondary300\",\n            slidercolordark=\"*secondary_600\",\n            blocktitletext_weight=\"600\",\n            blockborderwidth=\"3px\",\n            blockshadow=\"*shadowdrop_lg\",\n            buttonprimaryshadow=\"*shadowdroplg\",\n            buttonlargepadding=\"32px\",\n        )\nseafoam = Seafoam()\nwith gr.Blocks() as demo:\n    textbox = gr.Textbox(label=\"Name\")\n    slider = gr.Slider(label=\"Count\", minimum=0, maximum=100, step=1)\n    with gr.Row():\n        button = gr.Button(\"Submit\", variant=\"primary\")\n        clear = gr.Button(\"Clear\")\n    output = gr.Textbox(label=\"Output\")\n    def repeat(name, count):\n        time.sleep(3)\n        return name * count\n    button.click(repeat, [textbox, slider], output)\nif name == \"main\":\n    demo.launch(theme=seafoam)\n`\nLook how fun our theme looks now! With just a few variable changes, our theme looks completely different.\nYou may find it helpful to explore the source code of the other prebuilt themes to see how they modified the base theme. You can also find your browser's Inspector useful to select elements from the UI and see what CSS variables are being used in the styles panel.\nSharing Themes\nOnce you have created a theme, you can upload it to the HuggingFace Hub to let others view it, use it, and build off of it!\nUploading a Theme\nThere are two ways to upload a theme, via the theme class instance or the command line. We will cover both of them with the previously created seafoam theme.\nVia the class instance\nEach theme instance has a method called pushtohub we can use to upload a theme to the HuggingFace hub.\n`python\nseafoam.pushtohub(repo_name=\"seafoam\",\n                    version=\"0.0.1\",\n\t\t\t\t\ttoken=\"\")\n`\nVia the command line\nFirst save the theme to disk\n`python\nseafoam.dump(filename=\"seafoam.json\")\n`\nThen use the upload_theme command:\n`bash\nupload_theme\\\n\"seafoam.json\"\\\n\"seafoam\"\\\n--version \"0.0.1\"\\\n--token \"\"\n`\nIn order to upload a theme, you must have a HuggingFace account and pass your Access Token\nas the token argument. However, if you log in via the HuggingFace command line (which comes installed with gradio),\nyou can omit the token argument.\nThe version argument lets you specify a valid semantic version string for your theme.\nThat way your users are able to specify which version of your theme they want to use in their apps. This also lets you publish updates to your theme without worrying\nabout changing how previously created apps look. The version argument is optional. If omitted, the next patch version is automatically applied.\nTheme Previews\nBy calling pushtohub or upload_theme, the theme assets will be stored in a HuggingFace space.\nFor example, the theme preview for the calm seafoam theme is here: calm seafoam preview.\nDiscovering Themes\nThe Theme Gallery on the Gradio website shows all official and community themes. You can search, filter by official or community themes, and preview each theme's colors, fonts, and live demo.\nCommunity themes are sourced from the gradio/theme-gallery dataset on HuggingFace. To add your theme to the gallery, open a Pull Request to that dataset with your theme's metadata in manifest.json.\nDownloading\nTo use a theme from the hub, use the from_hub method on the ThemeClass and pass it to your app:\n`python\nmytheme = gr.Theme.fromhub(\"gradio/seafoam\")\nwith gr.Blocks() as demo:\n    ... # your code here\ndemo.launch(theme=my_theme)\n`\nYou can also pass the theme string directly to the launch() method of Blocks or Interface (e.g. demo.launch(theme=\"gradio/seafoam\"))\nYou can pin your app to an upstream theme version by using semantic versioning expressions.\nFor example, the following would ensure the theme we load from the seafoam repo was between versions 0.0.1 and 0.1.0:\n``python\nwith gr.Blocks() as demo:\n    ... # your code here\ndemo.launch(theme=\"gradio/seafoam@>=0.0.1,\n.wrapper {\n    position: relative;\n    padding-bottom: 56.25%;\n    padding-top: 25px;\n    height: 0;\n}\n.wrapper iframe {\n    position: absolute;\n    top: 0;\n    left: 0;\n    width: 100%;\n    height: 100%;\n}","type":"GUIDE"},{"title":"Time Plots","slug":"/guides/time-plots/","content":"Time Plots\nCreating visualizations with a time x-axis is a common use case. Let's dive in!\nCreating a Plot with a pd.Dataframe\nTime plots need a datetime column on the x-axis. Here's a simple example with some flight data:\n``python\nimport gradio as gr\nimport pandas as pd\nimport numpy as np\nimport random\nfrom datetime import datetime, timedelta\nnow = datetime.now()\ndf = pd.DataFrame({\n    'time': [now - timedelta(minutes=5*i) for i in range(25)],\n    'price': np.random.randint(100, 1000, 25),\n    'origin': [random.choice([\"DFW\", \"DAL\", \"HOU\"]) for _ in range(25)],\n    'destination': [random.choice([\"JFK\", \"LGA\", \"EWR\"]) for _ in range(25)],\n})\nwith gr.Blocks() as demo:\n    gr.LinePlot(df, x=\"time\", y=\"price\")\n    gr.ScatterPlot(df, x=\"time\", y=\"price\", color=\"origin\")\ndemo.launch()\n`\nAggregating by Time\nYou 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\".\n`python\nimport gradio as gr\nfrom data import df  \nwith gr.Blocks() as demo:\n    plot = gr.BarPlot(df, x=\"time\", y=\"price\", x_bin=\"10m\")\n    bins = gr.Radio([\"10m\", \"30m\", \"1h\"], label=\"Bin Size\")\n    bins.change(lambda bins: gr.BarPlot(x_bin=bins), bins, plot)\ndemo.launch()\n`\nDateTime Components\nYou can use gr.DateTime to accept input datetime data. This works well with plots for defining the x-axis range for the data.\n`python\nimport gradio as gr\nfrom data import df  \nwith gr.Blocks() as demo:\n    with gr.Row():\n        start = gr.DateTime(\"now - 24h\")\n        end = gr.DateTime(\"now\")\n        apply_btn = gr.Button(\"Apply\")\n    plot = gr.LinePlot(df, x=\"time\", y=\"price\")\n    applybtn.click(lambda start, end: gr.BarPlot(xlim=[start, end]), [start, end], plot)\n    \ndemo.launch()\n`\nNote how gr.DateTime can accept a full datetime string, or a shorthand using now - [0-9]+[smhd] format to refer to a past time.\nYou 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. \nBecause it is a custom component, you first need to pip install gradio_datetimerange. Then run the following:\n`python\nimport gradio as gr\nfrom gradio_datetimerange import DateTimeRange  \nfrom data import df  \nwith gr.Blocks() as demo:\n    daterange = DateTimeRange([\"now - 24h\", \"now\"])\n    plot1 = gr.LinePlot(df, x=\"time\", y=\"price\")\n    plot2 = gr.LinePlot(df, x=\"time\", y=\"price\", color=\"origin\")\n    daterange.bind([plot1, plot2])\ndemo.launch()\n`\nTry 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.\nRealTime Data\nIn 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:\n`python\nwith gr.Blocks() as demo:\n    timer = gr.Timer(5)\n    plot1 = gr.BarPlot(x=\"time\", y=\"price\")\n    plot2 = gr.BarPlot(x=\"time\", y=\"price\", color=\"origin\")\n    timer.tick(lambda: [getdata(), getdata()], outputs=[plot1, plot2])\n`\nYou can also use the every shorthand to attach a Timer to a component that has a function value:\n`python\nwith gr.Blocks() as demo:\n    timer = gr.Timer(5)\n    plot1 = gr.BarPlot(get_data, x=\"time\", y=\"price\", every=timer)\n    plot2 = gr.BarPlot(get_data, x=\"time\", y=\"price\", color=\"origin\", every=timer)\n``","type":"GUIDE"},{"title":"Understanding Gradio Share Links","slug":"/guides/understanding-gradio-share-links/","content":"Share Links and Share Servers\nYou may already know that you can share any Gradio app that you build by setting share=True in the .launch() method. In other words, if you do:\n``py\nimport gradio as gr\nwith gr.Blocks() as demo:\n    ...\ndemo.launch(share=True)\n`\nThis creates a publicly accessible share link (which looks like: https://xxxxx.gradio.live) to your Gradio application immediately, letting you share your app with anyone (while keeping the code and model running in your local environment). The link is created on Gradio's share server, which does not host your Gradio app, but instead creates a tunnel to your locally-running Gradio app. \nThis is particlarly useful when you are prototyping and want to get immediate feedback on your machine learning app, without having to deal with the hassle of hosting or deploying your application.\n  \nAt any given time, more than 5,000 Gradio apps are being shared through share links. But how is this link created, and how can you create your own share server? Read on!\nFast Reverse Proxy (FRP)\nGradio share links are powered by Fast Reverse Proxy (FRP), an open-source tunneling solution. Here's how it works:\nWhen you create a Gradio app with share=True, the FRP Client is automatically downloaded to your local machine (if not already installed). This client establishes a secure TLS tunnel to Gradio's Share Server, which hosts the FRP Server component capable of handling thousands of simultaneous connections.\nOnce the tunnel is established, Gradio's Share Server exposes your locally-running application to the internet under a unique domain in the format xxxxx.gradio.live. This entire process happens in the background, when you launch a Gradio app with share=True.\nNext, we'll dive deeper into both the FRP Client and FRP Server, as they are used in Gradio.\nFRP Client\nWe use a modified version of the FRP Client, which runs on your machine. We package binaries for the most common operating systems, and the FRP Client for your system is downloaded the first time you create a share link on your machine.\nCode:\nThe complete Go code for the client can be found in this directory.\nWe use this Make script to package the Go code into binaries for each operating system.\nTroubleshooting: Some antivirus programs (notably Windows Defender) block the download of the FRP Client. In this case, you'll see a message with details on how to install the file manually, something like:\n`\nCould not create share link. Missing file: /Users/.../frpcdarwinarm64_v0.3. \nPlease check your internet connection. This can happen if your antivirus software blocks the download of this file. You can install manually by following these steps: \nDownload this file: https://cdn-media.huggingface.co/frpc-gradio-0.3/frpcdarwinarm64\nRename the downloaded file to: frpcdarwinarm64_v0.3\nMove the file to this location: /Users/...\n`\nIf this does not work, you may need to whitelist this file with your antivirus in order to use the share links.\nFRP Server\nGradio runs a share server, which is a modified version of the FRP server. This server handles the public-facing side of the tunnel, receiving incoming connections from the internet and routing them to the appropriate FRP client running on your local machine.\nThe official Gradio share server is hosted at gradio.live, and we make our best effort to keep it running reliably at all times. This is the server that's used by default when you set share=True` in your Gradio applications. You can check the current operational status of the official Gradio share server at https://status.gradio.app/. \nIf you prefer, you can also host your own FRP server. This gives you complete control over the tunneling infrastructure and can be useful for enterprise deployments or situations where you need custom domains or additional security measures, or if you want to avoid the 72 hour timeout that is in place for links created through Gradio's official share server. Here are the instructions for running your own Gradio Share Server.\nCode:\nThe complete Go code for the client can be found in this directory.\nThe Dockerfile to launch the FRP Server can be found here.\nTroubleshooting: Gradio's Share Server may occasionally go down, despite our best effort to keep it running. If the status page shows that the Gradio server is down, we'll work on fixing it, no need to create an issue!","type":"GUIDE"},{"title":"Using Docs Mcp","slug":"/guides/using-docs-mcp/","content":"Using the Gradio Docs MCP Server\nIn this guide, we will describe how to use the official Gradio Docs MCP Server.\nPrerequisites\nYou will need an LLM application that supports tool calling using the MCP protocol, such as Claude Desktop, Cursor, or Cline (these are known as \"MCP Clients\").\nWhy an MCP Server?\nIf you're using LLMs in your workflow, adding this server will augment them with just the right context on gradio - which makes your experience a lot faster and smoother. \n \nThe server is running on Spaces and was launched entirely using Gradio, you can see all the code here. For more on building an mcp server with gradio, see the previous guide. \nInstalling in the Clients \nFor clients that support streamable HTTP (e.g. Cursor, Windsurf, Cline), simply add the following configuration to your MCP config:\n``json\n{\n  \"mcpServers\": {\n    \"gradio\": {\n      \"url\": \"https://gradio-docs-mcp.hf.space/gradio_api/mcp/\"\n    }\n  }\n}\n`\nWe've included step-by-step instructions for Cursor below, but you can consult the docs for Windsurf here, and Cline here which are similar to set up. \nCursor \nMake sure you're using the latest version of Cursor, and go to Cursor > Settings > Cursor Settings > MCP \nClick on '+ Add new global MCP server' \nCopy paste this json into the file that opens and then save it. \n`json\n{\n  \"mcpServers\": {\n    \"gradio\": {\n      \"url\": \"https://gradio-docs-mcp.hf.space/gradio_api/mcp/\"\n    }\n  }\n}\n`\nThat's it! You should see the tools load and the status go green in the settings page. You may have to click the refresh icon or wait a few seconds. \nClaude Desktop\nSince Claude Desktop only supports stdio, you will need to install Node.js to get this to work. \nMake sure you're using the latest version of Claude Desktop, and go to Claude > Settings > Developer > Edit Config \nOpen the file with your favorite editor and copy paste this json, then save the file. \n`json\n{\n  \"mcpServers\": {\n    \"gradio\": {\n      \"command\": \"npx\",\n      \"args\": [\n        \"mcp-remote\",\n        \"https://gradio-docs-mcp.hf.space/gradio_api/mcp/\"\n      ]\n    }\n  }\n}\n`\nQuit and re-open Claude Desktop, and you should be good to go. You should see it loaded in the Search and Tools icon or on the developer settings page. \n \nTools \nThere are currently only two tools in the server: gradiodocsmcploadgradiodocs and gradiodocsmcpsearchgradiodocs. \ngradiodocsmcploadgradio_docs: This tool takes no arguments and will load an /llms.txt style summary of Gradio's latest, full documentation. Very useful context the LLM can parse before answering questions or generating code. \ngradiodocsmcpsearchgradio_docs`: This tool takes a query as an argument and will run embedding search on Gradio's docs, guides, and demos to return the most useful context for the LLM to parse.","type":"GUIDE"},{"title":"Using Flagging","slug":"/guides/using-flagging/","content":"Using Flagging\nIntroduction\nWhen you demo a machine learning model, you might want to collect data from users who try the model, particularly data points in which the model is not behaving as expected. Capturing these \"hard\" data points is valuable because it allows you to improve your machine learning model and make it more reliable and robust.\nGradio simplifies the collection of this data by including a Flag button with every Interface. This allows a user or tester to easily send data back to the machine where the demo is running. In this Guide, we discuss more about how to use the flagging feature, both with gradio.Interface as well as with gradio.Blocks.\nThe Flag button in gradio.Interface\nFlagging with Gradio's Interface is especially easy. By default, underneath the output components, there is a button marked Flag. When a user testing your model sees input with interesting output, they can click the flag button to send the input and output data back to the machine where the demo is running. The sample is saved to a CSV log file (by default). If the demo involves images, audio, video, or other types of files, these are saved separately in a parallel directory and the paths to these files are saved in the CSV file.\nThere are four parameters in gradio.Interface that control how flagging works. We will go over them in greater detail.\nflagging_mode: this parameter can be set to either \"manual\" (default), \"auto\", or \"never\".\nmanual: users will see a button to flag, and samples are only flagged when the button is clicked.\nauto: users will not see a button to flag, but every sample will be flagged automatically.\nnever: users will not see a button to flag, and no sample will be flagged.\nflagging_options: this parameter can be either None (default) or a list of strings.\nIf None, then the user simply clicks on the Flag button and no additional options are shown.\nIf a list of strings are provided, then the user sees several buttons, corresponding to each of the strings that are provided. For example, if the value of this parameter is [\"Incorrect\", \"Ambiguous\"], then buttons labeled Flag as Incorrect and Flag as Ambiguous appear. This only applies if flagging_mode is \"manual\".\nThe chosen option is then logged along with the input and output.\nflagging_dir: this parameter takes a string.\nIt represents what to name the directory where flagged data is stored.\nflagging_callback: this parameter takes an instance of a subclass of the FlaggingCallback class\nUsing this parameter allows you to write custom code that gets run when the flag button is clicked\nBy default, this is set to an instance of gr.JSONLogger\nWhat happens to flagged data?\nWithin the directory provided by the flagging_dir argument, a JSON file will log the flagged data.\nHere's an example: The code below creates the calculator interface embedded below it:\n``python\nimport gradio as gr\ndef calculator(num1, operation, num2):\n    if operation == \"add\":\n        return num1 + num2\n    elif operation == \"subtract\":\n        return num1 - num2\n    elif operation == \"multiply\":\n        return num1 * num2\n    elif operation == \"divide\":\n        return num1 / num2\niface = gr.Interface(\n    calculator,\n    [\"number\", gr.Radio([\"add\", \"subtract\", \"multiply\", \"divide\"]), \"number\"],\n    \"number\",\n    flagging_mode=\"manual\"\n)\niface.launch()\n`\nWhen you click the flag button above, the directory where the interface was launched will include a new flagged subfolder, with a csv file inside it. This csv file includes all the data that was flagged.\n`directory\n+-- flagged/\n|   +-- logs.csv\n`\nflagged/logs.csv\n`csv\nnum1,operation,num2,Output,timestamp\n5,add,7,12,2022-01-31 11:40:51.093412\n6,subtract,1.5,4.5,2022-01-31 03:25:32.023542\n`\nIf the interface involves file data, such as for Image and Audio components, folders will be created to store those flagged data as well. For example an image input to image output interface will create the following structure.\n`directory\n+-- flagged/\n|   +-- logs.csv\n|   +-- image/\n|   |   +-- 0.png\n|   |   +-- 1.png\n|   +-- Output/\n|   |   +-- 0.png\n|   |   +-- 1.png\n`\nflagged/logs.csv\n`csv\nim,Output timestamp\nim/0.png,Output/0.png,2022-02-04 19:49:58.026963\nim/1.png,Output/1.png,2022-02-02 10:40:51.093412\n`\nIf you wish for the user to provide a reason for flagging, you can pass a list of strings to the flagging_options argument of Interface. Users will have to select one of these choices when flagging, and the option will be saved as an additional column to the CSV.\nIf we go back to the calculator example, the following code will create the interface embedded below it.\n`python\niface = gr.Interface(\n    calculator,\n    [\"number\", gr.Radio([\"add\", \"subtract\", \"multiply\", \"divide\"]), \"number\"],\n    \"number\",\n    flagging_mode=\"manual\",\n    flagging_options=[\"wrong sign\", \"off by one\", \"other\"]\n)\niface.launch()\n`\nWhen users click the flag button, the csv file will now include a column indicating the selected option.\nflagged/logs.csv\n`csv\nnum1,operation,num2,Output,flag,timestamp\n5,add,7,-12,wrong sign,2022-02-04 11:40:51.093412\n6,subtract,1.5,3.5,off by one,2022-02-04 11:42:32.062512\n`\nFlagging with Blocks\nWhat about if you are using gradio.Blocks? On one hand, you have even more flexibility\nwith Blocks -- you can write whatever Python code you want to run when a button is clicked,\nand assign that using the built-in events in Blocks.\nAt the same time, you might want to use an existing FlaggingCallback to avoid writing extra code.\nThis requires two steps:\nYou have to run your callback's .setup() somewhere in the code prior to the\n   first time you flag data\nWhen the flagging button is clicked, then you trigger the callback's .flag() method,\n   making sure to collect the arguments correctly and disabling the typical preprocessing.\nHere is an example with an image sepia filter Blocks demo that lets you flag\ndata using the default CSVLogger:\n`python\nimport numpy as np\nimport gradio as gr\ndef sepia(input_img, strength):\n    sepia_filter = strength * np.array(\n        [[0.393, 0.769, 0.189], [0.349, 0.686, 0.168], [0.272, 0.534, 0.131]]\n    ) + (1-strength) * np.identity(3)\n    sepiaimg = inputimg.dot(sepia_filter.T)\n    sepiaimg /= sepiaimg.max()\n    return sepia_img\ncallback = gr.CSVLogger()\nwith gr.Blocks() as demo:\n    with gr.Row():\n        with gr.Column():\n            img_input = gr.Image()\n            strength = gr.Slider(0, 1, 0.5)\n        img_output = gr.Image()\n    with gr.Row():\n        btn = gr.Button(\"Flag\")\n    # This needs to be called at some point prior to the first call to callback.flag()\n    callback.setup([imginput, strength, imgoutput], \"flaggeddatapoints\")\n    imginput.change(sepia, [imginput, strength], img_output)\n    strength.change(sepia, [imginput, strength], imgoutput)\n    # We can choose which components to flag -- in this case, we'll flag all of them\n    btn.click(lambda *args: callback.flag(list(args)), [imginput, strength, imgoutput], None, preprocess=False)\ndemo.launch()\n`\nPrivacy\nImportant Note: please make sure your users understand when the data they submit is being saved, and what you plan on doing with it. This is especially important when you use flagging_mode=auto` (when all of the data submitted through the demo is being flagged)\nThat's all! Happy building :)","type":"GUIDE"},{"title":"Using Gradio For Tabular Workflows","slug":"/guides/using-gradio-for-tabular-workflows/","content":"Using Gradio for Tabular Data Science Workflows\nIntroduction\nTabular data science is the most widely used domain of machine learning, with problems ranging from customer segmentation to churn prediction. Throughout various stages of the tabular data science workflow, communicating your work to stakeholders or clients can be cumbersome; which prevents data scientists from focusing on what matters, such as data analysis and model building. Data scientists can end up spending hours building a dashboard that takes in dataframe and returning plots, or returning a prediction or plot of clusters in a dataset. In this guide, we'll go through how to use gradio to improve your data science workflows. We will also talk about how to use gradio and skops to build interfaces with only one line of code!\nPrerequisites\nMake sure you have the gradio Python package already installed.\nLet's Create a Simple Interface!\nWe will take a look at how we can create a simple UI that predicts failures based on product information.\n``python\nimport gradio as gr\nimport pandas as pd\nimport joblib\nimport datasets\ninputs = [gr.Dataframe(rowcount = (2, \"dynamic\"), colcount=(4,\"dynamic\"), label=\"Input Data\", interactive=1)]\noutputs = [gr.Dataframe(rowcount = (2, \"dynamic\"), colcount=(1, \"fixed\"), label=\"Predictions\", headers=[\"Failures\"])]\nmodel = joblib.load(\"model.pkl\")\nwe will give our dataframe as example\ndf = datasets.load_dataset(\"merve/supersoaker-failures\")\ndf = df[\"train\"].to_pandas()\ndef infer(input_dataframe):\n  return pd.DataFrame(model.predict(input_dataframe))\ngr.Interface(fn = infer, inputs = inputs, outputs = outputs, examples = [[df.head(2)]]).launch()\n`\nLet's break down above code.\nfn: the inference function that takes input dataframe and returns predictions.\ninputs: the component we take our input with. We define our input as dataframe with 2 rows and 4 columns, which initially will look like an empty dataframe with the aforementioned shape. When the row_count is set to dynamic, you don't have to rely on the dataset you're inputting to pre-defined component.\noutputs: The dataframe component that stores outputs. This UI can take single or multiple samples to infer, and returns 0 or 1 for each sample in one column, so we give rowcount as 2 and colcount as 1 above. headers is a list made of header names for dataframe.\nexamples: You can either pass the input by dragging and dropping a CSV file, or a pandas DataFrame through examples, which headers will be automatically taken by the interface.\nWe will now create an example for a minimal data visualization dashboard. You can find a more comprehensive version in the related Spaces.\n`python\nimport gradio as gr\nimport pandas as pd\nimport datasets\nimport seaborn as sns\nimport matplotlib.pyplot as plt\ndf = datasets.load_dataset(\"merve/supersoaker-failures\")\ndf = df[\"train\"].to_pandas()\ndf.dropna(axis=0, inplace=True)\ndef plot(df):\n  plt.scatter(df.measurement13, df.measurement15, c = df.loading,alpha=0.5)\n  plt.savefig(\"scatter.png\")\n  df['failure'].value_counts().plot(kind='bar')\n  plt.savefig(\"bar.png\")\n  sns.heatmap(df.select_dtypes(include=\"number\").corr())\n  plt.savefig(\"corr.png\")\n  plots = [\"corr.png\",\"scatter.png\", \"bar.png\"]\n  return plots\ninputs = [gr.Dataframe(label=\"Supersoaker Production Data\")]\noutputs = [gr.Gallery(label=\"Profiling Dashboard\", columns=(1,3))]\ngr.Interface(plot, inputs=inputs, outputs=outputs, examples=[df.head(100)], title=\"Supersoaker Failures Analysis Dashboard\").launch()\n`\nWe will use the same dataset we used to train our model, but we will make a dashboard to visualize it this time.\nfn: The function that will create plots based on data.\ninputs: We use the same Dataframe component we used above.\noutputs: The Gallery component is used to keep our visualizations.\nexamples: We will have the dataset itself as the example.\nEasily load tabular data interfaces with one line of code using skops\nskops is a library built on top of huggingface_hub and sklearn. With the recent gradio integration of skops, you can build tabular data interfaces with one line of code!\n`python\nimport gradio as gr\ntitle and description are optional\ntitle = \"Supersoaker Defective Product Prediction\"\ndescription = \"This model predicts Supersoaker production line failures. Drag and drop any slice from dataset or edit values as you wish in below dataframe component.\"\ngr.load(\"huggingface/scikit-learn/tabular-playground\", title=title, description=description).launch()\n`\nsklearn models pushed to Hugging Face Hub using skops include a config.json file that contains an example input with column names, the task being solved (that can either be tabular-classification or tabular-regression). From the task type, gradio constructs the Interface and consumes column names and the example input to build it. You can refer to skops documentation on hosting models on Hub to learn how to push your models to Hub using skops`.","type":"GUIDE"},{"title":"Using Gradio In Other Programming Languages","slug":"/guides/using-gradio-in-other-programming-languages/","content":"Using Gradio in Other Programming Languages\nThe core gradio library is a Python library. But you can also use gradio to create UIs around programs written in other languages, thanks to Python's ability to interface with external processes. Using Python's subprocess module, you can call programs written in C++, Rust, or virtually any other language, allowing gradio to become a flexible UI layer for non-Python applications.\nIn this post, we'll walk through how to integrate gradio with C++ and Rust, using Python's subprocess module to invoke code written in these languages. We'll also discuss how to use Gradio with R, which is even easier, thanks to the reticulate R package, which makes it possible to install and import Python modules in R.\nUsing Gradio with C++\nLet’s start with a simple example of integrating a C++ program into a Gradio app. Suppose we have the following C++ program that adds two numbers:\n``cpp\n// add.cpp\n#include \nint main() {\n    double a, b;\n    std::cin >> a >> b;\n    std::cout  = std::env::args().collect();\n    if args.len() != 3 {\n        eprintln!(\"Usage: sepia  \");\n        return;\n    }\n    sepia_filter(&args[1], &args[2]);\n}\n`\nThis Rust program applies a sepia filter to an image. It takes two command-line arguments: the input image path and the output image path. You can compile this program using:\n`bash\ncargo build --release\n`\nNow, we can call this Rust program from Python and use Gradio to build the interface:\n`python\nimport gradio as gr\nimport subprocess\ndef applysepia(inputpath):\n    output_path = \"output.png\"\n    \n    process = subprocess.Popen(\n        ['./target/release/sepia', inputpath, outputpath], \n        stdout=subprocess.PIPE, \n        stderr=subprocess.PIPE\n    )\n    process.wait()\n    \n    return output_path\ndemo = gr.Interface(\n    fn=apply_sepia, \n    inputs=gr.Image(type=\"filepath\", label=\"Input Image\"), \n    outputs=gr.Image(label=\"Sepia Image\")\n)\ndemo.launch()\n`\nHere, when a user uploads an image and clicks submit, Gradio calls the Rust binary (sepia) to process the image, and returns the sepia-filtered output to Gradio.\nThis setup showcases how you can integrate performance-critical or specialized code written in Rust into a Gradio interface.\nUsing Gradio with R (via reticulate)\nIntegrating Gradio with R is particularly straightforward thanks to the reticulate package, which allows you to run Python code directly in R. Let’s walk through an example of using Gradio in R. \nInstallation\nFirst, you need to install the reticulate package in R:\n`r\ninstall.packages(\"reticulate\")\n`\nOnce installed, you can use the package to run Gradio directly from within an R script.\n``r\nlibrary(reticulate)\npy_install(\"gradio\", pip = TRUE)\ngr","type":"GUIDE"},{"title":"Using Hugging Face Integrations","slug":"/guides/using-hugging-face-integrations/","content":"Using Hugging Face Integrations\nIntroduction\nThe Hugging Face Hub is a central platform that has hundreds of thousands of models, datasets and demos (also known as Spaces). \nGradio has multiple features that make it extremely easy to leverage existing models and Spaces on the Hub. This guide walks through these features.\nDemos with the Hugging Face Inference Endpoints\nHugging Face has a service called Serverless Inference Endpoints, which allows you to send HTTP requests to models on the Hub. The API includes a generous free tier, and you can switch to dedicated Inference Endpoints when you want to use it in production. Gradio integrates directly with Serverless Inference Endpoints so that you can create a demo simply by specifying a model's name (e.g. Helsinki-NLP/opus-mt-en-es), like this:\n``python\nimport gradio as gr\ndemo = gr.load(\"Helsinki-NLP/opus-mt-en-es\", src=\"models\")\ndemo.launch()\n`\nFor any Hugging Face model supported in Inference Endpoints, Gradio automatically infers the expected input and output and make the underlying server calls, so you don't have to worry about defining the prediction function. \nNotice that we just put specify the model name and state that the src should be models (Hugging Face's Model Hub). There is no need to install any dependencies (except gradio) since you are not loading the model on your computer.\nYou might notice that the first inference takes a little bit longer. This happens since the Inference Endpoints is loading the model in the server. You get some benefits afterward:\nThe inference will be much faster.\nThe server caches your requests.\nYou get built-in automatic scaling.\nHosting your Gradio demos on Spaces\nHugging Face Spaces allows anyone to host their Gradio demos freely, and uploading your Gradio demos take a couple of minutes. You can head to hf.co/new-space, select the Gradio SDK, create an app.py file, and voila! You have a demo you can share with anyone else. To learn more, read this guide how to host on Hugging Face Spaces using the website.\nAlternatively, you can create a Space programmatically, making use of the huggingfacehub client library library. Here's an example:\n`python\nfrom huggingface_hub import (\n    create_repo,\n    getfullrepo_name,\n    upload_file,\n)\ncreaterepo(name=targetspacename, token=hftoken, repotype=\"space\", spacesdk=\"gradio\")\nreponame = getfullreponame(modelid=targetspacename, token=hftoken)\nfileurl = uploadfile(\n    pathorfileobj=\"file.txt\",\n    pathinrepo=\"app.py\",\n    repoid=reponame,\n    repo_type=\"space\",\n    token=hf_token,\n)\n`\nHere, createrepo creates a gradio repo with the target name under a specific account using that account's Write Token. reponame gets the full repo name of the related repo. Finally upload_file uploads a file inside the repo with the name app.py.\nLoading demos from Spaces\nYou can also use and remix existing Gradio demos on Hugging Face Spaces. For example, you could take two existing Gradio demos on Spaces and put them as separate tabs and create a new demo. You can run this new demo locally, or upload it to Spaces, allowing endless possibilities to remix and create new demos!\nHere's an example that does exactly that:\n`python\nimport gradio as gr\nwith gr.Blocks() as demo:\n  with gr.Tab(\"Translate to Spanish\"):\n    gr.load(\"gradio/en2es\", src=\"spaces\")\n  with gr.Tab(\"Translate to French\"):\n    gr.load(\"abidlabs/en2fr\", src=\"spaces\")\ndemo.launch()\n`\nNotice that we use gr.load(), the same method we used to load models using Inference Endpoints. However, here we specify that the src is spaces (Hugging Face Spaces). \nNote: loading a Space in this way may result in slight differences from the original Space. In particular, any attributes that apply to the entire Blocks, such as the theme or custom CSS/JS, will not be loaded. You can copy these properties from the Space you are loading into your own Blocks object. \nDemos with the Pipeline in transformers\nHugging Face's popular transformers library has a very easy-to-use abstraction, pipeline() that handles most of the complex code to offer a simple API for common tasks. By specifying the task and an (optional) model, you can build a demo around an existing model with few lines of Python:\n`python\nimport gradio as gr\nfrom transformers import pipeline\npipe = pipeline(\"translation\", model=\"Helsinki-NLP/opus-mt-en-es\")\ndef predict(text):\n  return pipe(text)[0][\"translation_text\"]\ndemo = gr.Interface(\n  fn=predict,\n  inputs='text',\n  outputs='text',\n)\ndemo.launch()\n`\nBut gradio actually makes it even easier to convert a pipeline to a demo, simply by using the gradio.Interface.from_pipeline methods, which skips the need to specify the input and output components:\n`python\nfrom transformers import pipeline\nimport gradio as gr\npipe = pipeline(\"translation\", model=\"Helsinki-NLP/opus-mt-en-es\")\ndemo = gr.Interface.from_pipeline(pipe)\ndemo.launch()\n`\nThe previous code produces the following interface, which you can try right here in your browser:\nRecap\nThat's it! Let's recap the various ways Gradio and Hugging Face work together:\nYou can build a demo around Inference Endpoints without having to load the model, by using gr.load().\nYou host your Gradio demo on Hugging Face Spaces, either using the GUI or entirely in Python.\nYou can load demos from Hugging Face Spaces to remix and create new Gradio demos using gr.load().\nYou can convert a transformers pipeline into a Gradio demo using from_pipeline()`.\n🤗","type":"GUIDE"},{"title":"View Api Page","slug":"/guides/view-api-page/","content":"API Page\nYou can use almost any Gradio app programmatically via the built-in API! In the footer of any Gradio app, you'll see a \"Use via API\" link. Clicking on the link opens up a detailed documentation page for the API that Gradio generates based on the function signatures in your Gradio app.\nConfiguring the API Page\nAPI endpoint names\nWhen you create a Gradio application, the API endpoint names are automatically generated based on the function names. You can change this by using the api_name parameter in gr.Interface or gr.ChatInterface. If you are using Gradio Blocks, you can name each event listener, like this:\n``python\nbtn.click(add, [num1, num2], output, api_name=\"addition\")\n`\nControlling API endpoint visibility\nWhen building a complex Gradio app, you might want to control how API endpoints appear or behave. Use the api_visibility parameter in any Blocks event listener to control this:\n\"public\" (default): The endpoint is shown in API docs and accessible to all\n\"undocumented\": The endpoint is hidden from API docs but still accessible to downstream apps\n\"private\": The endpoint is hidden from API docs and not callable by the Gradio client libraries (e.g. gradio_client or @gradio/client). Note: this does not block direct HTTP requests to the endpoint — it should not be relied upon as a security measure.\nTo hide an API endpoint from the documentation while still allowing programmatic access:\n`python\nbtn.click(add, [num1, num2], output, api_visibility=\"undocumented\")\n`\nHiding endpoints from client libraries\nIf you want to hide an API endpoint from the API docs and prevent it from being called by the Gradio client libraries, set api_visibility=\"private\":\n`python\nbtn.click(add, [num1, num2], output, api_visibility=\"private\")\n`\nNote: setting api_visibility=\"private\" also means that downstream apps will not be able to load your Gradio app using gr.load() as this function uses the Gradio API under the hood. However, the underlying HTTP endpoint is still accessible — this setting should not be relied upon for security.\nAdding API endpoints\nYou can also add new API routes to your Gradio application that do not correspond to events in your UI.\nFor example, in this Gradio application, we add a new route that adds numbers and slices a list:\n`py\nimport gradio as gr\nwith gr.Blocks() as demo:\n    with gr.Row():\n        input = gr.Textbox()\n        button = gr.Button(\"Submit\")\n    output = gr.Textbox()\n    def fn(a: int, b: int, c: list[str]) -> tuple[int, str]:\n        return a + b, c[a:b]\n    gr.api(fn, apiname=\"addand_slice\")\n, url,  = demo.launch()\n`\nThis will create a new route /addandslice which will show up in the \"view API\" page. It can be programmatically called by the Python or JS Clients (discussed below) like this:\n`py\nfrom gradio_client import Client\nclient = Client(url)\nresult = client.predict(\n        a=3,\n        b=5,\n        c=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],\n        apiname=\"/addand_slice\"\n)\nprint(result)\n`\nThe Clients\nThis API page not only lists all of the endpoints that can be used to query the Gradio app, but also shows the usage of both the Gradio Python client, and the Gradio JavaScript client. \nFor each endpoint, Gradio automatically generates a complete code snippet with the parameters and their types, as well as example inputs, allowing you to immediately test an endpoint. Here's an example showing an image file input and str output:\nThe API Recorder 🪄\nInstead of reading through the view API page, you can also use Gradio's built-in API recorder to generate the relevant code snippet. Simply click on the \"API Recorder\" button, use your Gradio app via the UI as you would normally, and then the API Recorder will generate the code using the Clients to recreate your all of your interactions programmatically.\nRun History\nNext to the \"Use via API\" link, the footer has a Runs link, which opens a page at /gradio_api/runs listing the runs made from this browser, grouped by endpoint. Each run shows its inputs, its outputs, how long the function took, and whether it succeeded. Clicking Load run puts a saved run's values back onto the page without calling the function again, which is a quick way to get back to an input you liked or to compare two results side by side.\nThe run history covers the same endpoints as this API page. An event listener with api_visibility=\"undocumented\" or \"private\" is not recorded, and neither is anything Gradio wires up on your behalf, such as loading an example.\nBy default, runs are saved in the browser's local storage and are never sent to the server, so each visitor only sees their own. If your app uses auth, this browser history is also scoped to the logged-in user. The most recent 100 browser runs are kept per running app.\nThe History storage control on this page can instead connect a private Hugging Face bucket. After connecting, future runs are stored in that bucket and can be opened from any browser that has access to it. Existing browser runs are not migrated, and switching back to This browser shows them again. On Spaces this requires Hugging Face OAuth; when running directly on localhost, Gradio uses the token from hf auth login. Bucket records are also scoped to the current app instance, because restarting an app may change its endpoints or input and output schemas.\nValues held in gr.State live on the server, so they are neither shown nor restored from either storage destination.\nThe link appears once the browser has saved its first run. To hide the link but keep recording, list the footer links you do want:\n`py\ndemo.launch(footer_links=[\"api\", \"gradio\", \"settings\"])\n`\nTo turn the feature off completely, set run_history=False. Nothing is recorded, the run history page returns a 404, and any runs this app had already saved are cleared from the browser the next time someone opens it:\n`py\ndemo.launch(run_history=False)\n`\nThis can also be set with the GRADIORUNHISTORY environment variable, which is handy for a Space whose code you would rather not edit.\nRuns made through the clients\nCalls made with the JavaScript client are recorded in the same way whenever that client runs in a browser, which is how a gr.Server app builds up a run history despite having no UI of its own. Pass record_history: false to opt a single client out:\n`js\nconst app = await Client.connect(\"abidlabs/my-app\", { record_history: false });\n`\nNothing is recorded when the JavaScript client runs in Node, since there is no browser-selected history destination, and the Python client does not record runs at all. run_history=False on the app takes precedence over either client.\nMCP Server\nThe API page also includes instructions on how to use the Gradio app as an Model Context Protocol (MCP) server, which is a standardized way to expose functions as tools so that they can be used by LLMs. \nFor the MCP sever, each tool, its description, and its parameters are listed, along with instructions on how to integrate with popular MCP Clients. Read more about Gradio's MCP integration here.\nOpenAPI Specification\nYou can access the complete OpenAPI (formerly Swagger) specification of your Gradio app's API at the endpoint /gradio_api/openapi.json`. The OpenAPI specification is a standardized, language-agnostic interface description for REST APIs that enables both humans and computers to discover and understand the capabilities of your service.","type":"GUIDE"},{"title":"Workflows","slug":"/guides/workflows/","content":"gr.Workflow\ngr.Workflow is a visual, node-based AI pipeline builder built into Gradio. It lets you chain together Hugging Face Spaces, models, datasets, and your own Python functions on a drag-and-drop canvas:\nQuickstart\nThe simplest possible Workflow app:\n``python\nimport gradio as gr\ngr.Workflow().launch()\n`\nOpen the app, drag Spaces, models, and datasets from the sidebar onto the canvas, connect their ports, and hit Run. As you add, remove, or change nodes and edges, a workflow.json file will automatically be created next to the Python script that created the Workflow. Pass graph= if you want to save it somewhere else. You can also use a coding agent to write or edit this file, allowing you to create workflows programmatically.\ngr.Workflow is already a complete Gradio app and must be created at the top level. It cannot be nested inside a gr.Blocks context.\nWhen running locally, launch() prints a private write-access URL. Open that URL to edit and save the workflow; the ordinary local URL and share URL are run-only. Keep the write-access URL private because edits affect the workflow seen by every visitor.\nBinding Python functions\nPass your own Python functions via bind= and they appear as callable nodes on the canvas. Gradio inspects the function signature to auto-generate input/output ports.\n`python\nimport gradio as gr\ndef summarize(text: str) -> str:\n    return text[:200]\ngr.Workflow(bind=[summarize]).launch()\n`\nUse a dict to give nodes explicit names:\n`python\ngr.Workflow(bind={\"My Summarizer\": summarize}).launch()\n`\nSignature inference is intentionally simple. Parameters annotated as int or float become number ports, bool becomes boolean, and strings, unannotated parameters, and other annotations default to text. Gradio initially generates one output port for each bound function. For media ports or multiple outputs, define the function node's ports explicitly in the workflow JSON.\nDefining edges in code\nFor pipelines you want to ship with a fixed topology, declare edges programmatically:\n`python\nimport gradio as gr\ndef clean(text: str) -> str:\n    return text.strip().lower()\ndef tag(text: str) -> str:\n    return f\"[processed] {text}\"\ngr.Workflow(\n    bind=[clean, tag],\n    edges=[(\"clean\", \"tag\")],\n).launch()\n`\nEach edge is a (fromfn, tofn) tuple referring to functions in bind=. Use \"fnname.portlabel\" to target a specific port when a node has multiple inputs or outputs; otherwise, the first port is used. Ensure the connected ports have compatible types.\nNote: edges= only connects bound Python functions while generating a new workflow. It cannot create edges to Space, model, or dataset nodes, and it is ignored when the workflow file already exists. Delete the file to regenerate the initial topology from bind and edges.\nLoading from a JSON file\nPass a graph= path to load a saved workflow topology. The canvas reads from the file on each page load and autosaves back to it when you add, remove, or change nodes and edges.\n`python\ngr.Workflow(graph=\"workflow.json\").launch()\n`\nIf the file doesn't exist yet, it's created on the first authorized edit. bind= does not automatically add or wire functions into an existing graph. To combine an existing graph with bound functions, either add the functions from the canvas's Functions menu or include an operator with \"kind\": \"fn\" whose \"fn\" value exactly matches a key in bind.\nWorkflow JSON format\nA workflow is a JSON file with three node collections:\n`json\n{\n  \"schema_version\": \"2\",\n  \"name\": \"My Pipeline\",\n  \"references\": [\n    {\n      \"id\": \"ref_prompt\", \"label\": \"Prompt\", \"role\": \"reference\",\n      \"asset_type\": \"text\",\n      \"inputs\":  [{\"id\": \"in\", \"label\": \"Text\", \"type\": \"text\"}],\n      \"outputs\": [{\"id\": \"out\", \"label\": \"Text\", \"type\": \"text\"}]\n    }\n  ],\n  \"operators\": [\n    {\n      \"id\": \"op_flux\", \"label\": \"FLUX.1\", \"role\": \"operator\",\n      \"kind\": \"model\",\n      \"model_id\": \"black-forest-labs/FLUX.1-schnell\",\n      \"endpoint\": \"texttoimage\",\n      \"pipeline_tag\": \"text-to-image\",\n      \"inputs\":  [{\"id\": \"prompt\", \"label\": \"Prompt\", \"type\": \"text\", \"required\": true}],\n      \"outputs\": [{\"id\": \"out0\", \"label\": \"Image\", \"type\": \"image\", \"outputindex\": 0}]\n    }\n  ],\n  \"subjects\": [\n    {\n      \"id\": \"sub_img\", \"label\": \"Output Image\", \"role\": \"subject\",\n      \"asset_type\": \"image\",\n      \"inputs\":  [{\"id\": \"in\", \"label\": \"Image\", \"type\": \"image\"}],\n      \"outputs\": [{\"id\": \"out\", \"label\": \"Image\", \"type\": \"image\"}]\n    }\n  ],\n  \"edges\": [\n    {\n      \"id\": \"e1\",\n      \"fromnodeid\": \"refprompt\", \"fromport_id\": \"out\",\n      \"tonodeid\":   \"opflux\",    \"toport_id\":   \"prompt\",\n      \"type\": \"text\"\n    },\n    {\n      \"id\": \"e2\",\n      \"fromnodeid\": \"opflux\", \"fromportid\": \"out0\",\n      \"tonodeid\":   \"subimg\", \"toport_id\":   \"in\",\n      \"type\": \"image\"\n    }\n  ]\n}\n`\nNode data may be omitted, and so may geometry. Include x and y on every node to control how the graph is arranged when someone opens it for the first time; leave them out and the canvas auto-arranges it. Either way the arrangement is only a starting point: each visitor is free to drag and resize cards, that arrangement is saved in their own browser rather than in the file, and workflow.json is never rewritten with it. height is measured from the rendered card. width is the default every viewer starts from — anyone can resize a card locally, and a writer's resize becomes the new default the next time an edit is saved.\n| Collection | Role |\n|---|---|\n| references | Inputs — uploaded files, editable text, literal values |\n| operators | Processing steps — Spaces, models, datasets, Python functions |\n| subjects | Outputs — the results being created |\nOperator kinds\n| kind | What it calls |\n|---|---|\n| \"space\" | A Gradio Space on the Hub via gradioclient; set spaceid and endpoint |\n| \"model\" | A Hugging Face model via InferenceClient; set modelid and a supported endpoint such as texttoimage. pipelinetag is also stored for discovery and compatibility with older graphs |\n| \"dataset\" | One row from a Hub dataset per run, selected by the rowindex input; set datasetid, datasetconfig, and datasetsplit |\n| \"fn\" | A Python function whose fn value matches a key passed via bind= |\nPort types\nPorts are typed so the canvas can validate connections. Supported types:\nimage · audio · video · text · number · boolean · gallery · file · json · model3d · any\nany is a compatibility fallback that can connect to every port type. file and any usually come from API schema inference and are not offered as reference or subject templates in the canvas picker.\nFan-out pipelines\nOne reference can feed multiple operators simultaneously. When you run the workflow in the interactive canvas, operators at the same dependency depth run in parallel:\n`python\nworkflow.json excerpt — one product photo → 4 FLUX Kontext branches\n\"edges\": [\n  {\"fromnodeid\": \"refproduct\", ..., \"tonodeid\": \"opkontext_0\", ...},\n  {\"fromnodeid\": \"refproduct\", ..., \"tonodeid\": \"opkontext_1\", ...},\n  {\"fromnodeid\": \"refproduct\", ..., \"tonodeid\": \"opkontext_2\", ...},\n  {\"fromnodeid\": \"refproduct\", ..., \"tonodeid\": \"opkontext_3\", ...}\n]\n`\nWhen the same workflow is invoked through its generated Gradio API, the server currently executes these branches sequentially.\nDeploying to Spaces\nA Workflow app is a standard Gradio app — deploy it to Hugging Face Spaces exactly like any other, by uploading the code to a Space, or by simply running in your terminal:\n`\ngradio deploy\n`\nSet hf_oauth: true in your Space so the owner can authenticate for editing. The owning user, or an organization member with write or admin access, can edit and save the workflow. Other visitors get a read-only canvas and can run the pipeline using their OAuth identity or a Hugging Face access token. Without OAuth enabled, the Space cannot identify its owner, so the deployed workflow remains run-only.\nAPI access\nEvery Workflow app is a Gradio app, meaning that it exposes its connected pipelines through the standard Gradio REST API. Each disconnected pipeline containing one or more output (subject) nodes gets one endpoint. Its name is derived from the first subject's label — for example, a pipeline whose first subject is labelled \"Output Image\" becomes /output_image.\nUncomputed reference nodes feeding that pipeline become the endpoint's parameters. If the pipeline has multiple subjects, the endpoint returns all of them in subject declaration order rather than creating one endpoint per subject. Use client.view_api() to see the exact endpoint names, parameters, and return values:\n`python\nfrom gradio_client import Client\nclient = Client(\"your-username/my-workflow\")\nclient.view_api()  # lists available endpoints and their parameters\nresult = client.predict(\"a sunset over mountains\", apiname=\"/outputimage\")\n``\nThis also means that you can reuse your workflows within larger workflows, making it possible to build modular and complex applications with Gradio Workflows!","type":"GUIDE"},{"title":"Wrapping Layouts","slug":"/guides/wrapping-layouts/","content":"Wrapping Layouts\nIntroduction\nGradio features blocks to easily layout applications. To use this feature, you need to stack or nest layout components and create a hierarchy with them. This isn't difficult to implement and maintain for small projects, but after the project gets more complex, this component hierarchy becomes difficult to maintain and reuse.\nIn this guide, we are going to explore how we can wrap the layout classes to create more maintainable and easy-to-read applications without sacrificing flexibility.\nExample\nWe are going to follow the implementation from this Huggingface Space example:\nImplementation\nThe wrapping utility has two important classes. The first one is the ``LayoutBase` class and the other one is the `Application` class.\nWe are going to look at the `render` and `attach_event` functions of them for brevity. You can look at the full implementation from the example code.\nSo let's start with the `LayoutBase` class.\nLayoutBase Class\nRender Function\n    Let's look at the `render` function in the `LayoutBase` class:\n`python\nother LayoutBase implementations\ndef render(self) -> None:\n    with self.main_layout:\n        for renderable in self.renderables:\n            renderable.render()\n    self.main_layout.render()\n`\nThis is a little confusing at first but if you consider the default implementation you can understand it easily.\nLet's look at an example:\nIn the default implementation, this is what we're doing:\n`python\nwith Row():\n    lefttextbox = Textbox(value=\"lefttextbox\")\n    righttextbox = Textbox(value=\"righttextbox\")\n`\nNow, pay attention to the Textbox variables. These variables' `render` parameter is true by default. So as we use the `with` syntax and create these variables, they are calling the `render` function under the `with` syntax.\nWe know the render function is called in the constructor with the implementation from the `gradio.blocks.Block` class:\n`python\nclass Block:\n    # constructor parameters are omitted for brevity\n    def init(self, ...):\n        # other assign functions \n        if render:\n            self.render()\n`\nSo our implementation looks like this:\n`python\nself.main_layout -> Row()\nwith self.main_layout:\n    left_textbox.render()\n    right_textbox.render()\n`\nWhat this means is by calling the components' render functions under the `with` syntax, we are actually simulating the default implementation.\nSo now let's consider two nested `with`s to see how the outer one works. For this, let's expand our example with the `Tab` component:\n`python\nwith Tab():\n    with Row():\n        firsttextbox = Textbox(value=\"firsttextbox\")\n        secondtextbox = Textbox(value=\"secondtextbox\")\n`\nPay attention to the Row and Tab components this time. We have created the Textbox variables above and added them to Row with the `with` syntax. Now we need to add the Row component to the Tab component. You can see that the Row component is created with default parameters, so its render parameter is true, that's why the render function is going to be executed under the Tab component's `with` syntax.\nTo mimic this implementation, we need to call the `render` function of the `mainlayout` variable after the `with` syntax of the `mainlayout` variable.\nSo the implementation looks like this:\n`python\nwith tabmainlayout:\n    with rowmainlayout:\n        first_textbox.render()\n        second_textbox.render()\n    rowmainlayout.render()\ntabmainlayout.render()\n`\nThe default implementation and our implementation are the same, but we are using the render function ourselves. So it requires a little work.\nNow, let's take a look at the `attach_event` function.\nAttach Event Function\n    The function is left as not implemented because it is specific to the class, so each class has to implement its attach_event function.\n`python\n    # other LayoutBase implementations\n    def attachevent(self, blockdict: Dict[str, Block]) -> None:\n        raise NotImplementedError\n`\nCheck out the `blockdict` variable in the `Application` class's `attachevent` function.\nApplication Class\nRender Function\n`python\n    # other Application implementations\n    def _render(self):\n        with self.app:\n            for child in self.children:\n                child.render()\n        self.app.render()\n`\nFrom the explanation of the `LayoutBase` class's `render` function, we can understand the `child.render` part.\nSo let's look at the bottom part, why are we calling the `app` variable's `render` function? It's important to call this function because if we look at the implementation in the `gradio.blocks.Blocks` class, we can see that it is adding the components and event functions into the root component. To put it another way, it is creating and structuring the gradio application.\nAttach Event Function\n    Let's see how we can attach events to components:\n`python\n    # other Application implementations\n    def attachevent(self):\n        block_dict: Dict[str, Block] = {}\n        for child in self.children:\n            blockdict.update(child.globalchildren_dict)\n        with self.app:\n            for child in self.children:\n                try:\n                    child.attachevent(blockdict=block_dict)\n                except NotImplementedError:\n                    print(f\"{child.name}'s attach_event is not implemented\")\n`\nYou can see why the `globalchildrenlist` is used in the `LayoutBase` class from the example code. With this, all the components in the application are gathered into one dictionary, so the component can access all the components with their names.\nThe `with` syntax is used here again to attach events to components. If we look at the `exit` function in the `gradio.blocks.Blocks` class, we can see that it is calling the `attachloadevents` function which is used for setting event triggers to components. So we have to use the `with` syntax to trigger the `exit` function.\nOf course, we can call `attachloadevents` without using the `with` syntax, but the function needs a `Context.root_block`, and it is set in the `enter` function. So we used the `with`` syntax here rather than calling the function ourselves.\nConclusion\nIn this guide, we saw\nHow we can wrap the layouts\nHow components are rendered\nHow we can structure our application with wrapped layout classes\nBecause the classes used in this guide are used for demonstration purposes, they may still not be totally optimized or modular. But that would make the guide much longer!\nI hope this guide helps you gain another view of the layout classes and gives you an idea about how you can use them for your needs. See the full implementation of our example here.","type":"GUIDE"},{"title":"JavaScript Client Library","slug":"/docs/js-client","content":"JavaScript Client Library\nInteract with Gradio APIs using our JavaScript (and TypeScript) client.\nInstallation\nThe Gradio JavaScript Client is available on npm as @gradio/client. You can install it as below:\n``shell\nnpm i @gradio/client\n`\nOr, you can include it directly in your HTML via the jsDelivr CDN:\n`html\n<script type=\"module\">\n\timport { Client } from \"https://cdn.jsdelivr.net/npm/@gradio/client/dist/index.min.js\";\n</script>\n`\nUsage\nThe JavaScript Gradio Client exposes the Client class, Client, along with various other utility functions. Client is used to initialise and establish a connection to, or duplicate, a Gradio app. \nClient\nThe Client function connects to the API of a hosted Gradio space and returns an object that allows you to make calls to that API.\nThe simplest example looks like this:\n`ts\nimport { Client } from \"@gradio/client\";\nconst app = await Client.connect(\"user/space-name\");\nconst result = await app.predict(\"/predict\");\n`\nThis function accepts two arguments: source and options:\nsource\nThis is the url or name of the gradio app whose API you wish to connect to. This parameter is required and should always be a string. For example:\n`ts\nClient.connect(\"user/space-name\");  \n`\noptions\nThe options object can optionally be passed a second parameter. This object has two properties, token and status_callback.\ntoken\nThis should be a Hugging Face personal access token and is required if you wish to make calls to a private gradio api. This option is optional and should be a string starting with \"hf_\".\nExample:\n`ts\nimport { Client } from \"@gradio/client\";\nconst app = await Client.connect(\"user/space-name\", { token: \"hf_...\" });\n`\nstatus_callback\nThis should be a function which will notify you of the status of a space if it is not running. If the gradio API you are connecting to is not awake and running or is not hosted on Hugging Face space then this function will do nothing.\nAdditional context\nApplications hosted on Hugging Face spaces can be in a number of different states. As spaces are a GitOps tool and will rebuild when new changes are pushed to the repository, they have various building, running and error states. If a space is not 'running' then the function passed as the status_callback will notify you of the current state of the space and the status of the space as it changes. Spaces that are building or sleeping can take longer than usual to respond, so you can use this information to give users feedback about the progress of their action.\n`ts\nimport { Client, type SpaceStatus } from \"@gradio/client\";\nconst app = await Client.connect(\"user/space-name\", {\n\t// The space_status parameter does not need to be manually annotated, this is just for illustration.\n\tspacestatus: (spacestatus: SpaceStatus) => console.log(space_status)\n});\n`\n`ts\ninterface SpaceStatusNormal {\n\tstatus: \"sleeping\" | \"running\" | \"building\" | \"error\" | \"stopped\";\n\tdetail:\n\t\t| \"SLEEPING\"\n\t\t| \"RUNNING\"\n\t\t| \"RUNNING_BUILDING\"\n\t\t| \"BUILDING\"\n\t\t| \"NOT_FOUND\";\n\tload_status: \"pending\" | \"error\" | \"complete\" | \"generating\";\n\tmessage: string;\n}\ninterface SpaceStatusError {\n\tstatus: \"space_error\";\n\tdetail: \"NOAPPFILE\" | \"CONFIGERROR\" | \"BUILDERROR\" | \"RUNTIME_ERROR\";\n\tload_status: \"error\";\n\tmessage: string;\n\tdiscussions_enabled: boolean;\ntype SpaceStatus = SpaceStatusNormal | SpaceStatusError;\n`\nThe gradio client returns an object with a number of methods and properties:\npredict\nThe predict method allows you to call an api endpoint and get a prediction result:\n`ts\nimport { Client } from \"@gradio/client\";\nconst app = await Client.connect(\"user/space-name\");\nconst result = await app.predict(\"/predict\");\n`\npredict accepts two parameters, endpoint and payload. It returns a promise that resolves to the prediction result.\nendpoint\nThis is the endpoint for an api request and is required. The default endpoint for a gradio.Interface is \"/predict\". Explicitly named endpoints have a custom name. The endpoint names can be found on the \"View API\" page of a space.\n`ts\nimport { Client } from \"@gradio/client\";\nconst app = await Client.connect(\"user/space-name\");\nconst result = await app.predict(\"/predict\");\n`\npayload\nThe payload argument is generally required but this depends on the API itself. If the API endpoint depends on values being passed in then the argument is required for the API request to succeed. The data that should be passed in is detailed on the \"View API\" page of a space, or accessible via the view_api() method of the client.\n`ts\nimport { Client } from \"@gradio/client\";\nconst app = await Client.connect(\"user/space-name\");\nconst result = await app.predict(\"/predict\", {\n\tinput: 1,\n\tword_1: \"Hello\",\n\tword_2: \"friends\"\n});\n`\nsubmit\nThe submit method provides a more flexible way to call an API endpoint, providing you with status updates about the current progress of the prediction as well as supporting more complex endpoint types.\n`ts\nimport { Client } from \"@gradio/client\";\nconst app = await Client.connect(\"user/space-name\");\nconst submission = app.submit(\"/predict\", { name: \"Chewbacca\" });\n`\nThe submit method accepts the same endpoint and payload arguments as predict.\nThe submit method does not return a promise and should not be awaited, instead it returns an async iterator with a  cancel method.\nAccessing values\nIterating the submission allows you to access the events related to the submitted API request. There are two types of events that can be listened for: \"data\" updates and \"status\" updates. By default only the \"data\" event is reported, but you can listen for the \"status\" event by manually passing the events you care about when instantiating the client:\n`ts\nimport { Client } from \"@gradio/client\";\nconst app = await Client.connect(\"user/space-name\", {\n\tevents: [\"data\", \"status\"]\n});\n`\n\"data\" updates are issued when the API computes a value, the callback provided as the second argument will be called when such a value is sent to the client. The shape of the data depends on the way the API itself is constructed. This event may fire more than once if that endpoint supports emmitting new values over time.\n\"status updates are issued when the status of a request changes. This information allows you to offer feedback to users when the queue position of the request changes, or when the request changes from queued to processing.\nThe status payload look like this:\n`ts\ninterface Status {\n\tqueue: boolean;\n\tcode?: string;\n\tsuccess?: boolean;\n\tstage: \"pending\" | \"error\" | \"complete\" | \"generating\";\n\tsize?: number;\n\tposition?: number;\n\teta?: number;\n\tmessage?: string;\n\tprogress_data?: Array<{\n\t\tprogress: number | null;\n\t\tindex: number | null;\n\t\tlength: number | null;\n\t\tunit: string | null;\n\t\tdesc: string | null;\n\t}>;\n\ttime?: Date;\n}\n`\nUsage looks like this:\n`ts\nimport { Client } from \"@gradio/client\";\nconst app = await Client.connect(\"user/space-name\");\nconst submission = app\n\t.submit(\"/predict\", { name: \"Chewbacca\" })\n\tfor await (const msg of submission) {\n\t\tif (msg.type === \"data\") {\n\t\t\tconsole.log(msg.data);\n\t\t}\n\t\tif (msg.type === \"status\") {\n\t\t\tconsole.log(msg);\n\t\t}\n\t}\n`\ncancel\nCertain types of gradio function can run repeatedly and in some cases indefinitely. the cancel method will stop such an endpoints and prevent the API from issuing additional updates.\n`ts\nimport { Client } from \"@gradio/client\";\nconst app = await Client.connect(\"user/space-name\");\nconst submission = app\n\t.submit(\"/predict\", { name: \"Chewbacca\" })\n// later\nsubmission.cancel();\n`\nview_api\nThe view_api method provides details about the API you are connected to. It returns a JavaScript object of all named endpoints, unnamed endpoints and what values they accept and return. This method does not accept arguments.\n`ts\nimport { Client } from \"@gradio/client\";\nconst app = await Client.connect(\"user/space-name\");\nconst apiinfo = await app.viewapi();\nconsole.log(api_info);\n`\nconfig\nThe config property contains the configuration for the gradio application you are connected to. This object may contain useful meta information about the application.\n`ts\nimport { Client } from \"@gradio/client\";\nconst app = await Client.connect(\"user/space-name\");\nconsole.log(app.config);\n`\nduplicate\nThe duplicate function will attempt to duplicate the space that is referenced and return an instance of client connected to that space. If the space has already been duplicated then it will not create a new duplicate and will instead connect to the existing duplicated space. The huggingface token that is passed in will dictate the user under which the space is created.\nduplicate accepts the same arguments as client with the addition of a private options property dictating whether the duplicated space should be private or public. A huggingface token is required for duplication to work.\n`ts\nimport { Client } from \"@gradio/client\";\nconst app = await Client.duplicate(\"user/space-name\", {\n\ttoken: \"hf_...\"\n});\n`\nThis function accepts two arguments: source and options:\nsource\nThe space to duplicate and connect to. See client's source parameter.\noptions\nAccepts all options that client accepts, except token is required. See client's options parameter.\nduplicate also accepts one additional options property.\nprivate\nThis is an optional property specific to duplicate's options object and will determine whether the space should be public or private. Spaces duplicated via the duplicate method are public by default.\n`ts\nimport { Client } from \"@gradio/client\";\nconst app = await Client.duplicate(\"user/space-name\", {\n\ttoken: \"hf_...\",\n\tprivate: true\n});\n`\ntimeout\nThis is an optional property specific to duplicate's options object and will set the timeout in minutes before the duplicated space will go to sleep.\n`ts\nimport { Client } from \"@gradio/client\";\nconst app = await Client.duplicate(\"user/space-name\", {\n\ttoken: \"hf_...\",\n\tprivate: true,\n\ttimeout: 5\n});\n`\nhardware\nThis is an optional property specific to duplicate's options object and will set the hardware for the duplicated space. By default the hardware used will match that of the original space. If this cannot be obtained it will default to \"cpu-basic\". For hardware upgrades (beyond the basic CPU tier), you may be required to provide billing information on Hugging Face.\nPossible hardware options are:\n\"cpu-basic\"\n\"cpu-upgrade\"\n\"cpu-xl\"\n\"t4-small\"\n\"t4-medium\"\n\"a10g-small\"\n\"a10g-large\"\n\"a10g-largex2\"\n\"a10g-largex4\"\n\"a100-large\"\n\"zero-a10g\"\n\"h100\"\n\"h100x8\"\n`ts\nimport { Client } from \"@gradio/client\";\nconst app = await Client.duplicate(\"user/space-name\", {\n\ttoken: \"hf_...\",\n\tprivate: true,\n\thardware: \"a10g-small\"\n});\n`\nhandlefile(fileor_url: File | string | Blob | Buffer)\nThis utility function is used to simplify the process of handling file inputs for the client.\nGradio APIs expect a special file datastructure that references a location on the server. These files can be manually uploaded but figuring what to do with different file types can be difficult depending on your environment.\nThis function will handle files regardless of whether or not they are local files (node only), URLs, Blobs, or Buffers. It will take in a reference and handle it accordingly,uploading the file where appropriate and generating the correct data structure for the client.\nThe return value of this function can be used anywhere in the input data where a file is expected:\n`ts\nimport { handle_file } from \"@gradio/client\";\nconst app = await Client.connect(\"user/space-name\");\nconst result = await app.predict(\"/predict\", {\n\tsingle: handle_file(file),\n\tflat: [handlefile(url), handlefile(buffer)],\n\tnested: {\n\t\timage: handle_file(url),\n\t\tlayers: [handle_file(buffer)]\n\t},\n\tdeeply_nested: {\n\t\timage: handle_file(url),\n\t\tlayers: [{\n\t\t\tlayer1: handle_file(buffer),\n\t\t\tlayer2: handle_file(buffer)\n\t\t}]\n\t}\n});\n`\nfilepaths\nhandle_file can be passed a local filepath which it will upload to the client server and return a reference that the client can understand. \nThis only works in a node environment.\nFilepaths are resolved relative to the current working directory, not the location of the file that calls handle_file.\n`ts\nimport { handle_file } from \"@gradio/client\";\n// not uploaded yet\nconst fileref = handlefile(\"path/to/file\");\nconst app = await Client.connect(\"user/space-name\");\n// upload happens here\nconst result = await app.predict(\"/predict\", {\n\tfile: file_ref,\n});\n`\nURLs\nhandle_file can be passed a URL which it will convert into a reference that the client can understand.\n`ts\nimport { handle_file } from \"@gradio/client\";\nconst urlref = handlefile(\"https://example.com/file.png\");\nconst app = await Client.connect(\"user/space-name\");\nconst result = await app.predict(\"/predict\", {\n\turl: url_ref,\n});\n`\nBlobs\nhandle_file can be passed a Blob which it will upload to the client server and return a reference that the client can understand.\nThe upload is not initiated until predict or submit are called.\n`ts\nimport { handle_file } from \"@gradio/client\";\n// not uploaded yet\nconst blobref = handlefile(new Blob([\"Hello, world!\"]));\nconst app = await Client.connect(\"user/space-name\");\n// upload happens here\nconst result = await app.predict(\"/predict\", {\n\tblob: blob_ref,\n});\n`\nBuffers\nhandle_file can be passed a Buffer which it will upload to the client server and return a reference that the client can understand.\n`ts\nimport { handle_file } from \"@gradio/client\";\nimport { readFileSync } from \"fs\";\n// not uploaded yet\nconst bufferref = handlefile(readFileSync(\"file.png\"));\nconst app = await Client.connect(\"user/space-name\");\n// upload happens here\nconst result = await app.predict(\"/predict\", {\n\tbuffer: buffer_ref,\n});\n``","type":"DOCS"},{"title":"multimodaltextbox","slug":"/docs/js/multimodaltextbox","content":"@gradio/multimodaltextbox\n v0.14.2\n``html\n    import { BaseMultimodalTextbox, BaseExample } from \"@gradio/multimodaltextbox\";\n`\nBaseMultimodalTextbox\n`javascript\n\texport let value = \"\";\n\texport let valueisoutput = false;\n\texport let lines = 1;\n\texport let placeholder = \"\";\n\texport let label: string;\n\texport let info: string | undefined = undefined;\n\texport let disabled = false;\n\texport let show_label = true;\n\texport let container = true;\n\texport let max_lines: number;\n\texport let type: \"text\" | \"password\" | \"email\" = \"text\";\n\texport let showcopybutton = false;\n\texport let rtl = false;\n\texport let autofocus = false;\n\texport let text_align: \"left\" | \"right\" | undefined = undefined;\n\texport let autoscroll = true;\n`\nBaseExample\n`javascript\n\texport let value: string;\n\texport let type: \"gallery\" | \"table\";\n\texport let selected = false;\n``","type":"DOCS"},{"title":"audio","slug":"/docs/js/audio","content":"@gradio/audio\n v0.24.3\n``html\n\timport { BaseStaticAudio, BaseInteractiveAudio, BasePlayer, BaseExample } from \"@gradio/audio\";\n`\nBaseExample:\n`javascript\n\texport let value: string;\n\texport let type: \"gallery\" | \"table\";\n\texport let selected = false;\n`\nBaseStaticAudio:\n`javascript\n\texport let value: null | { name: string; data: string } = null;\n\texport let label: string;\n\texport let name: string;\n\texport let show_label = true;\n\texport let autoplay: boolean;\n\texport let showdownloadbutton = true;\n\texport let showsharebutton = false;\n\texport let i18n: I18nFormatter;\n\texport let waveform_settings = {};\n`\nBaseInteractiveAudio:\n`javascript\n\texport let value: null | { name: string; data: string } = null;\n\texport let label: string;\n\texport let root: string;\n\texport let show_label = true;\n\texport let sources:\n\t\t| [\"microphone\"]\n\t\t| [\"upload\"]\n\t\t| [\"microphone\", \"upload\"]\n\t\t| [\"upload\", \"microphone\"] = [\"microphone\", \"upload\"];\n\texport let pending = false;\n\texport let streaming = false;\n\texport let autoplay = false;\n\texport let i18n: I18nFormatter;\n\texport let waveform_settings = {};\n\texport let dragging: boolean;\n\texport let active_source: \"microphone\" | \"upload\";\n\texport let handleresetvalue: () => void = () => {};\n`\nBasePlayer:\n`javascript\n\texport let value: null | { name: string; data: string } = null;\n\texport let label: string;\n\texport let autoplay: boolean;\n\texport let i18n: I18nFormatter;\n\texport let dispatch: (event: any, detail?: any) => void;\n\texport let dispatch_blob: (\n\t\tblobs: Uint8Array[] | Blob[],\n\t\tevent: \"stream\" | \"change\"\n\t) => Promise = () => Promise.resolve();\n\texport let interactive = false;\n\texport let waveform_settings = {};\n\texport let mode = \"\";\n\texport let handleresetvalue: () => void = () => {};\n``","type":"DOCS"},{"title":"model3D","slug":"/docs/js/model3D","content":"gradio/model3d\n``html\n    import {BaseModel3D, BaseModel3DUpload, BaseExample } from @gradio/model3d;\n`\nBaseModel3D\n`javascript\n\texport let value: FileData | null;\n\texport let clear_color: [number, number, number, number] = [0, 0, 0, 0];\n\texport let label = \"\";\n\texport let show_label: boolean;\n\texport let i18n: I18nFormatter;\n\texport let zoom_speed = 1;\n\t// alpha, beta, radius\n\texport let camera_position: [number | null, number | null, number | null] = [\n\t\tnull,\n\t\tnull,\n\t\tnull\n\t];\n`\nBaseModel3DUpload\n`javascript\n\texport let value: null | FileData;\n\texport let clear_color: [number, number, number, number] = [0, 0, 0, 0];\n\texport let label = \"\";\n\texport let show_label: boolean;\n\texport let root: string;\n\texport let i18n: I18nFormatter;\n\texport let zoom_speed = 1;\n\t// alpha, beta, radius\n\texport let camera_position: [number | null, number | null, number | null] = [\n\t\tnull,\n\t\tnull,\n\t\tnull\n\t];\n`\nBaseExample\n`javascript\n\texport let value: string;\n\texport let type: \"gallery\" | \"table\";\n\texport let selected = false;\n``","type":"DOCS"},{"title":"file","slug":"/docs/js/file","content":"@gradio/file\n v0.16.0\n``html\n\timport { BaseFile, BaseFileUpload, FilePreview, BaseExample } from \"@gradio/file\";\n`\nBaseFile\n`javascript\n\texport let value: FileData | FileData[] | null = null;\n\texport let label: string;\n\texport let show_label = true;\n\texport let selectable = false;\n\texport let height: number | undefined = undefined;\n\texport let i18n: I18nFormatter;\n`\nBaseFileUpload\n`javascript\n\texport let value: null | FileData | FileData[];\n\texport let label: string;\n\texport let show_label = true;\n\texport let file_count = \"single\";\n\texport let file_types: string[] | null = null;\n\texport let selectable = false;\n\texport let root: string;\n\texport let height: number | undefined = undefined;\n\texport let i18n: I18nFormatter;\n`\nFilePreview\n`javascript\n\texport let value: FileData | FileData[];\n\texport let selectable = false;\n\texport let height: number | undefined = undefined;\n\texport let i18n: I18nFormatter;\n`\nBaseExample\n`javascript\n\texport let value: FileData;\n\texport let type: \"gallery\" | \"table\";\n\texport let selected = false;\n``","type":"DOCS"},{"title":"atoms","slug":"/docs/js/atoms","content":"@gradio/atoms\n v0.26.2\n``html\n\timport { Block, BlockTitle, BlockLabel, IconButton, Empty, Info, ShareButton, UploadText} from \"@gradio/atoms\";\n`\nBlock:\n`javascript\n\texport let height: number | undefined = undefined;\n\texport let width: number | undefined = undefined;\n\texport let elem_id = \"\";\n\texport let elem_classes: string[] = [];\n\texport let variant: \"solid\" | \"dashed\" | \"none\" = \"solid\";\n\texport let border_mode: \"base\" | \"focus\" = \"base\";\n\texport let padding = true;\n\texport let type: \"normal\" | \"fieldset\" = \"normal\";\n\texport let test_id: string | undefined = undefined;\n\texport let explicit_call = false;\n\texport let container = true;\n\texport let visible = true;\n\texport let allow_overflow = true;\n\texport let scale: number | null = null;\n\texport let min_width = 0;\n`\nBlockTitle:\n`javascript\n\texport let show_label = true;\n\texport let info: string | undefined = undefined;\n`\nBlockLabel:\n`javascript\n\texport let label: string | null = null;\n\texport let Icon: any;\n\texport let show_label = true;\n\texport let disable = false;\n\texport let float = true;\n`\nIconButton:\n`javascript\n\texport let Icon: any;\n\texport let label = \"\";\n\texport let show_label = false;\n\texport let pending = false;\n`\nEmpty:\n`javascript\n\texport let size: \"small\" | \"large\" = \"small\";\n\texport let unpadded_box = false;\n`\nShareButton:\n`javascript\n\texport let formatter: (arg0: any) => Promise;\n\texport let value: any;\n\texport let i18n: I18nFormatter;\n`\nUploadText:\n`javascript\n\texport let type: \"video\" | \"image\" | \"audio\" | \"file\" | \"csv\" = \"file\";\n\texport let i18n: I18nFormatter;\n``","type":"DOCS"},{"title":"form","slug":"/docs/js/form","content":"@gradio/form\n v0.4.2\n``html\n\timport { Form } from \"@gradio/form\";\n`\nForm\n`javascript\n\texport let visible = true;\n\texport let scale: number | null = null;\n\texport let min_width = 0;\n``","type":"DOCS"},{"title":"uploadbutton","slug":"/docs/js/uploadbutton","content":"@gradio/uploadbutton\n v0.10.2\n``html\n    import { BaseUploadButton } from \"@gradio/uploadbutton\";\n`\nBaseUploadButton\n`javascript\n\texport let elem_id = \"\";\n\texport let elem_classes: string[] = [];\n\texport let visible = true;\n\texport let label: string;\n\texport let value: null | FileData | FileData[];\n\texport let file_count: string;\n\texport let file_types: string[] = [];\n\texport let root: string;\n\texport let size: \"sm\" | \"lg\" = \"lg\";\n\texport let scale: number | null = null;\n\texport let min_width: number | undefined = undefined;\n\texport let variant: \"primary\" | \"secondary\" | \"stop\" = \"secondary\";\n\texport let disabled = false;\n``","type":"DOCS"},{"title":"button","slug":"/docs/js/button","content":"@gradio/button\n v0.8.2\n``javascript\n\timport { BaseButton } from \"@gradio/button\";\n\timport { createEventDispatcher, tick, getContext } from \"svelte\";\n\tconst dispatch = createEventDispatcher();\n dispatch(\"click\")}\n{\"My Button\"}\n``","type":"DOCS"},{"title":"label","slug":"/docs/js/label","content":"@gradio/label\n v0.7.2\n``html\n\timport { BaseLabel } from \"@gradio/label\";\n`\nBaseLabel\n`javascript\n\texport let value: {\n\t\tlabel?: string;\n\t\tconfidences?: { label: string; confidence: number }[];\n\t};\n\texport let color: string | undefined = undefined;\n\texport let selectable = false;\n``","type":"DOCS"},{"title":"accordion","slug":"/docs/js/accordion","content":"@gradio/button\n v0.6.0\n``html\n\timport { Button } from \"@gradio/button\";\n\tcontent\n``","type":"DOCS"},{"title":"sidebar","slug":"/docs/js/sidebar","content":"@gradio/sidebar\n v0.2.12\n``html\n\timport { Sidebar } from \"@gradio/sidebar\";\n\t\n``","type":"DOCS"},{"title":"dataframe","slug":"/docs/js/dataframe","content":"@gradio/dataframe\n v0.24.5\nStandalone Svelte component that brings Gradio's Dataframe UI to any Svelte/SvelteKit project.\nThis component is lightweight, virtualized for efficient rendering of large datasets, and offers features like column freezing, and customizable styling via CSS variables. Use this component when you need a highly interactive, accessible, and easily themeable table for user-facing applications, especially where seamless Svelte/SvelteKit integration is important.\nInstall\nWith npm:\n``shell\nnpm i @gradio/dataframe\n`\nWith pnpm:\n`shell\npnpm add @gradio/dataframe\n`\nView on npm\nUsage (Svelte/SvelteKit)\n`svelte\n  import Dataframe from \"@gradio/dataframe\";\n  let value = {\n    data: [\n      [\"Alice\", 25, true],\n      [\"Bob\", 30, false]\n    ],\n    headers: [\"Name\", \"Age\", \"Active\"],\n  };\n  function handle_change(e: any) {\n    console.log(\"changed\", e.detail);\n  }\n  function handle_select(e: any) {\n    console.log(\"selected\", e.detail);\n  }\n  function handle_input(e: any) {\n    console.log(\"input\", e.detail);\n  }\n`\nProps\n`typescript\ninterface DataframeProps {\n  /\nThe value object containing the table data, headers, and optional metadata.\nExample: { data: [...], headers: [...], metadata?: any }\nDefault: { data: [[]], headers: [] }\n   */\n  value: {\n    data: (string | number | boolean)[][];\n    headers: string[];\n    metadata?: any;\n  };\n  /\nArray of data types per column. Supported: \"str\", \"number\", \"bool\", \"date\", \"markdown\", \"html\".\nDefault: []\n   */\n  datatype?: string[];\n  /\nEnable or disable cell editing.\nDefault: true\n   */\n  editable?: boolean;\n  /\nShow or hide the row number column.\nDefault: true\n   */\n  showrownumbers?: boolean;\n  /\nShow search input. Can be \"search\", \"filter\", or \"none.\nDefault: \"none\"\n   */\n  show_search?: \"none\" | \"search\" | \"filter\" | boolean;\n  /\nShow or hide the copy to clipboard button.\nDefault: true\n   */\n  showcopybutton?: boolean;\n  /\nShow or hide the fullscreen toggle button.\nDefault: true\n   */\n  showfullscreenbutton?: boolean;\n  /\nAccessible caption for the table.\nDefault: null\n   */\n  label?: string | null;\n  /\nShow or hide the dataframe label.\nDefault: true\n   */\n  show_label?: boolean;\n  /\n(Optional) Set column widths in CSS units (e.g. [\"100px\", \"20%\", ...]).\n   */\n  column_widths?: string[];\n  /\n(Optional) Set the maximum height of the table in pixels.\nDefault: 500\n   */\n  max_height?: number;\n  /\n(Optional) Set the maximum number of characters per cell.\n   */\n  max_chars?: number;\n  /\n(Optional) Enable or disable line breaks in cells.\nDefault: true\n   */\n  line_breaks?: boolean;\n  /\n(Optional) Enable or disable text wrapping in cells.\nDefault: false\n   */\n  wrap?: boolean;\n}\n`\nEvents\nThe component emits the following events:\n`ts\n// Fired when table data changes\non:change={(e: CustomEvent) => void}\n// Fired when a cell is selected\non:select={(e: CustomEvent) => void}\n// Fired on user input (search/filter)\non:input={(e: CustomEvent) => void}\n`\nExample:\n`svelte\n console.log('data', e.detail)}\n  on:input={(e) => console.log('input', e.detail)}\n  on:select={(e) => console.log('select', e.detail)}\n/>\n`\nTypeScript\nThe package publishes types.d.ts with DataframeProps module declarations.\nCustom Styling\nThe standalone package exposes a small set of public CSS variables you can use to theme the Dataframe. These variables are namespaced with --gr-df-* and are the recommended way to override the default styling.\nColor Variables\n--gr-df-table-bg-even — background for even rows\n--gr-df-table-bg-odd — background for odd rows\n--gr-df-copied-cell-color - background for copied cells\n--gr-df-table-border — table border color\n--gr-df-table-text — table text color\n--gr-df-accent — primary accent color\n--gr-df-accent-soft — soft/pale accent color\nFont Variables\n--gr-df-font-size — table body font-size\n--gr-df-font-mono — monospace font family\n--gr-df-font-sans — sans serif font family\nBorder/Radius Variables\n--gr-df-table-radius — table corner radius\nExample:\n`svelte\n  \n  .df-theme {\n    --gr-df-accent: #7c3aed;\n  }\n`\nAlternatively, you can target internal classes within the Dataframe using a global override. \n`css\n.df-theme :global(.cell-wrap) {\n  background-color: #7c3aed ;\n}\n``\nNote: This standalone component does not currently support the file upload functionality (e.g. drag-and-dropping to populate the dataframe) that is available in the Gradio Dataframe component.\nLicense\nMIT","type":"DOCS"},{"title":"upload","slug":"/docs/js/upload","content":"@gradio/upload\n v0.18.3\n``html\n    import { Upload, ModifyUpload, normalisefile, getfetchableurlorfile, upload, preparefiles } from \"@gradio/upload\";\n`\nUpload\n`javascript\n\texport let filetype: string | null = null;\n\texport let dragging = false;\n\texport let boundedheight = true;\n\texport let center = true;\n\texport let flex = true;\n\texport let file_count = \"single\";\n\texport let disable_click = false;\n\texport let root: string;\n\texport let hidden = false;\n`\nModifyUpload\n`javascript\n    export let editable = false;\n\texport let undoable = false;\n\texport let absolute = true;\n\texport let i18n: I18nFormatter;\n`\n`javascript\nexport function normalise_file(\n\tfile: FileData | null,\n\tserver_url: string,\n\tproxy_url: string | null\n): FileData | null;\nexport function normalise_file(\n\tfile: FileData[] | null,\n\tserver_url: string,\n\tproxy_url: string | null\n): FileData[] | null;\nexport function normalise_file(\n\tfile: FileData[] | FileData | null,\n\tserver_url: string, // root: string,\n\tproxyurl: string | null // rooturl: string | null\n): FileData[] | FileData | null;\nexport function normalise_file(\n\tfile: FileData[] | FileData | null,\n\tserver_url: string, // root: string,\n\tproxyurl: string | null // rooturl: string | null\n): FileData[] | FileData | null;\nexport function getfetchableurlorfile(\n\tpath: string | null,\n\tserver_url: string,\n\tproxy_url: string | null\n): string\nexport async function upload(\n\tfile_data: FileData[],\n\troot: string,\n\tuploadfn: typeof uploadfiles = upload_files\n): Promise\nexport async function prepare_files(\n\tfiles: File[],\n\tis_stream?: boolean\n): Promise {\n\treturn files.map(\n\t\t(f, i) =>\n\t\t\tnew FileData({\n\t\t\t\tpath: f.name,\n\t\t\t\torig_name: f.name,\n\t\t\t\tblob: f,\n\t\t\t\tsize: f.size,\n\t\t\t\tmime_type: f.type,\n\t\t\t\tis_stream\n\t\t\t})\n\t);\n}\n``","type":"DOCS"},{"title":"image","slug":"/docs/js/image","content":"@gradio/image\n v0.28.3\n``html\n\timport { BaseImageUploader, BaseStaticImage, Webcam, BaseExample } from \"@gradio/image\";\n`\nBaseImageUploader\n`javascript\n\texport let sources: (\"clipboard\" | \"webcam\" | \"upload\")[] = [\n\t\t\"upload\",\n\t\t\"clipboard\",\n\t\t\"webcam\"\n\t];\n\texport let streaming = false;\n\texport let pending = false;\n\texport let mirror_webcam: boolean;\n\texport let selectable = false;\n\texport let root: string;\n\texport let i18n: I18nFormatter;\n`\nBaseStaticImage\n`javascript\n\texport let value: null | FileData;\n\texport let label: string | undefined = undefined;\n\texport let show_label: boolean;\n\texport let showdownloadbutton = true;\n\texport let selectable = false;\n\texport let showsharebutton = false;\n\texport let root: string;\n\texport let i18n: I18nFormatter;\n`\nWebcam\n`javascript\n\texport let streaming = false;\n\texport let pending = false;\n\texport let mode: \"image\" | \"video\" = \"image\";\n\texport let mirror_webcam: boolean;\n\texport let include_audio: boolean;\n\texport let i18n: I18nFormatter;\n`\nBaseExample\n`javascript\n\texport let value: string;\n\texport let samples_dir: string;\n\texport let type: \"gallery\" | \"table\";\n\texport let selected = false;\n``","type":"DOCS"},{"title":"imageslider","slug":"/docs/js/imageslider","content":"technical notes\n v0.8.0\ntldr\nWe use object-fit: contain to show the full image at all times.\nThis causes the DOM width of the image to differ from the real image width.\nSlider positions are based on the unscaled image's coordinate space.\nZooming introduces translation and scale, which makes slider positions behave in surprising ways (including going negative).\ndetails\nThe main challenge with this component is managing image sizing. A different approach might surface other challenges, but I wanted to document this one somewhere because it’s not particularly intuitive.\nobject-fit: contain\nThe image slider is essentially two images overlaid exactly; the “comparison” image is gradually revealed by modifying its clip-path.\nWe have a few key requirements:\nThe whole image should be visible with no clipping.\nThe DOMRect of the image should ideally match 100% of the parent’s width and height—this is crucial when zooming, as we don’t want any part of the image to get clipped.\nBoth images must be identically overlaid.\nWe use a few standard CSS techniques to achieve this, but the key part for this discussion is object-fit: contain.\nThis is a great CSS property and ensures that the entire image is always visible which is a great baseline for the image slider. The challenge (and also the benefit) of object-fit: contain is that an image with width: 100% and this property will stretch to the full width of its parent, even if the image itself is narrower.\nThis is problematic because slider-progress should be relative to the unscaled image, not the container box. When someone sets slider_position=10 that should be 10% across the image, not the container.\nThis is fine. We manually calculate the “real” image width and offsets (there’s no built-in API for this), and map slider position values accordingly. It works, but introduces a few quirks:\nzooming needs to know about the 'real' image size. \nThe zoom applies constraints to prevent users from dragging the image out of view, so it needs to know the image's true start and end positions (i.e. the actual pixel bounds of the image within the container).\nslider positions can become 'negative' (and this is ok). \nThis is confusing but bear with me. \nAt the default zoom level, slider = 0 and slider = 100 correspond to the actual edges of the image. Makes sense. But when we zoom in, we still use the same 'unscaled, actual image coordinate space'. \nSo now, say the slider is at 25: it still refers to 25% across the unscaled image. But visually, that might no longer line up with the expected spot in the zoomed view. It’s viewport-relative, but calculated against a base coordinate system that isn’t.\nI did a picture to help conceptualise. Here we zoom (scale and translate) but the slider stays in the same position on the screen, corresponding to its 25% of image width + left offset origin.\nBecause of this, the 0 point might actually lie partway into the image’s visible region when zoomed. This means we can't actually compare the whole image at higher zoom levels unless we allow negative slider positions.\nSo that's exactly what we do.\nThe image slider performs a fair amount of translation and projections, nothing absurd but there is enough. We need to make sure that any time we are interacting with the slider position, our calculations can handle negative values.\nWe also need to dynamically clamp the slider position, based on:\nthe current zoom scale\nany translation offsets\nthe real image bounds (not just the DOMRect)","type":"DOCS"},{"title":"statustracker","slug":"/docs/js/statustracker","content":"@gradio/statustracker\n v0.15.3\n``html\n    import {StatusTracker, Toast, Loader} from @gradio/statustracker;\n`\nStatusTracker\n`javascript\n\texport let i18n: I18nFormatter;\n\texport let eta: number | null = null;\n\texport let queue = false;\n\texport let queue_position: number | null;\n\texport let queue_size: number | null;\n\texport let status: \"complete\" | \"pending\" | \"error\" | \"generating\";\n\texport let scrolltooutput = false;\n\texport let timer = true;\n\texport let show_progress: \"full\" | \"minimal\" | \"hidden\" = \"full\";\n\texport let message: string | null = null;\n\texport let progress: LoadingStatus[\"progress\"] | null | undefined = null;\n\texport let variant: \"default\" | \"center\" = \"default\";\n\texport let loading_text = \"Loading...\";\n\texport let absolute = true;\n\texport let translucent = false;\n\texport let border = false;\n\texport let autoscroll: boolean;\n`\nToast\n`javascript\n\texport let messages: ToastMessage[] = [];\n`\nLoader\n`javascript\n\texport let margin = true;\n``","type":"DOCS"},{"title":"highlightedtext","slug":"/docs/js/highlightedtext","content":"@gradio/highlightedtext\n v0.12.3\n``html\n    import { BaseStaticHighlightedText, BaseInteractiveHighlightedText } from @gradio/highlightedtext;\n`\nBaseStaticHighlightedText\n`javascript\n\texport let value: {\n\t\ttoken: string;\n\t\tclassorconfidence: string | number | null;\n\t}[] = [];\n\texport let show_legend = false;\n\texport let showinlinecategory = true;\n\texport let color_map: Record = {};\n\texport let selectable = false;\n`\nBaseInteractiveHighlightedText\n`javascript\n\texport let value: {\n\t\ttoken: string;\n\t\tclassorconfidence: string | number | null;\n\t}[] = [];\n\texport let show_legend = false;\n\texport let color_map: Record = {};\n\texport let selectable = false;\n``","type":"DOCS"},{"title":"utils","slug":"/docs/js/utils","content":"@gradio/utils\n v0.14.2\nGeneral functions for handling events in Gradio Svelte components\n``javascript\nexport async function uploadToHuggingFace(\n\t\tdata: string,\n\t\ttype: \"base64\" | \"url\"\n\t): Promise\nexport function copy(node: HTMLDivElement): ActionReturn\n``","type":"DOCS"},{"title":"imageeditor","slug":"/docs/js/imageeditor","content":"@gradio/imageeditor\n v0.20.2\nhello","type":"DOCS"},{"title":"radio","slug":"/docs/js/radio","content":"@gradio/radio\n v0.12.2\n``html\n    import { BaseRadio, BaseExample } from \"@gradio/radio\"; \n`\nBaseRadio\n`javascript\n\texport let display_value: string;\n\texport let internal_value: string | number;\n\texport let disabled = false;\n\texport let elem_id = \"\";\n\texport let selected: string | number | null = null;\n`\nBaseExample\n`javascript\n\texport let value: string;\n\texport let type: \"gallery\" | \"table\";\n\texport let selected = false;\n``","type":"DOCS"},{"title":"markdown","slug":"/docs/js/markdown","content":"@gradio/markdown\n v0.14.2\n``html\n    import { BaseMarkdown, MarkdownCode, BaseExample } from @gradio/markdown;\n`\nBaseMarkdown\n`javascript\n\texport let elem_id = \"\";\n\texport let elem_classes: string[] = [];\n\texport let visible = true;\n\texport let value: string;\n\texport let min_height = false;\n\texport let rtl = false;\n\texport let sanitize_html = true;\n\texport let line_breaks = false;\n\texport let latex_delimiters: {\n\t\tleft: string;\n\t\tright: string;\n\t\tdisplay: boolean;\n\t}[];\n`\nMarkdownCode\n`javascript\n\texport let chatbot = true;\n\texport let message: string;\n\texport let sanitize_html = true;\n\texport let latex_delimiters: {\n\t\tleft: string;\n\t\tright: string;\n\t\tdisplay: boolean;\n\t}[] = [];\n\texport let render_markdown = true;\n\texport let line_breaks = true;\n`\nBaseExample\n`javascript\n\texport let value: string;\n\texport let type: \"gallery\" | \"table\";\n\texport let selected = false;\n\texport let sanitize_html: boolean;\n\texport let line_breaks: boolean;\n\texport let latex_delimiters: {\n\t\tleft: string;\n\t\tright: string;\n\t\tdisplay: boolean;\n\t}[];\n``","type":"DOCS"},{"title":"dropdown","slug":"/docs/js/dropdown","content":"@gradio/dropdown\n v0.15.0\n``html\n\timport { BaseDropdown, BaseMultiselect, BaseExample } from \"@gradio/dropdown\";\n`\nBaseDropdown\n`javascript\n\texport let label: string;\n\texport let info: string | undefined = undefined;\n\texport let value: string | number | (string | number)[] | undefined = [];\n\texport let valueisoutput = false;\n\texport let choices: [string, string | number][];\n\texport let disabled = false;\n\texport let show_label: boolean;\n\texport let container = true;\n\texport let allowcustomvalue = false;\n\texport let filterable = true;\n\texport let numchoicesshown: number | null = 100; // Initial matches shown; scrolling loads more. null shows all matches.\n`\nBaseMultiselect\n`javascript\n\texport let label: string;\n\texport let info: string | undefined = undefined;\n\texport let value: string | number | (string | number)[] | undefined = [];\n\texport let valueisoutput = false;\n\texport let max_choices: number | null = null;\n\texport let choices: [string, string | number][];\n\texport let disabled = false;\n\texport let show_label: boolean;\n\texport let container = true;\n\texport let allowcustomvalue = false;\n\texport let filterable = true;\n\texport let numchoicesshown: number | null = 100; // Initial matches shown; scrolling loads more. null shows all matches.\n\texport let i18n: I18nFormatter;\n`\nBaseExample\n`javascript\n\texport let value: string;\n\texport let type: \"gallery\" | \"table\";\n\texport let selected = false;\n``","type":"DOCS"},{"title":"checkbox","slug":"/docs/js/checkbox","content":"@gradio/checkbox\n v0.8.3\n``html\n    import { BaseCheckbox } from \"@gradio/checkbox\";\n`\nBaseCheckBox:\n`javascript\n\texport let value = false;\n\texport let label = \"Checkbox\";\n\texport let mode: \"static\" | \"interactive\";\n``","type":"DOCS"},{"title":"code","slug":"/docs/js/code","content":"@gradio/code\n v0.19.0\n``html\n    import { BaseCode, BaseCopy, BaseDownload, BaseWidget, BaseExample} from \"gradio/code\";\n`\nBaseCode\n`javascript\n\texport let class_names = \"\";\n\texport let value = \"\";\n\texport let dark_mode: boolean;\n\texport let basic = true;\n\texport let language: string;\n\texport let lines = 5;\n\texport let extensions: Extension[] = [];\n\texport let use_tab = true;\n\texport let readonly = false;\n\texport let placeholder: string | HTMLElement | null | undefined = undefined;\n`\nBaseCopy\n`javascript\n\texport let value: string;\n`\nBaseDownload\n`javascript\n\texport let value: string;\n\texport let language: string;\n`\nBaseWidget\n`javascript\n\texport let value: string;\n\texport let language: string;\n`\nBaseExample\n`\n\texport let value: string;\n\texport let type: \"gallery\" | \"table\";\n\texport let selected = false;\n``","type":"DOCS"},{"title":"html","slug":"/docs/js/html","content":"@gradio/html\n v0.13.2\n``javascript\nimport { BaseHTML } from \"@gradio/html\";\n`\nBaseHTML\n`javascript\n\texport let elem_id = \"\";\n\texport let elem_classes: string[] = [];\n\texport let value: string;\n\texport let visible = true;\n\texport let min_height = false;\n``","type":"DOCS"},{"title":"chatbot","slug":"/docs/js/chatbot","content":"@gradio/chatbot\n v0.32.1\n``html\n\timport { BaseChatBot } from \"@gradio/chatbot\";\n`\nBaseChatBot\n`javascript\n\texport let value:\n\t\t| [\n\t\t\t\tstring | { file: FileData; alt_text: string | null } | null,\n\t\t\t\tstring | { file: FileData; alt_text: string | null } | null\n\t\t  ][]\n\t\t| null;\n\tlet old_value:\n\t\t| [\n\t\t\t\tstring | { file: FileData; alt_text: string | null } | null,\n\t\t\t\tstring | { file: FileData; alt_text: string | null } | null\n\t\t  ][]\n\t\t| null = null;\n\texport let latex_delimiters: {\n\t\tleft: string;\n\t\tright: string;\n\t\tdisplay: boolean;\n\t}[];\n\texport let pending_message = false;\n\texport let selectable = false;\n\texport let likeable = false;\n\texport let showsharebutton = false;\n\texport let rtl = false;\n\texport let showcopybutton = false;\n\texport let avatar_images: [string | null, string | null] = [null, null];\n\texport let sanitize_html = true;\n\texport let bubblefullwidth = true;\n\texport let render_markdown = true;\n\texport let line_breaks = true;\n\texport let root: string;\n\texport let root_url: null | string;\n\texport let i18n: I18nFormatter;\n\texport let layout: \"bubble\" | \"panel\" = \"bubble\";\n``","type":"DOCS"},{"title":"tooltip","slug":"/docs/js/tooltip","content":"@gradio/tooltip\n v0.2.1\n``javascript\nimport { Tooltip } from \"@gradio/tooltip\";\n`\n`javascript\n\texport let text: string;\n\texport let x: number;\n\texport let y: number;\n\texport let color: string;\n``","type":"DOCS"},{"title":"markdown-code","slug":"/docs/js/markdown-code","content":"@gradio/markdown\n v0.10.1\n``html\n    import { BaseMarkdown, MarkdownCode, BaseExample } from @gradio/markdown;\n`\nBaseMarkdown\n`javascript\n\texport let elem_id = \"\";\n\texport let elem_classes: string[] = [];\n\texport let visible = true;\n\texport let value: string;\n\texport let min_height = false;\n\texport let rtl = false;\n\texport let sanitize_html = true;\n\texport let line_breaks = false;\n\texport let latex_delimiters: {\n\t\tleft: string;\n\t\tright: string;\n\t\tdisplay: boolean;\n\t}[];\n`\nMarkdownCode\n`javascript\n\texport let chatbot = true;\n\texport let message: string;\n\texport let sanitize_html = true;\n\texport let latex_delimiters: {\n\t\tleft: string;\n\t\tright: string;\n\t\tdisplay: boolean;\n\t}[] = [];\n\texport let render_markdown = true;\n\texport let line_breaks = true;\n`\nBaseExample\n`javascript\n\texport let value: string;\n\texport let type: \"gallery\" | \"table\";\n\texport let selected = false;\n\texport let sanitize_html: boolean;\n\texport let line_breaks: boolean;\n\texport let latex_delimiters: {\n\t\tleft: string;\n\t\tright: string;\n\t\tdisplay: boolean;\n\t}[];\n``","type":"DOCS"},{"title":"gallery","slug":"/docs/js/gallery","content":"@gradio/gallery\n v0.19.1\n``html\n\timport { BaseGallery } from \"@gradio/gallery\";\n`\nBaseGallery\n`javascript\n\texport let show_label = true;\n\texport let label: string;\n\texport let root = \"\";\n\texport let root_url: null | string = null;\n\texport let value: { image: FileData; caption: string | null }[] | null = null;\n\texport let columns: number | number[] | undefined = [2];\n\texport let rows: number | number[] | undefined = undefined;\n\texport let height: number | \"auto\" = \"auto\";\n\texport let preview: boolean;\n\texport let allow_preview = true;\n\texport let object_fit: \"contain\" | \"cover\" | \"fill\" | \"none\" | \"scale-down\" =\n\t\t\"cover\";\n\texport let showsharebutton = false;\n\texport let showdownloadbutton = false;\n\texport let i18n: I18nFormatter;\n\texport let selected_index: number | null = null;\n``","type":"DOCS"},{"title":"json","slug":"/docs/js/json","content":"@gradio/json\n v0.8.2\n``html\n\timport { BaseJSON } from \"@gradio/json\";\n`\nBaseJSON\n`html\n\texport let value: any = {};\n``","type":"DOCS"},{"title":"colorpicker","slug":"/docs/js/colorpicker","content":"@gradio/colorpicker\n v0.5.15\n``html\n    import { BaseColorPicker, BaseExample } from \"@gradio/colorpicker\";\n`\nBaseColorPicker\n`javascript\n\texport let value = \"#000000\";\n\texport let valueisoutput = false;\n\texport let label: string;\n\texport let info: string | undefined = undefined;\n\texport let disabled = false;\n\texport let show_label = true;\n`\nBaseExample\n`javascript\n\texport let value: string;\n\texport let type: \"gallery\" | \"table\";\n\texport let selected = false;\n``","type":"DOCS"},{"title":"video","slug":"/docs/js/video","content":"@gradio/video\n v0.23.1\n``javascript\n\timport { BaseInteractiveVideo, BaseStaticVideo, BasePlayer } from \"@gradio/button\";\n\timport type { FileData } from \"@gradio/upload\";\n\timport type { Gradio } from \"@gradio/utils\";\n\texport let _video: FileData;\n\tUpload Video Here\n``","type":"DOCS"},{"title":"textbox","slug":"/docs/js/textbox","content":"@gradio/textbox\n v0.14.2\n``html\n    import { BaseTextbox, BaseExample } from \"@gradio/textbox\";\n`\nBaseTextbox\n`javascript\n\texport let value = \"\";\n\texport let valueisoutput = false;\n\texport let lines = 1;\n\texport let placeholder = \"\";\n\texport let label: string;\n\texport let info: string | undefined = undefined;\n\texport let disabled = false;\n\texport let show_label = true;\n\texport let container = true;\n\texport let max_lines: number;\n\texport let type: \"text\" | \"password\" | \"email\" = \"text\";\n\texport let showcopybutton = false;\n\texport let rtl = false;\n\texport let autofocus = false;\n\texport let text_align: \"left\" | \"right\" | undefined = undefined;\n\texport let autoscroll = true;\n\texport let max_length: number | undefined = undefined;\n`\nBaseExample\n`javascript\n\texport let value: string;\n\texport let type: \"gallery\" | \"table\";\n\texport let selected = false;\n``","type":"DOCS"},{"title":"js-client","slug":"/docs/js/js-client","content":"JavaScript Client Library\nInteract with Gradio APIs using our JavaScript (and TypeScript) client.\nInstallation\nThe Gradio JavaScript Client is available on npm as @gradio/client. You can install it as below:\n``shell\nnpm i @gradio/client\n`\nOr, you can include it directly in your HTML via the jsDelivr CDN:\n`html\n\timport { Client } from \"https://cdn.jsdelivr.net/npm/@gradio/client/dist/index.min.js\";\n`\nUsage\nThe JavaScript Gradio Client exposes the Client class, Client, along with various other utility functions. Client is used to initialise and establish a connection to, or duplicate, a Gradio app. \nClient\nThe Client function connects to the API of a hosted Gradio space and returns an object that allows you to make calls to that API.\nThe simplest example looks like this:\n`ts\nimport { Client } from \"@gradio/client\";\nconst app = await Client.connect(\"user/space-name\");\nconst result = await app.predict(\"/predict\");\n`\nThis function accepts two arguments: source and options:\nsource\nThis is the url or name of the gradio app whose API you wish to connect to. This parameter is required and should always be a string. For example:\n`ts\nClient.connect(\"user/space-name\");  \n`\noptions\nThe options object can optionally be passed a second parameter. This object has two properties, token and status_callback.\ntoken\nThis should be a Hugging Face personal access token and is required if you wish to make calls to a private gradio api. This option is optional and should be a string starting with \"hf_\".\nExample:\n`ts\nimport { Client } from \"@gradio/client\";\nconst app = await Client.connect(\"user/space-name\", { token: \"hf_...\" });\n`\nstatus_callback\nThis should be a function which will notify you of the status of a space if it is not running. If the gradio API you are connecting to is not awake and running or is not hosted on Hugging Face space then this function will do nothing.\nAdditional context\nApplications hosted on Hugging Face spaces can be in a number of different states. As spaces are a GitOps tool and will rebuild when new changes are pushed to the repository, they have various building, running and error states. If a space is not 'running' then the function passed as the status_callback will notify you of the current state of the space and the status of the space as it changes. Spaces that are building or sleeping can take longer than usual to respond, so you can use this information to give users feedback about the progress of their action.\n`ts\nimport { Client, type SpaceStatus } from \"@gradio/client\";\nconst app = await Client.connect(\"user/space-name\", {\n\t// The space_status parameter does not need to be manually annotated, this is just for illustration.\n\tspacestatus: (spacestatus: SpaceStatus) => console.log(space_status)\n});\n`\n`ts\ninterface SpaceStatusNormal {\n\tstatus: \"sleeping\" | \"running\" | \"building\" | \"error\" | \"stopped\";\n\tdetail:\n\t\t| \"SLEEPING\"\n\t\t| \"RUNNING\"\n\t\t| \"RUNNING_BUILDING\"\n\t\t| \"BUILDING\"\n\t\t| \"NOT_FOUND\";\n\tload_status: \"pending\" | \"error\" | \"complete\" | \"generating\";\n\tmessage: string;\n}\ninterface SpaceStatusError {\n\tstatus: \"space_error\";\n\tdetail: \"NOAPPFILE\" | \"CONFIGERROR\" | \"BUILDERROR\" | \"RUNTIME_ERROR\";\n\tload_status: \"error\";\n\tmessage: string;\n\tdiscussions_enabled: boolean;\ntype SpaceStatus = SpaceStatusNormal | SpaceStatusError;\n`\nThe gradio client returns an object with a number of methods and properties:\npredict\nThe predict method allows you to call an api endpoint and get a prediction result:\n`ts\nimport { Client } from \"@gradio/client\";\nconst app = await Client.connect(\"user/space-name\");\nconst result = await app.predict(\"/predict\");\n`\npredict accepts two parameters, endpoint and payload. It returns a promise that resolves to the prediction result.\nendpoint\nThis is the endpoint for an api request and is required. The default endpoint for a gradio.Interface is \"/predict\". Explicitly named endpoints have a custom name. The endpoint names can be found on the \"View API\" page of a space.\n`ts\nimport { Client } from \"@gradio/client\";\nconst app = await Client.connect(\"user/space-name\");\nconst result = await app.predict(\"/predict\");\n`\npayload\nThe payload argument is generally required but this depends on the API itself. If the API endpoint depends on values being passed in then the argument is required for the API request to succeed. The data that should be passed in is detailed on the \"View API\" page of a space, or accessible via the view_api() method of the client.\n`ts\nimport { Client } from \"@gradio/client\";\nconst app = await Client.connect(\"user/space-name\");\nconst result = await app.predict(\"/predict\", {\n\tinput: 1,\n\tword_1: \"Hello\",\n\tword_2: \"friends\"\n});\n`\nsubmit\nThe submit method provides a more flexible way to call an API endpoint, providing you with status updates about the current progress of the prediction as well as supporting more complex endpoint types.\n`ts\nimport { Client } from \"@gradio/client\";\nconst app = await Client.connect(\"user/space-name\");\nconst submission = app.submit(\"/predict\", { name: \"Chewbacca\" });\n`\nThe submit method accepts the same endpoint and payload arguments as predict.\nThe submit method does not return a promise and should not be awaited, instead it returns an async iterator with a  cancel method.\nAccessing values\nIterating the submission allows you to access the events related to the submitted API request. There are two types of events that can be listened for: \"data\" updates and \"status\" updates. By default only the \"data\" event is reported, but you can listen for the \"status\" event by manually passing the events you care about when instantiating the client:\n`ts\nimport { Client } from \"@gradio/client\";\nconst app = await Client.connect(\"user/space-name\", {\n\tevents: [\"data\", \"status\"]\n});\n`\n\"data\" updates are issued when the API computes a value, the callback provided as the second argument will be called when such a value is sent to the client. The shape of the data depends on the way the API itself is constructed. This event may fire more than once if that endpoint supports emmitting new values over time.\n\"status updates are issued when the status of a request changes. This information allows you to offer feedback to users when the queue position of the request changes, or when the request changes from queued to processing.\nThe status payload look like this:\n`ts\ninterface Status {\n\tqueue: boolean;\n\tcode?: string;\n\tsuccess?: boolean;\n\tstage: \"pending\" | \"error\" | \"complete\" | \"generating\";\n\tsize?: number;\n\tposition?: number;\n\teta?: number;\n\tmessage?: string;\n\tprogress_data?: Array;\n\ttime?: Date;\n}\n`\nUsage looks like this:\n`ts\nimport { Client } from \"@gradio/client\";\nconst app = await Client.connect(\"user/space-name\");\nconst submission = app\n\t.submit(\"/predict\", { name: \"Chewbacca\" })\n\tfor await (const msg of submission) {\n\t\tif (msg.type === \"data\") {\n\t\t\tconsole.log(msg.data);\n\t\t}\n\t\tif (msg.type === \"status\") {\n\t\t\tconsole.log(msg);\n\t\t}\n\t}\n`\ncancel\nCertain types of gradio function can run repeatedly and in some cases indefinitely. the cancel method will stop such an endpoints and prevent the API from issuing additional updates.\n`ts\nimport { Client } from \"@gradio/client\";\nconst app = await Client.connect(\"user/space-name\");\nconst submission = app\n\t.submit(\"/predict\", { name: \"Chewbacca\" })\n// later\nsubmission.cancel();\n`\nview_api\nThe view_api method provides details about the API you are connected to. It returns a JavaScript object of all named endpoints, unnamed endpoints and what values they accept and return. This method does not accept arguments.\n`ts\nimport { Client } from \"@gradio/client\";\nconst app = await Client.connect(\"user/space-name\");\nconst apiinfo = await app.viewapi();\nconsole.log(api_info);\n`\nconfig\nThe config property contains the configuration for the gradio application you are connected to. This object may contain useful meta information about the application.\n`ts\nimport { Client } from \"@gradio/client\";\nconst app = await Client.connect(\"user/space-name\");\nconsole.log(app.config);\n`\nduplicate\nThe duplicate function will attempt to duplicate the space that is referenced and return an instance of client connected to that space. If the space has already been duplicated then it will not create a new duplicate and will instead connect to the existing duplicated space. The huggingface token that is passed in will dictate the user under which the space is created.\nduplicate accepts the same arguments as client with the addition of a private options property dictating whether the duplicated space should be private or public. A huggingface token is required for duplication to work.\n`ts\nimport { Client } from \"@gradio/client\";\nconst app = await Client.duplicate(\"user/space-name\", {\n\ttoken: \"hf_...\"\n});\n`\nThis function accepts two arguments: source and options:\nsource\nThe space to duplicate and connect to. See client's source parameter.\noptions\nAccepts all options that client accepts, except token is required. See client's options parameter.\nduplicate also accepts one additional options property.\nprivate\nThis is an optional property specific to duplicate's options object and will determine whether the space should be public or private. Spaces duplicated via the duplicate method are public by default.\n`ts\nimport { Client } from \"@gradio/client\";\nconst app = await Client.duplicate(\"user/space-name\", {\n\ttoken: \"hf_...\",\n\tprivate: true\n});\n`\ntimeout\nThis is an optional property specific to duplicate's options object and will set the timeout in minutes before the duplicated space will go to sleep.\n`ts\nimport { Client } from \"@gradio/client\";\nconst app = await Client.duplicate(\"user/space-name\", {\n\ttoken: \"hf_...\",\n\tprivate: true,\n\ttimeout: 5\n});\n`\nhardware\nThis is an optional property specific to duplicate's options object and will set the hardware for the duplicated space. By default the hardware used will match that of the original space. If this cannot be obtained it will default to \"cpu-basic\". For hardware upgrades (beyond the basic CPU tier), you may be required to provide billing information on Hugging Face.\nPossible hardware options are:\n\"cpu-basic\"\n\"cpu-upgrade\"\n\"cpu-xl\"\n\"t4-small\"\n\"t4-medium\"\n\"a10g-small\"\n\"a10g-large\"\n\"a10g-largex2\"\n\"a10g-largex4\"\n\"a100-large\"\n\"zero-a10g\"\n\"h100\"\n\"h100x8\"\n`ts\nimport { Client } from \"@gradio/client\";\nconst app = await Client.duplicate(\"user/space-name\", {\n\ttoken: \"hf_...\",\n\tprivate: true,\n\thardware: \"a10g-small\"\n});\n`\nhandlefile(fileor_url: File | string | Blob | Buffer)\nThis utility function is used to simplify the process of handling file inputs for the client.\nGradio APIs expect a special file datastructure that references a location on the server. These files can be manually uploaded but figuring what to do with different file types can be difficult depending on your environment.\nThis function will handle files regardless of whether or not they are local files (node only), URLs, Blobs, or Buffers. It will take in a reference and handle it accordingly,uploading the file where appropriate and generating the correct data structure for the client.\nThe return value of this function can be used anywhere in the input data where a file is expected:\n`ts\nimport { handle_file } from \"@gradio/client\";\nconst app = await Client.connect(\"user/space-name\");\nconst result = await app.predict(\"/predict\", {\n\tsingle: handle_file(file),\n\tflat: [handlefile(url), handlefile(buffer)],\n\tnested: {\n\t\timage: handle_file(url),\n\t\tlayers: [handle_file(buffer)]\n\t},\n\tdeeply_nested: {\n\t\timage: handle_file(url),\n\t\tlayers: [{\n\t\t\tlayer1: handle_file(buffer),\n\t\t\tlayer2: handle_file(buffer)\n\t\t}]\n\t}\n});\n`\nfilepaths\nhandle_file can be passed a local filepath which it will upload to the client server and return a reference that the client can understand. \nThis only works in a node environment.\nFilepaths are resolved relative to the current working directory, not the location of the file that calls handle_file.\n`ts\nimport { handle_file } from \"@gradio/client\";\n// not uploaded yet\nconst fileref = handlefile(\"path/to/file\");\nconst app = await Client.connect(\"user/space-name\");\n// upload happens here\nconst result = await app.predict(\"/predict\", {\n\tfile: file_ref,\n});\n`\nURLs\nhandle_file can be passed a URL which it will convert into a reference that the client can understand.\n`ts\nimport { handle_file } from \"@gradio/client\";\nconst urlref = handlefile(\"https://example.com/file.png\");\nconst app = await Client.connect(\"user/space-name\");\nconst result = await app.predict(\"/predict\", {\n\turl: url_ref,\n});\n`\nBlobs\nhandle_file can be passed a Blob which it will upload to the client server and return a reference that the client can understand.\nThe upload is not initiated until predict or submit are called.\n`ts\nimport { handle_file } from \"@gradio/client\";\n// not uploaded yet\nconst blobref = handlefile(new Blob([\"Hello, world!\"]));\nconst app = await Client.connect(\"user/space-name\");\n// upload happens here\nconst result = await app.predict(\"/predict\", {\n\tblob: blob_ref,\n});\n`\nBuffers\nhandle_file can be passed a Buffer which it will upload to the client server and return a reference that the client can understand.\n`ts\nimport { handle_file } from \"@gradio/client\";\nimport { readFileSync } from \"fs\";\n// not uploaded yet\nconst bufferref = handlefile(readFileSync(\"file.png\"));\nconst app = await Client.connect(\"user/space-name\");\n// upload happens here\nconst result = await app.predict(\"/predict\", {\n\tbuffer: buffer_ref,\n});\n``","type":"DOCS"}]