[{"text": "A Job is a wrapper over the Future class that represents a prediction call\nthat has been submitted by the Gradio client. This class is not meant to be\ninstantiated directly, but rather is created by the Client.submit() method. \nA Job object includes methods to get the status of the prediction call, as\nwell to get the outputs of the prediction call. Job objects are also iterable,\nand can be used in a loop to get the outputs of prediction calls as they\nbecome available for generator endpoints.\n\n", "heading1": "Description", "source_page_url": "https://gradio.app/docs/python-client/job", "source_page_title": "Python Client - Job Docs"}, {"text": "Parameters \u25bc\n\n\n \n \n future: Future\n\nThe future object that represents the prediction call, created by the\nClient.submit() method\n\n\n \n \n communicator: Communicator | None\n\ndefault `= None`\n\nThe communicator object that is used to communicate between the client and the\nbackground thread running the job\n\n\n \n \n verbose: bool\n\ndefault `= True`\n\nWhether to print any status-related messages to the console\n\n\n \n \n space_id: str | None\n\ndefault `= None`\n\nThe space ID corresponding to the Client object that created this Job object\n\n", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/python-client/job", "source_page_title": "Python Client - Job Docs"}, {"text": "Description\n\nEvent listeners allow you to respond to user interactions with the UI\ncomponents you've defined in a Gradio Blocks app. When a user interacts with\nan element, such as changing a slider value or uploading an image, a function\nis called.\n\nSupported Event Listeners\n\nThe Job component supports the following event listeners. Each event listener\ntakes the same parameters, which are listed in the Event Parameters table\nbelow.\n\nListeners\n\n \n \n Job.result(fn, \u00b7\u00b7\u00b7)\n\nReturn the result of the call that the future represents. Raises\nCancelledError: If the future was cancelled, TimeoutError: If the future\ndidn't finish executing before the given timeout, and Exception: If the call\nraised then that exception will be raised.
\n\n \n \n Job.outputs(fn, \u00b7\u00b7\u00b7)\n\nReturns a list containing the latest outputs from the Job.
If the\nendpoint has multiple output components, the list will contain a tuple of\nresults. Otherwise, it will contain the results without storing them in\ntuples.
For endpoints that are queued, this list will contain the final\njob output even if that endpoint does not use a generator function.
\n\n \n \n Job.status(fn, \u00b7\u00b7\u00b7)\n\nReturns the latest status update from the Job in the form of a StatusUpdate\nobject, which contains the following fields: code, rank, queue_size, success,\ntime, eta, and progress_data.
progress_data is a list of updates emitted\nby the gr.Progress() tracker of the event handler. Each element of the list\nhas the following fields: index, length, unit, progress, desc. If the event\nhandler does not have a gr.Progress() tracker, the progress_data field will be\nNone.
\n\nEvent Parameters\n\nParameters \u25bc\n\n\n \n \n timeout: float | None\n\ndefault `= None`\n\nThe number of seconds to wait for the result if the future isn't done. If\nNone, then there is no limit on the wait time.\n\n", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/python-client/job", "source_page_title": "Python Client - Job Docs"}, {"text": "If you already have a recent version of `gradio`, then the `gradio_client` is\nincluded as a dependency. But note that this documentation reflects the latest\nversion of the `gradio_client`, so upgrade if you\u2019re not sure!\n\nThe lightweight `gradio_client` package can be installed from pip (or pip3)\nand is tested to work with **Python versions 3.9 or higher** :\n\n \n \n $ pip install --upgrade gradio_client\n\n", "heading1": "Installation", "source_page_url": "https://gradio.app/docs/python-client/introduction", "source_page_title": "Python Client - Introduction Docs"}, {"text": "Spaces\n\nStart by connecting instantiating a `Client` object and connecting it to a\nGradio app that is running on Hugging Face Spaces.\n\n \n \n from gradio_client import Client\n \n client = 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\n`hf_token` parameter. You can get your HF token here:\n\n\n \n \n from gradio_client import Client\n \n client = Client(\"abidlabs/my-private-space\", hf_token=\"...\")\n\n", "heading1": "Connecting to a Gradio App on Hugging Face", "source_page_url": "https://gradio.app/docs/python-client/introduction", "source_page_title": "Python Client - Introduction Docs"}, {"text": "use\n\nWhile you can use any public Space as an API, you may get rate limited by\nHugging Face if you make too many requests. For unlimited usage of a Space,\nsimply duplicate the Space to create a private Space, and then use it to make\nas many requests as you\u2019d like!\n\nThe `gradio_client` includes a class method: `Client.duplicate()` to make this\nprocess simple (you\u2019ll need to pass in your [Hugging Face\ntoken](https://huggingface.co/settings/tokens) or be logged in using the\nHugging Face CLI):\n\n \n \n import os\n from gradio_client import Client, file\n \n HF_TOKEN = os.environ.get(\"HF_TOKEN\")\n \n client = Client.duplicate(\"abidlabs/whisper\", hf_token=HF_TOKEN)\n client.predict(file(\"audio_sample.wav\"))\n \n >> \"This is a test of the whisper speech recognition model.\"\n\nIf you have previously duplicated a Space, re-running `duplicate()` will _not_\ncreate a new Space. Instead, the Client will attach to the previously-created\nSpace. So it is safe to re-run the `Client.duplicate()` method multiple times.\n\n**Note:** if the original Space uses GPUs, your private Space will as well,\nand your Hugging Face account will get billed based on the price of the GPU.\nTo minimize charges, your Space will automatically go to sleep after 1 hour of\ninactivity. You can also set the hardware using the `hardware` parameter of\n`duplicate()`.\n\n", "heading1": "Duplicating a Space for private", "source_page_url": "https://gradio.app/docs/python-client/introduction", "source_page_title": "Python Client - Introduction Docs"}, {"text": "app\n\nIf your app is running somewhere else, just provide the full URL instead,\nincluding the \u201chttp://\u201d or \u201chttps://\u201c. Here\u2019s an example of making predictions\nto a Gradio app that is running on a share URL:\n\n \n \n from gradio_client import Client\n \n client = Client(\"https://bec81a83-5b5c-471e.gradio.live\")\n\n", "heading1": "Connecting a general Gradio", "source_page_url": "https://gradio.app/docs/python-client/introduction", "source_page_title": "Python Client - Introduction Docs"}, {"text": "Once you have connected to a Gradio app, you can view the APIs that are\navailable to you by calling the `Client.view_api()` method. For the Whisper\nSpace, we see the following:\n\n \n \n Client.predict() Usage Info\n ---------------------------\n Named 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\nWe see that we have 1 API endpoint in this space, and shows us how to use the\nAPI endpoint to make a prediction: we should call the `.predict()` method\n(which we will explore below), providing a parameter `input_audio` of type\n`str`, which is a `filepath or URL`.\n\nWe should also provide the `api_name='/predict'` argument to the `predict()`\nmethod. Although this isn\u2019t necessary if a Gradio app has only 1 named\nendpoint, it does allow us to call different endpoints in a single app if they\nare available.\n\n", "heading1": "Inspecting the API endpoints", "source_page_url": "https://gradio.app/docs/python-client/introduction", "source_page_title": "Python Client - Introduction Docs"}, {"text": "As an alternative to running the `.view_api()` method, you can click on the\n\u201cUse via API\u201d link in the footer of the Gradio app, which shows us the same\ninformation, along with example usage.\n\n![](https://huggingface.co/datasets/huggingface/documentation-\nimages/resolve/main/gradio-guides/view-api.png)\n\nThe View API page also includes an \u201cAPI Recorder\u201d that lets you interact with\nthe Gradio UI normally and converts your interactions into the corresponding\ncode to run with the Python Client.\n\n", "heading1": "The \u201cView API\u201d Page", "source_page_url": "https://gradio.app/docs/python-client/introduction", "source_page_title": "Python Client - Introduction Docs"}, {"text": "The simplest way to make a prediction is simply to call the `.predict()`\nfunction with the appropriate arguments:\n\n \n \n from gradio_client import Client\n \n client = Client(\"abidlabs/en2fr\", api_name='/predict')\n client.predict(\"Hello\")\n \n >> Bonjour\n\nIf there are multiple parameters, then you should pass them as separate\narguments to `.predict()`, like this:\n\n \n \n from gradio_client import Client\n \n client = Client(\"gradio/calculator\")\n client.predict(4, \"add\", 5)\n \n >> 9.0\n\nIt is recommended to provide key-word arguments instead of positional\narguments:\n\n \n \n from gradio_client import Client\n \n client = Client(\"gradio/calculator\")\n client.predict(num1=4, operation=\"add\", num2=5)\n \n >> 9.0\n\nThis allows you to take advantage of default arguments. For example, this\nSpace includes the default value for the Slider component so you do not need\nto provide it when accessing it with the client.\n\n \n \n from gradio_client import Client\n \n client = Client(\"abidlabs/image_generator\")\n client.predict(text=\"an astronaut riding a camel\")\n\nThe default value is the initial value of the corresponding Gradio component.\nIf the component does not have an initial value, but if the corresponding\nargument in the predict function has a default value of `None`, then that\nparameter is also optional in the client. Of course, if you\u2019d like to override\nit, you can include it as well:\n\n \n \n from gradio_client import Client\n \n client = Client(\"abidlabs/image_generator\")\n client.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\nto the file enclosed within `gradio_client.file()`. This takes care of\nuploading the file to the Gradio server and ensures that the file is\npreprocessed correctly:\n\n \n \n from gradio_client import Client, file\n \n client = Client(\"abidlabs/whisper\")\n client.predict(\n ", "heading1": "Making a prediction", "source_page_url": "https://gradio.app/docs/python-client/introduction", "source_page_title": "Python Client - Introduction Docs"}, {"text": " to the Gradio server and ensures that the file is\npreprocessed correctly:\n\n \n \n from gradio_client import Client, file\n \n client = Client(\"abidlabs/whisper\")\n client.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\u2014\"\n\n", "heading1": "Making a prediction", "source_page_url": "https://gradio.app/docs/python-client/introduction", "source_page_title": "Python Client - Introduction Docs"}, {"text": "Oe should note that `.predict()` is a _blocking_ operation as it waits for the\noperation to complete before returning the prediction.\n\nIn many cases, you may be better off letting the job run in the background\nuntil you need the results of the prediction. You can do this by creating a\n`Job` instance using the `.submit()` method, and then later calling\n`.result()` on the job to get the result. For example:\n\n \n \n from gradio_client import Client\n \n client = Client(space=\"abidlabs/en2fr\")\n job = client.submit(\"Hello\", api_name=\"/predict\") This is not blocking\n \n Do something else\n \n job.result() This is blocking\n \n >> Bonjour\n\n", "heading1": "Running jobs asynchronously", "source_page_url": "https://gradio.app/docs/python-client/introduction", "source_page_title": "Python Client - Introduction Docs"}, {"text": "Alternatively, one can add one or more callbacks to perform actions after the\njob has completed running, like this:\n\n \n \n from gradio_client import Client\n \n def print_result(x):\n print(\"The translated result is: {x}\")\n \n client = Client(space=\"abidlabs/en2fr\")\n \n job = client.submit(\"Hello\", api_name=\"/predict\", result_callbacks=[print_result])\n \n Do something else\n \n >> The translated result is: Bonjour\n \n\n", "heading1": "Adding callbacks", "source_page_url": "https://gradio.app/docs/python-client/introduction", "source_page_title": "Python Client - Introduction Docs"}, {"text": "The `Job` object also allows you to get the status of the running job by\ncalling the `.status()` method. This returns a `StatusUpdate` object with the\nfollowing attributes: `code` (the status code, one of a set of defined strings\nrepresenting the status. See the `utils.Status` class), `rank` (the current\nposition of this job in the queue), `queue_size` (the total queue size), `eta`\n(estimated time this job will complete), `success` (a boolean representing\nwhether the job completed successfully), and `time` (the time that the status\nwas generated).\n\n \n \n from gradio_client import Client\n \n client = Client(src=\"gradio/calculator\")\n job = client.submit(5, \"add\", 4, api_name=\"/predict\")\n job.status()\n \n >> \n\n_Note_ : The `Job` class also has a `.done()` instance method which returns a\nboolean indicating whether the job has completed.\n\n", "heading1": "Status", "source_page_url": "https://gradio.app/docs/python-client/introduction", "source_page_title": "Python Client - Introduction Docs"}, {"text": "The `Job` class also has a `.cancel()` instance method that cancels jobs that\nhave been queued but not started. For example, if you run:\n\n \n \n client = Client(\"abidlabs/whisper\")\n job1 = client.submit(file(\"audio_sample1.wav\"))\n job2 = client.submit(file(\"audio_sample2.wav\"))\n job1.cancel() will return False, assuming the job has started\n job2.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\nsecond job has not yet started, it will be successfully canceled and removed\nfrom the queue.\n\n", "heading1": "Cancelling Jobs", "source_page_url": "https://gradio.app/docs/python-client/introduction", "source_page_title": "Python Client - Introduction Docs"}, {"text": "Some Gradio API endpoints do not return a single value, rather they return a\nseries of values. You can get the series of values that have been returned at\nany time from such a generator endpoint by running `job.outputs()`:\n\n \n \n from gradio_client import Client\n \n client = Client(src=\"gradio/count_generator\")\n job = client.submit(3, api_name=\"/count\")\n while not job.done():\n time.sleep(0.1)\n job.outputs()\n \n >> ['0', '1', '2']\n\nNote that running `job.result()` on a generator endpoint only gives you the\n_first_ value returned by the endpoint.\n\nThe `Job` object is also iterable, which means you can use it to display the\nresults of a generator function as they are returned from the endpoint. Here\u2019s\nthe equivalent example using the `Job` as a generator:\n\n \n \n from gradio_client import Client\n \n client = Client(src=\"gradio/count_generator\")\n job = client.submit(3, api_name=\"/count\")\n \n for o in job:\n print(o)\n \n >> 0\n >> 1\n >> 2\n\nYou can also cancel jobs that that have iterative outputs, in which case the\njob will finish as soon as the current iteration finishes running.\n\n \n \n from gradio_client import Client\n import time\n \n client = Client(\"abidlabs/test-yield\")\n job = client.submit(\"abcdef\")\n time.sleep(3)\n job.cancel() job cancels after 2 iterations\n\n", "heading1": "Generator Endpoints", "source_page_url": "https://gradio.app/docs/python-client/introduction", "source_page_title": "Python Client - Introduction Docs"}, {"text": "Gradio demos can include [session state](https://www.gradio.app/guides/state-\nin-blocks), which provides a way for demos to persist information from user\ninteractions within a page session.\n\nFor example, consider the following demo, which maintains a list of words that\na user has submitted in a `gr.State` component. When a user submits a new\nword, it is added to the state, and the number of previous occurrences of that\nword is displayed:\n\n \n \n import gradio as gr\n \n def count(word, list_of_words):\n return list_of_words.count(word), list_of_words + [word]\n \n with 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 \n demo.launch()\n\nIf you were to connect this this Gradio app using the Python Client, you would\nnotice that the API information only shows a single input and output:\n\n \n \n Client.predict() Usage Info\n ---------------------------\n Named 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\nThat is because the Python client handles state automatically for you \u2014 as you\nmake a series of requests, the returned state from one request is stored\ninternally and automatically supplied for the subsequent request. If you\u2019d\nlike to reset the state, you can do that by calling `Client.reset_session()`.\n\n", "heading1": "Demos with Session State", "source_page_url": "https://gradio.app/docs/python-client/introduction", "source_page_title": "Python Client - Introduction Docs"}, {"text": "The main Client class for the Python client. This class is used to connect\nto a remote Gradio app and call its API endpoints. \n\n", "heading1": "Description", "source_page_url": "https://gradio.app/docs/python-client/client", "source_page_title": "Python Client - Client Docs"}, {"text": "from gradio_client import Client\n \n client = Client(\"abidlabs/whisper-large-v2\") connecting to a Hugging Face Space\n client.predict(\"test.mp4\", api_name=\"/predict\")\n >> What a nice recording! returns the result of the remote API call\n \n client = Client(\"https://bec81a83-5b5c-471e.gradio.live\") connecting to a temporary Gradio share URL\n job = client.submit(\"hello\", api_name=\"/predict\") runs the prediction in a background thread\n job.result()\n >> 49 returns the result of the remote API call (blocking call)\n\n", "heading1": "Example usage", "source_page_url": "https://gradio.app/docs/python-client/client", "source_page_title": "Python Client - Client Docs"}, {"text": "Parameters \u25bc\n\n\n \n \n src: str\n\neither the name of the Hugging Face Space to load, (e.g. \"abidlabs/whisper-\nlarge-v2\") or the full URL (including \"http\" or \"https\") of the hosted Gradio\napp to load (e.g. \"http://mydomain.com/app\" or\n\"https://bec81a83-5b5c-471e.gradio.live/\").\n\n\n \n \n token: str | None\n\ndefault `= None`\n\noptional Hugging Face token to use to access private Spaces. By default, the\nlocally saved token is used if there is one. Find your tokens here:\nhttps://huggingface.co/settings/tokens.\n\n\n \n \n max_workers: int\n\ndefault `= 40`\n\nmaximum number of thread workers that can be used to make requests to the\nremote Gradio app simultaneously.\n\n\n \n \n verbose: bool\n\ndefault `= True`\n\nwhether the client should print statements to the console.\n\n\n \n \n auth: tuple[str, str] | None\n\ndefault `= None`\n\n\n \n \n httpx_kwargs: dict[str, Any] | None\n\ndefault `= None`\n\nadditional keyword arguments to pass to `httpx.Client`, `httpx.stream`,\n`httpx.get` and `httpx.post`. This can be used to set timeouts, proxies, http\nauth, etc.\n\n\n \n \n headers: dict[str, str] | None\n\ndefault `= None`\n\nadditional headers to send to the remote Gradio app on every request. By\ndefault only the HF authorization and user-agent headers are sent. This\nparameter will override the default headers if they have the same keys.\n\n\n \n \n download_files: str | Path | Literal[False]\n\ndefault `= \"/tmp/gradio\"`\n\ndirectory where the client should download output files on the local machine\nfrom the remote API. By default, uses the value of the GRADIO_TEMP_DIR\nenvironment variable which, if not set by the user, is a temporary directory\non your machine. If False, the client does not download files and returns a\nFileData dataclass object with the filepath on the remote machine instead.\n\n\n \n \n ssl_verify: bool\n\ndefault `= True`\n\nif False, skips certificate validation which allows the client to connect to\nGradio apps that are using self-signed ce", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/python-client/client", "source_page_title": "Python Client - Client Docs"}, {"text": "n the remote machine instead.\n\n\n \n \n ssl_verify: bool\n\ndefault `= True`\n\nif False, skips certificate validation which allows the client to connect to\nGradio apps that are using self-signed certificates.\n\n\n \n \n analytics_enabled: bool\n\ndefault `= True`\n\nWhether to allow basic telemetry. If None, will use GRADIO_ANALYTICS_ENABLED\nenvironment variable or default to True.\n\n", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/python-client/client", "source_page_title": "Python Client - Client Docs"}, {"text": "Description\n\nEvent listeners allow you to respond to user interactions with the UI\ncomponents you've defined in a Gradio Blocks app. When a user interacts with\nan element, such as changing a slider value or uploading an image, a function\nis called.\n\nSupported Event Listeners\n\nThe Client component supports the following event listeners. Each event\nlistener takes the same parameters, which are listed in the Event Parameters\ntable below.\n\nListeners\n\n \n \n Client.predict(fn, \u00b7\u00b7\u00b7)\n\nCalls the Gradio API and returns the result (this is a blocking call).\nArguments can be provided as positional arguments or as keyword arguments\n(latter is recommended).
\n\n \n \n Client.submit(fn, \u00b7\u00b7\u00b7)\n\nCreates and returns a Job object which calls the Gradio API in a background\nthread. The job can be used to retrieve the status and result of the remote\nAPI call. Arguments can be provided as positional arguments or as keyword\narguments (latter is recommended).
\n\n \n \n Client.view_api(fn, \u00b7\u00b7\u00b7)\n\nPrints the usage info for the API. If the Gradio app has multiple API\nendpoints, the usage info for each endpoint will be printed separately. If\nreturn_format=\"dict\" the info is returned in dictionary format, as shown in\nthe example below.
\n\n \n \n Client.duplicate(fn, \u00b7\u00b7\u00b7)\n\nDuplicates a Hugging Face Space under your account and returns a Client object\nfor the new Space. No duplication is created if the Space already exists in\nyour account (to override this, provide a new name for the new Space using\n`to_id`). To use this method, you must provide an `token` or be logged in via\nthe Hugging Face Hub CLI.
The new Space will be private by default and\nuse the same hardware as the original Space. This can be changed by using the\n`private` and `hardware` parameters. For hardware upgrades (beyond the basic\nCPU tier), you may be required to provide billing information on Hugging Face:\n
\n\nEvent Parameters\n\nPar", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/python-client/client", "source_page_title": "Python Client - Client Docs"}, {"text": "eters. For hardware upgrades (beyond the basic\nCPU tier), you may be required to provide billing information on Hugging Face:\n
\n\nEvent Parameters\n\nParameters \u25bc\n\n\n \n \n args: \n\nThe positional arguments to pass to the remote API endpoint. The order of the\narguments must match the order of the inputs in the Gradio app.\n\n\n \n \n api_name: str | None\n\ndefault `= None`\n\nThe name of the API endpoint to call starting with a leading slash, e.g.\n\"/predict\". Does not need to be provided if the Gradio app has only one named\nAPI endpoint.\n\n\n \n \n fn_index: int | None\n\ndefault `= None`\n\nAs an alternative to api_name, this parameter takes the index of the API\nendpoint to call, e.g. 0. Both api_name and fn_index can be provided, but if\nthey conflict, api_name will take precedence.\n\n\n \n \n headers: dict[str, str] | None\n\ndefault `= None`\n\nAdditional headers to send to the remote Gradio app on this request. This\nparameter will overrides the headers provided in the Client constructor if\nthey have the same keys.\n\n\n \n \n kwargs: \n\nThe keyword arguments to pass to the remote API endpoint.\n\n", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/python-client/client", "source_page_title": "Python Client - Client Docs"}, {"text": "ZeroGPU\n\nZeroGPU spaces are rate-limited to ensure that a single user does not hog all\nof the available GPUs. The limit is controlled by a special token that the\nHugging Face Hub infrastructure adds to all incoming requests to Spaces. This\ntoken is a request header called `X-IP-Token` and its value changes depending\non the user who makes a request to the ZeroGPU space.\n\n \n\nLet\u2019s say you want to create a space (Space A) that uses a ZeroGPU space\n(Space B) programmatically. Normally, calling Space B from Space A with the\nGradio Python client would quickly exhaust Space B\u2019s rate limit, as all the\nrequests to the ZeroGPU space would be missing the `X-IP-Token` request header\nand would therefore be treated as unauthenticated.\n\nIn order to avoid this, we need to extract the `X-IP-Token` of the user using\nSpace A before we call Space B programmatically. Where possible, specifically\nin the case of functions that are passed into event listeners directly, Gradio\nautomatically extracts the `X-IP-Token` from the incoming request and passes\nit into the Gradio Client. But if the Client is instantiated outside of such a\nfunction, then you may need to pass in the token manually.\n\nHow to do this will be explained in the following section.\n\n", "heading1": "Explaining Rate Limits for", "source_page_url": "https://gradio.app/docs/python-client/using-zero-gpu-spaces", "source_page_title": "Python Client - Using Zero Gpu Spaces Docs"}, {"text": "Token\n\nIn the following hypothetical example, when a user presses enter in the\ntextbox, the `generate()` function is called, which calls a second function,\n`text_to_image()`. Because the Gradio Client is being instantiated indirectly,\nin `text_to_image()`, we will need to extract their token from the `X-IP-\nToken` header of the incoming request. We will use this header when\nconstructing the gradio client.\n\n \n \n import gradio as gr\n from gradio_client import Client\n \n def 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 \n def generate(prompt, request: gr.Request):\n prompt = prompt[:300]\n return text_to_image(prompt, request)\n \n with gr.Blocks() as demo:\n image = gr.Image()\n prompt = gr.Textbox(max_lines=1)\n prompt.submit(generate, [prompt], [image])\n \n demo.launch()\n\n", "heading1": "Avoiding Rate Limits by Manually Passing an IP", "source_page_url": "https://gradio.app/docs/python-client/using-zero-gpu-spaces", "source_page_title": "Python Client - Using Zero Gpu Spaces Docs"}, {"text": "**Stream From a Gradio app in 5 lines**\n\n \n\nUse the `submit` method to get a job you can iterate over.\n\n \n\nIn python:\n\n \n \n from gradio_client import Client\n \n client = Client(\"gradio/llm_stream\")\n \n for result in client.submit(\"What's the best UI framework in Python?\"):\n print(result)\n\n \n\nIn typescript:\n\n \n \n import { Client } from \"@gradio/client\";\n \n const client = await Client.connect(\"gradio/llm_stream\")\n const job = client.submit(\"/predict\", {\"text\": \"What's the best UI framework in Python?\"})\n \n for await (const msg of job) console.log(msg.data)\n\n \n\n**Use the same keyword arguments as the app**\n\n \nIn the examples below, the upstream app has a function with parameters called\n`message`, `system_prompt`, and `tokens`. We can see that the client `predict`\ncall uses the same arguments.\n\nIn python:\n\n \n \n from gradio_client import Client\n \n client = Client(\"http://127.0.0.1:7860/\")\n result = client.predict(\n \t\tmessage=\"Hello!!\",\n \t\tsystem_prompt=\"You are helpful AI.\",\n \t\ttokens=10,\n \t\tapi_name=\"/chat\"\n )\n print(result)\n\nIn typescript:\n\n \n \n import { Client } from \"@gradio/client\";\n \n const client = await Client.connect(\"http://127.0.0.1:7860/\");\n const 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 \n console.log(result.data);\n\n \n\n**Better Error Messages**\n\n \nIf something goes wrong in the upstream app, the client will raise the same\nexception as the app provided that `show_error=True` in the original app's\n`launch()` function, or it's a `gr.Error` exception.\n\n", "heading1": "Ergonomic API \ud83d\udc86", "source_page_url": "https://gradio.app/docs/python-client/version-1-release", "source_page_title": "Python Client - Version 1 Release Docs"}, {"text": "Anything you can do in the UI, you can do with the client:\n\n * \ud83d\udd10Authentication\n * \ud83d\uded1 Job Cancelling\n * \u2139\ufe0f Access Queue Position and API\n * \ud83d\udcd5 View the API information\n\n \nHere's an example showing how to display the queue position of a pending job:\n\n \n \n from gradio_client import Client\n \n client = Client(\"gradio/diffusion_model\")\n \n job = client.submit(\"A cute cat\")\n while not job.done():\n status = job.status()\n print(f\"Current in position {status.rank} out of {status.queue_size}\")\n\n", "heading1": "Transparent Design \ud83e\ude9f", "source_page_url": "https://gradio.app/docs/python-client/version-1-release", "source_page_title": "Python Client - Version 1 Release Docs"}, {"text": "The client can run from pretty much any python and javascript environment\n(node, deno, the browser, Service Workers). \nHere's an example using the client from a Flask server using gevent:\n\n \n \n from gevent import monkey\n monkey.patch_all()\n \n from gradio_client import Client\n from flask import Flask, send_file\n import time\n \n app = Flask(__name__)\n \n imageclient = Client(\"gradio/diffusion_model\")\n \n @app.route(\"/gen\")\n def gen():\n result = imageclient.predict(\n \"A cute cat\",\n api_name=\"/predict\"\n )\n return send_file(result)\n \n if __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=5000)\n\n", "heading1": "Portable Design \u26fa\ufe0f", "source_page_url": "https://gradio.app/docs/python-client/version-1-release", "source_page_title": "Python Client - Version 1 Release Docs"}, {"text": "Changes\n\n \n\n**Python**\n\n * The `serialize` argument of the `Client` class was removed and has no effect.\n * The `upload_files` argument of the `Client` was removed.\n * All filepaths must be wrapped in the `handle_file` method. For example, `caption = client.predict(handle_file('./dog.jpg'))`.\n * The `output_dir` argument was removed. It is not specified in the `download_files` argument.\n\n \n\n**Javascript**\n\n \nThe client has been redesigned entirely. It was refactored from a function\ninto a class. An instance can now be constructed by awaiting the `connect`\nmethod.\n\n \n \n const app = await Client.connect(\"gradio/whisper\")\n\nThe app variable has the same methods as the python class (`submit`,\n`predict`, `view_api`, `duplicate`).\n\n", "heading1": "v1.0 Migration Guide and Breaking", "source_page_url": "https://gradio.app/docs/python-client/version-1-release", "source_page_title": "Python Client - Version 1 Release Docs"}, {"text": "`gradio-rs` is a Gradio Client in Rust built by\n[@JacobLinCool](https://github.com/JacobLinCool). You can find the repo\n[here](https://github.com/JacobLinCool/gradio-rs), and more in depth API\ndocumentation [here](https://docs.rs/gradio/latest/gradio/).\n\n", "heading1": "Introduction", "source_page_url": "https://gradio.app/docs/third-party-clients/rust-client", "source_page_title": "Third Party Clients - Rust Client Docs"}, {"text": "Here is an example of using BS-RoFormer model to separate vocals and\nbackground music from an audio file.\n\n \n \n use gradio::{PredictionInput, Client, ClientOptions};\n \n [tokio::main]\n async fn main() {\n if std::env::args().len() < 2 {\n println!(\"Please provide an audio file path as an argument\");\n std::process::exit(1);\n }\n let args: Vec = std::env::args().collect();\n let file_path = &args[1];\n println!(\"File: {}\", file_path);\n \n let client = Client::new(\"JacobLinCool/vocal-separation\", ClientOptions::default())\n .await\n .unwrap();\n \n let output = client\n .predict(\n \"/separate\",\n vec![\n PredictionInput::from_file(file_path),\n PredictionInput::from_value(\"BS-RoFormer\"),\n ],\n )\n .await\n .unwrap();\n println!(\n \"Vocals: {}\",\n output[0].clone().as_file().unwrap().url.unwrap()\n );\n println!(\n \"Background: {}\",\n output[1].clone().as_file().unwrap().url.unwrap()\n );\n }\n\nYou can find more examples [here](https://github.com/JacobLinCool/gradio-\nrs/tree/main/examples).\n\n", "heading1": "Usage", "source_page_url": "https://gradio.app/docs/third-party-clients/rust-client", "source_page_title": "Third Party Clients - Rust Client Docs"}, {"text": "cargo install gradio\n gr --help\n\nTake [stabilityai/stable-\ndiffusion-3-medium](https://huggingface.co/spaces/stabilityai/stable-\ndiffusion-3-medium) HF Space as an example:\n\n \n \n > gr list stabilityai/stable-diffusion-3-medium\n API Spec for stabilityai/stable-diffusion-3-medium:\n /infer\n Parameters:\n prompt ( str ) \n negative_prompt ( str ) \n seed ( float ) numeric value between 0 and 2147483647\n randomize_seed ( bool ) \n width ( float ) numeric value between 256 and 1344\n height ( float ) numeric value between 256 and 1344\n guidance_scale ( float ) numeric value between 0.0 and 10.0\n num_inference_steps ( float ) numeric value between 1 and 50\n Returns:\n Result ( filepath ) \n Seed ( float ) numeric value between 0 and 2147483647\n \n > gr run stabilityai/stable-diffusion-3-medium infer 'Rusty text \"AI & CLI\" on the snow.' '' 0 true 1024 1024 5 28\n Result: https://stabilityai-stable-diffusion-3-medium.hf.space/file=/tmp/gradio/5735ca7775e05f8d56d929d8f57b099a675c0a01/image.webp\n Seed: 486085626\n\nFor file input, simply use the file path as the argument:\n\n \n \n gr run hf-audio/whisper-large-v3 predict 'test-audio.wav' 'transcribe'\n output: \" Did you know you can try the coolest model on your command line?\"\n\n", "heading1": "Command Line Interface", "source_page_url": "https://gradio.app/docs/third-party-clients/rust-client", "source_page_title": "Third Party Clients - Rust Client Docs"}, {"text": "Gradio applications support programmatic requests from many environments:\n\n * The [Python Client](/docs/python-client): `gradio-client` allows you to make requests from Python environments.\n * The [JavaScript Client](/docs/js-client): `@gradio/client` allows you to make requests in TypeScript from the browser or server-side.\n * You can also query gradio apps [directly from cURL](/guides/querying-gradio-apps-with-curl).\n\n", "heading1": "Gradio Clients", "source_page_url": "https://gradio.app/docs/third-party-clients/introduction", "source_page_title": "Third Party Clients - Introduction Docs"}, {"text": "We also encourage the development and use of third party clients built by\nthe community:\n\n * [Rust Client](/docs/third-party-clients/rust-client): `gradio-rs` built by [@JacobLinCool](https://github.com/JacobLinCool) allows you to make requests in Rust.\n * [Powershell Client](https://github.com/rrg92/powershai): `powershai` built by [@rrg92](https://github.com/rrg92) allows you to make requests to Gradio apps directly from Powershell. See [here for documentation](https://github.com/rrg92/powershai/blob/main/docs/en-US/providers/HUGGING-FACE.md)\n\n", "heading1": "Community Clients", "source_page_url": "https://gradio.app/docs/third-party-clients/introduction", "source_page_title": "Third Party Clients - Introduction Docs"}, {"text": "A Gradio Interface includes a \u2018Flag\u2019 button that appears underneath the\noutput. By default, clicking on the Flag button sends the input and output\ndata back to the machine where the gradio demo is running, and saves it to a\nCSV log file. But this default behavior can be changed. To set what happens\nwhen the Flag button is clicked, you pass an instance of a subclass of\n_FlaggingCallback_ to the _flagging_callback_ parameter in the _Interface_\nconstructor. You can use one of the _FlaggingCallback_ subclasses that are\nlisted below, or you can create your own, which lets you do whatever you want\nwith the data that is being flagged.\n\nSimpleCSVLogger\n\n \n \n gradio.SimpleCSVLogger(\u00b7\u00b7\u00b7)\n\n", "heading1": "Description", "source_page_url": "https://gradio.app/docs/gradio/flagging", "source_page_title": "Gradio - Flagging Docs"}, {"text": "A simplified implementation of the FlaggingCallback abstract class provided\nfor illustrative purposes. Each flagged sample (both the input and output\ndata) is logged to a CSV file on the machine running the gradio app.\n\n", "heading1": "Description", "source_page_url": "https://gradio.app/docs/gradio/flagging", "source_page_title": "Gradio - Flagging Docs"}, {"text": "import gradio as gr\n def image_classifier(inp):\n return {'cat': 0.3, 'dog': 0.7}\n demo = gr.Interface(fn=image_classifier, inputs=\"image\", outputs=\"label\",\n flagging_callback=SimpleCSVLogger())\n\nCSVLogger\n\n \n \n gradio.CSVLogger(\u00b7\u00b7\u00b7)\n\n", "heading1": "Example Usage", "source_page_url": "https://gradio.app/docs/gradio/flagging", "source_page_title": "Gradio - Flagging Docs"}, {"text": "The default implementation of the FlaggingCallback abstract class in\ngradio>=5.0. Each flagged sample (both the input and output data) is logged to\na CSV file with headers on the machine running the gradio app. Unlike\nClassicCSVLogger, this implementation is concurrent-safe and it creates a new\ndataset file every time the headers of the CSV (derived from the labels of the\ncomponents) change. It also only creates columns for \"username\" and \"flag\" if\nthe flag_option and username are provided, respectively. \n\n", "heading1": "Description", "source_page_url": "https://gradio.app/docs/gradio/flagging", "source_page_title": "Gradio - Flagging Docs"}, {"text": "import gradio as gr\n def image_classifier(inp):\n return {'cat': 0.3, 'dog': 0.7}\n demo = gr.Interface(fn=image_classifier, inputs=\"image\", outputs=\"label\",\n flagging_callback=CSVLogger())\n\n", "heading1": "Example Usage", "source_page_url": "https://gradio.app/docs/gradio/flagging", "source_page_title": "Gradio - Flagging Docs"}, {"text": "Parameters \u25bc\n\n\n \n \n simplify_file_data: bool\n\ndefault `= True`\n\nIf True, the file data will be simplified before being written to the CSV\nfile. If CSVLogger is being used to cache examples, this is set to False to\npreserve the original FileData class\n\n\n \n \n verbose: bool\n\ndefault `= True`\n\nIf True, prints messages to the console about the dataset file creation\n\n\n \n \n dataset_file_name: str | None\n\ndefault `= None`\n\nThe name of the dataset file to be created (should end in \".csv\"). If None,\nthe dataset file will be named \"dataset1.csv\" or the next available number.\n\n[Using Flagging](../../guides/using-flagging/)\n\n", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/flagging", "source_page_title": "Gradio - Flagging Docs"}, {"text": "Displays an interactive table of parameters and their descriptions and\ndefault values with syntax highlighting. For each parameter, the user should\nprovide a type (e.g. a `str`), a human-readable description, and a default\nvalue. As this component does not accept user input, it is rarely used as an\ninput component. Internally, this component is used to display the parameters\nof components in the Custom Component Gallery ( \n\n", "heading1": "Description", "source_page_url": "https://gradio.app/docs/gradio/paramviewer", "source_page_title": "Gradio - Paramviewer Docs"}, {"text": "**As input component** : (Rarely used) passes value as a `dict[str, dict]`.\nThe key in the outer dictionary is the parameter name, while the inner\ndictionary has keys \"type\", \"description\", and \"default\" for each parameter.\n\nYour function should accept one of these types:\n\n \n \n def predict(\n \tvalue: dict[str, Parameter]\n )\n \t...\n\n \n\n**As output component** : Expects value as a `dict[str, dict]`. The key in\nthe outer dictionary is the parameter name, while the inner dictionary has\nkeys \"type\", \"description\", and \"default\" for each parameter.\n\nYour function should return one of these types:\n\n \n \n def predict(\u00b7\u00b7\u00b7) -> dict[str, Parameter]\n \t...\t\n \treturn value\n\n", "heading1": "Behavior", "source_page_url": "https://gradio.app/docs/gradio/paramviewer", "source_page_title": "Gradio - Paramviewer Docs"}, {"text": "Parameters \u25bc\n\n\n \n \n value: dict[str, Parameter] | None\n\ndefault `= None`\n\nA dictionary of dictionaries. The key in the outer dictionary is the parameter\nname, while the inner dictionary has keys \"type\", \"description\", and \"default\"\nfor each parameter. Markdown links are supported in \"description\".\n\n\n \n \n language: Literal['python', 'typescript']\n\ndefault `= \"python\"`\n\nThe language to display the code in. One of \"python\" or \"typescript\".\n\n\n \n \n linkify: list[str] | None\n\ndefault `= None`\n\nA list of strings to linkify. If any of these strings is found in the\ndescription, it will be rendered as a link.\n\n\n \n \n every: Timer | float | None\n\ndefault `= None`\n\nContinously calls `value` to recalculate it if `value` is a function (has no\neffect otherwise). Can provide a Timer whose tick resets `value`, or a float\nthat provides the regular interval for the reset Timer.\n\n\n \n \n inputs: Component | list[Component] | set[Component] | None\n\ndefault `= None`\n\nComponents that are used as inputs to calculate `value` if `value` is a\nfunction (has no effect otherwise). `value` is recalculated any time the\ninputs change.\n\n\n \n \n render: bool\n\ndefault `= True`\n\nIf False, component will not render be rendered in the Blocks context. Should\nbe used if the intention is to assign event listeners now but render the\ncomponent later.\n\n\n \n \n key: int | str | tuple[int | str, ...] | None\n\ndefault `= None`\n\nin a gr.render, Components with the same key across re-renders are treated as\nthe same component, not a new component. Properties set in 'preserved_by_key'\nare not reset across a re-render.\n\n\n \n \n preserved_by_key: list[str] | str | None\n\ndefault `= \"value\"`\n\nA list of parameters from this component's constructor. Inside a gr.render()\nfunction, if a component is re-rendered with the same key, these (and only\nthese) parameters will be preserved in the UI (if they have been changed by\nthe user or an event listener) instead of re", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/paramviewer", "source_page_title": "Gradio - Paramviewer Docs"}, {"text": "er()\nfunction, if a component is re-rendered with the same key, these (and only\nthese) parameters will be preserved in the UI (if they have been changed by\nthe user or an event listener) instead of re-rendered based on the values\nprovided during constructor.\n\n\n \n \n header: str | None\n\ndefault `= \"Parameters\"`\n\nThe header to display above the table of parameters, also includes a toggle\nbutton that closes/opens all details at once. If None, no header will be\ndisplayed.\n\n\n \n \n anchor_links: bool | str\n\ndefault `= False`\n\nIf True, creates anchor links for each parameter that can be used to link\ndirectly to that parameter. If a string, creates anchor links with the given\nstring as the prefix to prevent conflicts with other ParamViewer components.\n\n\n \n \n max_height: int | str | None\n\ndefault `= None`\n\nThe maximum height of the component, specified in pixels if a number is\npassed, or in CSS units if a string is passed. If content exceeds the height,\nthe parameter table will scroll vertically while the header remains fixed in\nplace. If content is shorter than the height, the component will shrink to fit\nthe content.\n\n", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/paramviewer", "source_page_title": "Gradio - Paramviewer Docs"}, {"text": "Shortcuts\n\n \n \n gradio.ParamViewer\n\nInterface String Shortcut `\"paramviewer\"`\n\nInitialization Uses default values\n\n", "heading1": "Shortcuts", "source_page_url": "https://gradio.app/docs/gradio/paramviewer", "source_page_title": "Gradio - Paramviewer Docs"}, {"text": "Description\n\nEvent listeners allow you to respond to user interactions with the UI\ncomponents you've defined in a Gradio Blocks app. When a user interacts with\nan element, such as changing a slider value or uploading an image, a function\nis called.\n\nSupported Event Listeners\n\nThe ParamViewer component supports the following event listeners. Each event\nlistener takes the same parameters, which are listed in the Event Parameters\ntable below.\n\nListeners\n\n \n \n ParamViewer.change(fn, \u00b7\u00b7\u00b7)\n\nTriggered when the value of the ParamViewer changes either because of user\ninput (e.g. a user types in a textbox) OR because of a function update (e.g.\nan image receives a value from the output of an event trigger). See `.input()`\nfor a listener that is only triggered by user input.\n\n \n \n ParamViewer.upload(fn, \u00b7\u00b7\u00b7)\n\nThis listener is triggered when the user uploads a file into the ParamViewer.\n\nEvent Parameters\n\nParameters \u25bc\n\n\n \n \n fn: Callable | None | Literal['decorator']\n\ndefault `= \"decorator\"`\n\nthe function to call when this event is triggered. Often a machine learning\nmodel's prediction function. Each parameter of the function corresponds to one\ninput component, and the function should return a single value or a tuple of\nvalues, with each element in the tuple corresponding to one output component.\n\n\n \n \n inputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n\ndefault `= None`\n\nList of gradio.components to use as inputs. If the function takes no inputs,\nthis should be an empty list.\n\n\n \n \n outputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n\ndefault `= None`\n\nList of gradio.components to use as outputs. If the function returns no\noutputs, this should be an empty list.\n\n\n \n \n api_name: str | None\n\ndefault `= None`\n\ndefines how the endpoint appears in the API docs. Can be a string or None. If\nset to a string, the", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/paramviewer", "source_page_title": "Gradio - Paramviewer Docs"}, {"text": "rns no\noutputs, this should be an empty list.\n\n\n \n \n api_name: str | None\n\ndefault `= None`\n\ndefines how the endpoint appears in the API docs. Can be a string or None. If\nset to a string, the endpoint will be exposed in the API docs with the given\nname. If None (default), the name of the function will be used as the API\nendpoint.\n\n\n \n \n api_description: str | None | Literal[False]\n\ndefault `= None`\n\nDescription of the API endpoint. Can be a string, None, or False. If set to a\nstring, the endpoint will be exposed in the API docs with the given\ndescription. If None, the function's docstring will be used as the API\nendpoint description. If False, then no description will be displayed in the\nAPI docs.\n\n\n \n \n scroll_to_output: bool\n\ndefault `= False`\n\nIf True, will scroll to output component on completion\n\n\n \n \n show_progress: Literal['full', 'minimal', 'hidden']\n\ndefault `= \"full\"`\n\nhow to show the progress animation while event is running: \"full\" shows a\nspinner which covers the output component area as well as a runtime display in\nthe upper right corner, \"minimal\" only shows the runtime display, \"hidden\"\nshows no progress animation at all\n\n\n \n \n show_progress_on: Component | list[Component] | None\n\ndefault `= None`\n\nComponent or list of components to show the progress animation on. If None,\nwill show the progress animation on all of the output components.\n\n\n \n \n queue: bool\n\ndefault `= True`\n\nIf True, will place the request on the queue, if the queue has been enabled.\nIf False, will not put this event on the queue, even if the queue has been\nenabled. If None, will use the queue setting of the gradio app.\n\n\n \n \n batch: bool\n\ndefault `= False`\n\nIf True, then the function should process a batch of inputs, meaning that it\nshould accept a list of input values for each parameter. The lists should be\nof equal length (and be up to length `max_batch_size`). The function is then\n*required* to return a tuple of lists", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/paramviewer", "source_page_title": "Gradio - Paramviewer Docs"}, {"text": " that it\nshould accept a list of input values for each parameter. The lists should be\nof equal length (and be up to length `max_batch_size`). The function is then\n*required* to return a tuple of lists (even if there is only 1 output\ncomponent), with each list in the tuple corresponding to one output component.\n\n\n \n \n max_batch_size: int\n\ndefault `= 4`\n\nMaximum number of inputs to batch together if this is called from the queue\n(only relevant if batch=True)\n\n\n \n \n preprocess: bool\n\ndefault `= True`\n\nIf False, will not run preprocessing of component data before running 'fn'\n(e.g. leaving it as a base64 string if this method is called with the `Image`\ncomponent).\n\n\n \n \n postprocess: bool\n\ndefault `= True`\n\nIf False, will not run postprocessing of component data before returning 'fn'\noutput to the browser.\n\n\n \n \n cancels: dict[str, Any] | list[dict[str, Any]] | None\n\ndefault `= None`\n\nA list of other events to cancel when this listener is triggered. For example,\nsetting cancels=[click_event] will cancel the click_event, where click_event\nis the return value of another components .click method. Functions that have\nnot yet run (or generators that are iterating) will be cancelled, but\nfunctions that are currently running will be allowed to finish.\n\n\n \n \n trigger_mode: Literal['once', 'multiple', 'always_last'] | None\n\ndefault `= None`\n\nIf \"once\" (default for all events except `.change()`) would not allow any\nsubmissions while an event is pending. If set to \"multiple\", unlimited\nsubmissions are allowed while pending, and \"always_last\" (default for\n`.change()` and `.key_up()` events) would allow a second submission after the\npending event is complete.\n\n\n \n \n js: str | Literal[True] | None\n\ndefault `= None`\n\nOptional frontend js method to run before running 'fn'. Input arguments for js\nmethod are values of 'inputs' and 'outputs', return should be a list of values\nfor output components.\n\n\n \n \n concurrency_limit: in", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/paramviewer", "source_page_title": "Gradio - Paramviewer Docs"}, {"text": "js method to run before running 'fn'. Input arguments for js\nmethod are values of 'inputs' and 'outputs', return should be a list of values\nfor output components.\n\n\n \n \n concurrency_limit: int | None | Literal['default']\n\ndefault `= \"default\"`\n\nIf set, this is the maximum number of this event that can be running\nsimultaneously. Can be set to None to mean no concurrency_limit (any number of\nthis event can be running simultaneously). Set to \"default\" to use the default\nconcurrency limit (defined by the `default_concurrency_limit` parameter in\n`Blocks.queue()`, which itself is 1 by default).\n\n\n \n \n concurrency_id: str | None\n\ndefault `= None`\n\nIf set, this is the id of the concurrency group. Events with the same\nconcurrency_id will be limited by the lowest set concurrency_limit.\n\n\n \n \n api_visibility: Literal['public', 'private', 'undocumented']\n\ndefault `= \"public\"`\n\ncontrols the visibility and accessibility of this endpoint. Can be \"public\"\n(shown in API docs and callable by clients), \"private\" (hidden from API docs\nand not callable by clients), or \"undocumented\" (hidden from API docs but\ncallable by clients and via gr.load). If fn is None, api_visibility will\nautomatically be set to \"private\".\n\n\n \n \n time_limit: int | None\n\ndefault `= None`\n\n\n \n \n stream_every: float\n\ndefault `= 0.5`\n\n\n \n \n key: int | str | tuple[int | str, ...] | None\n\ndefault `= None`\n\nA unique key for this event listener to be used in @gr.render(). If set, this\nvalue identifies an event as identical across re-renders when the key is\nidentical.\n\n\n \n \n validator: Callable | None\n\ndefault `= None`\n\nOptional validation function to run before the main function. If provided,\nthis function will be executed first with queue=False, and only if it\ncompletes successfully will the main function be called. The validator\nreceives the same inputs as the main function and should return a\n`gr.validate()` for each input value.\n\n[Documenting Custom Comp", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/paramviewer", "source_page_title": "Gradio - Paramviewer Docs"}, {"text": "completes successfully will the main function be called. The validator\nreceives the same inputs as the main function and should return a\n`gr.validate()` for each input value.\n\n[Documenting Custom Components](../../guides/documenting-custom-components/)\n\n", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/paramviewer", "source_page_title": "Gradio - Paramviewer Docs"}, {"text": "Creates an audio component that can be used to upload/record audio (as an\ninput) or display audio (as an output).\n\n", "heading1": "Description", "source_page_url": "https://gradio.app/docs/gradio/audio", "source_page_title": "Gradio - Audio Docs"}, {"text": "**As input component** : passes audio as one of these formats (depending on\n`type`): a `str` filepath, or `tuple` of (sample rate in Hz, audio data as\nnumpy array). If the latter, the audio data is a 16-bit `int` array whose\nvalues range from -32768 to 32767 and shape of the audio data array is\n(samples,) for mono audio or (samples, channels) for multi-channel audio.\n\nYour function should accept one of these types:\n\n \n \n def predict(\n \tvalue: str | tuple[int, np.ndarray] | None\n )\n \t...\n\n \n\n**As output component** : expects audio data in any of these formats: a\n`str` or `pathlib.Path` filepath or URL to an audio file, or a `bytes` object\n(recommended for streaming), or a `tuple` of (sample rate in Hz, audio data as\nnumpy array). Note: if audio is supplied as a numpy array, the audio will be\nnormalized by its peak value to avoid distortion or clipping in the resulting\naudio.\n\nYour function should return one of these types:\n\n \n \n def predict(\u00b7\u00b7\u00b7) -> str | Path | bytes | tuple[int, np.ndarray] | None\n \t...\t\n \treturn value\n\n", "heading1": "Behavior", "source_page_url": "https://gradio.app/docs/gradio/audio", "source_page_title": "Gradio - Audio Docs"}, {"text": "Parameters \u25bc\n\n\n \n \n value: str | Path | tuple[int, np.ndarray] | Callable | None\n\ndefault `= None`\n\nA path, URL, or [sample_rate, numpy array] tuple (sample rate in Hz, audio\ndata as a float or int numpy array) for the default value that Audio component\nis going to take. If a function is provided, the function will be called each\ntime the app loads to set the initial value of this component.\n\n\n \n \n sources: list[Literal['upload', 'microphone']] | Literal['upload', 'microphone'] | None\n\ndefault `= None`\n\nA list of sources permitted for audio. \"upload\" creates a box where user can\ndrop an audio file, \"microphone\" creates a microphone input. The first element\nin the list will be used as the default source. If None, defaults to\n[\"upload\", \"microphone\"], or [\"microphone\"] if `streaming` is True.\n\n\n \n \n type: Literal['numpy', 'filepath']\n\ndefault `= \"numpy\"`\n\nThe format the audio file is converted to before being passed into the\nprediction function. \"numpy\" converts the audio to a tuple consisting of: (int\nsample rate, numpy.array for the data), \"filepath\" passes a str path to a\ntemporary file containing the audio.\n\n\n \n \n label: str | I18nData | None\n\ndefault `= None`\n\nthe label for this component. Appears above the component and is also used as\nthe header if there are a table of examples for this component. If None and\nused in a `gr.Interface`, the label will be the name of the parameter this\ncomponent is assigned to.\n\n\n \n \n every: Timer | float | None\n\ndefault `= None`\n\nContinously calls `value` to recalculate it if `value` is a function (has no\neffect otherwise). Can provide a Timer whose tick resets `value`, or a float\nthat provides the regular interval for the reset Timer.\n\n\n \n \n inputs: Component | list[Component] | set[Component] | None\n\ndefault `= None`\n\nComponents that are used as inputs to calculate `value` if `value` is a\nfunction (has no effect otherwise). `value` is recalculated any time the\ninputs change.", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/audio", "source_page_title": "Gradio - Audio Docs"}, {"text": "set[Component] | None\n\ndefault `= None`\n\nComponents that are used as inputs to calculate `value` if `value` is a\nfunction (has no effect otherwise). `value` is recalculated any time the\ninputs change.\n\n\n \n \n show_label: bool | None\n\ndefault `= None`\n\nif True, will display label.\n\n\n \n \n container: bool\n\ndefault `= True`\n\nIf True, will place the component in a container - providing some extra\npadding around the border.\n\n\n \n \n scale: int | None\n\ndefault `= None`\n\nRelative width compared to adjacent Components in a Row. For example, if\nComponent A has scale=2, and Component B has scale=1, A will be twice as wide\nas B. Should be an integer.\n\n\n \n \n min_width: int\n\ndefault `= 160`\n\nMinimum pixel width, will wrap if not sufficient screen space to satisfy this\nvalue. If a certain scale value results in this Component being narrower than\nmin_width, the min_width parameter will be respected first.\n\n\n \n \n interactive: bool | None\n\ndefault `= None`\n\nIf True, will allow users to upload and edit an audio file. If False, can only\nbe used to play audio. If not provided, this is inferred based on whether the\ncomponent is used as an input or output.\n\n\n \n \n visible: bool | Literal['hidden']\n\ndefault `= True`\n\nIf False, component will be hidden. If \"hidden\", component will be visually\nhidden and not take up space in the layout but still exist in the DOM If\n\"hidden\", component will be visually hidden and not take up space in the\nlayout but still exist in the DOM.\n\n\n \n \n streaming: bool\n\ndefault `= False`\n\nIf set to True when used in a `live` interface as an input, will automatically\nstream webcam feed. When used set as an output, takes audio chunks yield from\nthe backend and combines them into one streaming audio output.\n\n\n \n \n elem_id: str | None\n\ndefault `= None`\n\nAn optional string that is assigned as the id of this component in the HTML\nDOM. Can be used for targeting CSS styles.\n\n\n \n \n elem_classes: list", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/audio", "source_page_title": "Gradio - Audio Docs"}, {"text": " \n elem_id: str | None\n\ndefault `= None`\n\nAn optional string that is assigned as the id of this component in the HTML\nDOM. Can be used for targeting CSS styles.\n\n\n \n \n elem_classes: list[str] | str | None\n\ndefault `= None`\n\nAn optional list of strings that are assigned as the classes of this component\nin the HTML DOM. Can be used for targeting CSS styles.\n\n\n \n \n render: bool\n\ndefault `= True`\n\nif False, component will not be rendered in the Blocks context. Should be used\nif the intention is to assign event listeners now but render the component\nlater.\n\n\n \n \n key: int | str | tuple[int | str, ...] | None\n\ndefault `= None`\n\nin a gr.render, Components with the same key across re-renders are treated as\nthe same component, not a new component. Properties set in 'preserved_by_key'\nare not reset across a re-render.\n\n\n \n \n preserved_by_key: list[str] | str | None\n\ndefault `= \"value\"`\n\nA list of parameters from this component's constructor. Inside a gr.render()\nfunction, if a component is re-rendered with the same key, these (and only\nthese) parameters will be preserved in the UI (if they have been changed by\nthe user or an event listener) instead of re-rendered based on the values\nprovided during constructor.\n\n\n \n \n format: Literal['wav', 'mp3'] | None\n\ndefault `= None`\n\nthe file extension with which to save audio files. Either 'wav' or 'mp3'. wav\nfiles are lossless but will tend to be larger files. mp3 files tend to be\nsmaller. This parameter applies both when this component is used as an input\n(and `type` is \"filepath\") to determine which file format to convert user-\nprovided audio to, and when this component is used as an output to determine\nthe format of audio returned to the user. If None, no file format conversion\nis done and the audio is kept as is. In the case where output audio is\nreturned from the prediction function as numpy array and no `format` is\nprovided, it will be returned as a \"wav\" file.\n\n\n \n \n au", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/audio", "source_page_title": "Gradio - Audio Docs"}, {"text": "and the audio is kept as is. In the case where output audio is\nreturned from the prediction function as numpy array and no `format` is\nprovided, it will be returned as a \"wav\" file.\n\n\n \n \n autoplay: bool\n\ndefault `= False`\n\nWhether to automatically play the audio when the component is used as an\noutput. Note: browsers will not autoplay audio files if the user has not\ninteracted with the page yet.\n\n\n \n \n editable: bool\n\ndefault `= True`\n\nIf True, allows users to manipulate the audio file if the component is\ninteractive. Defaults to True.\n\n\n \n \n buttons: list[Literal['download', 'share'] | Button] | None\n\ndefault `= None`\n\nA list of buttons to show in the top right corner of the component. Valid\noptions are \"download\", \"share\", or a gr.Button() instance. The \"download\"\nbutton allows the user to save the audio to their device. The \"share\" button\nallows the user to share the audio via Hugging Face Spaces Discussions. Custom\ngr.Button() instances will appear in the toolbar with their configured icon\nand/or label, and clicking them will trigger any .click() events registered on\nthe button. By default, only the \"download\" and \"share\" buttons are shown.\n\n\n \n \n waveform_options: WaveformOptions | dict | None\n\ndefault `= None`\n\nA dictionary of options for the waveform display. Options include:\nwaveform_color (str), waveform_progress_color (str), skip_length (int),\ntrim_region_color (str). Default is None, which uses the default values for\nthese options. See `gr.WaveformOptions` docs.\n\n\n \n \n loop: bool\n\ndefault `= False`\n\nIf True, the audio will loop when it reaches the end and continue playing from\nthe beginning.\n\n\n \n \n recording: bool\n\ndefault `= False`\n\nIf True, the audio component will be set to record audio from the microphone\nif the source is set to \"microphone\". Defaults to False.\n\n\n \n \n subtitles: str | Path | list[dict[str, Any]] | None\n\ndefault `= None`\n\nA subtitle file (srt, vtt, or json) for the audio, ", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/audio", "source_page_title": "Gradio - Audio Docs"}, {"text": "hone\nif the source is set to \"microphone\". Defaults to False.\n\n\n \n \n subtitles: str | Path | list[dict[str, Any]] | None\n\ndefault `= None`\n\nA subtitle file (srt, vtt, or json) for the audio, or a list of subtitle\ndictionaries in the format [{\"text\": str, \"timestamp\": [start, end]}] where\ntimestamps are in seconds. JSON files should contain an array of subtitle\nobjects.\n\n\n \n \n playback_position: float\n\ndefault `= 0`\n\nThe starting playback position in seconds. This value is also updated as the\naudio plays, reflecting the current playback position.\n\n", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/audio", "source_page_title": "Gradio - Audio Docs"}, {"text": "Shortcuts\n\n \n \n gradio.Audio\n\nInterface String Shortcut `\"audio\"`\n\nInitialization Uses default values\n\n \n \n gradio.Microphone\n\nInterface String Shortcut `\"microphone\"`\n\nInitialization Uses sources=[\"microphone\"]\n\n", "heading1": "Shortcuts", "source_page_url": "https://gradio.app/docs/gradio/audio", "source_page_title": "Gradio - Audio Docs"}, {"text": "generate_tonereverse_audio\n\n", "heading1": "Demos", "source_page_url": "https://gradio.app/docs/gradio/audio", "source_page_title": "Gradio - Audio Docs"}, {"text": "Description\n\nEvent listeners allow you to respond to user interactions with the UI\ncomponents you've defined in a Gradio Blocks app. When a user interacts with\nan element, such as changing a slider value or uploading an image, a function\nis called.\n\nSupported Event Listeners\n\nThe Audio component supports the following event listeners. Each event\nlistener takes the same parameters, which are listed in the Event Parameters\ntable below.\n\nListeners\n\n \n \n Audio.stream(fn, \u00b7\u00b7\u00b7)\n\nThis listener is triggered when the user streams the Audio.\n\n \n \n Audio.change(fn, \u00b7\u00b7\u00b7)\n\nTriggered when the value of the Audio changes either because of user input\n(e.g. a user types in a textbox) OR because of a function update (e.g. an\nimage receives a value from the output of an event trigger). See `.input()`\nfor a listener that is only triggered by user input.\n\n \n \n Audio.clear(fn, \u00b7\u00b7\u00b7)\n\nThis listener is triggered when the user clears the Audio using the clear\nbutton for the component.\n\n \n \n Audio.play(fn, \u00b7\u00b7\u00b7)\n\nThis listener is triggered when the user plays the media in the Audio.\n\n \n \n Audio.pause(fn, \u00b7\u00b7\u00b7)\n\nThis listener is triggered when the media in the Audio stops for any reason.\n\n \n \n Audio.stop(fn, \u00b7\u00b7\u00b7)\n\nThis listener is triggered when the user reaches the end of the media playing\nin the Audio.\n\n \n \n Audio.pause(fn, \u00b7\u00b7\u00b7)\n\nThis listener is triggered when the media in the Audio stops for any reason.\n\n \n \n Audio.start_recording(fn, \u00b7\u00b7\u00b7)\n\nThis listener is triggered when the user starts recording with the Audio.\n\n \n \n Audio.pause_recording(fn, \u00b7\u00b7\u00b7)\n\nThis listener is triggered when the user pauses recording with the Audio.\n\n \n \n Audio.stop_recording(fn, \u00b7\u00b7\u00b7)\n\nThis listener is triggered when the user stops recording with the Audio.\n\n \n \n Audio.upload(fn, \u00b7\u00b7\u00b7)\n\nThis listener is triggered when the user uploads a file into the Audio.\n\n \n \n Audio.input(fn, \u00b7\u00b7\u00b7)\n\nThis listener is tr", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/audio", "source_page_title": "Gradio - Audio Docs"}, {"text": "r stops recording with the Audio.\n\n \n \n Audio.upload(fn, \u00b7\u00b7\u00b7)\n\nThis listener is triggered when the user uploads a file into the Audio.\n\n \n \n Audio.input(fn, \u00b7\u00b7\u00b7)\n\nThis listener is triggered when the user changes the value of the Audio.\n\nEvent Parameters\n\nParameters \u25bc\n\n\n \n \n fn: Callable | None | Literal['decorator']\n\ndefault `= \"decorator\"`\n\nthe function to call when this event is triggered. Often a machine learning\nmodel's prediction function. Each parameter of the function corresponds to one\ninput component, and the function should return a single value or a tuple of\nvalues, with each element in the tuple corresponding to one output component.\n\n\n \n \n inputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n\ndefault `= None`\n\nList of gradio.components to use as inputs. If the function takes no inputs,\nthis should be an empty list.\n\n\n \n \n outputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n\ndefault `= None`\n\nList of gradio.components to use as outputs. If the function returns no\noutputs, this should be an empty list.\n\n\n \n \n api_name: str | None\n\ndefault `= None`\n\ndefines how the endpoint appears in the API docs. Can be a string or None. If\nset to a string, the endpoint will be exposed in the API docs with the given\nname. If None (default), the name of the function will be used as the API\nendpoint.\n\n\n \n \n api_description: str | None | Literal[False]\n\ndefault `= None`\n\nDescription of the API endpoint. Can be a string, None, or False. If set to a\nstring, the endpoint will be exposed in the API docs with the given\ndescription. If None, the function's docstring will be used as the API\nendpoint description. If False, then no description will be displayed in the\nAPI docs.\n\n\n \n \n scroll_to_output: bool\n\ndefault `= False`\n\nIf True, will scroll to output component on completion\n\n\n \n \n show_p", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/audio", "source_page_title": "Gradio - Audio Docs"}, {"text": "f False, then no description will be displayed in the\nAPI docs.\n\n\n \n \n scroll_to_output: bool\n\ndefault `= False`\n\nIf True, will scroll to output component on completion\n\n\n \n \n show_progress: Literal['full', 'minimal', 'hidden']\n\ndefault `= \"minimal\"`\n\nhow to show the progress animation while event is running: \"full\" shows a\nspinner which covers the output component area as well as a runtime display in\nthe upper right corner, \"minimal\" only shows the runtime display, \"hidden\"\nshows no progress animation at all\n\n\n \n \n show_progress_on: Component | list[Component] | None\n\ndefault `= None`\n\nComponent or list of components to show the progress animation on. If None,\nwill show the progress animation on all of the output components.\n\n\n \n \n queue: bool\n\ndefault `= True`\n\nIf True, will place the request on the queue, if the queue has been enabled.\nIf False, will not put this event on the queue, even if the queue has been\nenabled. If None, will use the queue setting of the gradio app.\n\n\n \n \n batch: bool\n\ndefault `= False`\n\nIf True, then the function should process a batch of inputs, meaning that it\nshould accept a list of input values for each parameter. The lists should be\nof equal length (and be up to length `max_batch_size`). The function is then\n*required* to return a tuple of lists (even if there is only 1 output\ncomponent), with each list in the tuple corresponding to one output component.\n\n\n \n \n max_batch_size: int\n\ndefault `= 4`\n\nMaximum number of inputs to batch together if this is called from the queue\n(only relevant if batch=True)\n\n\n \n \n preprocess: bool\n\ndefault `= True`\n\nIf False, will not run preprocessing of component data before running 'fn'\n(e.g. leaving it as a base64 string if this method is called with the `Image`\ncomponent).\n\n\n \n \n postprocess: bool\n\ndefault `= True`\n\nIf False, will not run postprocessing of component data before returning 'fn'\noutput to the browser.\n\n\n \n \n c", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/audio", "source_page_title": "Gradio - Audio Docs"}, {"text": "with the `Image`\ncomponent).\n\n\n \n \n postprocess: bool\n\ndefault `= True`\n\nIf False, will not run postprocessing of component data before returning 'fn'\noutput to the browser.\n\n\n \n \n cancels: dict[str, Any] | list[dict[str, Any]] | None\n\ndefault `= None`\n\nA list of other events to cancel when this listener is triggered. For example,\nsetting cancels=[click_event] will cancel the click_event, where click_event\nis the return value of another components .click method. Functions that have\nnot yet run (or generators that are iterating) will be cancelled, but\nfunctions that are currently running will be allowed to finish.\n\n\n \n \n trigger_mode: Literal['once', 'multiple', 'always_last'] | None\n\ndefault `= None`\n\nIf \"once\" (default for all events except `.change()`) would not allow any\nsubmissions while an event is pending. If set to \"multiple\", unlimited\nsubmissions are allowed while pending, and \"always_last\" (default for\n`.change()` and `.key_up()` events) would allow a second submission after the\npending event is complete.\n\n\n \n \n js: str | Literal[True] | None\n\ndefault `= None`\n\nOptional frontend js method to run before running 'fn'. Input arguments for js\nmethod are values of 'inputs' and 'outputs', return should be a list of values\nfor output components.\n\n\n \n \n concurrency_limit: int | None | Literal['default']\n\ndefault `= \"default\"`\n\nIf set, this is the maximum number of this event that can be running\nsimultaneously. Can be set to None to mean no concurrency_limit (any number of\nthis event can be running simultaneously). Set to \"default\" to use the default\nconcurrency limit (defined by the `default_concurrency_limit` parameter in\n`Blocks.queue()`, which itself is 1 by default).\n\n\n \n \n concurrency_id: str | None\n\ndefault `= None`\n\nIf set, this is the id of the concurrency group. Events with the same\nconcurrency_id will be limited by the lowest set concurrency_limit.\n\n\n \n \n api_visibility: Literal['public', 'pr", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/audio", "source_page_title": "Gradio - Audio Docs"}, {"text": "= None`\n\nIf set, this is the id of the concurrency group. Events with the same\nconcurrency_id will be limited by the lowest set concurrency_limit.\n\n\n \n \n api_visibility: Literal['public', 'private', 'undocumented']\n\ndefault `= \"public\"`\n\ncontrols the visibility and accessibility of this endpoint. Can be \"public\"\n(shown in API docs and callable by clients), \"private\" (hidden from API docs\nand not callable by clients), or \"undocumented\" (hidden from API docs but\ncallable by clients and via gr.load). If fn is None, api_visibility will\nautomatically be set to \"private\".\n\n\n \n \n time_limit: int | None\n\ndefault `= None`\n\n\n \n \n stream_every: float\n\ndefault `= 0.5`\n\n\n \n \n key: int | str | tuple[int | str, ...] | None\n\ndefault `= None`\n\nA unique key for this event listener to be used in @gr.render(). If set, this\nvalue identifies an event as identical across re-renders when the key is\nidentical.\n\n\n \n \n validator: Callable | None\n\ndefault `= None`\n\nOptional validation function to run before the main function. If provided,\nthis function will be executed first with queue=False, and only if it\ncompletes successfully will the main function be called. The validator\nreceives the same inputs as the main function and should return a\n`gr.validate()` for each input value.\n\n", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/audio", "source_page_title": "Gradio - Audio Docs"}, {"text": "", "heading1": "Helper Classes", "source_page_url": "https://gradio.app/docs/gradio/audio", "source_page_title": "Gradio - Audio Docs"}, {"text": "gradio.WaveformOptions(\u00b7\u00b7\u00b7)\n\nDescription\n\nA dataclass for specifying options for the waveform display in the Audio\ncomponent. An instance of this class can be passed into the `waveform_options`\nparameter of `gr.Audio`.\n\nInitialization\n\nParameters \u25bc\n\n\n \n \n waveform_color: str | None\n\ndefault `= None`\n\nThe color (as a hex string or valid CSS color) of the full waveform\nrepresenting the amplitude of the audio. Defaults to a light gray color.\n\n\n \n \n waveform_progress_color: str | None\n\ndefault `= None`\n\nThe color (as a hex string or valid CSS color) that the waveform fills with to\nas the audio plays. Defaults to the accent color.\n\n\n \n \n trim_region_color: str | None\n\ndefault `= None`\n\nThe color (as a hex string or valid CSS color) of the trim region. Defaults to\nthe accent color.\n\n\n \n \n show_recording_waveform: bool\n\ndefault `= True`\n\nIf True, shows a waveform when recording audio or playing audio. If False,\nuses the default browser audio players. For streamed audio, the default\nbrowser audio player is always used.\n\n\n \n \n skip_length: int | float\n\ndefault `= 5`\n\nThe percentage (between 0 and 100) of the audio to skip when clicking on the\nskip forward / skip backward buttons.\n\n\n \n \n sample_rate: int\n\ndefault `= 44100`\n\nThe output sample rate (in Hz) of the audio after editing.\n\n", "heading1": "WaveformOptions", "source_page_url": "https://gradio.app/docs/gradio/audio", "source_page_title": "Gradio - Audio Docs"}, {"text": "Validates that the audio length is within the specified min and max length (in\nseconds). You can use this to construct a validator that will check if the\nuser-provided audio is either too short or too long.\n\n \n \n import gradio as gr\n demo = 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 )\n demo.launch()\n\nInitialization\n\nParameters \u25bc\n\n\n \n \n audio: tuple[int, 'np.ndarray']\n\nA tuple of (sample rate in Hz, audio data as numpy array).\n\n\n \n \n min_length: float | None\n\nMinimum length of audio in seconds. If None, no minimum length check is\nperformed.\n\n\n \n \n max_length: float | None\n\nMaximum length of audio in seconds. If None, no maximum length check is\nperformed.\n\n[Streaming Inputs](../../guides/streaming-inputs/)[Streaming\nOutputs](../../guides/streaming-outputs/)[Automatic Voice\nDetection](../../guides/automatic-voice-detection/)[Real Time Speech\nRecognition](../../guides/real-time-speech-recognition/)\n\n", "heading1": "is_audio_correct_length", "source_page_url": "https://gradio.app/docs/gradio/audio", "source_page_title": "Gradio - Audio Docs"}, {"text": "Tab (or its alias TabItem) is a layout element. Components defined within\nthe Tab will be visible when this tab is selected tab.\n\n", "heading1": "Description", "source_page_url": "https://gradio.app/docs/gradio/tab", "source_page_title": "Gradio - Tab Docs"}, {"text": "with 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\n", "heading1": "Example Usage", "source_page_url": "https://gradio.app/docs/gradio/tab", "source_page_title": "Gradio - Tab Docs"}, {"text": "Parameters \u25bc\n\n\n \n \n label: str | I18nData | None\n\ndefault `= None`\n\nThe visual label for the tab\n\n\n \n \n visible: bool | Literal['hidden']\n\ndefault `= True`\n\nIf False, Tab will be hidden.\n\n\n \n \n interactive: bool\n\ndefault `= True`\n\nIf False, Tab will not be clickable.\n\n\n \n \n id: int | str | None\n\ndefault `= None`\n\nAn optional identifier for the tab, required if you wish to control the\nselected tab from a predict function.\n\n\n \n \n elem_id: str | None\n\ndefault `= None`\n\nAn optional string that is assigned as the id of the
containing the\ncontents of the Tab layout. The same string followed by \"-button\" is attached\nto the Tab button. Can be used for targeting CSS styles.\n\n\n \n \n elem_classes: list[str] | str | None\n\ndefault `= None`\n\nAn optional string or list of strings that are assigned as the class of this\ncomponent in the HTML DOM. Can be used for targeting CSS styles.\n\n\n \n \n scale: int | None\n\ndefault `= None`\n\nrelative size compared to adjacent elements. 1 or greater indicates the Tab\nwill expand in size.\n\n\n \n \n render: bool\n\ndefault `= True`\n\nIf False, this layout will not be rendered in the Blocks context. Should be\nused if the intention is to assign event listeners now but render the\ncomponent later.\n\n\n \n \n key: int | str | tuple[int | str, ...] | None\n\ndefault `= None`\n\n\n \n \n preserved_by_key: list[str] | str | None\n\ndefault `= None`\n\n\n \n \n render_children: bool\n\ndefault `= False`\n\nIf True, the children of this Tab will be rendered on the page (but hidden)\nwhen the Tab is visible but inactive. This can be useful if you want to ensure\nthat any components (e.g. videos or audio) within the Tab are pre-loaded\nbefore the user clicks on the Tab.\n\n", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/tab", "source_page_title": "Gradio - Tab Docs"}, {"text": "", "heading1": "Methods", "source_page_url": "https://gradio.app/docs/gradio/tab", "source_page_title": "Gradio - Tab Docs"}, {"text": "![](data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20fill='%23808080'%20viewBox='0%200%20640%20512'%3e%3c!--!%20Font%20Awesome%20Pro%206.0.0%20by%20@fontawesome%20-%20https://fontawesome.com%20License%20-%20https://fontawesome.com/license%20\\(Commercial%20License\\)%20Copyright%202022%20Fonticons,%20Inc.%20--%3e%3cpath%20d='M172.5%20131.1C228.1%2075.51%20320.5%2075.51%20376.1%20131.1C426.1%20181.1%20433.5%20260.8%20392.4%20318.3L391.3%20319.9C381%20334.2%20361%20337.6%20346.7%20327.3C332.3%20317%20328.9%20297%20339.2%20282.7L340.3%20281.1C363.2%20249%20359.6%20205.1%20331.7%20177.2C300.3%20145.8%20249.2%20145.8%20217.7%20177.2L105.5%20289.5C73.99%20320.1%2073.99%20372%20105.5%20403.5C133.3%20431.4%20177.3%20435%20209.3%20412.1L210.9%20410.1C225.3%20400.7%20245.3%20404%20255.5%20418.4C265.8%20432.8%20262.5%20452.8%20248.1%20463.1L246.5%20464.2C188.1%20505.3%20110.2%20498.7%2060.21%20448.8C3.741%20392.3%203.741%20300.7%2060.21%20244.3L172.5%20131.1zM467.5%20380C411%20436.5%20319.5%20436.5%20263%20380C213%20330%20206.5%20251.2%20247.6%20193.7L248.7%20192.1C258.1%20177.8%20278.1%20174.4%20293.3%20184.7C307.7%20194.1%20311.1%20214.1%20300.8%20229.3L299.7%20230.9C276.8%20262.1%20280.4%20306.9%20308.3%20334.8C339.7%20366.2%20390.8%20366.2%20422.3%20334.8L534.5%20222.5C566%20191%20566%20139.1%20534.5%20108.5C506.7%2080.63%20462.7%2076.99%20430.7%2099.9L429.1%20101C414.7%20111.3%20394.7%20107.1%20384.5%2093.58C374.2%2079.2%20377.5%2059.21%20391.9%2048.94L393.5%2047.82C451%206.731%20529.8%2013.25%20579.8%2063.24C636.3%20119.7%20636.3%20211.3%20579.8%20267.7L467.5%20380z'/%3e%3c/svg%3e)\n\n \n \n gradio.Tab.select(\u00b7\u00b7\u00b7)\n\nDescription\n![](data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20fill='%23808080'%20viewBox='0%200%20640%20512'%3e%3c!--!%20Font%20Awesome%20Pro%206.0.0%20by%20@fontawesome%20-%20https://fontawesome.com%20License%20-%20https://fontawesome.com/license%20\\(Commercial%20License\\)%20Copyright%202022%20Fonticons,%20Inc.%20--%", "heading1": "select", "source_page_url": "https://gradio.app/docs/gradio/tab", "source_page_title": "Gradio - Tab Docs"}, {"text": "20Font%20Awesome%20Pro%206.0.0%20by%20@fontawesome%20-%20https://fontawesome.com%20License%20-%20https://fontawesome.com/license%20\\(Commercial%20License\\)%20Copyright%202022%20Fonticons,%20Inc.%20--%3e%3cpath%20d='M172.5%20131.1C228.1%2075.51%20320.5%2075.51%20376.1%20131.1C426.1%20181.1%20433.5%20260.8%20392.4%20318.3L391.3%20319.9C381%20334.2%20361%20337.6%20346.7%20327.3C332.3%20317%20328.9%20297%20339.2%20282.7L340.3%20281.1C363.2%20249%20359.6%20205.1%20331.7%20177.2C300.3%20145.8%20249.2%20145.8%20217.7%20177.2L105.5%20289.5C73.99%20320.1%2073.99%20372%20105.5%20403.5C133.3%20431.4%20177.3%20435%20209.3%20412.1L210.9%20410.1C225.3%20400.7%20245.3%20404%20255.5%20418.4C265.8%20432.8%20262.5%20452.8%20248.1%20463.1L246.5%20464.2C188.1%20505.3%20110.2%20498.7%2060.21%20448.8C3.741%20392.3%203.741%20300.7%2060.21%20244.3L172.5%20131.1zM467.5%20380C411%20436.5%20319.5%20436.5%20263%20380C213%20330%20206.5%20251.2%20247.6%20193.7L248.7%20192.1C258.1%20177.8%20278.1%20174.4%20293.3%20184.7C307.7%20194.1%20311.1%20214.1%20300.8%20229.3L299.7%20230.9C276.8%20262.1%20280.4%20306.9%20308.3%20334.8C339.7%20366.2%20390.8%20366.2%20422.3%20334.8L534.5%20222.5C566%20191%20566%20139.1%20534.5%20108.5C506.7%2080.63%20462.7%2076.99%20430.7%2099.9L429.1%20101C414.7%20111.3%20394.7%20107.1%20384.5%2093.58C374.2%2079.2%20377.5%2059.21%20391.9%2048.94L393.5%2047.82C451%206.731%20529.8%2013.25%20579.8%2063.24C636.3%20119.7%20636.3%20211.3%20579.8%20267.7L467.5%20380z'/%3e%3c/svg%3e)\n\nEvent listener for when the user selects the Tab. Uses event data\ngradio.SelectData to carry `value` referring to the label of the Tab, and\n`selected` to refer to state of the Tab. See\nhttps://www.gradio.app/main/docs/gradio/eventdata documentation for more\ndetails.\n\nParameters \u25bc\n\n\n \n \n fn: Callable | None | Literal['decorator']\n\ndefault `= \"decorator\"`\n\nthe function to call when this event is triggered. Often a machine learning\nmodel's prediction function. Each parameter of the function corre", "heading1": "select", "source_page_url": "https://gradio.app/docs/gradio/tab", "source_page_title": "Gradio - Tab Docs"}, {"text": "le | None | Literal['decorator']\n\ndefault `= \"decorator\"`\n\nthe function to call when this event is triggered. Often a machine learning\nmodel's prediction function. Each parameter of the function corresponds to one\ninput component, and the function should return a single value or a tuple of\nvalues, with each element in the tuple corresponding to one output component.\n\n\n \n \n inputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n\ndefault `= None`\n\nList of gradio.components to use as inputs. If the function takes no inputs,\nthis should be an empty list.\n\n\n \n \n outputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n\ndefault `= None`\n\nList of gradio.components to use as outputs. If the function returns no\noutputs, this should be an empty list.\n\n\n \n \n api_name: str | None\n\ndefault `= None`\n\ndefines how the endpoint appears in the API docs. Can be a string or None. If\nset to a string, the endpoint will be exposed in the API docs with the given\nname. If None (default), the name of the function will be used as the API\nendpoint.\n\n\n \n \n api_description: str | None | Literal[False]\n\ndefault `= None`\n\nDescription of the API endpoint. Can be a string, None, or False. If set to a\nstring, the endpoint will be exposed in the API docs with the given\ndescription. If None, the function's docstring will be used as the API\nendpoint description. If False, then no description will be displayed in the\nAPI docs.\n\n\n \n \n scroll_to_output: bool\n\ndefault `= False`\n\nIf True, will scroll to output component on completion\n\n\n \n \n show_progress: Literal['full', 'minimal', 'hidden']\n\ndefault `= \"full\"`\n\nhow to show the progress animation while event is running: \"full\" shows a\nspinner which covers the output component area as well as a runtime display in\nthe upper right corner, \"minimal\" only shows the runtime display, \"hidden\"\nshows no progress anim", "heading1": "select", "source_page_url": "https://gradio.app/docs/gradio/tab", "source_page_title": "Gradio - Tab Docs"}, {"text": "running: \"full\" shows a\nspinner which covers the output component area as well as a runtime display in\nthe upper right corner, \"minimal\" only shows the runtime display, \"hidden\"\nshows no progress animation at all\n\n\n \n \n show_progress_on: Component | list[Component] | None\n\ndefault `= None`\n\nComponent or list of components to show the progress animation on. If None,\nwill show the progress animation on all of the output components.\n\n\n \n \n queue: bool\n\ndefault `= True`\n\nIf True, will place the request on the queue, if the queue has been enabled.\nIf False, will not put this event on the queue, even if the queue has been\nenabled. If None, will use the queue setting of the gradio app.\n\n\n \n \n batch: bool\n\ndefault `= False`\n\nIf True, then the function should process a batch of inputs, meaning that it\nshould accept a list of input values for each parameter. The lists should be\nof equal length (and be up to length `max_batch_size`). The function is then\n*required* to return a tuple of lists (even if there is only 1 output\ncomponent), with each list in the tuple corresponding to one output component.\n\n\n \n \n max_batch_size: int\n\ndefault `= 4`\n\nMaximum number of inputs to batch together if this is called from the queue\n(only relevant if batch=True)\n\n\n \n \n preprocess: bool\n\ndefault `= True`\n\nIf False, will not run preprocessing of component data before running 'fn'\n(e.g. leaving it as a base64 string if this method is called with the `Image`\ncomponent).\n\n\n \n \n postprocess: bool\n\ndefault `= True`\n\nIf False, will not run postprocessing of component data before returning 'fn'\noutput to the browser.\n\n\n \n \n cancels: dict[str, Any] | list[dict[str, Any]] | None\n\ndefault `= None`\n\nA list of other events to cancel when this listener is triggered. For example,\nsetting cancels=[click_event] will cancel the click_event, where click_event\nis the return value of another components .click method. Functions that have\nnot yet run (or", "heading1": "select", "source_page_url": "https://gradio.app/docs/gradio/tab", "source_page_title": "Gradio - Tab Docs"}, {"text": "ner is triggered. For example,\nsetting cancels=[click_event] will cancel the click_event, where click_event\nis the return value of another components .click method. Functions that have\nnot yet run (or generators that are iterating) will be cancelled, but\nfunctions that are currently running will be allowed to finish.\n\n\n \n \n trigger_mode: Literal['once', 'multiple', 'always_last'] | None\n\ndefault `= None`\n\nIf \"once\" (default for all events except `.change()`) would not allow any\nsubmissions while an event is pending. If set to \"multiple\", unlimited\nsubmissions are allowed while pending, and \"always_last\" (default for\n`.change()` and `.key_up()` events) would allow a second submission after the\npending event is complete.\n\n\n \n \n js: str | Literal[True] | None\n\ndefault `= None`\n\nOptional frontend js method to run before running 'fn'. Input arguments for js\nmethod are values of 'inputs' and 'outputs', return should be a list of values\nfor output components.\n\n\n \n \n concurrency_limit: int | None | Literal['default']\n\ndefault `= \"default\"`\n\nIf set, this is the maximum number of this event that can be running\nsimultaneously. Can be set to None to mean no concurrency_limit (any number of\nthis event can be running simultaneously). Set to \"default\" to use the default\nconcurrency limit (defined by the `default_concurrency_limit` parameter in\n`Blocks.queue()`, which itself is 1 by default).\n\n\n \n \n concurrency_id: str | None\n\ndefault `= None`\n\nIf set, this is the id of the concurrency group. Events with the same\nconcurrency_id will be limited by the lowest set concurrency_limit.\n\n\n \n \n api_visibility: Literal['public', 'private', 'undocumented']\n\ndefault `= \"public\"`\n\ncontrols the visibility and accessibility of this endpoint. Can be \"public\"\n(shown in API docs and callable by clients), \"private\" (hidden from API docs\nand not callable by clients), or \"undocumented\" (hidden from API docs but\ncallable by clients and via gr.load). If fn is", "heading1": "select", "source_page_url": "https://gradio.app/docs/gradio/tab", "source_page_title": "Gradio - Tab Docs"}, {"text": "c\"\n(shown in API docs and callable by clients), \"private\" (hidden from API docs\nand not callable by clients), or \"undocumented\" (hidden from API docs but\ncallable by clients and via gr.load). If fn is None, api_visibility will\nautomatically be set to \"private\".\n\n\n \n \n time_limit: int | None\n\ndefault `= None`\n\n\n \n \n stream_every: float\n\ndefault `= 0.5`\n\n\n \n \n key: int | str | tuple[int | str, ...] | None\n\ndefault `= None`\n\nA unique key for this event listener to be used in @gr.render(). If set, this\nvalue identifies an event as identical across re-renders when the key is\nidentical.\n\n\n \n \n validator: Callable | None\n\ndefault `= None`\n\nOptional validation function to run before the main function. If provided,\nthis function will be executed first with queue=False, and only if it\ncompletes successfully will the main function be called. The validator\nreceives the same inputs as the main function and should return a\n`gr.validate()` for each input value.\n\n[Controlling Layout](../../guides/controlling-layout/)\n\n", "heading1": "select", "source_page_url": "https://gradio.app/docs/gradio/tab", "source_page_title": "Gradio - Tab Docs"}, {"text": "![](data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20fill='%23808080'%20viewBox='0%200%20640%20512'%3e%3c!--!%20Font%20Awesome%20Pro%206.0.0%20by%20@fontawesome%20-%20https://fontawesome.com%20License%20-%20https://fontawesome.com/license%20\\(Commercial%20License\\)%20Copyright%202022%20Fonticons,%20Inc.%20--%3e%3cpath%20d='M172.5%20131.1C228.1%2075.51%20320.5%2075.51%20376.1%20131.1C426.1%20181.1%20433.5%20260.8%20392.4%20318.3L391.3%20319.9C381%20334.2%20361%20337.6%20346.7%20327.3C332.3%20317%20328.9%20297%20339.2%20282.7L340.3%20281.1C363.2%20249%20359.6%20205.1%20331.7%20177.2C300.3%20145.8%20249.2%20145.8%20217.7%20177.2L105.5%20289.5C73.99%20320.1%2073.99%20372%20105.5%20403.5C133.3%20431.4%20177.3%20435%20209.3%20412.1L210.9%20410.1C225.3%20400.7%20245.3%20404%20255.5%20418.4C265.8%20432.8%20262.5%20452.8%20248.1%20463.1L246.5%20464.2C188.1%20505.3%20110.2%20498.7%2060.21%20448.8C3.741%20392.3%203.741%20300.7%2060.21%20244.3L172.5%20131.1zM467.5%20380C411%20436.5%20319.5%20436.5%20263%20380C213%20330%20206.5%20251.2%20247.6%20193.7L248.7%20192.1C258.1%20177.8%20278.1%20174.4%20293.3%20184.7C307.7%20194.1%20311.1%20214.1%20300.8%20229.3L299.7%20230.9C276.8%20262.1%20280.4%20306.9%20308.3%20334.8C339.7%20366.2%20390.8%20366.2%20422.3%20334.8L534.5%20222.5C566%20191%20566%20139.1%20534.5%20108.5C506.7%2080.63%20462.7%2076.99%20430.7%2099.9L429.1%20101C414.7%20111.3%20394.7%20107.1%20384.5%2093.58C374.2%2079.2%20377.5%2059.21%20391.9%2048.94L393.5%2047.82C451%206.731%20529.8%2013.25%20579.8%2063.24C636.3%20119.7%20636.3%20211.3%20579.8%20267.7L467.5%20380z'/%3e%3c/svg%3e)\n\n \n \n gradio.Tab.select(\u00b7\u00b7\u00b7)\n\nDescription\n![](data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20fill='%23808080'%20viewBox='0%200%20640%20512'%3e%3c!--!%20Font%20Awesome%20Pro%206.0.0%20by%20@fontawesome%20-%20https://fontawesome.com%20License%20-%20https://fontawesome.com/license%20\\(Commercial%20License\\)%20Copyright%202022%20Fonticons,%20Inc.%20--%", "heading1": "select", "source_page_url": "https://gradio.app/docs/gradio/tab", "source_page_title": "Gradio - Tab Docs"}, {"text": "20Font%20Awesome%20Pro%206.0.0%20by%20@fontawesome%20-%20https://fontawesome.com%20License%20-%20https://fontawesome.com/license%20\\(Commercial%20License\\)%20Copyright%202022%20Fonticons,%20Inc.%20--%3e%3cpath%20d='M172.5%20131.1C228.1%2075.51%20320.5%2075.51%20376.1%20131.1C426.1%20181.1%20433.5%20260.8%20392.4%20318.3L391.3%20319.9C381%20334.2%20361%20337.6%20346.7%20327.3C332.3%20317%20328.9%20297%20339.2%20282.7L340.3%20281.1C363.2%20249%20359.6%20205.1%20331.7%20177.2C300.3%20145.8%20249.2%20145.8%20217.7%20177.2L105.5%20289.5C73.99%20320.1%2073.99%20372%20105.5%20403.5C133.3%20431.4%20177.3%20435%20209.3%20412.1L210.9%20410.1C225.3%20400.7%20245.3%20404%20255.5%20418.4C265.8%20432.8%20262.5%20452.8%20248.1%20463.1L246.5%20464.2C188.1%20505.3%20110.2%20498.7%2060.21%20448.8C3.741%20392.3%203.741%20300.7%2060.21%20244.3L172.5%20131.1zM467.5%20380C411%20436.5%20319.5%20436.5%20263%20380C213%20330%20206.5%20251.2%20247.6%20193.7L248.7%20192.1C258.1%20177.8%20278.1%20174.4%20293.3%20184.7C307.7%20194.1%20311.1%20214.1%20300.8%20229.3L299.7%20230.9C276.8%20262.1%20280.4%20306.9%20308.3%20334.8C339.7%20366.2%20390.8%20366.2%20422.3%20334.8L534.5%20222.5C566%20191%20566%20139.1%20534.5%20108.5C506.7%2080.63%20462.7%2076.99%20430.7%2099.9L429.1%20101C414.7%20111.3%20394.7%20107.1%20384.5%2093.58C374.2%2079.2%20377.5%2059.21%20391.9%2048.94L393.5%2047.82C451%206.731%20529.8%2013.25%20579.8%2063.24C636.3%20119.7%20636.3%20211.3%20579.8%20267.7L467.5%20380z'/%3e%3c/svg%3e)\n\nEvent listener for when the user selects the Tab. Uses event data\ngradio.SelectData to carry `value` referring to the label of the Tab, and\n`selected` to refer to state of the Tab. See\nhttps://www.gradio.app/main/docs/gradio/eventdata documentation for more\ndetails.\n\nParameters \u25bc\n\n\n \n \n fn: Callable | None | Literal['decorator']\n\ndefault `= \"decorator\"`\n\nthe function to call when this event is triggered. Often a machine learning\nmodel's prediction function. Each parameter of the function corre", "heading1": "select", "source_page_url": "https://gradio.app/docs/gradio/tab", "source_page_title": "Gradio - Tab Docs"}, {"text": "le | None | Literal['decorator']\n\ndefault `= \"decorator\"`\n\nthe function to call when this event is triggered. Often a machine learning\nmodel's prediction function. Each parameter of the function corresponds to one\ninput component, and the function should return a single value or a tuple of\nvalues, with each element in the tuple corresponding to one output component.\n\n\n \n \n inputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n\ndefault `= None`\n\nList of gradio.components to use as inputs. If the function takes no inputs,\nthis should be an empty list.\n\n\n \n \n outputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n\ndefault `= None`\n\nList of gradio.components to use as outputs. If the function returns no\noutputs, this should be an empty list.\n\n\n \n \n api_name: str | None\n\ndefault `= None`\n\ndefines how the endpoint appears in the API docs. Can be a string or None. If\nset to a string, the endpoint will be exposed in the API docs with the given\nname. If None (default), the name of the function will be used as the API\nendpoint.\n\n\n \n \n api_description: str | None | Literal[False]\n\ndefault `= None`\n\nDescription of the API endpoint. Can be a string, None, or False. If set to a\nstring, the endpoint will be exposed in the API docs with the given\ndescription. If None, the function's docstring will be used as the API\nendpoint description. If False, then no description will be displayed in the\nAPI docs.\n\n\n \n \n scroll_to_output: bool\n\ndefault `= False`\n\nIf True, will scroll to output component on completion\n\n\n \n \n show_progress: Literal['full', 'minimal', 'hidden']\n\ndefault `= \"full\"`\n\nhow to show the progress animation while event is running: \"full\" shows a\nspinner which covers the output component area as well as a runtime display in\nthe upper right corner, \"minimal\" only shows the runtime display, \"hidden\"\nshows no progress anim", "heading1": "select", "source_page_url": "https://gradio.app/docs/gradio/tab", "source_page_title": "Gradio - Tab Docs"}, {"text": "running: \"full\" shows a\nspinner which covers the output component area as well as a runtime display in\nthe upper right corner, \"minimal\" only shows the runtime display, \"hidden\"\nshows no progress animation at all\n\n\n \n \n show_progress_on: Component | list[Component] | None\n\ndefault `= None`\n\nComponent or list of components to show the progress animation on. If None,\nwill show the progress animation on all of the output components.\n\n\n \n \n queue: bool\n\ndefault `= True`\n\nIf True, will place the request on the queue, if the queue has been enabled.\nIf False, will not put this event on the queue, even if the queue has been\nenabled. If None, will use the queue setting of the gradio app.\n\n\n \n \n batch: bool\n\ndefault `= False`\n\nIf True, then the function should process a batch of inputs, meaning that it\nshould accept a list of input values for each parameter. The lists should be\nof equal length (and be up to length `max_batch_size`). The function is then\n*required* to return a tuple of lists (even if there is only 1 output\ncomponent), with each list in the tuple corresponding to one output component.\n\n\n \n \n max_batch_size: int\n\ndefault `= 4`\n\nMaximum number of inputs to batch together if this is called from the queue\n(only relevant if batch=True)\n\n\n \n \n preprocess: bool\n\ndefault `= True`\n\nIf False, will not run preprocessing of component data before running 'fn'\n(e.g. leaving it as a base64 string if this method is called with the `Image`\ncomponent).\n\n\n \n \n postprocess: bool\n\ndefault `= True`\n\nIf False, will not run postprocessing of component data before returning 'fn'\noutput to the browser.\n\n\n \n \n cancels: dict[str, Any] | list[dict[str, Any]] | None\n\ndefault `= None`\n\nA list of other events to cancel when this listener is triggered. For example,\nsetting cancels=[click_event] will cancel the click_event, where click_event\nis the return value of another components .click method. Functions that have\nnot yet run (or", "heading1": "select", "source_page_url": "https://gradio.app/docs/gradio/tab", "source_page_title": "Gradio - Tab Docs"}, {"text": "ner is triggered. For example,\nsetting cancels=[click_event] will cancel the click_event, where click_event\nis the return value of another components .click method. Functions that have\nnot yet run (or generators that are iterating) will be cancelled, but\nfunctions that are currently running will be allowed to finish.\n\n\n \n \n trigger_mode: Literal['once', 'multiple', 'always_last'] | None\n\ndefault `= None`\n\nIf \"once\" (default for all events except `.change()`) would not allow any\nsubmissions while an event is pending. If set to \"multiple\", unlimited\nsubmissions are allowed while pending, and \"always_last\" (default for\n`.change()` and `.key_up()` events) would allow a second submission after the\npending event is complete.\n\n\n \n \n js: str | Literal[True] | None\n\ndefault `= None`\n\nOptional frontend js method to run before running 'fn'. Input arguments for js\nmethod are values of 'inputs' and 'outputs', return should be a list of values\nfor output components.\n\n\n \n \n concurrency_limit: int | None | Literal['default']\n\ndefault `= \"default\"`\n\nIf set, this is the maximum number of this event that can be running\nsimultaneously. Can be set to None to mean no concurrency_limit (any number of\nthis event can be running simultaneously). Set to \"default\" to use the default\nconcurrency limit (defined by the `default_concurrency_limit` parameter in\n`Blocks.queue()`, which itself is 1 by default).\n\n\n \n \n concurrency_id: str | None\n\ndefault `= None`\n\nIf set, this is the id of the concurrency group. Events with the same\nconcurrency_id will be limited by the lowest set concurrency_limit.\n\n\n \n \n api_visibility: Literal['public', 'private', 'undocumented']\n\ndefault `= \"public\"`\n\ncontrols the visibility and accessibility of this endpoint. Can be \"public\"\n(shown in API docs and callable by clients), \"private\" (hidden from API docs\nand not callable by clients), or \"undocumented\" (hidden from API docs but\ncallable by clients and via gr.load). If fn is", "heading1": "select", "source_page_url": "https://gradio.app/docs/gradio/tab", "source_page_title": "Gradio - Tab Docs"}, {"text": "c\"\n(shown in API docs and callable by clients), \"private\" (hidden from API docs\nand not callable by clients), or \"undocumented\" (hidden from API docs but\ncallable by clients and via gr.load). If fn is None, api_visibility will\nautomatically be set to \"private\".\n\n\n \n \n time_limit: int | None\n\ndefault `= None`\n\n\n \n \n stream_every: float\n\ndefault `= 0.5`\n\n\n \n \n key: int | str | tuple[int | str, ...] | None\n\ndefault `= None`\n\nA unique key for this event listener to be used in @gr.render(). If set, this\nvalue identifies an event as identical across re-renders when the key is\nidentical.\n\n\n \n \n validator: Callable | None\n\ndefault `= None`\n\nOptional validation function to run before the main function. If provided,\nthis function will be executed first with queue=False, and only if it\ncompletes successfully will the main function be called. The validator\nreceives the same inputs as the main function and should return a\n`gr.validate()` for each input value.\n\n", "heading1": "select", "source_page_url": "https://gradio.app/docs/gradio/tab", "source_page_title": "Gradio - Tab Docs"}, {"text": "Any code in a `if gr.NO_RELOAD` code-block will not be re-evaluated when\nthe source file is reloaded. This is helpful for importing modules that do not\nlike to be reloaded (tiktoken, numpy) as well as database connections and long\nrunning set up code.\n\n", "heading1": "Description", "source_page_url": "https://gradio.app/docs/gradio/NO_RELOAD", "source_page_title": "Gradio - No_Reload Docs"}, {"text": "import gradio as gr\n \n if gr.NO_RELOAD:\n \tfrom transformers import pipeline\n \tpipe = pipeline(\"text-classification\", model=\"cardiffnlp/twitter-roberta-base-sentiment-latest\")\n \n gr.Interface.from_pipeline(pipe).launch()\n\n", "heading1": "Example Usage", "source_page_url": "https://gradio.app/docs/gradio/NO_RELOAD", "source_page_title": "Gradio - No_Reload Docs"}, {"text": "Sidebar is a collapsible panel that renders child components on the left\nside of the screen within a Blocks layout.\n\n", "heading1": "Description", "source_page_url": "https://gradio.app/docs/gradio/sidebar", "source_page_title": "Gradio - Sidebar Docs"}, {"text": "with gr.Blocks() as demo:\n with gr.Sidebar():\n gr.Textbox()\n gr.Button()\n\n", "heading1": "Example Usage", "source_page_url": "https://gradio.app/docs/gradio/sidebar", "source_page_title": "Gradio - Sidebar Docs"}, {"text": "Parameters \u25bc\n\n\n \n \n label: str | I18nData | None\n\ndefault `= None`\n\nname of the sidebar. Not displayed to the user.\n\n\n \n \n open: bool\n\ndefault `= True`\n\nif True, sidebar is open by default.\n\n\n \n \n visible: bool | Literal['hidden']\n\ndefault `= True`\n\n\n \n \n elem_id: str | None\n\ndefault `= None`\n\nAn optional string that is assigned as the id of this component in the HTML\nDOM. Can be used for targeting CSS styles.\n\n\n \n \n elem_classes: list[str] | str | None\n\ndefault `= None`\n\nAn optional string or list of strings that are assigned as the class of this\ncomponent in the HTML DOM. Can be used for targeting CSS styles.\n\n\n \n \n render: bool\n\ndefault `= True`\n\nIf False, this layout will not be rendered in the Blocks context. Should be\nused if the intention is to assign event listeners now but render the\ncomponent later.\n\n\n \n \n width: int | str\n\ndefault `= 320`\n\nThe width of the sidebar, specified in pixels if a number is passed, or in CSS\nunits if a string is passed.\n\n\n \n \n position: Literal['left', 'right']\n\ndefault `= \"left\"`\n\nThe position of the sidebar in the layout, either \"left\" or \"right\". Defaults\nto \"left\".\n\n\n \n \n key: int | str | tuple[int | str, ...] | None\n\ndefault `= None`\n\nin a gr.render, Components with the same key across re-renders are treated as\nthe same component, not a new component. Properties set in 'preserved_by_key'\nare not reset across a re-render.\n\n\n \n \n preserved_by_key: list[str] | str | None\n\ndefault `= None`\n\nA list of parameters from this component's constructor. Inside a gr.render()\nfunction, if a component is re-rendered with the same key, these (and only\nthese) parameters will be preserved in the UI (if they have been changed by\nthe user or an event listener) instead of re-rendered based on the values\nprovided during constructor.\n\n", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/sidebar", "source_page_title": "Gradio - Sidebar Docs"}, {"text": "", "heading1": "Methods", "source_page_url": "https://gradio.app/docs/gradio/sidebar", "source_page_title": "Gradio - Sidebar Docs"}, {"text": "![](data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20fill='%23808080'%20viewBox='0%200%20640%20512'%3e%3c!--!%20Font%20Awesome%20Pro%206.0.0%20by%20@fontawesome%20-%20https://fontawesome.com%20License%20-%20https://fontawesome.com/license%20\\(Commercial%20License\\)%20Copyright%202022%20Fonticons,%20Inc.%20--%3e%3cpath%20d='M172.5%20131.1C228.1%2075.51%20320.5%2075.51%20376.1%20131.1C426.1%20181.1%20433.5%20260.8%20392.4%20318.3L391.3%20319.9C381%20334.2%20361%20337.6%20346.7%20327.3C332.3%20317%20328.9%20297%20339.2%20282.7L340.3%20281.1C363.2%20249%20359.6%20205.1%20331.7%20177.2C300.3%20145.8%20249.2%20145.8%20217.7%20177.2L105.5%20289.5C73.99%20320.1%2073.99%20372%20105.5%20403.5C133.3%20431.4%20177.3%20435%20209.3%20412.1L210.9%20410.1C225.3%20400.7%20245.3%20404%20255.5%20418.4C265.8%20432.8%20262.5%20452.8%20248.1%20463.1L246.5%20464.2C188.1%20505.3%20110.2%20498.7%2060.21%20448.8C3.741%20392.3%203.741%20300.7%2060.21%20244.3L172.5%20131.1zM467.5%20380C411%20436.5%20319.5%20436.5%20263%20380C213%20330%20206.5%20251.2%20247.6%20193.7L248.7%20192.1C258.1%20177.8%20278.1%20174.4%20293.3%20184.7C307.7%20194.1%20311.1%20214.1%20300.8%20229.3L299.7%20230.9C276.8%20262.1%20280.4%20306.9%20308.3%20334.8C339.7%20366.2%20390.8%20366.2%20422.3%20334.8L534.5%20222.5C566%20191%20566%20139.1%20534.5%20108.5C506.7%2080.63%20462.7%2076.99%20430.7%2099.9L429.1%20101C414.7%20111.3%20394.7%20107.1%20384.5%2093.58C374.2%2079.2%20377.5%2059.21%20391.9%2048.94L393.5%2047.82C451%206.731%20529.8%2013.25%20579.8%2063.24C636.3%20119.7%20636.3%20211.3%20579.8%20267.7L467.5%20380z'/%3e%3c/svg%3e)\n\n \n \n gradio.Sidebar.expand(\u00b7\u00b7\u00b7)\n\nDescription\n![](data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20fill='%23808080'%20viewBox='0%200%20640%20512'%3e%3c!--!%20Font%20Awesome%20Pro%206.0.0%20by%20@fontawesome%20-%20https://fontawesome.com%20License%20-%20https://fontawesome.com/license%20\\(Commercial%20License\\)%20Copyright%202022%20Fonticons,%20Inc.%2", "heading1": "expand", "source_page_url": "https://gradio.app/docs/gradio/sidebar", "source_page_title": "Gradio - Sidebar Docs"}, {"text": "--!%20Font%20Awesome%20Pro%206.0.0%20by%20@fontawesome%20-%20https://fontawesome.com%20License%20-%20https://fontawesome.com/license%20\\(Commercial%20License\\)%20Copyright%202022%20Fonticons,%20Inc.%20--%3e%3cpath%20d='M172.5%20131.1C228.1%2075.51%20320.5%2075.51%20376.1%20131.1C426.1%20181.1%20433.5%20260.8%20392.4%20318.3L391.3%20319.9C381%20334.2%20361%20337.6%20346.7%20327.3C332.3%20317%20328.9%20297%20339.2%20282.7L340.3%20281.1C363.2%20249%20359.6%20205.1%20331.7%20177.2C300.3%20145.8%20249.2%20145.8%20217.7%20177.2L105.5%20289.5C73.99%20320.1%2073.99%20372%20105.5%20403.5C133.3%20431.4%20177.3%20435%20209.3%20412.1L210.9%20410.1C225.3%20400.7%20245.3%20404%20255.5%20418.4C265.8%20432.8%20262.5%20452.8%20248.1%20463.1L246.5%20464.2C188.1%20505.3%20110.2%20498.7%2060.21%20448.8C3.741%20392.3%203.741%20300.7%2060.21%20244.3L172.5%20131.1zM467.5%20380C411%20436.5%20319.5%20436.5%20263%20380C213%20330%20206.5%20251.2%20247.6%20193.7L248.7%20192.1C258.1%20177.8%20278.1%20174.4%20293.3%20184.7C307.7%20194.1%20311.1%20214.1%20300.8%20229.3L299.7%20230.9C276.8%20262.1%20280.4%20306.9%20308.3%20334.8C339.7%20366.2%20390.8%20366.2%20422.3%20334.8L534.5%20222.5C566%20191%20566%20139.1%20534.5%20108.5C506.7%2080.63%20462.7%2076.99%20430.7%2099.9L429.1%20101C414.7%20111.3%20394.7%20107.1%20384.5%2093.58C374.2%2079.2%20377.5%2059.21%20391.9%2048.94L393.5%2047.82C451%206.731%20529.8%2013.25%20579.8%2063.24C636.3%20119.7%20636.3%20211.3%20579.8%20267.7L467.5%20380z'/%3e%3c/svg%3e)\n\nThis listener is triggered when the Sidebar is expanded.\n\nParameters \u25bc\n\n\n \n \n fn: Callable | None | Literal['decorator']\n\ndefault `= \"decorator\"`\n\nthe function to call when this event is triggered. Often a machine learning\nmodel's prediction function. Each parameter of the function corresponds to one\ninput component, and the function should return a single value or a tuple of\nvalues, with each element in the tuple corresponding to one output component.\n\n\n \n \n inputs: Component | B", "heading1": "expand", "source_page_url": "https://gradio.app/docs/gradio/sidebar", "source_page_title": "Gradio - Sidebar Docs"}, {"text": " to one\ninput component, and the function should return a single value or a tuple of\nvalues, with each element in the tuple corresponding to one output component.\n\n\n \n \n inputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n\ndefault `= None`\n\nList of gradio.components to use as inputs. If the function takes no inputs,\nthis should be an empty list.\n\n\n \n \n outputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n\ndefault `= None`\n\nList of gradio.components to use as outputs. If the function returns no\noutputs, this should be an empty list.\n\n\n \n \n api_name: str | None\n\ndefault `= None`\n\ndefines how the endpoint appears in the API docs. Can be a string or None. If\nset to a string, the endpoint will be exposed in the API docs with the given\nname. If None (default), the name of the function will be used as the API\nendpoint.\n\n\n \n \n api_description: str | None | Literal[False]\n\ndefault `= None`\n\nDescription of the API endpoint. Can be a string, None, or False. If set to a\nstring, the endpoint will be exposed in the API docs with the given\ndescription. If None, the function's docstring will be used as the API\nendpoint description. If False, then no description will be displayed in the\nAPI docs.\n\n\n \n \n scroll_to_output: bool\n\ndefault `= False`\n\nIf True, will scroll to output component on completion\n\n\n \n \n show_progress: Literal['full', 'minimal', 'hidden']\n\ndefault `= \"full\"`\n\nhow to show the progress animation while event is running: \"full\" shows a\nspinner which covers the output component area as well as a runtime display in\nthe upper right corner, \"minimal\" only shows the runtime display, \"hidden\"\nshows no progress animation at all\n\n\n \n \n show_progress_on: Component | list[Component] | None\n\ndefault `= None`\n\nComponent or list of components to show the progress animation on. If None,\nwill show the progress animat", "heading1": "expand", "source_page_url": "https://gradio.app/docs/gradio/sidebar", "source_page_title": "Gradio - Sidebar Docs"}, {"text": "at all\n\n\n \n \n show_progress_on: Component | list[Component] | None\n\ndefault `= None`\n\nComponent or list of components to show the progress animation on. If None,\nwill show the progress animation on all of the output components.\n\n\n \n \n queue: bool\n\ndefault `= True`\n\nIf True, will place the request on the queue, if the queue has been enabled.\nIf False, will not put this event on the queue, even if the queue has been\nenabled. If None, will use the queue setting of the gradio app.\n\n\n \n \n batch: bool\n\ndefault `= False`\n\nIf True, then the function should process a batch of inputs, meaning that it\nshould accept a list of input values for each parameter. The lists should be\nof equal length (and be up to length `max_batch_size`). The function is then\n*required* to return a tuple of lists (even if there is only 1 output\ncomponent), with each list in the tuple corresponding to one output component.\n\n\n \n \n max_batch_size: int\n\ndefault `= 4`\n\nMaximum number of inputs to batch together if this is called from the queue\n(only relevant if batch=True)\n\n\n \n \n preprocess: bool\n\ndefault `= True`\n\nIf False, will not run preprocessing of component data before running 'fn'\n(e.g. leaving it as a base64 string if this method is called with the `Image`\ncomponent).\n\n\n \n \n postprocess: bool\n\ndefault `= True`\n\nIf False, will not run postprocessing of component data before returning 'fn'\noutput to the browser.\n\n\n \n \n cancels: dict[str, Any] | list[dict[str, Any]] | None\n\ndefault `= None`\n\nA list of other events to cancel when this listener is triggered. For example,\nsetting cancels=[click_event] will cancel the click_event, where click_event\nis the return value of another components .click method. Functions that have\nnot yet run (or generators that are iterating) will be cancelled, but\nfunctions that are currently running will be allowed to finish.\n\n\n \n \n trigger_mode: Literal['once', 'multiple', 'always_last'] | None\n\ndefaul", "heading1": "expand", "source_page_url": "https://gradio.app/docs/gradio/sidebar", "source_page_title": "Gradio - Sidebar Docs"}, {"text": "ators that are iterating) will be cancelled, but\nfunctions that are currently running will be allowed to finish.\n\n\n \n \n trigger_mode: Literal['once', 'multiple', 'always_last'] | None\n\ndefault `= None`\n\nIf \"once\" (default for all events except `.change()`) would not allow any\nsubmissions while an event is pending. If set to \"multiple\", unlimited\nsubmissions are allowed while pending, and \"always_last\" (default for\n`.change()` and `.key_up()` events) would allow a second submission after the\npending event is complete.\n\n\n \n \n js: str | Literal[True] | None\n\ndefault `= None`\n\nOptional frontend js method to run before running 'fn'. Input arguments for js\nmethod are values of 'inputs' and 'outputs', return should be a list of values\nfor output components.\n\n\n \n \n concurrency_limit: int | None | Literal['default']\n\ndefault `= \"default\"`\n\nIf set, this is the maximum number of this event that can be running\nsimultaneously. Can be set to None to mean no concurrency_limit (any number of\nthis event can be running simultaneously). Set to \"default\" to use the default\nconcurrency limit (defined by the `default_concurrency_limit` parameter in\n`Blocks.queue()`, which itself is 1 by default).\n\n\n \n \n concurrency_id: str | None\n\ndefault `= None`\n\nIf set, this is the id of the concurrency group. Events with the same\nconcurrency_id will be limited by the lowest set concurrency_limit.\n\n\n \n \n api_visibility: Literal['public', 'private', 'undocumented']\n\ndefault `= \"public\"`\n\ncontrols the visibility and accessibility of this endpoint. Can be \"public\"\n(shown in API docs and callable by clients), \"private\" (hidden from API docs\nand not callable by clients), or \"undocumented\" (hidden from API docs but\ncallable by clients and via gr.load). If fn is None, api_visibility will\nautomatically be set to \"private\".\n\n\n \n \n time_limit: int | None\n\ndefault `= None`\n\n\n \n \n stream_every: float\n\ndefault `= 0.5`\n\n\n \n \n key: int | str | t", "heading1": "expand", "source_page_url": "https://gradio.app/docs/gradio/sidebar", "source_page_title": "Gradio - Sidebar Docs"}, {"text": " api_visibility will\nautomatically be set to \"private\".\n\n\n \n \n time_limit: int | None\n\ndefault `= None`\n\n\n \n \n stream_every: float\n\ndefault `= 0.5`\n\n\n \n \n key: int | str | tuple[int | str, ...] | None\n\ndefault `= None`\n\nA unique key for this event listener to be used in @gr.render(). If set, this\nvalue identifies an event as identical across re-renders when the key is\nidentical.\n\n\n \n \n validator: Callable | None\n\ndefault `= None`\n\nOptional validation function to run before the main function. If provided,\nthis function will be executed first with queue=False, and only if it\ncompletes successfully will the main function be called. The validator\nreceives the same inputs as the main function and should return a\n`gr.validate()` for each input value.\n\n", "heading1": "expand", "source_page_url": "https://gradio.app/docs/gradio/sidebar", "source_page_title": "Gradio - Sidebar Docs"}, {"text": "![](data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20fill='%23808080'%20viewBox='0%200%20640%20512'%3e%3c!--!%20Font%20Awesome%20Pro%206.0.0%20by%20@fontawesome%20-%20https://fontawesome.com%20License%20-%20https://fontawesome.com/license%20\\(Commercial%20License\\)%20Copyright%202022%20Fonticons,%20Inc.%20--%3e%3cpath%20d='M172.5%20131.1C228.1%2075.51%20320.5%2075.51%20376.1%20131.1C426.1%20181.1%20433.5%20260.8%20392.4%20318.3L391.3%20319.9C381%20334.2%20361%20337.6%20346.7%20327.3C332.3%20317%20328.9%20297%20339.2%20282.7L340.3%20281.1C363.2%20249%20359.6%20205.1%20331.7%20177.2C300.3%20145.8%20249.2%20145.8%20217.7%20177.2L105.5%20289.5C73.99%20320.1%2073.99%20372%20105.5%20403.5C133.3%20431.4%20177.3%20435%20209.3%20412.1L210.9%20410.1C225.3%20400.7%20245.3%20404%20255.5%20418.4C265.8%20432.8%20262.5%20452.8%20248.1%20463.1L246.5%20464.2C188.1%20505.3%20110.2%20498.7%2060.21%20448.8C3.741%20392.3%203.741%20300.7%2060.21%20244.3L172.5%20131.1zM467.5%20380C411%20436.5%20319.5%20436.5%20263%20380C213%20330%20206.5%20251.2%20247.6%20193.7L248.7%20192.1C258.1%20177.8%20278.1%20174.4%20293.3%20184.7C307.7%20194.1%20311.1%20214.1%20300.8%20229.3L299.7%20230.9C276.8%20262.1%20280.4%20306.9%20308.3%20334.8C339.7%20366.2%20390.8%20366.2%20422.3%20334.8L534.5%20222.5C566%20191%20566%20139.1%20534.5%20108.5C506.7%2080.63%20462.7%2076.99%20430.7%2099.9L429.1%20101C414.7%20111.3%20394.7%20107.1%20384.5%2093.58C374.2%2079.2%20377.5%2059.21%20391.9%2048.94L393.5%2047.82C451%206.731%20529.8%2013.25%20579.8%2063.24C636.3%20119.7%20636.3%20211.3%20579.8%20267.7L467.5%20380z'/%3e%3c/svg%3e)\n\n \n \n gradio.Sidebar.collapse(\u00b7\u00b7\u00b7)\n\nDescription\n![](data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20fill='%23808080'%20viewBox='0%200%20640%20512'%3e%3c!--!%20Font%20Awesome%20Pro%206.0.0%20by%20@fontawesome%20-%20https://fontawesome.com%20License%20-%20https://fontawesome.com/license%20\\(Commercial%20License\\)%20Copyright%202022%20Fonticons,%20Inc.", "heading1": "collapse", "source_page_url": "https://gradio.app/docs/gradio/sidebar", "source_page_title": "Gradio - Sidebar Docs"}, {"text": "c!--!%20Font%20Awesome%20Pro%206.0.0%20by%20@fontawesome%20-%20https://fontawesome.com%20License%20-%20https://fontawesome.com/license%20\\(Commercial%20License\\)%20Copyright%202022%20Fonticons,%20Inc.%20--%3e%3cpath%20d='M172.5%20131.1C228.1%2075.51%20320.5%2075.51%20376.1%20131.1C426.1%20181.1%20433.5%20260.8%20392.4%20318.3L391.3%20319.9C381%20334.2%20361%20337.6%20346.7%20327.3C332.3%20317%20328.9%20297%20339.2%20282.7L340.3%20281.1C363.2%20249%20359.6%20205.1%20331.7%20177.2C300.3%20145.8%20249.2%20145.8%20217.7%20177.2L105.5%20289.5C73.99%20320.1%2073.99%20372%20105.5%20403.5C133.3%20431.4%20177.3%20435%20209.3%20412.1L210.9%20410.1C225.3%20400.7%20245.3%20404%20255.5%20418.4C265.8%20432.8%20262.5%20452.8%20248.1%20463.1L246.5%20464.2C188.1%20505.3%20110.2%20498.7%2060.21%20448.8C3.741%20392.3%203.741%20300.7%2060.21%20244.3L172.5%20131.1zM467.5%20380C411%20436.5%20319.5%20436.5%20263%20380C213%20330%20206.5%20251.2%20247.6%20193.7L248.7%20192.1C258.1%20177.8%20278.1%20174.4%20293.3%20184.7C307.7%20194.1%20311.1%20214.1%20300.8%20229.3L299.7%20230.9C276.8%20262.1%20280.4%20306.9%20308.3%20334.8C339.7%20366.2%20390.8%20366.2%20422.3%20334.8L534.5%20222.5C566%20191%20566%20139.1%20534.5%20108.5C506.7%2080.63%20462.7%2076.99%20430.7%2099.9L429.1%20101C414.7%20111.3%20394.7%20107.1%20384.5%2093.58C374.2%2079.2%20377.5%2059.21%20391.9%2048.94L393.5%2047.82C451%206.731%20529.8%2013.25%20579.8%2063.24C636.3%20119.7%20636.3%20211.3%20579.8%20267.7L467.5%20380z'/%3e%3c/svg%3e)\n\nThis listener is triggered when the Sidebar is collapsed.\n\nParameters \u25bc\n\n\n \n \n fn: Callable | None | Literal['decorator']\n\ndefault `= \"decorator\"`\n\nthe function to call when this event is triggered. Often a machine learning\nmodel's prediction function. Each parameter of the function corresponds to one\ninput component, and the function should return a single value or a tuple of\nvalues, with each element in the tuple corresponding to one output component.\n\n\n \n \n inputs: Component ", "heading1": "collapse", "source_page_url": "https://gradio.app/docs/gradio/sidebar", "source_page_title": "Gradio - Sidebar Docs"}, {"text": "nds to one\ninput component, and the function should return a single value or a tuple of\nvalues, with each element in the tuple corresponding to one output component.\n\n\n \n \n inputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n\ndefault `= None`\n\nList of gradio.components to use as inputs. If the function takes no inputs,\nthis should be an empty list.\n\n\n \n \n outputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n\ndefault `= None`\n\nList of gradio.components to use as outputs. If the function returns no\noutputs, this should be an empty list.\n\n\n \n \n api_name: str | None\n\ndefault `= None`\n\ndefines how the endpoint appears in the API docs. Can be a string or None. If\nset to a string, the endpoint will be exposed in the API docs with the given\nname. If None (default), the name of the function will be used as the API\nendpoint.\n\n\n \n \n api_description: str | None | Literal[False]\n\ndefault `= None`\n\nDescription of the API endpoint. Can be a string, None, or False. If set to a\nstring, the endpoint will be exposed in the API docs with the given\ndescription. If None, the function's docstring will be used as the API\nendpoint description. If False, then no description will be displayed in the\nAPI docs.\n\n\n \n \n scroll_to_output: bool\n\ndefault `= False`\n\nIf True, will scroll to output component on completion\n\n\n \n \n show_progress: Literal['full', 'minimal', 'hidden']\n\ndefault `= \"full\"`\n\nhow to show the progress animation while event is running: \"full\" shows a\nspinner which covers the output component area as well as a runtime display in\nthe upper right corner, \"minimal\" only shows the runtime display, \"hidden\"\nshows no progress animation at all\n\n\n \n \n show_progress_on: Component | list[Component] | None\n\ndefault `= None`\n\nComponent or list of components to show the progress animation on. If None,\nwill show the progress ani", "heading1": "collapse", "source_page_url": "https://gradio.app/docs/gradio/sidebar", "source_page_title": "Gradio - Sidebar Docs"}, {"text": "on at all\n\n\n \n \n show_progress_on: Component | list[Component] | None\n\ndefault `= None`\n\nComponent or list of components to show the progress animation on. If None,\nwill show the progress animation on all of the output components.\n\n\n \n \n queue: bool\n\ndefault `= True`\n\nIf True, will place the request on the queue, if the queue has been enabled.\nIf False, will not put this event on the queue, even if the queue has been\nenabled. If None, will use the queue setting of the gradio app.\n\n\n \n \n batch: bool\n\ndefault `= False`\n\nIf True, then the function should process a batch of inputs, meaning that it\nshould accept a list of input values for each parameter. The lists should be\nof equal length (and be up to length `max_batch_size`). The function is then\n*required* to return a tuple of lists (even if there is only 1 output\ncomponent), with each list in the tuple corresponding to one output component.\n\n\n \n \n max_batch_size: int\n\ndefault `= 4`\n\nMaximum number of inputs to batch together if this is called from the queue\n(only relevant if batch=True)\n\n\n \n \n preprocess: bool\n\ndefault `= True`\n\nIf False, will not run preprocessing of component data before running 'fn'\n(e.g. leaving it as a base64 string if this method is called with the `Image`\ncomponent).\n\n\n \n \n postprocess: bool\n\ndefault `= True`\n\nIf False, will not run postprocessing of component data before returning 'fn'\noutput to the browser.\n\n\n \n \n cancels: dict[str, Any] | list[dict[str, Any]] | None\n\ndefault `= None`\n\nA list of other events to cancel when this listener is triggered. For example,\nsetting cancels=[click_event] will cancel the click_event, where click_event\nis the return value of another components .click method. Functions that have\nnot yet run (or generators that are iterating) will be cancelled, but\nfunctions that are currently running will be allowed to finish.\n\n\n \n \n trigger_mode: Literal['once', 'multiple', 'always_last'] | None\n\ndef", "heading1": "collapse", "source_page_url": "https://gradio.app/docs/gradio/sidebar", "source_page_title": "Gradio - Sidebar Docs"}, {"text": "nerators that are iterating) will be cancelled, but\nfunctions that are currently running will be allowed to finish.\n\n\n \n \n trigger_mode: Literal['once', 'multiple', 'always_last'] | None\n\ndefault `= None`\n\nIf \"once\" (default for all events except `.change()`) would not allow any\nsubmissions while an event is pending. If set to \"multiple\", unlimited\nsubmissions are allowed while pending, and \"always_last\" (default for\n`.change()` and `.key_up()` events) would allow a second submission after the\npending event is complete.\n\n\n \n \n js: str | Literal[True] | None\n\ndefault `= None`\n\nOptional frontend js method to run before running 'fn'. Input arguments for js\nmethod are values of 'inputs' and 'outputs', return should be a list of values\nfor output components.\n\n\n \n \n concurrency_limit: int | None | Literal['default']\n\ndefault `= \"default\"`\n\nIf set, this is the maximum number of this event that can be running\nsimultaneously. Can be set to None to mean no concurrency_limit (any number of\nthis event can be running simultaneously). Set to \"default\" to use the default\nconcurrency limit (defined by the `default_concurrency_limit` parameter in\n`Blocks.queue()`, which itself is 1 by default).\n\n\n \n \n concurrency_id: str | None\n\ndefault `= None`\n\nIf set, this is the id of the concurrency group. Events with the same\nconcurrency_id will be limited by the lowest set concurrency_limit.\n\n\n \n \n api_visibility: Literal['public', 'private', 'undocumented']\n\ndefault `= \"public\"`\n\ncontrols the visibility and accessibility of this endpoint. Can be \"public\"\n(shown in API docs and callable by clients), \"private\" (hidden from API docs\nand not callable by clients), or \"undocumented\" (hidden from API docs but\ncallable by clients and via gr.load). If fn is None, api_visibility will\nautomatically be set to \"private\".\n\n\n \n \n time_limit: int | None\n\ndefault `= None`\n\n\n \n \n stream_every: float\n\ndefault `= 0.5`\n\n\n \n \n key: int | str ", "heading1": "collapse", "source_page_url": "https://gradio.app/docs/gradio/sidebar", "source_page_title": "Gradio - Sidebar Docs"}, {"text": "ne, api_visibility will\nautomatically be set to \"private\".\n\n\n \n \n time_limit: int | None\n\ndefault `= None`\n\n\n \n \n stream_every: float\n\ndefault `= 0.5`\n\n\n \n \n key: int | str | tuple[int | str, ...] | None\n\ndefault `= None`\n\nA unique key for this event listener to be used in @gr.render(). If set, this\nvalue identifies an event as identical across re-renders when the key is\nidentical.\n\n\n \n \n validator: Callable | None\n\ndefault `= None`\n\nOptional validation function to run before the main function. If provided,\nthis function will be executed first with queue=False, and only if it\ncompletes successfully will the main function be called. The validator\nreceives the same inputs as the main function and should return a\n`gr.validate()` for each input value.\n\n[Controlling Layout](../../guides/controlling-layout/)\n\n", "heading1": "collapse", "source_page_url": "https://gradio.app/docs/gradio/sidebar", "source_page_title": "Gradio - Sidebar Docs"}, {"text": "![](data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20fill='%23808080'%20viewBox='0%200%20640%20512'%3e%3c!--!%20Font%20Awesome%20Pro%206.0.0%20by%20@fontawesome%20-%20https://fontawesome.com%20License%20-%20https://fontawesome.com/license%20\\(Commercial%20License\\)%20Copyright%202022%20Fonticons,%20Inc.%20--%3e%3cpath%20d='M172.5%20131.1C228.1%2075.51%20320.5%2075.51%20376.1%20131.1C426.1%20181.1%20433.5%20260.8%20392.4%20318.3L391.3%20319.9C381%20334.2%20361%20337.6%20346.7%20327.3C332.3%20317%20328.9%20297%20339.2%20282.7L340.3%20281.1C363.2%20249%20359.6%20205.1%20331.7%20177.2C300.3%20145.8%20249.2%20145.8%20217.7%20177.2L105.5%20289.5C73.99%20320.1%2073.99%20372%20105.5%20403.5C133.3%20431.4%20177.3%20435%20209.3%20412.1L210.9%20410.1C225.3%20400.7%20245.3%20404%20255.5%20418.4C265.8%20432.8%20262.5%20452.8%20248.1%20463.1L246.5%20464.2C188.1%20505.3%20110.2%20498.7%2060.21%20448.8C3.741%20392.3%203.741%20300.7%2060.21%20244.3L172.5%20131.1zM467.5%20380C411%20436.5%20319.5%20436.5%20263%20380C213%20330%20206.5%20251.2%20247.6%20193.7L248.7%20192.1C258.1%20177.8%20278.1%20174.4%20293.3%20184.7C307.7%20194.1%20311.1%20214.1%20300.8%20229.3L299.7%20230.9C276.8%20262.1%20280.4%20306.9%20308.3%20334.8C339.7%20366.2%20390.8%20366.2%20422.3%20334.8L534.5%20222.5C566%20191%20566%20139.1%20534.5%20108.5C506.7%2080.63%20462.7%2076.99%20430.7%2099.9L429.1%20101C414.7%20111.3%20394.7%20107.1%20384.5%2093.58C374.2%2079.2%20377.5%2059.21%20391.9%2048.94L393.5%2047.82C451%206.731%20529.8%2013.25%20579.8%2063.24C636.3%20119.7%20636.3%20211.3%20579.8%20267.7L467.5%20380z'/%3e%3c/svg%3e)\n\n \n \n gradio.Sidebar.expand(\u00b7\u00b7\u00b7)\n\nDescription\n![](data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20fill='%23808080'%20viewBox='0%200%20640%20512'%3e%3c!--!%20Font%20Awesome%20Pro%206.0.0%20by%20@fontawesome%20-%20https://fontawesome.com%20License%20-%20https://fontawesome.com/license%20\\(Commercial%20License\\)%20Copyright%202022%20Fonticons,%20Inc.%2", "heading1": "expand", "source_page_url": "https://gradio.app/docs/gradio/sidebar", "source_page_title": "Gradio - Sidebar Docs"}, {"text": "--!%20Font%20Awesome%20Pro%206.0.0%20by%20@fontawesome%20-%20https://fontawesome.com%20License%20-%20https://fontawesome.com/license%20\\(Commercial%20License\\)%20Copyright%202022%20Fonticons,%20Inc.%20--%3e%3cpath%20d='M172.5%20131.1C228.1%2075.51%20320.5%2075.51%20376.1%20131.1C426.1%20181.1%20433.5%20260.8%20392.4%20318.3L391.3%20319.9C381%20334.2%20361%20337.6%20346.7%20327.3C332.3%20317%20328.9%20297%20339.2%20282.7L340.3%20281.1C363.2%20249%20359.6%20205.1%20331.7%20177.2C300.3%20145.8%20249.2%20145.8%20217.7%20177.2L105.5%20289.5C73.99%20320.1%2073.99%20372%20105.5%20403.5C133.3%20431.4%20177.3%20435%20209.3%20412.1L210.9%20410.1C225.3%20400.7%20245.3%20404%20255.5%20418.4C265.8%20432.8%20262.5%20452.8%20248.1%20463.1L246.5%20464.2C188.1%20505.3%20110.2%20498.7%2060.21%20448.8C3.741%20392.3%203.741%20300.7%2060.21%20244.3L172.5%20131.1zM467.5%20380C411%20436.5%20319.5%20436.5%20263%20380C213%20330%20206.5%20251.2%20247.6%20193.7L248.7%20192.1C258.1%20177.8%20278.1%20174.4%20293.3%20184.7C307.7%20194.1%20311.1%20214.1%20300.8%20229.3L299.7%20230.9C276.8%20262.1%20280.4%20306.9%20308.3%20334.8C339.7%20366.2%20390.8%20366.2%20422.3%20334.8L534.5%20222.5C566%20191%20566%20139.1%20534.5%20108.5C506.7%2080.63%20462.7%2076.99%20430.7%2099.9L429.1%20101C414.7%20111.3%20394.7%20107.1%20384.5%2093.58C374.2%2079.2%20377.5%2059.21%20391.9%2048.94L393.5%2047.82C451%206.731%20529.8%2013.25%20579.8%2063.24C636.3%20119.7%20636.3%20211.3%20579.8%20267.7L467.5%20380z'/%3e%3c/svg%3e)\n\nThis listener is triggered when the Sidebar is expanded.\n\nParameters \u25bc\n\n\n \n \n fn: Callable | None | Literal['decorator']\n\ndefault `= \"decorator\"`\n\nthe function to call when this event is triggered. Often a machine learning\nmodel's prediction function. Each parameter of the function corresponds to one\ninput component, and the function should return a single value or a tuple of\nvalues, with each element in the tuple corresponding to one output component.\n\n\n \n \n inputs: Component | B", "heading1": "expand", "source_page_url": "https://gradio.app/docs/gradio/sidebar", "source_page_title": "Gradio - Sidebar Docs"}, {"text": " to one\ninput component, and the function should return a single value or a tuple of\nvalues, with each element in the tuple corresponding to one output component.\n\n\n \n \n inputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n\ndefault `= None`\n\nList of gradio.components to use as inputs. If the function takes no inputs,\nthis should be an empty list.\n\n\n \n \n outputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n\ndefault `= None`\n\nList of gradio.components to use as outputs. If the function returns no\noutputs, this should be an empty list.\n\n\n \n \n api_name: str | None\n\ndefault `= None`\n\ndefines how the endpoint appears in the API docs. Can be a string or None. If\nset to a string, the endpoint will be exposed in the API docs with the given\nname. If None (default), the name of the function will be used as the API\nendpoint.\n\n\n \n \n api_description: str | None | Literal[False]\n\ndefault `= None`\n\nDescription of the API endpoint. Can be a string, None, or False. If set to a\nstring, the endpoint will be exposed in the API docs with the given\ndescription. If None, the function's docstring will be used as the API\nendpoint description. If False, then no description will be displayed in the\nAPI docs.\n\n\n \n \n scroll_to_output: bool\n\ndefault `= False`\n\nIf True, will scroll to output component on completion\n\n\n \n \n show_progress: Literal['full', 'minimal', 'hidden']\n\ndefault `= \"full\"`\n\nhow to show the progress animation while event is running: \"full\" shows a\nspinner which covers the output component area as well as a runtime display in\nthe upper right corner, \"minimal\" only shows the runtime display, \"hidden\"\nshows no progress animation at all\n\n\n \n \n show_progress_on: Component | list[Component] | None\n\ndefault `= None`\n\nComponent or list of components to show the progress animation on. If None,\nwill show the progress animat", "heading1": "expand", "source_page_url": "https://gradio.app/docs/gradio/sidebar", "source_page_title": "Gradio - Sidebar Docs"}, {"text": "at all\n\n\n \n \n show_progress_on: Component | list[Component] | None\n\ndefault `= None`\n\nComponent or list of components to show the progress animation on. If None,\nwill show the progress animation on all of the output components.\n\n\n \n \n queue: bool\n\ndefault `= True`\n\nIf True, will place the request on the queue, if the queue has been enabled.\nIf False, will not put this event on the queue, even if the queue has been\nenabled. If None, will use the queue setting of the gradio app.\n\n\n \n \n batch: bool\n\ndefault `= False`\n\nIf True, then the function should process a batch of inputs, meaning that it\nshould accept a list of input values for each parameter. The lists should be\nof equal length (and be up to length `max_batch_size`). The function is then\n*required* to return a tuple of lists (even if there is only 1 output\ncomponent), with each list in the tuple corresponding to one output component.\n\n\n \n \n max_batch_size: int\n\ndefault `= 4`\n\nMaximum number of inputs to batch together if this is called from the queue\n(only relevant if batch=True)\n\n\n \n \n preprocess: bool\n\ndefault `= True`\n\nIf False, will not run preprocessing of component data before running 'fn'\n(e.g. leaving it as a base64 string if this method is called with the `Image`\ncomponent).\n\n\n \n \n postprocess: bool\n\ndefault `= True`\n\nIf False, will not run postprocessing of component data before returning 'fn'\noutput to the browser.\n\n\n \n \n cancels: dict[str, Any] | list[dict[str, Any]] | None\n\ndefault `= None`\n\nA list of other events to cancel when this listener is triggered. For example,\nsetting cancels=[click_event] will cancel the click_event, where click_event\nis the return value of another components .click method. Functions that have\nnot yet run (or generators that are iterating) will be cancelled, but\nfunctions that are currently running will be allowed to finish.\n\n\n \n \n trigger_mode: Literal['once', 'multiple', 'always_last'] | None\n\ndefaul", "heading1": "expand", "source_page_url": "https://gradio.app/docs/gradio/sidebar", "source_page_title": "Gradio - Sidebar Docs"}, {"text": "ators that are iterating) will be cancelled, but\nfunctions that are currently running will be allowed to finish.\n\n\n \n \n trigger_mode: Literal['once', 'multiple', 'always_last'] | None\n\ndefault `= None`\n\nIf \"once\" (default for all events except `.change()`) would not allow any\nsubmissions while an event is pending. If set to \"multiple\", unlimited\nsubmissions are allowed while pending, and \"always_last\" (default for\n`.change()` and `.key_up()` events) would allow a second submission after the\npending event is complete.\n\n\n \n \n js: str | Literal[True] | None\n\ndefault `= None`\n\nOptional frontend js method to run before running 'fn'. Input arguments for js\nmethod are values of 'inputs' and 'outputs', return should be a list of values\nfor output components.\n\n\n \n \n concurrency_limit: int | None | Literal['default']\n\ndefault `= \"default\"`\n\nIf set, this is the maximum number of this event that can be running\nsimultaneously. Can be set to None to mean no concurrency_limit (any number of\nthis event can be running simultaneously). Set to \"default\" to use the default\nconcurrency limit (defined by the `default_concurrency_limit` parameter in\n`Blocks.queue()`, which itself is 1 by default).\n\n\n \n \n concurrency_id: str | None\n\ndefault `= None`\n\nIf set, this is the id of the concurrency group. Events with the same\nconcurrency_id will be limited by the lowest set concurrency_limit.\n\n\n \n \n api_visibility: Literal['public', 'private', 'undocumented']\n\ndefault `= \"public\"`\n\ncontrols the visibility and accessibility of this endpoint. Can be \"public\"\n(shown in API docs and callable by clients), \"private\" (hidden from API docs\nand not callable by clients), or \"undocumented\" (hidden from API docs but\ncallable by clients and via gr.load). If fn is None, api_visibility will\nautomatically be set to \"private\".\n\n\n \n \n time_limit: int | None\n\ndefault `= None`\n\n\n \n \n stream_every: float\n\ndefault `= 0.5`\n\n\n \n \n key: int | str | t", "heading1": "expand", "source_page_url": "https://gradio.app/docs/gradio/sidebar", "source_page_title": "Gradio - Sidebar Docs"}, {"text": " api_visibility will\nautomatically be set to \"private\".\n\n\n \n \n time_limit: int | None\n\ndefault `= None`\n\n\n \n \n stream_every: float\n\ndefault `= 0.5`\n\n\n \n \n key: int | str | tuple[int | str, ...] | None\n\ndefault `= None`\n\nA unique key for this event listener to be used in @gr.render(). If set, this\nvalue identifies an event as identical across re-renders when the key is\nidentical.\n\n\n \n \n validator: Callable | None\n\ndefault `= None`\n\nOptional validation function to run before the main function. If provided,\nthis function will be executed first with queue=False, and only if it\ncompletes successfully will the main function be called. The validator\nreceives the same inputs as the main function and should return a\n`gr.validate()` for each input value.\n\n", "heading1": "expand", "source_page_url": "https://gradio.app/docs/gradio/sidebar", "source_page_title": "Gradio - Sidebar Docs"}, {"text": "![](data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20fill='%23808080'%20viewBox='0%200%20640%20512'%3e%3c!--!%20Font%20Awesome%20Pro%206.0.0%20by%20@fontawesome%20-%20https://fontawesome.com%20License%20-%20https://fontawesome.com/license%20\\(Commercial%20License\\)%20Copyright%202022%20Fonticons,%20Inc.%20--%3e%3cpath%20d='M172.5%20131.1C228.1%2075.51%20320.5%2075.51%20376.1%20131.1C426.1%20181.1%20433.5%20260.8%20392.4%20318.3L391.3%20319.9C381%20334.2%20361%20337.6%20346.7%20327.3C332.3%20317%20328.9%20297%20339.2%20282.7L340.3%20281.1C363.2%20249%20359.6%20205.1%20331.7%20177.2C300.3%20145.8%20249.2%20145.8%20217.7%20177.2L105.5%20289.5C73.99%20320.1%2073.99%20372%20105.5%20403.5C133.3%20431.4%20177.3%20435%20209.3%20412.1L210.9%20410.1C225.3%20400.7%20245.3%20404%20255.5%20418.4C265.8%20432.8%20262.5%20452.8%20248.1%20463.1L246.5%20464.2C188.1%20505.3%20110.2%20498.7%2060.21%20448.8C3.741%20392.3%203.741%20300.7%2060.21%20244.3L172.5%20131.1zM467.5%20380C411%20436.5%20319.5%20436.5%20263%20380C213%20330%20206.5%20251.2%20247.6%20193.7L248.7%20192.1C258.1%20177.8%20278.1%20174.4%20293.3%20184.7C307.7%20194.1%20311.1%20214.1%20300.8%20229.3L299.7%20230.9C276.8%20262.1%20280.4%20306.9%20308.3%20334.8C339.7%20366.2%20390.8%20366.2%20422.3%20334.8L534.5%20222.5C566%20191%20566%20139.1%20534.5%20108.5C506.7%2080.63%20462.7%2076.99%20430.7%2099.9L429.1%20101C414.7%20111.3%20394.7%20107.1%20384.5%2093.58C374.2%2079.2%20377.5%2059.21%20391.9%2048.94L393.5%2047.82C451%206.731%20529.8%2013.25%20579.8%2063.24C636.3%20119.7%20636.3%20211.3%20579.8%20267.7L467.5%20380z'/%3e%3c/svg%3e)\n\n \n \n gradio.Sidebar.collapse(\u00b7\u00b7\u00b7)\n\nDescription\n![](data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20fill='%23808080'%20viewBox='0%200%20640%20512'%3e%3c!--!%20Font%20Awesome%20Pro%206.0.0%20by%20@fontawesome%20-%20https://fontawesome.com%20License%20-%20https://fontawesome.com/license%20\\(Commercial%20License\\)%20Copyright%202022%20Fonticons,%20Inc.", "heading1": "collapse", "source_page_url": "https://gradio.app/docs/gradio/sidebar", "source_page_title": "Gradio - Sidebar Docs"}, {"text": "c!--!%20Font%20Awesome%20Pro%206.0.0%20by%20@fontawesome%20-%20https://fontawesome.com%20License%20-%20https://fontawesome.com/license%20\\(Commercial%20License\\)%20Copyright%202022%20Fonticons,%20Inc.%20--%3e%3cpath%20d='M172.5%20131.1C228.1%2075.51%20320.5%2075.51%20376.1%20131.1C426.1%20181.1%20433.5%20260.8%20392.4%20318.3L391.3%20319.9C381%20334.2%20361%20337.6%20346.7%20327.3C332.3%20317%20328.9%20297%20339.2%20282.7L340.3%20281.1C363.2%20249%20359.6%20205.1%20331.7%20177.2C300.3%20145.8%20249.2%20145.8%20217.7%20177.2L105.5%20289.5C73.99%20320.1%2073.99%20372%20105.5%20403.5C133.3%20431.4%20177.3%20435%20209.3%20412.1L210.9%20410.1C225.3%20400.7%20245.3%20404%20255.5%20418.4C265.8%20432.8%20262.5%20452.8%20248.1%20463.1L246.5%20464.2C188.1%20505.3%20110.2%20498.7%2060.21%20448.8C3.741%20392.3%203.741%20300.7%2060.21%20244.3L172.5%20131.1zM467.5%20380C411%20436.5%20319.5%20436.5%20263%20380C213%20330%20206.5%20251.2%20247.6%20193.7L248.7%20192.1C258.1%20177.8%20278.1%20174.4%20293.3%20184.7C307.7%20194.1%20311.1%20214.1%20300.8%20229.3L299.7%20230.9C276.8%20262.1%20280.4%20306.9%20308.3%20334.8C339.7%20366.2%20390.8%20366.2%20422.3%20334.8L534.5%20222.5C566%20191%20566%20139.1%20534.5%20108.5C506.7%2080.63%20462.7%2076.99%20430.7%2099.9L429.1%20101C414.7%20111.3%20394.7%20107.1%20384.5%2093.58C374.2%2079.2%20377.5%2059.21%20391.9%2048.94L393.5%2047.82C451%206.731%20529.8%2013.25%20579.8%2063.24C636.3%20119.7%20636.3%20211.3%20579.8%20267.7L467.5%20380z'/%3e%3c/svg%3e)\n\nThis listener is triggered when the Sidebar is collapsed.\n\nParameters \u25bc\n\n\n \n \n fn: Callable | None | Literal['decorator']\n\ndefault `= \"decorator\"`\n\nthe function to call when this event is triggered. Often a machine learning\nmodel's prediction function. Each parameter of the function corresponds to one\ninput component, and the function should return a single value or a tuple of\nvalues, with each element in the tuple corresponding to one output component.\n\n\n \n \n inputs: Component ", "heading1": "collapse", "source_page_url": "https://gradio.app/docs/gradio/sidebar", "source_page_title": "Gradio - Sidebar Docs"}, {"text": "nds to one\ninput component, and the function should return a single value or a tuple of\nvalues, with each element in the tuple corresponding to one output component.\n\n\n \n \n inputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n\ndefault `= None`\n\nList of gradio.components to use as inputs. If the function takes no inputs,\nthis should be an empty list.\n\n\n \n \n outputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n\ndefault `= None`\n\nList of gradio.components to use as outputs. If the function returns no\noutputs, this should be an empty list.\n\n\n \n \n api_name: str | None\n\ndefault `= None`\n\ndefines how the endpoint appears in the API docs. Can be a string or None. If\nset to a string, the endpoint will be exposed in the API docs with the given\nname. If None (default), the name of the function will be used as the API\nendpoint.\n\n\n \n \n api_description: str | None | Literal[False]\n\ndefault `= None`\n\nDescription of the API endpoint. Can be a string, None, or False. If set to a\nstring, the endpoint will be exposed in the API docs with the given\ndescription. If None, the function's docstring will be used as the API\nendpoint description. If False, then no description will be displayed in the\nAPI docs.\n\n\n \n \n scroll_to_output: bool\n\ndefault `= False`\n\nIf True, will scroll to output component on completion\n\n\n \n \n show_progress: Literal['full', 'minimal', 'hidden']\n\ndefault `= \"full\"`\n\nhow to show the progress animation while event is running: \"full\" shows a\nspinner which covers the output component area as well as a runtime display in\nthe upper right corner, \"minimal\" only shows the runtime display, \"hidden\"\nshows no progress animation at all\n\n\n \n \n show_progress_on: Component | list[Component] | None\n\ndefault `= None`\n\nComponent or list of components to show the progress animation on. If None,\nwill show the progress ani", "heading1": "collapse", "source_page_url": "https://gradio.app/docs/gradio/sidebar", "source_page_title": "Gradio - Sidebar Docs"}, {"text": "on at all\n\n\n \n \n show_progress_on: Component | list[Component] | None\n\ndefault `= None`\n\nComponent or list of components to show the progress animation on. If None,\nwill show the progress animation on all of the output components.\n\n\n \n \n queue: bool\n\ndefault `= True`\n\nIf True, will place the request on the queue, if the queue has been enabled.\nIf False, will not put this event on the queue, even if the queue has been\nenabled. If None, will use the queue setting of the gradio app.\n\n\n \n \n batch: bool\n\ndefault `= False`\n\nIf True, then the function should process a batch of inputs, meaning that it\nshould accept a list of input values for each parameter. The lists should be\nof equal length (and be up to length `max_batch_size`). The function is then\n*required* to return a tuple of lists (even if there is only 1 output\ncomponent), with each list in the tuple corresponding to one output component.\n\n\n \n \n max_batch_size: int\n\ndefault `= 4`\n\nMaximum number of inputs to batch together if this is called from the queue\n(only relevant if batch=True)\n\n\n \n \n preprocess: bool\n\ndefault `= True`\n\nIf False, will not run preprocessing of component data before running 'fn'\n(e.g. leaving it as a base64 string if this method is called with the `Image`\ncomponent).\n\n\n \n \n postprocess: bool\n\ndefault `= True`\n\nIf False, will not run postprocessing of component data before returning 'fn'\noutput to the browser.\n\n\n \n \n cancels: dict[str, Any] | list[dict[str, Any]] | None\n\ndefault `= None`\n\nA list of other events to cancel when this listener is triggered. For example,\nsetting cancels=[click_event] will cancel the click_event, where click_event\nis the return value of another components .click method. Functions that have\nnot yet run (or generators that are iterating) will be cancelled, but\nfunctions that are currently running will be allowed to finish.\n\n\n \n \n trigger_mode: Literal['once', 'multiple', 'always_last'] | None\n\ndef", "heading1": "collapse", "source_page_url": "https://gradio.app/docs/gradio/sidebar", "source_page_title": "Gradio - Sidebar Docs"}, {"text": "nerators that are iterating) will be cancelled, but\nfunctions that are currently running will be allowed to finish.\n\n\n \n \n trigger_mode: Literal['once', 'multiple', 'always_last'] | None\n\ndefault `= None`\n\nIf \"once\" (default for all events except `.change()`) would not allow any\nsubmissions while an event is pending. If set to \"multiple\", unlimited\nsubmissions are allowed while pending, and \"always_last\" (default for\n`.change()` and `.key_up()` events) would allow a second submission after the\npending event is complete.\n\n\n \n \n js: str | Literal[True] | None\n\ndefault `= None`\n\nOptional frontend js method to run before running 'fn'. Input arguments for js\nmethod are values of 'inputs' and 'outputs', return should be a list of values\nfor output components.\n\n\n \n \n concurrency_limit: int | None | Literal['default']\n\ndefault `= \"default\"`\n\nIf set, this is the maximum number of this event that can be running\nsimultaneously. Can be set to None to mean no concurrency_limit (any number of\nthis event can be running simultaneously). Set to \"default\" to use the default\nconcurrency limit (defined by the `default_concurrency_limit` parameter in\n`Blocks.queue()`, which itself is 1 by default).\n\n\n \n \n concurrency_id: str | None\n\ndefault `= None`\n\nIf set, this is the id of the concurrency group. Events with the same\nconcurrency_id will be limited by the lowest set concurrency_limit.\n\n\n \n \n api_visibility: Literal['public', 'private', 'undocumented']\n\ndefault `= \"public\"`\n\ncontrols the visibility and accessibility of this endpoint. Can be \"public\"\n(shown in API docs and callable by clients), \"private\" (hidden from API docs\nand not callable by clients), or \"undocumented\" (hidden from API docs but\ncallable by clients and via gr.load). If fn is None, api_visibility will\nautomatically be set to \"private\".\n\n\n \n \n time_limit: int | None\n\ndefault `= None`\n\n\n \n \n stream_every: float\n\ndefault `= 0.5`\n\n\n \n \n key: int | str ", "heading1": "collapse", "source_page_url": "https://gradio.app/docs/gradio/sidebar", "source_page_title": "Gradio - Sidebar Docs"}, {"text": "ne, api_visibility will\nautomatically be set to \"private\".\n\n\n \n \n time_limit: int | None\n\ndefault `= None`\n\n\n \n \n stream_every: float\n\ndefault `= 0.5`\n\n\n \n \n key: int | str | tuple[int | str, ...] | None\n\ndefault `= None`\n\nA unique key for this event listener to be used in @gr.render(). If set, this\nvalue identifies an event as identical across re-renders when the key is\nidentical.\n\n\n \n \n validator: Callable | None\n\ndefault `= None`\n\nOptional validation function to run before the main function. If provided,\nthis function will be executed first with queue=False, and only if it\ncompletes successfully will the main function be called. The validator\nreceives the same inputs as the main function and should return a\n`gr.validate()` for each input value.\n\n", "heading1": "collapse", "source_page_url": "https://gradio.app/docs/gradio/sidebar", "source_page_title": "Gradio - Sidebar Docs"}, {"text": "The gr.SelectData class is a subclass of gr.EventData that specifically\ncarries information about the `.select()` event. When gr.SelectData is added\nas a type hint to an argument of an event listener method, a gr.SelectData\nobject will automatically be passed as the value of that argument. The\nattributes of this object contains information about the event that triggered\nthe listener. \n\n", "heading1": "Description", "source_page_url": "https://gradio.app/docs/gradio/selectdata", "source_page_title": "Gradio - Selectdata Docs"}, {"text": "import gradio as gr\n \n with 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 \n demo.launch()\n\n", "heading1": "Example Usage", "source_page_url": "https://gradio.app/docs/gradio/selectdata", "source_page_title": "Gradio - Selectdata Docs"}, {"text": "Parameters \u25bc\n\n\n \n \n index: int | tuple[int, int]\n\nThe index of the selected item. Is a tuple if the component is two dimensional\nor selection is a range.\n\n\n \n \n value: Any\n\nThe value of the selected item.\n\n\n \n \n row_value: list[float | str]\n\nThe value of the entire row that the selected item belongs to, as a 1-D list.\nOnly implemented for the `Dataframe` component, returns None for other\ncomponents.\n\n\n \n \n col_value: list[float | str]\n\nThe value of the entire column that the selected item belongs to, as a 1-D\nlist. Only implemented for the `Dataframe` component, returns None for other\ncomponents.\n\n\n \n \n selected: bool\n\nTrue if the item was selected, False if deselected.\n\n", "heading1": "Attributes", "source_page_url": "https://gradio.app/docs/gradio/selectdata", "source_page_title": "Gradio - Selectdata Docs"}, {"text": "gallery_selectionstictactoe\n\n", "heading1": "Demos", "source_page_url": "https://gradio.app/docs/gradio/selectdata", "source_page_title": "Gradio - Selectdata Docs"}, {"text": "Creates a button, that when clicked, allows a user to download a single\nfile of arbitrary type. \n\n", "heading1": "Description", "source_page_url": "https://gradio.app/docs/gradio/downloadbutton", "source_page_title": "Gradio - Downloadbutton Docs"}, {"text": "**As input component** : (Rarely used) passes the file as a `str` into the\nfunction.\n\nYour function should accept one of these types:\n\n \n \n def predict(\n \tvalue: str | None\n )\n \t...\n\n \n\n**As output component** : Expects a `str` or `pathlib.Path` filepath\n\nYour function should return one of these types:\n\n \n \n def predict(\u00b7\u00b7\u00b7) -> str | Path | None\n \t...\t\n \treturn value\n\n", "heading1": "Behavior", "source_page_url": "https://gradio.app/docs/gradio/downloadbutton", "source_page_title": "Gradio - Downloadbutton Docs"}, {"text": "Parameters \u25bc\n\n\n \n \n label: str\n\ndefault `= \"Download\"`\n\nText to display on the button. Defaults to \"Download\".\n\n\n \n \n value: str | Path | Callable | None\n\ndefault `= None`\n\nA str or pathlib.Path filepath or URL to download, or a Callable that returns\na str or pathlib.Path filepath or URL to download.\n\n\n \n \n every: Timer | float | None\n\ndefault `= None`\n\nContinously calls `value` to recalculate it if `value` is a function (has no\neffect otherwise). Can provide a Timer whose tick resets `value`, or a float\nthat provides the regular interval for the reset Timer.\n\n\n \n \n inputs: Component | list[Component] | set[Component] | None\n\ndefault `= None`\n\nComponents that are used as inputs to calculate `value` if `value` is a\nfunction (has no effect otherwise). `value` is recalculated any time the\ninputs change.\n\n\n \n \n variant: Literal['primary', 'secondary', 'stop']\n\ndefault `= \"secondary\"`\n\n'primary' for main call-to-action, 'secondary' for a more subdued style,\n'stop' for a stop button.\n\n\n \n \n visible: bool | Literal['hidden']\n\ndefault `= True`\n\nIf False, component will be hidden. If \"hidden\", component will be visually\nhidden and not take up space in the layout but still exist in the DOM\n\n\n \n \n size: Literal['sm', 'md', 'lg']\n\ndefault `= \"lg\"`\n\nsize of the button. Can be \"sm\", \"md\", or \"lg\".\n\n\n \n \n icon: str | None\n\ndefault `= None`\n\nURL or path to the icon file to display within the button. If None, no icon\nwill be displayed.\n\n\n \n \n scale: int | None\n\ndefault `= None`\n\nrelative size compared to adjacent Components. For example if Components A and\nB are in a Row, and A has scale=2, and B has scale=1, A will be twice as wide\nas B. Should be an integer. scale applies in Rows, and to top-level Components\nin Blocks where fill_height=True.\n\n\n \n \n min_width: int | None\n\ndefault `= None`\n\nminimum pixel width, will wrap if not sufficient screen space to satisfy this\nvalue. If a certain scale v", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/downloadbutton", "source_page_title": "Gradio - Downloadbutton Docs"}, {"text": "nts\nin Blocks where fill_height=True.\n\n\n \n \n min_width: int | None\n\ndefault `= None`\n\nminimum pixel width, will wrap if not sufficient screen space to satisfy this\nvalue. If a certain scale value results in this Component being narrower than\nmin_width, the min_width parameter will be respected first.\n\n\n \n \n interactive: bool\n\ndefault `= True`\n\nIf False, the UploadButton will be in a disabled state.\n\n\n \n \n elem_id: str | None\n\ndefault `= None`\n\nAn optional string that is assigned as the id of this component in the HTML\nDOM. Can be used for targeting CSS styles.\n\n\n \n \n elem_classes: list[str] | str | None\n\ndefault `= None`\n\nAn optional list of strings that are assigned as the classes of this component\nin the HTML DOM. Can be used for targeting CSS styles.\n\n\n \n \n render: bool\n\ndefault `= True`\n\nIf False, component will not render be rendered in the Blocks context. Should\nbe used if the intention is to assign event listeners now but render the\ncomponent later.\n\n\n \n \n key: int | str | tuple[int | str, ...] | None\n\ndefault `= None`\n\nin a gr.render, Components with the same key across re-renders are treated as\nthe same component, not a new component. Properties set in 'preserved_by_key'\nare not reset across a re-render.\n\n\n \n \n preserved_by_key: list[str] | str | None\n\ndefault `= \"value\"`\n\nA list of parameters from this component's constructor. Inside a gr.render()\nfunction, if a component is re-rendered with the same key, these (and only\nthese) parameters will be preserved in the UI (if they have been changed by\nthe user or an event listener) instead of re-rendered based on the values\nprovided during constructor.\n\n", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/downloadbutton", "source_page_title": "Gradio - Downloadbutton Docs"}, {"text": "Shortcuts\n\n \n \n gradio.DownloadButton\n\nInterface String Shortcut `\"downloadbutton\"`\n\nInitialization Uses default values\n\n", "heading1": "Shortcuts", "source_page_url": "https://gradio.app/docs/gradio/downloadbutton", "source_page_title": "Gradio - Downloadbutton Docs"}, {"text": "upload_and_download\n\n", "heading1": "Demos", "source_page_url": "https://gradio.app/docs/gradio/downloadbutton", "source_page_title": "Gradio - Downloadbutton Docs"}, {"text": "Description\n\nEvent listeners allow you to respond to user interactions with the UI\ncomponents you've defined in a Gradio Blocks app. When a user interacts with\nan element, such as changing a slider value or uploading an image, a function\nis called.\n\nSupported Event Listeners\n\nThe DownloadButton component supports the following event listeners. Each\nevent listener takes the same parameters, which are listed in the Event\nParameters table below.\n\nListeners\n\n \n \n DownloadButton.click(fn, \u00b7\u00b7\u00b7)\n\nTriggered when the DownloadButton is clicked.\n\nEvent Parameters\n\nParameters \u25bc\n\n\n \n \n fn: Callable | None | Literal['decorator']\n\ndefault `= \"decorator\"`\n\nthe function to call when this event is triggered. Often a machine learning\nmodel's prediction function. Each parameter of the function corresponds to one\ninput component, and the function should return a single value or a tuple of\nvalues, with each element in the tuple corresponding to one output component.\n\n\n \n \n inputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n\ndefault `= None`\n\nList of gradio.components to use as inputs. If the function takes no inputs,\nthis should be an empty list.\n\n\n \n \n outputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None\n\ndefault `= None`\n\nList of gradio.components to use as outputs. If the function returns no\noutputs, this should be an empty list.\n\n\n \n \n api_name: str | None\n\ndefault `= None`\n\ndefines how the endpoint appears in the API docs. Can be a string or None. If\nset to a string, the endpoint will be exposed in the API docs with the given\nname. If None (default), the name of the function will be used as the API\nendpoint.\n\n\n \n \n api_description: str | None | Literal[False]\n\ndefault `= None`\n\nDescription of the API endpoint. Can be a string, None, or False. If set to a\nstring, the endpoint will be exposed in the API docs wit", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/downloadbutton", "source_page_title": "Gradio - Downloadbutton Docs"}, {"text": " api_description: str | None | Literal[False]\n\ndefault `= None`\n\nDescription of the API endpoint. Can be a string, None, or False. If set to a\nstring, the endpoint will be exposed in the API docs with the given\ndescription. If None, the function's docstring will be used as the API\nendpoint description. If False, then no description will be displayed in the\nAPI docs.\n\n\n \n \n scroll_to_output: bool\n\ndefault `= False`\n\nIf True, will scroll to output component on completion\n\n\n \n \n show_progress: Literal['full', 'minimal', 'hidden']\n\ndefault `= \"full\"`\n\nhow to show the progress animation while event is running: \"full\" shows a\nspinner which covers the output component area as well as a runtime display in\nthe upper right corner, \"minimal\" only shows the runtime display, \"hidden\"\nshows no progress animation at all\n\n\n \n \n show_progress_on: Component | list[Component] | None\n\ndefault `= None`\n\nComponent or list of components to show the progress animation on. If None,\nwill show the progress animation on all of the output components.\n\n\n \n \n queue: bool\n\ndefault `= True`\n\nIf True, will place the request on the queue, if the queue has been enabled.\nIf False, will not put this event on the queue, even if the queue has been\nenabled. If None, will use the queue setting of the gradio app.\n\n\n \n \n batch: bool\n\ndefault `= False`\n\nIf True, then the function should process a batch of inputs, meaning that it\nshould accept a list of input values for each parameter. The lists should be\nof equal length (and be up to length `max_batch_size`). The function is then\n*required* to return a tuple of lists (even if there is only 1 output\ncomponent), with each list in the tuple corresponding to one output component.\n\n\n \n \n max_batch_size: int\n\ndefault `= 4`\n\nMaximum number of inputs to batch together if this is called from the queue\n(only relevant if batch=True)\n\n\n \n \n preprocess: bool\n\ndefault `= True`\n\nIf False, will not run preprocess", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/downloadbutton", "source_page_title": "Gradio - Downloadbutton Docs"}, {"text": "t `= 4`\n\nMaximum number of inputs to batch together if this is called from the queue\n(only relevant if batch=True)\n\n\n \n \n preprocess: bool\n\ndefault `= True`\n\nIf False, will not run preprocessing of component data before running 'fn'\n(e.g. leaving it as a base64 string if this method is called with the `Image`\ncomponent).\n\n\n \n \n postprocess: bool\n\ndefault `= True`\n\nIf False, will not run postprocessing of component data before returning 'fn'\noutput to the browser.\n\n\n \n \n cancels: dict[str, Any] | list[dict[str, Any]] | None\n\ndefault `= None`\n\nA list of other events to cancel when this listener is triggered. For example,\nsetting cancels=[click_event] will cancel the click_event, where click_event\nis the return value of another components .click method. Functions that have\nnot yet run (or generators that are iterating) will be cancelled, but\nfunctions that are currently running will be allowed to finish.\n\n\n \n \n trigger_mode: Literal['once', 'multiple', 'always_last'] | None\n\ndefault `= None`\n\nIf \"once\" (default for all events except `.change()`) would not allow any\nsubmissions while an event is pending. If set to \"multiple\", unlimited\nsubmissions are allowed while pending, and \"always_last\" (default for\n`.change()` and `.key_up()` events) would allow a second submission after the\npending event is complete.\n\n\n \n \n js: str | Literal[True] | None\n\ndefault `= None`\n\nOptional frontend js method to run before running 'fn'. Input arguments for js\nmethod are values of 'inputs' and 'outputs', return should be a list of values\nfor output components.\n\n\n \n \n concurrency_limit: int | None | Literal['default']\n\ndefault `= \"default\"`\n\nIf set, this is the maximum number of this event that can be running\nsimultaneously. Can be set to None to mean no concurrency_limit (any number of\nthis event can be running simultaneously). Set to \"default\" to use the default\nconcurrency limit (defined by the `default_concurrency_limit` parameter in", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/downloadbutton", "source_page_title": "Gradio - Downloadbutton Docs"}, {"text": "ne to mean no concurrency_limit (any number of\nthis event can be running simultaneously). Set to \"default\" to use the default\nconcurrency limit (defined by the `default_concurrency_limit` parameter in\n`Blocks.queue()`, which itself is 1 by default).\n\n\n \n \n concurrency_id: str | None\n\ndefault `= None`\n\nIf set, this is the id of the concurrency group. Events with the same\nconcurrency_id will be limited by the lowest set concurrency_limit.\n\n\n \n \n api_visibility: Literal['public', 'private', 'undocumented']\n\ndefault `= \"public\"`\n\ncontrols the visibility and accessibility of this endpoint. Can be \"public\"\n(shown in API docs and callable by clients), \"private\" (hidden from API docs\nand not callable by clients), or \"undocumented\" (hidden from API docs but\ncallable by clients and via gr.load). If fn is None, api_visibility will\nautomatically be set to \"private\".\n\n\n \n \n time_limit: int | None\n\ndefault `= None`\n\n\n \n \n stream_every: float\n\ndefault `= 0.5`\n\n\n \n \n key: int | str | tuple[int | str, ...] | None\n\ndefault `= None`\n\nA unique key for this event listener to be used in @gr.render(). If set, this\nvalue identifies an event as identical across re-renders when the key is\nidentical.\n\n\n \n \n validator: Callable | None\n\ndefault `= None`\n\nOptional validation function to run before the main function. If provided,\nthis function will be executed first with queue=False, and only if it\ncompletes successfully will the main function be called. The validator\nreceives the same inputs as the main function and should return a\n`gr.validate()` for each input value.\n\n", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/downloadbutton", "source_page_title": "Gradio - Downloadbutton Docs"}, {"text": "The gr.UndoData class is a subclass of gr.Event data that specifically\ncarries information about the `.undo()` event. When gr.UndoData is added as a\ntype hint to an argument of an event listener method, a gr.UndoData object\nwill automatically be passed as the value of that argument. The attributes of\nthis object contains information about the event that triggered the listener.\n\n", "heading1": "Description", "source_page_url": "https://gradio.app/docs/gradio/undodata", "source_page_title": "Gradio - Undodata Docs"}, {"text": "import gradio as gr\n \n def 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 \n with gr.Blocks() as demo:\n chatbot = gr.Chatbot()\n chatbot.undo(undo, chatbot, chatbot)\n demo.launch()\n\n", "heading1": "Example Usage", "source_page_url": "https://gradio.app/docs/gradio/undodata", "source_page_title": "Gradio - Undodata Docs"}, {"text": "Parameters \u25bc\n\n\n \n \n index: int | tuple[int, int]\n\nThe index of the user message that should be undone.\n\n\n \n \n value: Any\n\nThe value of the user message that should be undone.\n\n", "heading1": "Attributes", "source_page_url": "https://gradio.app/docs/gradio/undodata", "source_page_title": "Gradio - Undodata Docs"}, {"text": "Blocks is Gradio's low-level API that allows you to create more custom web\napplications and demos than Interfaces (yet still entirely in Python). \n \nCompared to the Interface class, Blocks offers more flexibility and control\nover: (1) the layout of components (2) the events that trigger the execution\nof functions (3) data flows (e.g. inputs can trigger outputs, which can\ntrigger the next level of outputs). Blocks also offers ways to group together\nrelated demos such as with tabs. \n \nThe basic usage of Blocks is as follows: create a Blocks object, then use it\nas a context (with the \"with\" statement), and then define layouts, components,\nor events within the Blocks context. Finally, call the launch() method to\nlaunch the demo. \n\n", "heading1": "Description", "source_page_url": "https://gradio.app/docs/gradio/blocks", "source_page_title": "Gradio - Blocks Docs"}, {"text": "import gradio as gr\n def update(name):\n return f\"Welcome to Gradio, {name}!\"\n \n with 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 \n demo.launch()\n\n", "heading1": "Example Usage", "source_page_url": "https://gradio.app/docs/gradio/blocks", "source_page_title": "Gradio - Blocks Docs"}, {"text": "Parameters \u25bc\n\n\n \n \n analytics_enabled: bool | None\n\ndefault `= None`\n\nWhether to allow basic telemetry. If None, will use GRADIO_ANALYTICS_ENABLED\nenvironment variable or default to True.\n\n\n \n \n mode: str\n\ndefault `= \"blocks\"`\n\nA human-friendly name for the kind of Blocks or Interface being created. Used\ninternally for analytics.\n\n\n \n \n title: str | I18nData\n\ndefault `= \"Gradio\"`\n\nThe tab title to display when this is opened in a browser window.\n\n\n \n \n fill_height: bool\n\ndefault `= False`\n\nWhether to vertically expand top-level child components to the height of the\nwindow. If True, expansion occurs when the scale value of the child components\n>= 1.\n\n\n \n \n fill_width: bool\n\ndefault `= False`\n\nWhether to horizontally expand to fill container fully. If False, centers and\nconstrains app to a maximum width. Only applies if this is the outermost\n`Blocks` in your Gradio app.\n\n\n \n \n delete_cache: tuple[int, int] | None\n\ndefault `= None`\n\nA tuple corresponding [frequency, age] both expressed in number of seconds.\nEvery `frequency` seconds, the temporary files created by this Blocks instance\nwill be deleted if more than `age` seconds have passed since the file was\ncreated. For example, setting this to (86400, 86400) will delete temporary\nfiles every day. The cache will be deleted entirely when the server restarts.\nIf None, no cache deletion will occur.\n\n", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/blocks", "source_page_title": "Gradio - Blocks Docs"}, {"text": "blocks_helloblocks_flipperblocks_kinematics\n\n", "heading1": "Demos", "source_page_url": "https://gradio.app/docs/gradio/blocks", "source_page_title": "Gradio - Blocks Docs"}, {"text": "", "heading1": "Methods", "source_page_url": "https://gradio.app/docs/gradio/blocks", "source_page_title": "Gradio - Blocks Docs"}, {"text": "![](data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20fill='%23808080'%20viewBox='0%200%20640%20512'%3e%3c!--!%20Font%20Awesome%20Pro%206.0.0%20by%20@fontawesome%20-%20https://fontawesome.com%20License%20-%20https://fontawesome.com/license%20\\(Commercial%20License\\)%20Copyright%202022%20Fonticons,%20Inc.%20--%3e%3cpath%20d='M172.5%20131.1C228.1%2075.51%20320.5%2075.51%20376.1%20131.1C426.1%20181.1%20433.5%20260.8%20392.4%20318.3L391.3%20319.9C381%20334.2%20361%20337.6%20346.7%20327.3C332.3%20317%20328.9%20297%20339.2%20282.7L340.3%20281.1C363.2%20249%20359.6%20205.1%20331.7%20177.2C300.3%20145.8%20249.2%20145.8%20217.7%20177.2L105.5%20289.5C73.99%20320.1%2073.99%20372%20105.5%20403.5C133.3%20431.4%20177.3%20435%20209.3%20412.1L210.9%20410.1C225.3%20400.7%20245.3%20404%20255.5%20418.4C265.8%20432.8%20262.5%20452.8%20248.1%20463.1L246.5%20464.2C188.1%20505.3%20110.2%20498.7%2060.21%20448.8C3.741%20392.3%203.741%20300.7%2060.21%20244.3L172.5%20131.1zM467.5%20380C411%20436.5%20319.5%20436.5%20263%20380C213%20330%20206.5%20251.2%20247.6%20193.7L248.7%20192.1C258.1%20177.8%20278.1%20174.4%20293.3%20184.7C307.7%20194.1%20311.1%20214.1%20300.8%20229.3L299.7%20230.9C276.8%20262.1%20280.4%20306.9%20308.3%20334.8C339.7%20366.2%20390.8%20366.2%20422.3%20334.8L534.5%20222.5C566%20191%20566%20139.1%20534.5%20108.5C506.7%2080.63%20462.7%2076.99%20430.7%2099.9L429.1%20101C414.7%20111.3%20394.7%20107.1%20384.5%2093.58C374.2%2079.2%20377.5%2059.21%20391.9%2048.94L393.5%2047.82C451%206.731%20529.8%2013.25%20579.8%2063.24C636.3%20119.7%20636.3%20211.3%20579.8%20267.7L467.5%20380z'/%3e%3c/svg%3e)\n\n \n \n gradio.Blocks.launch(\u00b7\u00b7\u00b7)\n\nDescription\n![](data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20fill='%23808080'%20viewBox='0%200%20640%20512'%3e%3c!--!%20Font%20Awesome%20Pro%206.0.0%20by%20@fontawesome%20-%20https://fontawesome.com%20License%20-%20https://fontawesome.com/license%20\\(Commercial%20License\\)%20Copyright%202022%20Fonticons,%20Inc.%20", "heading1": "launch", "source_page_url": "https://gradio.app/docs/gradio/blocks", "source_page_title": "Gradio - Blocks Docs"}, {"text": "-!%20Font%20Awesome%20Pro%206.0.0%20by%20@fontawesome%20-%20https://fontawesome.com%20License%20-%20https://fontawesome.com/license%20\\(Commercial%20License\\)%20Copyright%202022%20Fonticons,%20Inc.%20--%3e%3cpath%20d='M172.5%20131.1C228.1%2075.51%20320.5%2075.51%20376.1%20131.1C426.1%20181.1%20433.5%20260.8%20392.4%20318.3L391.3%20319.9C381%20334.2%20361%20337.6%20346.7%20327.3C332.3%20317%20328.9%20297%20339.2%20282.7L340.3%20281.1C363.2%20249%20359.6%20205.1%20331.7%20177.2C300.3%20145.8%20249.2%20145.8%20217.7%20177.2L105.5%20289.5C73.99%20320.1%2073.99%20372%20105.5%20403.5C133.3%20431.4%20177.3%20435%20209.3%20412.1L210.9%20410.1C225.3%20400.7%20245.3%20404%20255.5%20418.4C265.8%20432.8%20262.5%20452.8%20248.1%20463.1L246.5%20464.2C188.1%20505.3%20110.2%20498.7%2060.21%20448.8C3.741%20392.3%203.741%20300.7%2060.21%20244.3L172.5%20131.1zM467.5%20380C411%20436.5%20319.5%20436.5%20263%20380C213%20330%20206.5%20251.2%20247.6%20193.7L248.7%20192.1C258.1%20177.8%20278.1%20174.4%20293.3%20184.7C307.7%20194.1%20311.1%20214.1%20300.8%20229.3L299.7%20230.9C276.8%20262.1%20280.4%20306.9%20308.3%20334.8C339.7%20366.2%20390.8%20366.2%20422.3%20334.8L534.5%20222.5C566%20191%20566%20139.1%20534.5%20108.5C506.7%2080.63%20462.7%2076.99%20430.7%2099.9L429.1%20101C414.7%20111.3%20394.7%20107.1%20384.5%2093.58C374.2%2079.2%20377.5%2059.21%20391.9%2048.94L393.5%2047.82C451%206.731%20529.8%2013.25%20579.8%2063.24C636.3%20119.7%20636.3%20211.3%20579.8%20267.7L467.5%20380z'/%3e%3c/svg%3e)\n\nLaunches a simple web server that serves the demo. Can also be used to create\na public link used by anyone to access the demo from their browser by setting\nshare=True.\n\nExample Usage\n![](data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20fill='%23808080'%20viewBox='0%200%20640%20512'%3e%3c!--!%20Font%20Awesome%20Pro%206.0.0%20by%20@fontawesome%20-%20https://fontawesome.com%20License%20-%20https://fontawesome.com/license%20\\(Commercial%20License\\)%20Copyright%202022%20Fonticons,%20", "heading1": "launch", "source_page_url": "https://gradio.app/docs/gradio/blocks", "source_page_title": "Gradio - Blocks Docs"}, {"text": "3e%3c!--!%20Font%20Awesome%20Pro%206.0.0%20by%20@fontawesome%20-%20https://fontawesome.com%20License%20-%20https://fontawesome.com/license%20\\(Commercial%20License\\)%20Copyright%202022%20Fonticons,%20Inc.%20--%3e%3cpath%20d='M172.5%20131.1C228.1%2075.51%20320.5%2075.51%20376.1%20131.1C426.1%20181.1%20433.5%20260.8%20392.4%20318.3L391.3%20319.9C381%20334.2%20361%20337.6%20346.7%20327.3C332.3%20317%20328.9%20297%20339.2%20282.7L340.3%20281.1C363.2%20249%20359.6%20205.1%20331.7%20177.2C300.3%20145.8%20249.2%20145.8%20217.7%20177.2L105.5%20289.5C73.99%20320.1%2073.99%20372%20105.5%20403.5C133.3%20431.4%20177.3%20435%20209.3%20412.1L210.9%20410.1C225.3%20400.7%20245.3%20404%20255.5%20418.4C265.8%20432.8%20262.5%20452.8%20248.1%20463.1L246.5%20464.2C188.1%20505.3%20110.2%20498.7%2060.21%20448.8C3.741%20392.3%203.741%20300.7%2060.21%20244.3L172.5%20131.1zM467.5%20380C411%20436.5%20319.5%20436.5%20263%20380C213%20330%20206.5%20251.2%20247.6%20193.7L248.7%20192.1C258.1%20177.8%20278.1%20174.4%20293.3%20184.7C307.7%20194.1%20311.1%20214.1%20300.8%20229.3L299.7%20230.9C276.8%20262.1%20280.4%20306.9%20308.3%20334.8C339.7%20366.2%20390.8%20366.2%20422.3%20334.8L534.5%20222.5C566%20191%20566%20139.1%20534.5%20108.5C506.7%2080.63%20462.7%2076.99%20430.7%2099.9L429.1%20101C414.7%20111.3%20394.7%20107.1%20384.5%2093.58C374.2%2079.2%20377.5%2059.21%20391.9%2048.94L393.5%2047.82C451%206.731%20529.8%2013.25%20579.8%2063.24C636.3%20119.7%20636.3%20211.3%20579.8%20267.7L467.5%20380z'/%3e%3c/svg%3e)\n\n \n \n import gradio as gr\n def reverse(text):\n return text[::-1]\n with gr.Blocks() as demo:\n button = gr.Button(value=\"Reverse\")\n button.click(reverse, gr.Textbox(), gr.Textbox())\n demo.launch(share=True, auth=(\"username\", \"password\"))\n\nParameters \u25bc\n\n\n \n \n inline: bool | None\n\ndefault `= None`\n\nwhether to display in the gradio app inline in an iframe. Defaults to True in\npython notebooks; False otherwise.\n\n\n \n \n inbrowser: bool\n\ndefault ", "heading1": "launch", "source_page_url": "https://gradio.app/docs/gradio/blocks", "source_page_title": "Gradio - Blocks Docs"}, {"text": " \n inline: bool | None\n\ndefault `= None`\n\nwhether to display in the gradio app inline in an iframe. Defaults to True in\npython notebooks; False otherwise.\n\n\n \n \n inbrowser: bool\n\ndefault `= False`\n\nwhether to automatically launch the gradio app in a new tab on the default\nbrowser.\n\n\n \n \n share: bool | None\n\ndefault `= None`\n\nwhether to create a publicly shareable link for the gradio app. Creates an SSH\ntunnel to make your UI accessible from anywhere. If not provided, it is set to\nFalse by default every time, except when running in Google Colab. When\nlocalhost is not accessible (e.g. Google Colab), setting share=False is not\nsupported. Can be set by environment variable GRADIO_SHARE=True.\n\n\n \n \n debug: bool\n\ndefault `= False`\n\nif True, blocks the main thread from running. If running in Google Colab, this\nis needed to print the errors in the cell output.\n\n\n \n \n max_threads: int\n\ndefault `= 40`\n\nthe maximum number of total threads that the Gradio app can generate in\nparallel. The default is inherited from the starlette library (currently 40).\n\n\n \n \n auth: Callable[[str, str], bool] | tuple[str, str] | list[tuple[str, str]] | None\n\ndefault `= None`\n\nIf provided, username and password (or list of username-password tuples)\nrequired to access app. Can also provide function that takes username and\npassword and returns True if valid login.\n\n\n \n \n auth_message: str | None\n\ndefault `= None`\n\nIf provided, HTML message provided on login page.\n\n\n \n \n prevent_thread_lock: bool\n\ndefault `= False`\n\nBy default, the gradio app blocks the main thread while the server is running.\nIf set to True, the gradio app will not block and the gradio server will\nterminate as soon as the script finishes.\n\n\n \n \n show_error: bool\n\ndefault `= False`\n\nIf True, any errors in the gradio app will be displayed in an alert modal and\nprinted in the browser console log. They will also be displayed in the alert\nmodal of downstream apps", "heading1": "launch", "source_page_url": "https://gradio.app/docs/gradio/blocks", "source_page_title": "Gradio - Blocks Docs"}, {"text": "\n\ndefault `= False`\n\nIf True, any errors in the gradio app will be displayed in an alert modal and\nprinted in the browser console log. They will also be displayed in the alert\nmodal of downstream apps that gr.load() this app.\n\n\n \n \n server_name: str | None\n\ndefault `= None`\n\nto make app accessible on local network, set this to \"0.0.0.0\". Can be set by\nenvironment variable GRADIO_SERVER_NAME. If None, will use \"127.0.0.1\".\n\n\n \n \n server_port: int | None\n\ndefault `= None`\n\nwill start gradio app on this port (if available). Can be set by environment\nvariable GRADIO_SERVER_PORT. If None, will search for an available port\nstarting at 7860.\n\n\n \n \n height: int\n\ndefault `= 500`\n\nThe height in pixels of the iframe element containing the gradio app (used if\ninline=True)\n\n\n \n \n width: int | str\n\ndefault `= \"100%\"`\n\nThe width in pixels of the iframe element containing the gradio app (used if\ninline=True)\n\n\n \n \n favicon_path: str | Path | None\n\ndefault `= None`\n\nIf a path to a file (.png, .gif, or .ico) is provided, it will be used as the\nfavicon for the web page.\n\n\n \n \n ssl_keyfile: str | None\n\ndefault `= None`\n\nIf a path to a file is provided, will use this as the private key file to\ncreate a local server running on https.\n\n\n \n \n ssl_certfile: str | None\n\ndefault `= None`\n\nIf a path to a file is provided, will use this as the signed certificate for\nhttps. Needs to be provided if ssl_keyfile is provided.\n\n\n \n \n ssl_keyfile_password: str | None\n\ndefault `= None`\n\nIf a password is provided, will use this with the ssl certificate for https.\n\n\n \n \n ssl_verify: bool\n\ndefault `= True`\n\nIf False, skips certificate validation which allows self-signed certificates\nto be used.\n\n\n \n \n quiet: bool\n\ndefault `= False`\n\nIf True, suppresses most print statements.\n\n\n \n \n footer_links: list[Literal['api', 'gradio', 'settings'] | dict[str, str]] | None\n\ndefault `= None`\n\nThe links to display in the ", "heading1": "launch", "source_page_url": "https://gradio.app/docs/gradio/blocks", "source_page_title": "Gradio - Blocks Docs"}, {"text": "t `= False`\n\nIf True, suppresses most print statements.\n\n\n \n \n footer_links: list[Literal['api', 'gradio', 'settings'] | dict[str, str]] | None\n\ndefault `= None`\n\nThe links to display in the footer of the app. Accepts a list, where each\nelement of the list must be one of \"api\", \"gradio\", or \"settings\"\ncorresponding to the API docs, \"built with Gradio\", and settings pages\nrespectively. If None, all three links will be shown in the footer. An empty\nlist means that no footer is shown.\n\n\n \n \n allowed_paths: list[str] | None\n\ndefault `= None`\n\nList of complete filepaths or parent directories that gradio is allowed to\nserve. Must be absolute paths. Warning: if you provide directories, any files\nin these directories or their subdirectories are accessible to all users of\nyour app. Can be set by comma separated environment variable\nGRADIO_ALLOWED_PATHS. These files are generally assumed to be secure and will\nbe displayed in the browser when possible.\n\n\n \n \n blocked_paths: list[str] | None\n\ndefault `= None`\n\nList of complete filepaths or parent directories that gradio is not allowed to\nserve (i.e. users of your app are not allowed to access). Must be absolute\npaths. Warning: takes precedence over `allowed_paths` and all other\ndirectories exposed by Gradio by default. Can be set by comma separated\nenvironment variable GRADIO_BLOCKED_PATHS.\n\n\n \n \n root_path: str | None\n\ndefault `= None`\n\nThe root path (or \"mount point\") of the application, if it's not served from\nthe root (\"/\") of the domain. Often used when the application is behind a\nreverse proxy that forwards requests to the application. For example, if the\napplication is served at \"https://example.com/myapp\", the `root_path` should\nbe set to \"/myapp\". A full URL beginning with http:// or https:// can be\nprovided, which will be used as the root path in its entirety. Can be set by\nenvironment variable GRADIO_ROOT_PATH. Defaults to \"\".\n\n\n \n \n app_kwargs: dict[str, Any] | None\n\ndefa", "heading1": "launch", "source_page_url": "https://gradio.app/docs/gradio/blocks", "source_page_title": "Gradio - Blocks Docs"}, {"text": "ps:// can be\nprovided, which will be used as the root path in its entirety. Can be set by\nenvironment variable GRADIO_ROOT_PATH. Defaults to \"\".\n\n\n \n \n app_kwargs: dict[str, Any] | None\n\ndefault `= None`\n\nAdditional keyword arguments to pass to the underlying FastAPI app as a\ndictionary of parameter keys and argument values. For example, `{\"docs_url\":\n\"/docs\"}`\n\n\n \n \n state_session_capacity: int\n\ndefault `= 10000`\n\nThe maximum number of sessions whose information to store in memory. If the\nnumber of sessions exceeds this number, the oldest sessions will be removed.\nReduce capacity to reduce memory usage when using gradio.State or returning\nupdated components from functions. Defaults to 10000.\n\n\n \n \n share_server_address: str | None\n\ndefault `= None`\n\nUse this to specify a custom FRP server and port for sharing Gradio apps (only\napplies if share=True). If not provided, will use the default FRP server at\nhttps://gradio.live. See https://github.com/huggingface/frp for more\ninformation.\n\n\n \n \n share_server_protocol: Literal['http', 'https'] | None\n\ndefault `= None`\n\nUse this to specify the protocol to use for the share links. Defaults to\n\"https\", unless a custom share_server_address is provided, in which case it\ndefaults to \"http\". If you are using a custom share_server_address and want to\nuse https, you must set this to \"https\".\n\n\n \n \n share_server_tls_certificate: str | None\n\ndefault `= None`\n\nThe path to a TLS certificate file to use when connecting to a custom share\nserver. This parameter is not used with the default FRP server at\nhttps://gradio.live. Otherwise, you must provide a valid TLS certificate file\n(e.g. a \"cert.pem\") relative to the current working directory, or the\nconnection will not use TLS encryption, which is insecure.\n\n\n \n \n auth_dependency: Callable[[fastapi.Request], str | None] | None\n\ndefault `= None`\n\nA function that takes a FastAPI request and returns a string user ID or None.\nIf the functio", "heading1": "launch", "source_page_url": "https://gradio.app/docs/gradio/blocks", "source_page_title": "Gradio - Blocks Docs"}, {"text": "nsecure.\n\n\n \n \n auth_dependency: Callable[[fastapi.Request], str | None] | None\n\ndefault `= None`\n\nA function that takes a FastAPI request and returns a string user ID or None.\nIf the function returns None for a specific request, that user is not\nauthorized to access the app (they will see a 401 Unauthorized response). To\nbe used with external authentication systems like OAuth. Cannot be used with\n`auth`.\n\n\n \n \n max_file_size: str | int | None\n\ndefault `= None`\n\nThe maximum file size in bytes that can be uploaded. Can be a string of the\nform \"\", where value is any positive integer and unit is one of\n\"b\", \"kb\", \"mb\", \"gb\", \"tb\". If None, no limit is set.\n\n\n \n \n enable_monitoring: bool | None\n\ndefault `= None`\n\nEnables traffic monitoring of the app through the /monitoring endpoint. By\ndefault is None, which enables this endpoint. If explicitly True, will also\nprint the monitoring URL to the console. If False, will disable monitoring\naltogether.\n\n\n \n \n strict_cors: bool\n\ndefault `= True`\n\nIf True, prevents external domains from making requests to a Gradio server\nrunning on localhost. If False, allows requests to localhost that originate\nfrom localhost but also, crucially, from \"null\". This parameter should\nnormally be True to prevent CSRF attacks but may need to be False when\nembedding a *locally-running Gradio app* using web components.\n\n\n \n \n node_server_name: str | None\n\ndefault `= None`\n\n\n \n \n node_port: int | None\n\ndefault `= None`\n\n\n \n \n ssr_mode: bool | None\n\ndefault `= None`\n\nIf True, the Gradio app will be rendered using server-side rendering mode,\nwhich is typically more performant and provides better SEO, but this requires\nNode 20+ to be installed on the system. If False, the app will be rendered\nusing client-side rendering mode. If None, will use GRADIO_SSR_MODE\nenvironment variable or default to False.\n\n\n \n \n pwa: bool | None\n\ndefault `= None`\n\nIf True, the Gradio app will", "heading1": "launch", "source_page_url": "https://gradio.app/docs/gradio/blocks", "source_page_title": "Gradio - Blocks Docs"}, {"text": " rendered\nusing client-side rendering mode. If None, will use GRADIO_SSR_MODE\nenvironment variable or default to False.\n\n\n \n \n pwa: bool | None\n\ndefault `= None`\n\nIf True, the Gradio app will be set up as an installable PWA (Progressive Web\nApp). If set to None (default behavior), then the PWA feature will be enabled\nif this Gradio app is launched on Spaces, but not otherwise.\n\n\n \n \n mcp_server: bool | None\n\ndefault `= None`\n\nIf True, the Gradio app will be set up as an MCP server and documented\nfunctions will be added as MCP tools. If None (default behavior), then the\nGRADIO_MCP_SERVER environment variable will be used to determine if the MCP\nserver should be enabled.\n\n\n \n \n i18n: I18n | None\n\ndefault `= None`\n\nAn I18n instance containing custom translations, which are used to translate\nstrings in our components (e.g. the labels of components or Markdown strings).\nThis feature can only be used to translate static text in the frontend, not\nvalues in the backend.\n\n\n \n \n theme: Theme | str | None\n\ndefault `= None`\n\nA Theme object or a string representing a theme. If a string, will look for a\nbuilt-in theme with that name (e.g. \"soft\" or \"default\"), or will attempt to\nload a theme from the Hugging Face Hub (e.g. \"gradio/monochrome\"). If None,\nwill use the Default theme.\n\n\n \n \n css: str | None\n\ndefault `= None`\n\nCustom css as a code string. This css will be included in the demo webpage.\n\n\n \n \n css_paths: str | Path | list[str | Path] | None\n\ndefault `= None`\n\nCustom css as a pathlib.Path to a css file or a list of such paths. This css\nfiles will be read, concatenated, and included in the demo webpage. If the\n`css` parameter is also set, the css from `css` will be included first.\n\n\n \n \n js: str | Literal[True] | None\n\ndefault `= None`\n\nCustom js as a code string. The js code will automatically be executed when\nthe page loads. For more flexibility, use the head parameter to insert js\ninside \n```\n\n3. That's it!\n\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.\n\nCustomization\n\nYou can customize the appearance of the widget by modifying the CSS. Some ideas:\n- Change the colors to match your website's theme\n- Adjust the size and position of the widget\n- Add animations for opening/closing\n- Modify the message styling\n\n![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio-guides/Screen%20Recording%202024-12-19%20at%203.32.46%E2%80%AFPM.gif)\n\nIf you build a website widget from a Gradio app, feel free to share it on X and tag [the Gradio account](https://x.com/Gradio), and we are hap", "heading1": "Prerequisites", "source_page_url": "https://gradio.app/guides/creating-a-website-widget-from-a-gradio-chatbot", "source_page_title": "Chatbots - Creating A Website Widget From A Gradio Chatbot Guide"}, {"text": "%20Recording%202024-12-19%20at%203.32.46%E2%80%AFPM.gif)\n\nIf you build a website widget from a Gradio app, feel free to share it on X and tag [the Gradio account](https://x.com/Gradio), and we are happy to help you amplify!", "heading1": "Prerequisites", "source_page_url": "https://gradio.app/guides/creating-a-website-widget-from-a-gradio-chatbot", "source_page_title": "Chatbots - Creating A Website Widget From A Gradio Chatbot Guide"}, {"text": "**Important 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](/guides/creating-a-chatbot-fast).\n\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:\n\n$demo_chatbot_streaming\n\n**Prerequisite**: We'll be using the `gradio.Blocks` class to build our Chatbot demo.\nYou can [read the Guide to Blocks first](https://gradio.app/blocks-and-event-listeners) 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`.\n\n", "heading1": "Introduction", "source_page_url": "https://gradio.app/guides/creating-a-custom-chatbot-with-blocks", "source_page_title": "Chatbots - Creating A Custom Chatbot With Blocks Guide"}, {"text": "Let'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\n$code_chatbot_simple\n\nThere are three Gradio components here:\n\n- A `Chatbot`, whose value stores the entire history of the conversation, as a list of response pairs between the user and bot.\n- A `Textbox` where the user can type their message, and then hit enter/submit to trigger the chatbot response\n- A `ClearButton` button to clear the Textbox and entire Chatbot history\n\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.\n\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$demo_chatbot_simple\n\nTip: For better type hinting and auto-completion in your IDE, you can use the `gr.ChatMessage` dataclass:\n\n```python\nfrom gradio import ChatMessage\n\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```\n\n", "heading1": "A Simple Chatbot Demo", "source_page_url": "https://gradio.app/guides/creating-a-custom-chatbot-with-blocks", "source_page_title": "Chatbots - Creating A Custom Chatbot With Blocks Guide"}, {"text": "There 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\n$code_chatbot_streaming\n\nYou'll notice that when a user submits their message, we now _chain_ two event events with `.then()`:\n\n1. The 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}`.\n\n2. The 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](/guides/key-features/iterative-outputs).\n\n\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.\n\n\n", "heading1": "Add Streaming to your Chatbot", "source_page_url": "https://gradio.app/guides/creating-a-custom-chatbot-with-blocks", "source_page_title": "Chatbots - Creating A Custom Chatbot With Blocks Guide"}, {"text": "The `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\n```py\ndef bot(history):\n response = {\"role\": \"assistant\", \"content\": \"**That's cool!**\"}\n history.append(response)\n return history\n```\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 `alt_text` key. The `alt_text` is optional, so you can also just pass in a tuple with a single element `{\"path\": \"filepath\"}`, like this:\n\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```\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\n$code_chatbot_multimodal\n$demo_chatbot_multimodal\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:\n\n- [project-baize/Baize-7B](https://huggingface.co/spaces/project-baize/Baize-7B): A stylized chatbot that allows you to stop generation as well as regenerate responses.\n- [MAGAer13/mPLUG-Owl](https://huggingface.co/spaces/MAGAer13/mPLUG-Ow", "heading1": "Adding Markdown, Images, Audio, or Videos", "source_page_url": "https://gradio.app/guides/creating-a-custom-chatbot-with-blocks", "source_page_title": "Chatbots - Creating A Custom Chatbot With Blocks Guide"}, {"text": "ingface.co/spaces/project-baize/Baize-7B): A stylized chatbot that allows you to stop generation as well as regenerate responses.\n- [MAGAer13/mPLUG-Owl](https://huggingface.co/spaces/MAGAer13/mPLUG-Owl): A multimodal chatbot that allows you to upvote and downvote responses.\n", "heading1": "Adding Markdown, Images, Audio, or Videos", "source_page_url": "https://gradio.app/guides/creating-a-custom-chatbot-with-blocks", "source_page_title": "Chatbots - Creating A Custom Chatbot With Blocks Guide"}, {"text": "Let'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\n$code_llm_llamaindex\n\n", "heading1": "Llama Index", "source_page_url": "https://gradio.app/guides/chatinterface-examples", "source_page_title": "Chatbots - Chatinterface Examples Guide"}, {"text": "Here'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\n$code_llm_langchain\n\nTip: For quick prototyping, the community-maintained langchain-gradio repo makes it even easier to build chatbots on top of LangChain.\n\n", "heading1": "LangChain", "source_page_url": "https://gradio.app/guides/chatinterface-examples", "source_page_title": "Chatbots - Chatinterface Examples Guide"}, {"text": "Of course, we could also use the `openai` library directy. Here a similar example to the LangChain , but this time with streaming as well:\n\nTip: For quick prototyping, the openai-gradio library makes it even easier to build chatbots on top of OpenAI models.\n\n\n", "heading1": "OpenAI", "source_page_url": "https://gradio.app/guides/chatinterface-examples", "source_page_title": "Chatbots - Chatinterface Examples Guide"}, {"text": "Of 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\n$code_llm_hf_transformers\n\n", "heading1": "Hugging Face `transformers`", "source_page_url": "https://gradio.app/guides/chatinterface-examples", "source_page_title": "Chatbots - Chatinterface Examples Guide"}, {"text": "The 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\n$code_llm_sambanova\n\nTip: For quick prototyping, the sambanova-gradio library makes it even easier to build chatbots on top of SambaNova models.\n\n", "heading1": "SambaNova", "source_page_url": "https://gradio.app/guides/chatinterface-examples", "source_page_title": "Chatbots - Chatinterface Examples Guide"}, {"text": "The 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\n$code_llm_hyperbolic\n\nTip: For quick prototyping, the hyperbolic-gradio library makes it even easier to build chatbots on top of Hyperbolic models.\n\n\n", "heading1": "Hyperbolic", "source_page_url": "https://gradio.app/guides/chatinterface-examples", "source_page_title": "Chatbots - Chatinterface Examples Guide"}, {"text": "Anthropic'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\n$code_llm_claude\n\n\n", "heading1": "Anthropic's Claude", "source_page_url": "https://gradio.app/guides/chatinterface-examples", "source_page_title": "Chatbots - Chatinterface Examples Guide"}, {"text": "The 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. \n\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. \n\n![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio-guides/Screen%20Recording%202024-12-18%20at%204.26.55%E2%80%AFPM.gif)\n\n", "heading1": "How does it work?", "source_page_url": "https://gradio.app/guides/creating-a-discord-bot-from-a-gradio-app", "source_page_title": "Chatbots - Creating A Discord Bot From A Gradio App Guide"}, {"text": "* Install the latest version of `gradio` and the `discord.py` libraries:\n\n```\npip install --upgrade gradio discord.py~=2.0\n```\n\n* Have 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](https://huggingface.co/spaces/abidlabs/gradio-playground-bot), which takes in an image and/or text and generates the code to generate the corresponding Gradio app.\n\nNow, we are ready to get started!\n\n\n1. Create a Discord application\n\nFirst, go to the [Discord apps dashboard](https://discord.com/developers/applications). Look for the \"New Application\" button and click it. Give your application a name, and then click \"Create\".\n\n![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio-guides/discord-4.png)\n\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.\n\nThen click on the \"Reset Token\" button. A new token will be generated. Copy it as we will need it for the next step.\n\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.\n\n![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio-guides/discord-3.png)\n\n\n\n2. Write a Discord bot\n\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\n```python\nbot.py\nimport discord\n\nTOKEN = PASTE YOUR DISCORD BOT TOKEN HERE\n\nclient = discord.Client()\n\n@client.event\nasync def on_ready():\n print(f'{client.user} has connected to Discord!')\n\nclient.run(TOKEN)\n```\n\nNow, run this file: `python bot.py`, w", "heading1": "Prerequisites", "source_page_url": "https://gradio.app/guides/creating-a-discord-bot-from-a-gradio-app", "source_page_title": "Chatbots - Creating A Discord Bot From A Gradio App Guide"}, {"text": "CORD BOT TOKEN HERE\n\nclient = discord.Client()\n\n@client.event\nasync def on_ready():\n print(f'{client.user} has connected to Discord!')\n\nclient.run(TOKEN)\n```\n\nNow, run this file: `python bot.py`, which should run and print a message like:\n\n```text\nWe have logged in as GradioPlaygroundBot1451\n```\n\nIf that is working, we are ready to add Gradio-specific code. We will be using the [Gradio Python Client](https://www.gradio.app/guides/getting-started-with-the-python-client) to query the Gradio Playground Space mentioned above. Here's the updated `bot.py` file:\n\n```python\nimport discord\nfrom gradio_client import Client, handle_file\nimport httpx\nimport os\n\nTOKEN = PASTE YOUR DISCORD BOT TOKEN HERE\n\nintents = discord.Intents.default()\nintents.message_content = True\n\nclient = discord.Client(intents=intents)\ngradio_client = Client(\"abidlabs/gradio-playground-bot\")\n\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\n@client.event\nasync def on_ready():\n print(f'We have logged in as {client.user}')\n\n@client.event\nasync def on_message(message):\n Ignore messages from the bot itself\n if message.author == client.user:\n return\n\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\"<@{client.user.id}>\", \"\").strip()\n\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 image_path = download_image(attachment)\n files.append(handle_file(image_path))", "heading1": "Prerequisites", "source_page_url": "https://gradio.app/guides/creating-a-discord-bot-from-a-gradio-app", "source_page_title": "Chatbots - Creating A Discord Bot From A Gradio App Guide"}, {"text": ".filename.lower().endswith(ext) for ext in ['png', 'jpg', 'jpeg', 'gif', 'webp']):\n image_path = download_image(attachment)\n files.append(handle_file(image_path))\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])\n\nclient.run(TOKEN)\n```\n\n3. Add the bot to your Discord Server\n\nNow we are ready to install the bot on our server. Go back to the [Discord apps dashboard](https://discord.com/developers/applications). Under the Settings section, click on the \"OAuth2\" option. Scroll down to the \"OAuth2 URL Generator\" box and select the \"bot\" checkbox:\n\n![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio-guides/discord-2.png)\n\n\n\nThen in \"Bot Permissions\" box that pops up underneath, enable the following permissions:\n\n![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio-guides/discord-1.png)\n\n\nCopy the generated URL that appears underneath, which should look something like:\n\n```text\nhttps://discord.com/oauth2/authorize?client_id=1319011745452265575&permissions=377957238784&integration_type=0&scope=bot\n```\n\nPaste it into your browser, which should allow you to add the Discord bot to any Discord server that you manage.\n\n\n4. That's it!\n\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!\n\nThe bot will:\n1. Listen for mentions\n2. Process any attached images\n3. Send the text and images to your Gradio app\n4. Stream the responses back to the Discord channel\n\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.\n\n![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/", "heading1": "Prerequisites", "source_page_url": "https://gradio.app/guides/creating-a-discord-bot-from-a-gradio-app", "source_page_title": "Chatbots - Creating A Discord Bot From A Gradio App Guide"}, {"text": "c example - you can extend it to handle more types of files, add error handling, or integrate with different Gradio apps.\n\n![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio-guides/Screen%20Recording%202024-12-18%20at%204.26.55%E2%80%AFPM.gif)\n\nIf you build a Discord bot from a Gradio app, feel free to share it on X and tag [the Gradio account](https://x.com/Gradio), and we are happy to help you amplify!", "heading1": "Prerequisites", "source_page_url": "https://gradio.app/guides/creating-a-discord-bot-from-a-gradio-app", "source_page_title": "Chatbots - Creating A Discord Bot From A Gradio App Guide"}, {"text": "The 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. \n\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. \n\n![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio-guides/Screen%20Recording%202024-12-19%20at%203.30.00%E2%80%AFPM.gif)\n\n", "heading1": "How does it work?", "source_page_url": "https://gradio.app/guides/creating-a-slack-bot-from-a-gradio-app", "source_page_title": "Chatbots - Creating A Slack Bot From A Gradio App Guide"}, {"text": "* Install the latest version of `gradio` and the `slack-bolt` library:\n\n```bash\npip install --upgrade gradio slack-bolt~=1.0\n```\n\n* Have 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](https://huggingface.co/spaces/abidlabs/gradio-playground-bot), which takes in an image and/or text and generates the code to generate the corresponding Gradio app.\n\nNow, we are ready to get started!\n\n1. Create a Slack App\n\n1. Go to [api.slack.com/apps](https://api.slack.com/apps) and click \"Create New App\"\n2. Choose \"From scratch\" and give your app a name\n3. Select the workspace where you want to develop your app\n4. Under \"OAuth & Permissions\", scroll to \"Scopes\" and add these Bot Token Scopes:\n - `app_mentions:read`\n - `chat:write`\n - `files:read`\n - `files:write`\n5. In the same \"OAuth & Permissions\" page, scroll back up and click the button to install the app to your workspace.\n6. Note the \"Bot User OAuth Token\" (starts with `xoxb-`) that appears as we'll need it later\n7. Click on \"Socket Mode\" in the menu bar. When the page loads, click the toggle to \"Enable Socket Mode\"\n8. Give your token a name, such as `socket-token` and copy the token that is generated (starts with `xapp-`) as we'll need it later.\n9. Finally, go to the \"Event Subscription\" option in the menu bar. Click the toggle to \"Enable Events\" and subscribe to the `app_mention` bot event.\n\n2. Write a Slack bot\n\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\n```py\nfrom slack_bolt import App\nfrom slack_bolt.adapter.socket_mode import SocketModeHandler\n\nSLACK_BOT_TOKEN = PASTE YOUR SLACK BOT TOKEN HERE\nSLACK_APP_TOKEN = PASTE YOUR SLACK APP TOKEN HERE\n\napp = App(token=SLACK_BOT_TOKEN)\n\n@app.event(\"app_mention\")\ndef handle_app_mention_ev", "heading1": "Prerequisites", "source_page_url": "https://gradio.app/guides/creating-a-slack-bot-from-a-gradio-app", "source_page_title": "Chatbots - Creating A Slack Bot From A Gradio App Guide"}, {"text": "eHandler\n\nSLACK_BOT_TOKEN = PASTE YOUR SLACK BOT TOKEN HERE\nSLACK_APP_TOKEN = PASTE YOUR SLACK APP TOKEN HERE\n\napp = App(token=SLACK_BOT_TOKEN)\n\n@app.event(\"app_mention\")\ndef handle_app_mention_events(body, say):\n user_id = body[\"event\"][\"user\"]\n say(f\"Hi <@{user_id}>! You mentioned me and said: {body['event']['text']}\")\n\nif __name__ == \"__main__\":\n handler = SocketModeHandler(app, SLACK_APP_TOKEN)\n handler.start()\n```\n\nIf that is working, we are ready to add Gradio-specific code. We will be using the [Gradio Python Client](https://www.gradio.app/guides/getting-started-with-the-python-client) to query the Gradio Playground Space mentioned above. Here's the updated `bot.py` file:\n\n```python\nfrom slack_bolt import App\nfrom slack_bolt.adapter.socket_mode import SocketModeHandler\n\nSLACK_BOT_TOKEN = PASTE YOUR SLACK BOT TOKEN HERE\nSLACK_APP_TOKEN = PASTE YOUR SLACK APP TOKEN HERE\n\napp = App(token=SLACK_BOT_TOKEN)\ngradio_client = Client(\"abidlabs/gradio-playground-bot\")\n\ndef download_image(url, filename):\n headers = {\"Authorization\": f\"Bearer {SLACK_BOT_TOKEN}\"}\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\n\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'<\\2|\\1>', message)\n cleaned = re.sub(r'```\\w+\\n', '```', cleaned)\n return cleaned.strip()\n\n@app.event(\"app_mention\")\ndef handle_app_mention_events(body, say):\n Extract the message content without the bot mention\n text = body[\"event\"][\"text\"]\n bot_user_id = body[\"authorizations\"][0][\"user_id\"]\n clean_message = text.replace(f\"<@{bot_user_id}>\", \"\").strip()\n \n Handle images if present\n files = []\n if \"files\" in body[\"event\"]:\n for", "heading1": "Prerequisites", "source_page_url": "https://gradio.app/guides/creating-a-slack-bot-from-a-gradio-app", "source_page_title": "Chatbots - Creating A Slack Bot From A Gradio App Guide"}, {"text": "= body[\"authorizations\"][0][\"user_id\"]\n clean_message = text.replace(f\"<@{bot_user_id}>\", \"\").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 image_path = download_image(file[\"url_private_download\"], file[\"name\"])\n files.append(handle_file(image_path))\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 cleaned_response = slackify_message(response[-1])\n say(cleaned_response)\n\nif __name__ == \"__main__\":\n handler = SocketModeHandler(app, SLACK_APP_TOKEN)\n handler.start()\n```\n3. Add the bot to your Slack Workplace\n\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.\n\nFinally, invite your bot to the channel:\n1. In your new channel, type `/invite @YourBotName`\n2. Select your bot from the dropdown\n3. Click \"Invite to Channel\"\n\n4. That's it!\n\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!\n\nThe bot will:\n1. Listen for mentions\n2. Process any attached images\n3. Send the text and images to your Gradio app\n4. Stream the responses back to the Slack channel\n\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!\n\n![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio-guides/Screen%20Recording%202024-12-19%20at%203.30.00%E2%80%AFPM.gif)\n\nIf you build a Slack bot from a Gradio app, feel free to share it on X and tag [the Gradio account](https://x.com/Gr", "heading1": "Prerequisites", "source_page_url": "https://gradio.app/guides/creating-a-slack-bot-from-a-gradio-app", "source_page_title": "Chatbots - Creating A Slack Bot From A Gradio App Guide"}, {"text": "/main/gradio-guides/Screen%20Recording%202024-12-19%20at%203.30.00%E2%80%AFPM.gif)\n\nIf you build a Slack bot from a Gradio app, feel free to share it on X and tag [the Gradio account](https://x.com/Gradio), and we are happy to help you amplify!", "heading1": "Prerequisites", "source_page_url": "https://gradio.app/guides/creating-a-slack-bot-from-a-gradio-app", "source_page_title": "Chatbots - Creating A Slack Bot From A Gradio App Guide"}, {"text": "Let'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\n$code_streaming_filter\n$demo_streaming_filter\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\nTip: 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", "heading1": "A Realistic Image Demo", "source_page_url": "https://gradio.app/guides/streaming-inputs", "source_page_title": "Additional Features - Streaming Inputs Guide"}, {"text": "For 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.\n\nWe can do so by just specifying the input image component as the output of the stream event.\n\n$code_streaming_filter_unified\n$demo_streaming_filter_unified\n\n", "heading1": "Unified Image Demos", "source_page_url": "https://gradio.app/guides/streaming-inputs", "source_page_title": "Additional Features - Streaming Inputs Guide"}, {"text": "Your 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.\n\nLet's showcase this with a sample demo:\n\n```python\ndef transcribe_handler(current_audio, state, transcript):\n next_text = transcribe(current_audio, history=state)\n state.append(current_audio)\n state = state[-3:]\n return state, transcript + next_text\n\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 time_limit=10, stream_every=1)\n\n\ndemo.launch()\n```\n\n", "heading1": "Keeping track of past inputs or outputs", "source_page_url": "https://gradio.app/guides/streaming-inputs", "source_page_title": "Additional Features - Streaming Inputs Guide"}, {"text": "For an end-to-end example of streaming from the webcam, see the object detection from webcam [guide](/main/guides/object-detection-from-webcam-with-webrtc).", "heading1": "End-to-End Examples", "source_page_url": "https://gradio.app/guides/streaming-inputs", "source_page_title": "Additional Features - Streaming Inputs Guide"}, {"text": "To add custom buttons to a component, pass a list of `gr.Button()` instances to the `buttons` parameter:\n\n```python\nimport gradio as gr\n\nrefresh_btn = gr.Button(\"Refresh\", variant=\"secondary\", size=\"sm\")\nclear_btn = gr.Button(\"Clear\", variant=\"secondary\", size=\"sm\")\n\ntextbox = gr.Textbox(\n value=\"Sample text\",\n label=\"Text Input\",\n buttons=[refresh_btn, clear_btn]\n)\n```\n\nYou can also mix built-in buttons (as strings) with custom buttons:\n\n```python\ncode = gr.Code(\n value=\"print('Hello')\",\n language=\"python\",\n buttons=[\"copy\", \"download\", refresh_btn, export_btn]\n)\n```\n\n", "heading1": "Basic Usage", "source_page_url": "https://gradio.app/guides/custom-buttons", "source_page_title": "Additional Features - Custom Buttons Guide"}, {"text": "Custom buttons work just like regular `gr.Button` components. You can connect them to Python functions or JavaScript functions using the `.click()` method:\n\nPython Functions\n\n```python\ndef refresh_data():\n import random\n return f\"Refreshed: {random.randint(1000, 9999)}\"\n\nrefresh_btn.click(refresh_data, outputs=textbox)\n```\n\nJavaScript Functions\n\n```python\nclear_btn.click(\n None,\n inputs=[],\n outputs=textbox,\n js=\"() => ''\"\n)\n```\n\nCombined Python and JavaScript\n\nYou can use the same button for both Python and JavaScript logic:\n\n```python\nalert_btn.click(\n None,\n inputs=textbox,\n outputs=[],\n js=\"(text) => { alert('Text: ' + text); return []; }\"\n)\n```\n\n", "heading1": "Connecting Button Events", "source_page_url": "https://gradio.app/guides/custom-buttons", "source_page_title": "Additional Features - Custom Buttons Guide"}, {"text": "Here's a complete example showing custom buttons with both Python and JavaScript functions:\n\n$code_textbox_custom_buttons\n\n\n", "heading1": "Complete Example", "source_page_url": "https://gradio.app/guides/custom-buttons", "source_page_title": "Additional Features - Custom Buttons Guide"}, {"text": "- Custom buttons appear in the component's toolbar, typically in the top-right corner\n- Only the `value` of the Button is used, other attributes like `icon` are not used.\n- Buttons are rendered in the order they appear in the `buttons` list\n- Built-in buttons (like \"copy\", \"download\") can be hidden by omitting them from the list\n- Custom buttons work with component events in the same way as as regular buttons\n", "heading1": "Notes", "source_page_url": "https://gradio.app/guides/custom-buttons", "source_page_title": "Additional Features - Custom Buttons Guide"}, {"text": "Gradio 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 \n\n1. Set `streaming=True` in your `gr.Audio` or `gr.Video` output component.\n2. Write a python generator that yields the next \"chunk\" of audio or video.\n3. Set `autoplay=True` so that the media starts playing automatically.\n\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.\n\nWe'll finish with some simple examples illustrating these points.\n\nStreaming Audio\n\n```python\nimport gradio as gr\nfrom time import sleep\n\ndef keep_repeating(audio_file):\n for _ in range(10):\n sleep(0.5)\n yield audio_file\n\ngr.Interface(keep_repeating,\n gr.Audio(sources=[\"microphone\"], type=\"filepath\"),\n gr.Audio(streaming=True, autoplay=True)\n).launch()\n```\n\nStreaming Video\n\n```python\nimport gradio as gr\nfrom time import sleep\n\ndef keep_repeating(video_file):\n for _ in range(10):\n sleep(0.5)\n yield video_file\n\ngr.Interface(keep_repeating,\n gr.Video(sources=[\"webcam\"], format=\"mp4\"),\n gr.Video(streaming=True, autoplay=True)\n).launch()\n```\n\n", "heading1": "Streaming Media", "source_page_url": "https://gradio.app/guides/streaming-outputs", "source_page_title": "Additional Features - Streaming Outputs Guide"}, {"text": "For an end-to-end example of streaming media, see the object detection from video [guide](/main/guides/object-detection-from-video) or the streaming AI-generated audio with [transformers](https://huggingface.co/docs/transformers/index) [guide](/main/guides/streaming-ai-generated-audio).", "heading1": "End-to-End Examples", "source_page_url": "https://gradio.app/guides/streaming-outputs", "source_page_title": "Additional Features - Streaming Outputs Guide"}, {"text": "**API endpoint names**\n\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\n```python\nbtn.click(add, [num1, num2], output, api_name=\"addition\")\n```\n\n**Controlling API endpoint visibility**\n\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\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 completely disabled and inaccessible\n\nTo hide an API endpoint from the documentation while still allowing programmatic access:\n\n```python\nbtn.click(add, [num1, num2], output, api_visibility=\"undocumented\")\n```\n\n**Disabling API endpoints**\n\nIf you want to disable an API endpoint altogether so that no one can access it programmatically, set `api_visibility=\"private\"`:\n\n```python\nbtn.click(add, [num1, num2], output, api_visibility=\"private\")\n```\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.\n\n**Adding API endpoints**\n\nYou can also add new API routes to your Gradio application that do not correspond to events in your UI.\n\nFor example, in this Gradio application, we add a new route that adds numbers and slices a list:\n\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, api_name=\"add_and_slice\")\n\n_, url, _ = demo.laun", "heading1": "Configuring the API Page", "source_page_url": "https://gradio.app/guides/view-api-page", "source_page_title": "Additional Features - View Api Page Guide"}, {"text": " 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\n_, url, _ = demo.launch()\n```\n\nThis will create a new route `/add_and_slice` 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\n```py\nfrom gradio_client import Client\n\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```\n\n", "heading1": "Configuring the API Page", "source_page_url": "https://gradio.app/guides/view-api-page", "source_page_title": "Additional Features - View Api Page Guide"}, {"text": "This 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](https://gradio.app/guides/getting-started-with-the-python-client/), and [the Gradio JavaScript client](https://gradio.app/guides/getting-started-with-the-js-client/). \n\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:\n\n![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio-guides/view-api-snippet.png)\n\n\n", "heading1": "The Clients", "source_page_url": "https://gradio.app/guides/view-api-page", "source_page_title": "Additional Features - View Api Page Guide"}, {"text": "Instead 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.\n\n![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio-guides/api-recorder.gif)\n\n", "heading1": "The API Recorder \ud83e\ude84", "source_page_url": "https://gradio.app/guides/view-api-page", "source_page_title": "Additional Features - View Api Page Guide"}, {"text": "The 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. \n\n![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio-guides/view-api-mcp.png)\n\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](https://www.gradio.app/guides/building-mcp-server-with-gradio).\n\n", "heading1": "MCP Server", "source_page_url": "https://gradio.app/guides/view-api-page", "source_page_title": "Additional Features - View Api Page Guide"}, {"text": "You 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.\n", "heading1": "OpenAPI Specification", "source_page_url": "https://gradio.app/guides/view-api-page", "source_page_title": "Additional Features - View Api Page Guide"}, {"text": "When 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.\n\nYou can control the deletion behavior further with the following two parameters of `gr.State`:\n\n1. `delete_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.\n2. `time_to_live` - 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.\n\n", "heading1": "Automatic deletion of `gr.State`", "source_page_url": "https://gradio.app/guides/resource-cleanup", "source_page_title": "Additional Features - Resource Cleanup Guide"}, {"text": "Your 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 \ud83d\ude09).\n\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.\n\n", "heading1": "Automatic cache cleanup via `delete_cache`", "source_page_url": "https://gradio.app/guides/resource-cleanup", "source_page_title": "Additional Features - Resource Cleanup Guide"}, {"text": "Additionally, 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.\n\n", "heading1": "The `unload` event", "source_page_url": "https://gradio.app/guides/resource-cleanup", "source_page_title": "Additional Features - Resource Cleanup Guide"}, {"text": "The 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\n$code_state_cleanup\n$demo_state_cleanup", "heading1": "Putting it all together", "source_page_url": "https://gradio.app/guides/resource-cleanup", "source_page_title": "Additional Features - Resource Cleanup Guide"}, {"text": "By 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.\n\nPer-Page Navbar Configuration\n\nYou can have different navbar configurations for each page of your app:\n\n```python\nimport gradio as gr\n\nwith gr.Blocks() as demo:\n Navbar for the main page\n navbar = gr.Navbar(\n visible=True,\n main_page_name=\"Dashboard\",\n value=[(\"About\", \"https://example.com/about\")]\n )\n \n gr.Textbox(label=\"Main page content\")\n\nwith demo.route(\"Settings\"):\n Different navbar for the Settings page\n navbar = gr.Navbar(\n visible=True,\n main_page_name=\"Home\",\n value=[(\"Documentation\", \"https://docs.example.com\")]\n )\n gr.Textbox(label=\"Settings page\")\n\ndemo.launch()\n```\n\n\n**Important Notes:**\n- You can have one `gr.Navbar` component per page. Each page's navbar configuration is independent.\n- The `main_page_name` parameter customizes the title of the home page link in the navbar.\n- The `value` parameter allows you to add additional links to the navbar, which can be internal pages or external URLs.\n- If no `gr.Navbar` component is present on a page, the default navbar behavior is used (visible with \"Home\" as the home page title).\n- You can update the navbar properties using standard Gradio event handling, just like with any other component.\n\nHere's an example that demonstrates the last point:\n\n$code_navbar_customization\n\n", "heading1": "Customizing the Navbar", "source_page_url": "https://gradio.app/guides/multipage-apps", "source_page_title": "Additional Features - Multipage Apps Guide"}, {"text": "You can initialize the `I18n` class with multiple language dictionaries to add custom translations:\n\n```python\nimport gradio as gr\n\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\": \"\u00a1Hola, bienvenido a mi aplicaci\u00f3n!\", \"submit\": \"Enviar\"},\n fr={\"greeting\": \"Bonjour, bienvenue dans mon application!\", \"submit\": \"Soumettre\"}\n)\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\"))\n\nPass the i18n instance to the launch method\ndemo.launch(i18n=i18n)\n```\n\n", "heading1": "Setting Up Translations", "source_page_url": "https://gradio.app/guides/internationalization", "source_page_title": "Additional Features - Internationalization Guide"}, {"text": "When 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.\n\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.\n\n", "heading1": "How It Works", "source_page_url": "https://gradio.app/guides/internationalization", "source_page_title": "Additional Features - Internationalization Guide"}, {"text": "Locale 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.\n\n", "heading1": "Valid Locale Codes", "source_page_url": "https://gradio.app/guides/internationalization", "source_page_title": "Additional Features - Internationalization Guide"}, {"text": "The following component properties typically support internationalization:\n\n- `description`\n- `info`\n- `title`\n- `placeholder`\n- `value`\n- `label`\n\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.", "heading1": "Supported Component Properties", "source_page_url": "https://gradio.app/guides/internationalization", "source_page_title": "Additional Features - Internationalization Guide"}, {"text": "1. `GRADIO_SERVER_PORT`\n\n- **Description**: Specifies the port on which the Gradio app will run.\n- **Default**: `7860`\n- **Example**:\n ```bash\n export GRADIO_SERVER_PORT=8000\n ```\n\n2. `GRADIO_SERVER_NAME`\n\n- **Description**: Defines the host name for the Gradio server. To make Gradio accessible from any IP address, set this to `\"0.0.0.0\"`\n- **Default**: `\"127.0.0.1\"` \n- **Example**:\n ```bash\n export GRADIO_SERVER_NAME=\"0.0.0.0\"\n ```\n\n3. `GRADIO_NUM_PORTS`\n\n- **Description**: Defines the number of ports to try when starting the Gradio server.\n- **Default**: `100`\n- **Example**:\n ```bash\n export GRADIO_NUM_PORTS=200\n ```\n\n4. `GRADIO_ANALYTICS_ENABLED`\n\n- **Description**: Whether Gradio should provide \n- **Default**: `\"True\"`\n- **Options**: `\"True\"`, `\"False\"`\n- **Example**:\n ```sh\n export GRADIO_ANALYTICS_ENABLED=\"True\"\n ```\n\n5. `GRADIO_DEBUG`\n\n- **Description**: 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.\n- **Default**: `0`\n- **Example**:\n ```sh\n export GRADIO_DEBUG=1\n ```\n\n6. `GRADIO_FLAGGING_MODE`\n\n- **Description**: Controls whether users can flag inputs/outputs in the Gradio interface. See [the Guide on flagging](/guides/using-flagging) for more details.\n- **Default**: `\"manual\"`\n- **Options**: `\"never\"`, `\"manual\"`, `\"auto\"`\n- **Example**:\n ```sh\n export GRADIO_FLAGGING_MODE=\"never\"\n ```\n\n7. `GRADIO_TEMP_DIR`\n\n- **Description**: Specifies the directory where temporary files created by Gradio are stored.\n- **Default**: System default temporary directory\n- **Example**:\n ```sh\n export GRADIO_TEMP_DIR=\"/path/to/temp\"\n ```\n\n8. `GRADIO_ROOT_PATH`\n\n- **Description**: Sets the root path for the Gradio application. Useful if running Gradio [behind a reverse proxy](/guides/running-gradio-on-your-web-server-with-nginx).\n- **Default**: `\"\"`\n- **Example**:\n ```sh\n export GRADIO_ROOT_PATH=", "heading1": "Key Environment Variables", "source_page_url": "https://gradio.app/guides/environment-variables", "source_page_title": "Additional Features - Environment Variables Guide"}, {"text": "r the Gradio application. Useful if running Gradio [behind a reverse proxy](/guides/running-gradio-on-your-web-server-with-nginx).\n- **Default**: `\"\"`\n- **Example**:\n ```sh\n export GRADIO_ROOT_PATH=\"/myapp\"\n ```\n\n9. `GRADIO_SHARE`\n\n- **Description**: Enables or disables sharing the Gradio app.\n- **Default**: `\"False\"`\n- **Options**: `\"True\"`, `\"False\"`\n- **Example**:\n ```sh\n export GRADIO_SHARE=\"True\"\n ```\n\n10. `GRADIO_ALLOWED_PATHS`\n\n- **Description**: 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.\n- **Default**: `\"\"`\n- **Example**:\n ```sh\n export GRADIO_ALLOWED_PATHS=\"/mnt/sda1,/mnt/sda2\"\n ```\n\n11. `GRADIO_BLOCKED_PATHS`\n\n- **Description**: 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.\n- **Default**: `\"\"`\n- **Example**:\n ```sh\n export GRADIO_BLOCKED_PATHS=\"/users/x/gradio_app/admin,/users/x/gradio_app/keys\"\n ```\n\n12. `FORWARDED_ALLOW_IPS`\n\n- **Description**: 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` [objec", "heading1": "Key Environment Variables", "source_page_url": "https://gradio.app/guides/environment-variables", "source_page_title": "Additional Features - Environment Variables Guide"}, {"text": " 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](https://www.gradio.app/docs/gradio/request) `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.\n- **Default**: `\"127.0.0.1\"`\n- **Example**:\n ```sh\n export FORWARDED_ALLOW_IPS=\"127.0.0.1,192.168.1.100\"\n ```\n\n13. `GRADIO_CACHE_EXAMPLES`\n\n- **Description**: 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\".\n- **Default**: `\"false\"`\n- **Example**:\n ```sh\n export GRADIO_CACHE_EXAMPLES=\"true\"\n ```\n\n\n14. `GRADIO_CACHE_MODE`\n\n- **Description**: How to cache examples. Only applies if `cache_examples` is set to `True` either via enviornment variable or by an explicit parameter, AND no no explicit argument is passed for the `cache_mode` 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.\n\n- **Default**: `\"eager\"`\n- **Example**:\n ```sh\n export GRADIO_CACHE_MODE=\"lazy\"\n ```\n\n\n15. `GRADIO_EXAMPLES_CACHE`\n\n- **Description**: If you set `cache_examples=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/cached_examples//` subdirectory within your", "heading1": "Key Environment Variables", "source_page_url": "https://gradio.app/guides/environment-variables", "source_page_title": "Additional Features - Environment Variables Guide"}, {"text": "e()`, `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/cached_examples//` subdirectory within your app's working directory. You can customize the location of cached example files created by Gradio by setting the environment variable `GRADIO_EXAMPLES_CACHE` to an absolute path or a path relative to your working directory.\n- **Default**: `\".gradio/cached_examples/\"`\n- **Example**:\n ```sh\n export GRADIO_EXAMPLES_CACHE=\"custom_cached_examples/\"\n ```\n\n\n16. `GRADIO_SSR_MODE`\n\n- **Description**: 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.\n\n- **Default**: `\"False\"` (except on Hugging Face Spaces, where this environment variable sets it to `True`)\n- **Options**: `\"True\"`, `\"False\"`\n- **Example**:\n ```sh\n export GRADIO_SSR_MODE=\"True\"\n ```\n\n17. `GRADIO_NODE_SERVER_NAME`\n\n- **Description**: Defines the host name for the Gradio node server. (Only applies if `ssr_mode` is set to `True`.)\n- **Default**: `GRADIO_SERVER_NAME` if it is set, otherwise `\"127.0.0.1\"`\n- **Example**:\n ```sh\n export GRADIO_NODE_SERVER_NAME=\"0.0.0.0\"\n ```\n\n18. `GRADIO_NODE_NUM_PORTS`\n\n- **Description**: Defines the number of ports to try when starting the Gradio node server. (Only applies if `ssr_mode` is set to `True`.)\n- **Default**: `100`\n- **Example**:\n ```sh\n export GRADIO_NODE_NUM_PORTS=200\n ```\n\n19. `GRADIO_RESET_EXAMPLES_CACHE`\n\n- **Description**: 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. \n- **Default**: `\"False\"`\n- **Options**: `\"True\"`, `\"False\"`\n- **Example**:\n ```sh\n export GRADIO_RESET_EXAMPLES_CACHE=\"True\"\n ```\n\n20. `GRADIO_CHAT_FLAGGING_MODE`\n\n- **Description**: Controls whether users can flag", "heading1": "Key Environment Variables", "source_page_url": "https://gradio.app/guides/environment-variables", "source_page_title": "Additional Features - Environment Variables Guide"}, {"text": "e\"`\n- **Options**: `\"True\"`, `\"False\"`\n- **Example**:\n ```sh\n export GRADIO_RESET_EXAMPLES_CACHE=\"True\"\n ```\n\n20. `GRADIO_CHAT_FLAGGING_MODE`\n\n- **Description**: Controls whether users can flag messages in `gr.ChatInterface` applications. Similar to `GRADIO_FLAGGING_MODE` but specifically for chat interfaces.\n- **Default**: `\"never\"`\n- **Options**: `\"never\"`, `\"manual\"`\n- **Example**:\n ```sh\n export GRADIO_CHAT_FLAGGING_MODE=\"manual\"\n ```\n\n21. `GRADIO_WATCH_DIRS`\n\n- **Description**: 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.\n- **Default**: `\"\"`\n- **Example**:\n ```sh\n export GRADIO_WATCH_DIRS=\"/path/to/src,/path/to/templates\"\n ```\n\n22. `GRADIO_VIBE_MODE`\n\n- **Description**: 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.\n- **Default**: `\"\"`\n- **Options**: Any non-empty string enables the mode\n- **Example**:\n ```sh\n export GRADIO_VIBE_MODE=\"1\"\n ```\n\n23. `GRADIO_MCP_SERVER`\n\n- **Description**: 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.\n- **Default**: `\"False\"`\n- **Options**: `\"True\"`, `\"False\"`\n- **Example**:\n ```sh\n export GRADIO_MCP_SERVER=\"True\"\n ```\n\n\n\n\n\n", "heading1": "Key Environment Variables", "source_page_url": "https://gradio.app/guides/environment-variables", "source_page_title": "Additional Features - Environment Variables Guide"}, {"text": "*Options**: `\"True\"`, `\"False\"`\n- **Example**:\n ```sh\n export GRADIO_MCP_SERVER=\"True\"\n ```\n\n\n\n\n\n", "heading1": "Key Environment Variables", "source_page_url": "https://gradio.app/guides/environment-variables", "source_page_title": "Additional Features - Environment Variables Guide"}, {"text": "To set environment variables in your terminal, use the `export` command followed by the variable name and its value. For example:\n\n```sh\nexport GRADIO_SERVER_PORT=8000\n```\n\nIf you're using a `.env` file to manage your environment variables, you can add them like this:\n\n```sh\nGRADIO_SERVER_PORT=8000\nGRADIO_SERVER_NAME=\"localhost\"\n```\n\nThen, use a tool like `dotenv` to load these variables when running your application.\n\n\n\n", "heading1": "How to Set Environment Variables", "source_page_url": "https://gradio.app/guides/environment-variables", "source_page_title": "Additional Features - Environment Variables Guide"}, {"text": "Client side functions are ideal for updating component properties (like visibility, placeholders, interactive state, or styling). \n\nHere's a basic example:\n\n```py\nimport gradio as gr\n\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 )\n\ndemo.launch()\n```\n\n\n", "heading1": "When to Use Client Side Functions", "source_page_url": "https://gradio.app/guides/client-side-functions", "source_page_title": "Additional Features - Client Side Functions Guide"}, {"text": "Client side functions have some important restrictions:\n* They can only update component properties (not values)\n* They cannot take any inputs\n\nHere are some functions that will work with `js=True`:\n\n```py\nSimple property updates\nlambda: gr.Textbox(lines=4)\n\nMultiple component updates\nlambda: [gr.Textbox(lines=4), gr.Button(interactive=False)]\n\nUsing gr.update() for property changes\nlambda: gr.update(visible=True, interactive=False)\n```\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](https://github.com/abidlabs/groovy-transpiler).\n\n\n", "heading1": "Limitations", "source_page_url": "https://gradio.app/guides/client-side-functions", "source_page_title": "Additional Features - Client Side Functions Guide"}, {"text": "Here's a more complete example showing how client side functions can improve the user experience:\n\n$code_todo_list_js\n\n\n", "heading1": "Complete Example", "source_page_url": "https://gradio.app/guides/client-side-functions", "source_page_title": "Additional Features - Client Side Functions Guide"}, {"text": "When you set `js=True`, Gradio:\n\n1. Transpiles your Python function to JavaScript\n\n2. Runs the function directly in the browser\n\n3. Still sends the request to the server (for consistency and to handle any side effects)\n\nThis provides immediate visual feedback while ensuring your application state remains consistent.\n", "heading1": "Behind the Scenes", "source_page_url": "https://gradio.app/guides/client-side-functions", "source_page_title": "Additional Features - Client Side Functions Guide"}, {"text": "Gradio demos can be easily shared publicly by setting `share=True` in the `launch()` method. Like this:\n\n```python\nimport gradio as gr\n\ndef greet(name):\n return \"Hello \" + name + \"!\"\n\ndemo = gr.Interface(fn=greet, inputs=\"textbox\", outputs=\"textbox\")\n\ndemo.launch(share=True) Share your demo with just 1 extra parameter \ud83d\ude80\n```\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.\n\n![sharing](https://github.com/gradio-app/gradio/blob/main/guides/assets/sharing.svg?raw=true)\n\n\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](https://github.com/huggingface/frp/) on your own cloud server to overcome this restriction.)\n\nTip: Keep in mind that share links are publicly accessible, meaning that anyone can use your model for prediction! Therefore, make sure not to expose any sensitive information through the functions you write, or allow any critical changes to occur on your device. Or you can [add authentication to your Gradio app](authentication) as discussed below.\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](https://www.ssh.com/ssh/tunneling/example) to share your local server with specific users.\n\n\n", "heading1": "Sharing Demos", "source_page_url": "https://gradio.app/guides/sharing-your-app", "source_page_title": "Additional Features - Sharing Your App Guide"}, {"text": "If you'd like to have a permanent link to your Gradio demo on the internet, use Hugging Face Spaces. [Hugging Face Spaces](http://huggingface.co/spaces/) provides the infrastructure to permanently host your machine learning model for free!\n\nAfter you have [created a free Hugging Face account](https://huggingface.co/join), you have two methods to deploy your Gradio app to Hugging Face Spaces:\n\n1. From terminal: run `gradio deploy` in your app directory. The CLI will gather some basic metadata, upload all the files in the current directory (respecting any `.gitignore` file that may be present in the root of the directory), and then launch your app on Spaces. To update your Space, you can re-run this command or enable the Github Actions option in the CLI to automatically update the Spaces on `git push`.\n\n2. From your browser: Drag and drop a folder containing your Gradio model and all related files [here](https://huggingface.co/new-space). See [this guide how to host on Hugging Face Spaces](https://huggingface.co/blog/gradio-spaces) for more information, or watch the embedded video:\n\n\n\n", "heading1": "Hosting on HF Spaces", "source_page_url": "https://gradio.app/guides/sharing-your-app", "source_page_title": "Additional Features - Sharing Your App Guide"}, {"text": "You 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.\n\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.\n\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\n$code_deep_link\n$demo_deep_link\n\n\n", "heading1": "Sharing Deep Links", "source_page_url": "https://gradio.app/guides/sharing-your-app", "source_page_title": "Additional Features - Sharing Your App Guide"}, {"text": "Once 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 \u2014 right in their browser! The best part is that you can embed interactive demos even in static websites, such as GitHub pages.\n\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:\n\n![Embed this Space dropdown option](https://github.com/gradio-app/gradio/blob/main/guides/assets/embed_this_space.png?raw=true)\n\nEmbedding with Web Components\n\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.\n\nTo embed with Web Components:\n\n1. Import 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\n```html\n\n```\n\n2. Add\n\n```html\n\n```\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\n```html\n\n```\n\n\n\nYou can see examples of h", "heading1": "Embedding Hosted Spaces", "source_page_url": "https://gradio.app/guides/sharing-your-app", "source_page_title": "Additional Features - Sharing Your App Guide"}, {"text": "=> {\n let v = obj.info.version;\n content = document.querySelector('.prose');\n content.innerHTML = content.innerHTML.replaceAll(\"{GRADIO_VERSION}\", v);\n});\n\n\nYou can see examples of how web components look on the Gradio landing page.\n\nYou can also customize the appearance and behavior of your web component with attributes that you pass into the `` tag:\n\n- `src`: as we've seen, the `src` attributes links to the URL of the hosted Gradio demo that you would like to embed\n- `space`: 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.\n- `control_page_title`: a boolean designating whether the html title of the page should be set to the title of the Gradio app (by default `\"false\"`)\n- `initial_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.\n- `container`: whether to show the border frame and information about where the Space is hosted (by default `\"true\"`)\n- `info`: whether to show just the information about where the Space is hosted underneath the embedded app (by default `\"true\"`)\n- `autoscroll`: whether to autoscroll to the output when prediction has finished (by default `\"false\"`)\n- `eager`: whether to load the Gradio app as soon as the page loads (by default `\"false\"`)\n- `theme_mode`: whether to use the `dark`, `light`, or default `system` theme mode (by default `\"system\"`)\n- `render`: an event that is triggered once the embedded space has finished rendering.\n\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\n```html\n\n```\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\n```html\n\n```\n\n_Note: 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._\n\nEmbedding with IFrames\n\nTo embed with IFrames instead (if you cannot add javascript to your website, for example), add this element:\n\n```html\n\n```\n\nAgain, you can find the `src=` attribute to your Space's embed URL, which you can find in the \"Embed this Space\" button.\n\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.\n\n", "heading1": "Embedding Hosted Spaces", "source_page_url": "https://gradio.app/guides/sharing-your-app", "source_page_title": "Additional Features - Sharing Your App Guide"}, {"text": "You can use almost any Gradio app as an API! In the footer of a Gradio app [like this one](https://huggingface.co/spaces/gradio/hello_world), you'll see a \"Use via API\" link.\n\n![Use via API](https://github.com/gradio-app/gradio/blob/main/guides/assets/use_via_api.png?raw=true)\n\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](https://gradio.app/guides/getting-started-with-the-python-client/), or [the JavaScript client](https://gradio.app/guides/getting-started-with-the-js-client/). For each endpoint, Gradio automatically generates the parameters and their types, as well as example inputs, like this.\n\n![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio-guides/view-api.png)\n\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\n```python\nbtn.click(add, [num1, num2], output, api_name=\"addition\")\n```\n\nThis will add and document the endpoint `/addition/` to the automatically generated API page. Read more about the [API page here](./view-api-page).\n\n", "heading1": "API Page", "source_page_url": "https://gradio.app/guides/sharing-your-app", "source_page_title": "Additional Features - Sharing Your App Guide"}, {"text": "When 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\n```python\nimport gradio as gr\n\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\n\nio = gr.Interface(echo, \"textbox\", \"textbox\").launch()\n```\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`.\n\n", "heading1": "Accessing the Network Request Directly", "source_page_url": "https://gradio.app/guides/sharing-your-app", "source_page_title": "Additional Features - Sharing Your App Guide"}, {"text": "In 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.mount_gradio_app()`.\n\nHere's a complete example:\n\n$code_custom_path\n\nNote that this approach also allows you run your Gradio apps on custom paths (`http://localhost:8000/gradio` in the example above).\n\n\n", "heading1": "Mounting Within Another FastAPI App", "source_page_url": "https://gradio.app/guides/sharing-your-app", "source_page_title": "Additional Features - Sharing Your App Guide"}, {"text": "Password-protected app\n\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\n```python\ndemo.launch(auth=(\"admin\", \"pass1234\"))\n```\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.\n\nHere's an example of a function that accepts any login where the username and password are the same:\n\n```python\ndef same_auth(username, password):\n return username == password\ndemo.launch(auth=same_auth)\n```\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](accessing-the-network-request-directly) as discussed above, and then reading the `.username` attribute of the request. Here's an example:\n\n\n```python\nimport gradio as gr\n\ndef update_message(request: gr.Request):\n return f\"Welcome, {request.username}\"\n\nwith gr.Blocks() as demo:\n m = gr.Markdown()\n demo.load(update_message, None, m)\n\ndemo.launch(auth=[(\"Abubakar\", \"Abubakar\"), (\"Ali\", \"Ali\")])\n```\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.\n\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\n```python\nimport gradio as gr\n\ndef update_message(request: gr.Request):\n return f\"Welcome, {request.username}\"\n\nwith gr.Blocks() as ", "heading1": "Authentication", "source_page_url": "https://gradio.app/guides/sharing-your-app", "source_page_title": "Additional Features - Sharing Your App Guide"}, {"text": " Let's update the previous example to include a log out button:\n\n```python\nimport gradio as gr\n\ndef update_message(request: gr.Request):\n return f\"Welcome, {request.username}\"\n\nwith gr.Blocks() as demo:\n m = gr.Markdown()\n logout_button = gr.Button(\"Logout\", link=\"/logout\")\n demo.load(update_message, None, m)\n\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 `all_session=false` (i.e. `/logout?all_session=false`).\n\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).\n\nOAuth (Login via Hugging Face)\n\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](https://huggingface.co/spaces/Wauplin/gradio-oauth-demo) for a live demo.\n\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\n`gr.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 def", "heading1": "Authentication", "source_page_url": "https://gradio.app/guides/sharing-your-app", "source_page_title": "Additional Features - Sharing Your App Guide"}, {"text": "e. 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](https://huggingface.co/docs/hub/spaces-oauthscopes) for more details).\n\nHere is a short example:\n\n$code_login_with_huggingface\n\nWhen the user clicks on the login button, they get redirected in a new page to authorize your Space.\n\n
\n\n
\n\nUsers can revoke access to their profile at any time in their [settings](https://huggingface.co/settings/connected-applications).\n\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.\n\n**Security 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](/guides/sharing-your-apppassword-protected-app) 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.\n\n\nOAuth (with external providers)\n\nIt is also possible to authenticate with external OAuth pr", "heading1": "Authentication", "source_page_url": "https://gradio.app/guides/sharing-your-app", "source_page_title": "Additional Features - Sharing Your App Guide"}, {"text": "erence is that the `gr.OAuthProfile` or `gr.OAuthToken` will be `None` in the corresponding functions.\n\n\nOAuth (with external providers)\n\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](mounting-within-another-fast-api-app)). 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 `auth_dependency` parameter in `gr.mount_gradio_app`.\n\nSimilar to [FastAPI dependency functions](https://fastapi.tiangolo.com/tutorial/dependencies/), 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.\n\nFirst, let's show a simplistic example to illustrate the `auth_dependency` parameter:\n\n```python\nfrom fastapi import FastAPI, Request\nimport gradio as gr\n\napp = FastAPI()\n\ndef get_user(request: Request):\n return request.headers.get(\"user\")\n\ndemo = gr.Interface(lambda s: f\"Hello {s}!\", \"textbox\", \"textbox\")\n\napp = gr.mount_gradio_app(app, demo, path=\"/demo\", auth_dependency=get_user)\n\nif __name__ == '__main__':\n uvicorn.run(app)\n```\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.\n\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](https://console.cloud.google.com/project)):\n\n```python\nimport os\nfrom authlib.integrations.starlette_client import OAuth, OAuthError\nfrom fastapi import FastA", "heading1": "Authentication", "source_page_url": "https://gradio.app/guides/sharing-your-app", "source_page_title": "Additional Features - Sharing Your App Guide"}, {"text": "entials on the [Google Developer Console](https://console.cloud.google.com/project)):\n\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\n\napp = FastAPI()\n\nReplace these with your own OAuth settings\nGOOGLE_CLIENT_ID = \"...\"\nGOOGLE_CLIENT_SECRET = \"...\"\nSECRET_KEY = \"...\"\n\nconfig_data = {'GOOGLE_CLIENT_ID': GOOGLE_CLIENT_ID, 'GOOGLE_CLIENT_SECRET': GOOGLE_CLIENT_SECRET}\nstarlette_config = Config(environ=config_data)\noauth = OAuth(starlette_config)\noauth.register(\n name='google',\n server_metadata_url='https://accounts.google.com/.well-known/openid-configuration',\n client_kwargs={'scope': 'openid email profile'},\n)\n\nSECRET_KEY = os.environ.get('SECRET_KEY') or \"a_very_secret_key\"\napp.add_middleware(SessionMiddleware, secret_key=SECRET_KEY)\n\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\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\n@app.route('/logout')\nasync def logout(request: Request):\n request.session.pop('user', None)\n return RedirectResponse(url='/')\n\n@app.route('/login')\nasync def login(request: Request):\n redirect_uri = request.url_for('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 redirect_uri = urlunparse(urlparse(str(redirect_uri))._replace(scheme='https'))\n return await oauth.google.authorize_redirect(request, redirect_uri)\n\n@app.route('/auth')\nasync def auth(request: Reque", "heading1": "Authentication", "source_page_url": "https://gradio.app/guides/sharing-your-app", "source_page_title": "Additional Features - Sharing Your App Guide"}, {"text": "direct_uri = urlunparse(urlparse(str(redirect_uri))._replace(scheme='https'))\n return await oauth.google.authorize_redirect(request, redirect_uri)\n\n@app.route('/auth')\nasync def auth(request: Request):\n try:\n access_token = await oauth.google.authorize_access_token(request)\n except OAuthError:\n return RedirectResponse(url='/')\n request.session['user'] = dict(access_token)[\"userinfo\"]\n return RedirectResponse(url='/')\n\nwith gr.Blocks() as login_demo:\n gr.Button(\"Login\", link=\"/login\")\n\napp = gr.mount_gradio_app(app, login_demo, path=\"/login-demo\")\n\ndef greet(request: gr.Request):\n return f\"Welcome to Gradio, {request.username}\"\n\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)\n\napp = gr.mount_gradio_app(app, main_demo, path=\"/gradio\", auth_dependency=get_user)\n\nif __name__ == '__main__':\n uvicorn.run(app)\n```\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](https://huggingface.co/spaces/gradio/oauth-example).\n\n", "heading1": "Authentication", "source_page_url": "https://gradio.app/guides/sharing-your-app", "source_page_title": "Additional Features - Sharing Your App Guide"}, {"text": "Gradio 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](https://www.gradio.app/guides/building-mcp-server-with-gradio).\n\n", "heading1": "MCP Servers", "source_page_url": "https://gradio.app/guides/sharing-your-app", "source_page_title": "Additional Features - Sharing Your App Guide"}, {"text": "When 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](accessing-the-network-request-directly)) 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](https://github.com/gradio-app/gradio/blob/main/demo/rate_limit/run.py).\n\n", "heading1": "Rate Limits", "source_page_url": "https://gradio.app/guides/sharing-your-app", "source_page_title": "Additional Features - Sharing Your App Guide"}, {"text": "By default, Gradio collects certain analytics to help us better understand the usage of the `gradio` library. This includes the following information:\n\n* What environment the Gradio app is running on (e.g. Colab Notebook, Hugging Face Spaces)\n* What input/output components are being used in the Gradio app\n* Whether the Gradio app is utilizing certain advanced features, such as `auth` or `show_error`\n* The IP address which is used solely to measure the number of unique developers using Gradio\n* The version of Gradio that is running\n\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 `analytics_enabled` parameter to `False` in `gr.Blocks`, `gr.Interface`, or `gr.ChatInterface`. Or, you can set the GRADIO_ANALYTICS_ENABLED environment variable to `\"False\"` to apply this to all Gradio apps created across your system.\n\n*Note*: this reflects the analytics policy as of `gradio>=4.32.0`.\n\n", "heading1": "Analytics", "source_page_url": "https://gradio.app/guides/sharing-your-app", "source_page_title": "Additional Features - Sharing Your App Guide"}, {"text": "[Progressive Web Apps (PWAs)](https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps) are web applications that are regular web pages or websites, but can appear to the user like installable platform-specific applications.\n\nGradio apps can be easily served as PWAs by setting the `pwa=True` parameter in the `launch()` method. Here's an example:\n\n```python\nimport gradio as gr\n\ndef greet(name):\n return \"Hello \" + name + \"!\"\n\ndemo = gr.Interface(fn=greet, inputs=\"textbox\", outputs=\"textbox\")\n\ndemo.launch(pwa=True) Launch your app as a PWA\n```\n\nThis will generate a PWA that can be installed on your device. Here's how it looks:\n\n![Installing PWA](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio-guides/install-pwa.gif)\n\nWhen you specify `favicon_path` in the `launch()` method, the icon will be used as the app's icon. Here's an example:\n\n```python\ndemo.launch(pwa=True, favicon_path=\"./hf-logo.svg\") Use a custom icon for your PWA\n```\n\n![Custom PWA Icon](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio-guides/pwa-favicon.png)\n", "heading1": "Progressive Web App (PWA)", "source_page_url": "https://gradio.app/guides/sharing-your-app", "source_page_title": "Additional Features - Sharing Your App Guide"}, {"text": "By default, each event listener has its own queue, which handles one request at a time. This can be configured via two arguments:\n\n- `concurrency_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\n```python\nimport gradio as gr\n\nwith gr.Blocks() as demo:\n prompt = gr.Textbox()\n image = gr.Image()\n generate_btn = gr.Button(\"Generate Image\")\n generate_btn.click(image_gen, prompt, image, concurrency_limit=5)\n```\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.\n\nIf you want to manage multiple event listeners using a shared queue, you can use the `concurrency_id` argument:\n\n- `concurrency_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\n```python\nimport gradio as gr\n\nwith gr.Blocks() as demo:\n prompt = gr.Textbox()\n image = gr.Image()\n generate_btn_1 = gr.Button(\"Generate Image via model 1\")\n generate_btn_2 = gr.Button(\"Generate Image via model 2\")\n generate_btn_3 = gr.Button(\"Generate Image via model 3\")\n generate_btn_1.click(image_gen_1, prompt, image, concurrency_limit=2, concurrency_id=\"gpu_queue\")\n generate_btn_2.click(image_gen_2, prompt, image, concurrency_id=\"gpu_queue\")\n generate_btn_3.click(image_gen_3, prompt, image, concurrency_id=\"gpu_queue\")\n```\n\nIn this example, all three event listeners share a queue identified by `\"gpu_queue\"`. The queue can handle up to 2 concurrent requests at a time, as defined by the `concurrency_limit`.\n\nNotes\n\n- To ensure unlimited concurrency for an event listener, se", "heading1": "Configuring the Queue", "source_page_url": "https://gradio.app/guides/queuing", "source_page_title": "Additional Features - Queuing Guide"}, {"text": " identified by `\"gpu_queue\"`. The queue can handle up to 2 concurrent requests at a time, as defined by the `concurrency_limit`.\n\nNotes\n\n- To 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.\n- The default concurrency limit for all queues can be set globally using the `default_concurrency_limit` parameter in `Blocks.queue()`. \n\nThese configurations make it easy to manage the queuing behavior of your Gradio app.\n", "heading1": "Configuring the Queue", "source_page_url": "https://gradio.app/guides/queuing", "source_page_title": "Additional Features - Queuing Guide"}, {"text": "- **1. Static files**. You can designate static files or directories using the `gr.set_static_paths` 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.\n\n- **2. Files 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).\n\n- **3. Files 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.\n\n\n", "heading1": "Files Gradio allows users to access", "source_page_url": "https://gradio.app/guides/file-access", "source_page_title": "Additional Features - File Access Guide"}, {"text": "First, 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\nTip: You can customize the location of the cache by setting the `GRADIO_TEMP_DIR` environment variable to an absolute path, such as `/home/usr/scripts/project/temp/`. \n\nFiles Gradio moves to the cache\n\nGradio moves three kinds of files into the cache\n\n1. Files 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`\n\n2. File paths returned by a prediction function in your Gradio application, if they ALSO meet one of the conditions below:\n\n* It is in the `allowed_paths` parameter of the `Blocks.launch` method.\n* It is in the current working directory of the python interpreter.\n* It is in the temp directory obtained by `tempfile.gettempdir()`.\n\n**Note:** 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. \n\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.\n\n3. Files uploaded by a user to your Gradio app (e.g. through the `File` or `Image` input components).\n\nTip: If at any time Gradio blocks a file that you would like it to process, add its path to the `allowed_paths` p", "heading1": "The Gradio cache", "source_page_url": "https://gradio.app/guides/file-access", "source_page_title": "Additional Features - File Access Guide"}, {"text": "d by a user to your Gradio app (e.g. through the `File` or `Image` input components).\n\nTip: 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", "heading1": "The Gradio cache", "source_page_url": "https://gradio.app/guides/file-access", "source_page_title": "Additional Features - File Access Guide"}, {"text": "While running, Gradio apps will NOT ALLOW users to access:\n\n- **Files that you explicitly block via the `blocked_paths` parameter in `launch()`**. You can pass in a list of additional directories or exact filepaths to the `blocked_paths` parameter in `launch()`. This parameter takes precedence over the files that Gradio exposes by default, or by the `allowed_paths` parameter or the `gr.set_static_paths` function.\n\n- **Any other paths on the host machine**. Users should NOT be able to access other arbitrary paths on the host.\n\n", "heading1": "The files Gradio will not allow others to access", "source_page_url": "https://gradio.app/guides/file-access", "source_page_title": "Additional Features - File Access Guide"}, {"text": "Sharing 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 `max_file_size` parameter of `.launch`. For example, the following two code snippets limit file uploads to 5 megabytes per file.\n\n```python\nimport gradio as gr\n\ndemo = gr.Interface(lambda x: x, \"image\", \"image\")\n\ndemo.launch(max_file_size=\"5mb\")\nor\ndemo.launch(max_file_size=5 * gr.FileSize.MB)\n```\n\n", "heading1": "Uploading Files", "source_page_url": "https://gradio.app/guides/file-access", "source_page_title": "Additional Features - File Access Guide"}, {"text": "* Set a `max_file_size` for your application.\n* Do 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. \n* Make `allowed_paths` as small as possible. If a path in `allowed_paths` 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.\n* Run 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`.\n\n\n", "heading1": "Best Practices", "source_page_url": "https://gradio.app/guides/file-access", "source_page_title": "Additional Features - File Access Guide"}, {"text": "Both `gr.set_static_paths` 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\n```txt\n\u251c\u2500\u2500 assets\n\u2502 \u2514\u2500\u2500 logo.png\n\u2514\u2500\u2500 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\n```python\nfrom pathlib import Path\n\nimport gradio as gr\n\ngr.set_static_paths(paths=[Path.cwd().absolute()/\"assets\"])\n\nwith gr.Blocks() as demo:\n gr.HTML(\"\")\n\ndemo.launch()\n```\n", "heading1": "Example: Accessing local files", "source_page_url": "https://gradio.app/guides/file-access", "source_page_title": "Additional Features - File Access Guide"}, {"text": "Make 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](./custom-components-in-five-minutes) of custom components and the [Key Concepts](./key-component-concepts) guide before starting.\n\n\n", "heading1": "Step 0: Prerequisites", "source_page_url": "https://gradio.app/guides/pdf-component-example", "source_page_title": "Custom Components - Pdf Component Example Guide"}, {"text": "Navigate to a directory of your choosing and run the following command:\n\n```bash\ngradio cc create PDF\n```\n\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!\n\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![directory structure](https://gradio-builds.s3.amazonaws.com/assets/pdf-guide/CodeStructure.png)\n\nTip: 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 --template `\n\n", "heading1": "Step 1: Creating the custom component", "source_page_url": "https://gradio.app/guides/pdf-component-example", "source_page_title": "Custom Components - Pdf Component Example Guide"}, {"text": "We're going to use the [pdfjs](https://mozilla.github.io/pdf.js/) 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.\n\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`.\n\nThe complete `package.json` should look like this:\n\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\nTip: Running `npm install` will install the latest version of the package available. You can install a specific version with `npm install package@`. You can find all of the gradio javascript package documentation [here](https://www.gradio.app/main/docs/js). It is recommended you use the same versions as me as the API can change.\n\nNavigate to `Index.svelte` and delete mentions of `JSONView`\n\n```ts\nimport { JsonView } from \"@zerodevx/svelte-json-view\";\n```\n\n```svelte\n\n```\n\n", "heading1": "Step 2: Frontend - modify javascript dependencies", "source_page_url": "https://gradio.app/guides/pdf-component-example", "source_page_title": "Custom Components - Pdf Component Example Guide"}, {"text": "Run 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.\n\nAfter launching the dev server, you should see a link printed to your console that says `Frontend Server (Go here): ... `.\n \n![](https://gradio-builds.s3.amazonaws.com/assets/pdf-guide/dev_server_terminal.png)\n\nYou should see the following:\n\n![](https://gradio-builds.s3.amazonaws.com/assets/pdf-guide/frontend_start.png)\n\n\nIts not impressive yet but we're ready to start coding!\n\n", "heading1": "Step 3: Frontend - Launching the Dev Server", "source_page_url": "https://gradio.app/guides/pdf-component-example", "source_page_title": "Custom Components - Pdf Component Example Guide"}, {"text": "We'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, delete all ", "heading1": "Step 4: Frontend - The basic skeleton", "source_page_url": "https://gradio.app/guides/pdf-component-example", "source_page_title": "Custom Components - Pdf Component Example Guide"}, {"text": "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\n```svelte\n\n {if loading_status}\n \n {/if}\n \n {if _value}\n \n {:else}\n \n Upload your PDF\n \n {/if}\n\n```\n\nYou should see the following when you navigate to your app after saving your current changes:\n\n![](https://gradio-builds.s3.amazonaws.com/assets/pdf-guide/frontend_1.png)\n\n", "heading1": "Step 4: Frontend - The basic skeleton", "source_page_url": "https://gradio.app/guides/pdf-component-example", "source_page_title": "Custom Components - Pdf Component Example Guide"}, {"text": "The `Upload your PDF` text looks a bit small and barebones. \nLets customize it!\n\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\nTip: 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\n\n
\n\t \n Drop PDF\n - or -\n Click to Upload\n
\n\n\n```\n\nNow import `PdfUploadText.svelte` in your `\n\n\n\t\n
\n\n\n```\n\n\nTip: Exercise for the reader - reduce the code duplication between `Index.svelte` and `Example.svelte` \ud83d\ude0a\n\n\nYou will not be able to render examples until we make some changes to the backend code in the next step!\n\n", "heading1": "Step 8.5: The Example view", "source_page_url": "https://gradio.app/guides/pdf-component-example", "source_page_title": "Custom Components - Pdf Component Example Guide"}, {"text": "The backend changes needed are smaller.\nWe're almost done!\n\nWhat we're going to do is:\n* Add `change` and `upload` events to our component.\n* Add a `height` property to let users control the height of the PDF.\n* Set 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.\n* Modify the `preprocess` method to return a string corresponding to the path of our uploaded PDF.\n* Modify the `postprocess` to turn a path to a PDF created in an event handler to a `FileData`.\n\nWhen all is said an done, your component's backend code should look like this:\n\n```python\nfrom __future__ import annotations\nfrom typing import Any, Callable, TYPE_CHECKING\n\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\n\nclass PDF(Component):\n\n EVENTS = [\"change\", \"upload\"]\n\n data_model = FileData\n\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 show_label=show_label, container=container,\n scale=scale, min_width=min_width,\n interactive=interactive, visible=visible,\n ", "heading1": "Step 9: The backend", "source_page_url": "https://gradio.app/guides/pdf-component-example", "source_page_title": "Custom Components - Pdf Component Example Guide"}, {"text": " show_label=show_label, container=container,\n scale=scale, min_width=min_width,\n interactive=interactive, visible=visible,\n elem_id=elem_id, elem_classes=elem_classes,\n render=render, load_fn=load_fn, every=every)\n self.height = height\n\n def preprocess(self, payload: FileData) -> str:\n return payload.path\n\n def postprocess(self, value: str | None) -> FileData:\n if not value:\n return None\n return FileData(path=value)\n\n def example_payload(self):\n return \"https://gradio-builds.s3.amazonaws.com/assets/pdf-guide/fw9.pdf\"\n\n def example_value(self):\n return \"https://gradio-builds.s3.amazonaws.com/assets/pdf-guide/fw9.pdf\"\n```\n\n", "heading1": "Step 9: The backend", "source_page_url": "https://gradio.app/guides/pdf-component-example", "source_page_title": "Custom Components - Pdf Component Example Guide"}, {"text": "To test our backend code, let's add a more complex demo that performs Document Question and Answering with huggingface transformers.\n\nIn our `demo` directory, create a `requirements.txt` file with the following packages\n\n```\ntorch\ntransformers\npdf2image\npytesseract\n```\n\n\nTip: Remember to install these yourself and restart the dev server! You may need to install extra non-python dependencies for `pdf2image`. See [here](https://pypi.org/project/pdf2image/). 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 convert_from_path\nfrom transformers import pipeline\nfrom pathlib import Path\n\ndir_ = Path(__file__).parent\n\np = pipeline(\n \"document-question-answering\",\n model=\"impira/layoutlm-document-qa\",\n)\n\ndef qa(question: str, doc: str) -> str:\n img = convert_from_path(doc)[0]\n output = p(img, question)\n return sorted(output, key=lambda x: x[\"score\"], reverse=True)[0]['answer']\n\n\ndemo = gr.Interface(\n qa,\n [gr.Textbox(label=\"Question\"), PDF(label=\"Document\")],\n gr.Textbox(),\n)\n\ndemo.launch()\n```\n\nSee our demo in action below!\n\n\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](https://pypi.org/) and [HuggingFace Spaces](https://huggingface.co/spaces).\n\n\nTip: You may need to add the following lines to the `Dockerfile` of your HuggingFace Space.\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\n\nENV TRANSFORMERS_CACHE=/tmp/cache/\n```\n\n", "heading1": "Step 10: Add a demo and publish!", "source_page_url": "https://gradio.app/guides/pdf-component-example", "source_page_title": "Custom Components - Pdf Component Example Guide"}, {"text": "In 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).\n\nHere is a simple demo with the Blocks api:\n\n```python\nimport gradio as gr\nfrom gradio_pdf import PDF\n\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)\n\ndemo.launch()\n```\n\n\nI hope you enjoyed this tutorial!\nThe complete source code for our component is [here](https://huggingface.co/spaces/freddyaboulton/gradio_pdf/tree/main/src).\nPlease don't hesitate to reach out to the gradio community on the [HuggingFace Discord](https://discord.gg/hugging-face-879548962464493619) if you get stuck.\n", "heading1": "Conclusion", "source_page_url": "https://gradio.app/guides/pdf-component-example", "source_page_title": "Custom Components - Pdf Component Example Guide"}, {"text": "For 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\n```bash\ngradio cc create MultimodalChatbot --template Chatbot\n```\n\nAnd we're ready to go!\n\nTip: Make sure to modify the `Author` key in the `pyproject.toml` file.\n\n", "heading1": "Part 1 - Creating our project", "source_page_url": "https://gradio.app/guides/multimodal-chatbot-part1", "source_page_title": "Custom Components - Multimodal Chatbot Part1 Guide"}, {"text": "Open up the `multimodalchatbot.py` file in your favorite code editor and let's get started modifying the backend of our component.\n\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](./backend).\n\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.\n\nImport the `FileData` and `GradioModel` classes from `gradio.data_classes` and modify the existing `ChatbotData` class to look like the following:\n\n```python\nclass FileMessage(GradioModel):\n file: FileData\n alt_text: Optional[str] = None\n\n\nclass MultimodalMessage(GradioModel):\n text: Optional[str] = None\n files: Optional[List[FileMessage]] = None\n\n\nclass ChatbotData(GradioRootModel):\n root: List[Tuple[Optional[MultimodalMessage], Optional[MultimodalMessage]]]\n\n\nclass MultimodalChatbot(Component):\n ...\n data_model = ChatbotData\n```\n\n\nTip: The `data_model`s are implemented using `Pydantic V2`. Read the documentation [here](https://docs.pydantic.dev/latest/).\n\nWe've done the hardest part already!\n\n", "heading1": "Part 2a - The backend data_model", "source_page_url": "https://gradio.app/guides/multimodal-chatbot-part1", "source_page_title": "Custom Components - Multimodal Chatbot Part1 Guide"}, {"text": "For the `preprocess` method, we will keep it simple and pass a list of `MultimodalMessage`s 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\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\nTip: Learn about the reasoning behind the `preprocess` and `postprocess` methods in the [key concepts guide](./key-component-concepts)\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.\n\nWe can leave the `postprocess` method as is and modify the `_postprocess_chat_messages`\n\n```python\ndef _postprocess_chat_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 chat_message = MultimodalMessage(**chat_message)\n chat_message.text = inspect.cleandoc(chat_message.text or \"\")\n for file_ in chat_message.files:\n file_.file.mime_type = client_utils.get_mimetype(file_.file.path)\n return chat_message\n```\n\nBefore we wrap up with the backend code, let's modify the `example_value` and `example_payload` method to return a valid dictionary representation of the `ChatbotData`:\n\n```python\ndef example_value(self) -> Any:\n return [[{\"text\": \"Hello!\", \"files\": []}, None]]\n\ndef example_payload(self) -> Any:\n return [[{\"text\": \"Hello!\", \"files\": []}, None]]\n```\n\nCongrats - the backend is complete!\n\n", "heading1": "Part 2b - The pre and postprocess methods", "source_page_url": "https://gradio.app/guides/multimodal-chatbot-part1", "source_page_title": "Custom Components - Multimodal Chatbot Part1 Guide"}, {"text": "The 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.\n\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\n```ts\nexport type FileMessage = {\n\tfile: FileData;\n\talt_text?: string;\n};\n\n\nexport type MultimodalMessage = {\n\ttext: string;\n\tfiles?: FileMessage[];\n}\n```\n\nNow let's import them in `Index.svelte` and modify the type annotations for `value` and `_value`.\n\n```ts\nimport type { FileMessage, MultimodalMessage } from \"./shared/utils\";\n\nexport let value: [\n MultimodalMessage | null,\n MultimodalMessage | null\n][] = [];\n\nlet _value: [\n MultimodalMessage | null,\n MultimodalMessage | null\n][];\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\n```ts\nfunction process_message(msg: MultimodalMessage | null): MultimodalMessage | null {\n if (msg === null) {\n return msg;\n }\n msg.text = redirect_src_url(msg.text);\n msg.files = msg.files.map(normalize_messages);\n return msg;\n}\n\n$: _value = value\n ? value.map(([user_msg, bot_msg]) => [\n process_message(user_msg),\n process_message(bot_msg)\n ])\n : [];\n```\n\n", "heading1": "Part 3a - The Index.svelte file", "source_page_url": "https://gradio.app/guides/multimodal-chatbot-part1", "source_page_title": "Custom Components - Multimodal Chatbot Part1 Guide"}, {"text": "Let's begin similarly to the `Index.svelte` file and let's first modify the type annotations.\nImport `Mulimodal` message at the top of the `\n\n\n\n\n\t{if loading_status}\n\t\t\n\t{/if}\n

{value}

\n\n```\n\n", "heading1": "The Index.svelte file", "source_page_url": "https://gradio.app/guides/frontend", "source_page_title": "Custom Components - Frontend Guide"}, {"text": "The `Example.svelte` file should expose the following props:\n\n```typescript\n export let value: string;\n export let type: \"gallery\" | \"table\";\n export let selected = false;\n export let index: number;\n```\n\n* `value`: The example value that should be displayed.\n\n* `type`: 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. \n\n* `selected`: You can also adjust how the examples are displayed if a user \"selects\" a particular example by using the selected variable.\n\n* `index`: The current index of the selected value.\n\n* Any additional props your \"non-example\" component takes!\n\nThis is the `Example.svelte` file for the code `Radio` component:\n\n```svelte\n\n\n\n\t{value}\n\n\n\n```\n\n", "heading1": "The Example.svelte file", "source_page_url": "https://gradio.app/guides/frontend", "source_page_title": "Custom Components - Frontend Guide"}, {"text": "If 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.\n\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.\n\nThe `upload` function will upload an array of `FileData` values to the server.\n\nHere's an example of loading files from an `` element when its value changes.\n\n\n```svelte\n\n\n\n```\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.\n\nFor WASM support, you should get the upload function from the `Context` and pass that as the third parameter of the `upload` function.\n\n```typescript\n\n```\n\n", "heading1": "Handling Files", "source_page_url": "https://gradio.app/guides/frontend", "source_page_title": "Custom Components - Frontend Guide"}, {"text": "Most of Gradio's frontend components are published on [npm](https://www.npmjs.com/), 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\n```svelte\n\n\n\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```\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](https://gradio.app/main/docs/js).\nWe'll be adding more packages and documentation over the coming weeks!\n\n", "heading1": "Leveraging Existing Gradio Components", "source_page_url": "https://gradio.app/guides/frontend", "source_page_title": "Custom Components - Frontend Guide"}, {"text": "You can explore our component library via Storybook. You'll be able to interact with our components and see them in their various states.\n\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.\n\n[Storybook Link](https://gradio.app/main/docs/js/storybook)\n\n", "heading1": "Matching Gradio Core's Design System", "source_page_url": "https://gradio.app/guides/frontend", "source_page_title": "Custom Components - Frontend Guide"}, {"text": "If 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.\n\nCurrently, it is possible to configure the following:\n\nVite options:\n- `plugins`: A list of vite plugins to use.\n\nSvelte options:\n- `preprocess`: A list of svelte preprocessors to use.\n- `extensions`: A list of file extensions to compile to `.svelte` files.\n- `build.target`: The target to build for, this may be necessary to support newer javascript features. See the [esbuild docs](https://esbuild.github.io/api/target) for more information.\n\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.\n\nExample for a Vite plugin\n\nCustom components can use Vite plugins to customize the build process. Check out the [Vite Docs](https://vitejs.dev/guide/using-plugins.html) for more information. \n\nHere we configure [TailwindCSS](https://tailwindcss.com), a utility-first CSS framework. Setup is easiest using the version 4 prerelease. \n\n```\nnpm install tailwindcss@next @tailwindcss/vite@next\n```\n\nIn `gradio.config.js`:\n\n```typescript\nimport tailwindcss from \"@tailwindcss/vite\";\nexport default {\n plugins: [tailwindcss()]\n};\n```\n\nThen create a `style.css` file with the following content:\n\n```css\n@import \"tailwindcss\";\n```\n\nImport this file into `Index.svelte`. Note, that you need to import the css file containing `@import` and cannot just use a `