[{"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": "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": "**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": "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": "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": "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": "`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": "Creates a file explorer component that allows users to browse files on the\nmachine hosting the Gradio app. As an input component, it also allows users to\nselect files to be used as input to a function, while as an output component,\nit displays selected files.\n\n", "heading1": "Description", "source_page_url": "https://gradio.app/docs/gradio/fileexplorer", "source_page_title": "Gradio - Fileexplorer Docs"}, {"text": "**Using FileExplorer as an input component.**\n\nHow FileExplorer will pass its value to your function:\n\nType: `list[str] | str | None`\n\nPasses the selected file or directory as a `str` path (relative to `root`) or\n`list[str}` depending on `file_count`\n\nExample Code\n\n \n \n \n import gradio as gr\n \n def predict(\n value: list[str] | str | None\n ):\n process value from the FileExplorer component\n return \"prediction\"\n \n interface = gr.Interface(predict, gr.FileExplorer(), gr.Textbox())\n interface.launch()\n \n \n\n \n\n**Using FileExplorer as an output component**\n\nHow FileExplorer expects you to return a value:\n\nType: `str | list[str] | None`\n\nExpects function to return a `str` path to a file, or `list[str]` consisting\nof paths to files.\n\nExample Code\n\n \n \n \n import gradio as gr\n \n def predict(text) -> str | list[str] | None\n process value to return to the FileExplorer component\n return value\n \n interface = gr.Interface(predict, gr.Textbox(), gr.FileExplorer())\n interface.launch()\n \n \n\n", "heading1": "Behavior", "source_page_url": "https://gradio.app/docs/gradio/fileexplorer", "source_page_title": "Gradio - Fileexplorer Docs"}, {"text": "Parameters \u25bc\n\n\n \n \n glob: str\n\ndefault `= \"**/*\"`\n\nThe glob-style pattern used to select which files to display, e.g. \"*\" to\nmatch all files, \"*.png\" to match all .png files, \"**/*.txt\" to match any .txt\nfile in any subdirectory, etc. The default value matches all files and folders\nrecursively. See the Python glob documentation at\nhttps://docs.python.org/3/library/glob.html for more information.\n\n\n \n \n value: str | list[str] | Callable | None\n\ndefault `= None`\n\nThe file (or list of files, depending on the `file_count` parameter) to show\nas \"selected\" when the component is first loaded. If a callable is provided,\nit will be called when the app loads to set the initial value of the\ncomponent. If not provided, no files are shown as selected.\n\n\n \n \n file_count: Literal['single', 'multiple']\n\ndefault `= \"multiple\"`\n\nWhether to allow single or multiple files to be selected. If \"single\", the\ncomponent will return a single absolute file path as a string. If \"multiple\",\nthe component will return a list of absolute file paths as a list of strings.\n\n\n \n \n root_dir: str | Path\n\ndefault `= \".\"`\n\nPath to root directory to select files from. If not provided, defaults to\ncurrent working directory. Raises ValueError if the directory does not exist.\n\n\n \n \n ignore_glob: str | None\n\ndefault `= None`\n\nThe glob-style, case-sensitive pattern that will be used to exclude files from\nthe list. For example, \"*.py\" will exclude all .py files from the list. See\nthe Python glob documentation at https://docs.python.org/3/library/glob.html\nfor more information.\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", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/fileexplorer", "source_page_title": "Gradio - Fileexplorer Docs"}, {"text": "onent. 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.\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 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\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 height: int | str | None\n\ndefault `= None`\n\nThe maximum height of the file component, specified in pixels if a number is\npassed, or in CSS units if a string is passed. If more files are uploaded than\ncan fit in the height, a scrollbar will appear.\n\n\n \n \n max_height: int | str | None\n\ndefault `= 500`\n\n\n \n \n min_height: int | str | None\n\ndefault `= None`\n\n\n \n \n interactive: bool | None\n\ndefault `= None`\n\nif True, will allow users to select file(s); if False, will only display\nfile", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/fileexplorer", "source_page_title": "Gradio - Fileexplorer Docs"}, {"text": "\n\n \n \n min_height: int | str | None\n\ndefault `= None`\n\n\n \n \n interactive: bool | None\n\ndefault `= None`\n\nif True, will allow users to select file(s); if False, will only display\nfiles. If not provided, this is inferred based on whether the component is\nused 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\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\n \n \n buttons: list[Button] | None\n\ndefault `= None`\n\nA list of gr.Button() instances to show in the top right corner of the\ncomponent. Custom buttons will appear in the toolbar with their configured", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/fileexplorer", "source_page_title": "Gradio - Fileexplorer Docs"}, {"text": " \n buttons: list[Button] | None\n\ndefault `= None`\n\nA list of gr.Button() instances to show in the top right corner of the\ncomponent. Custom buttons will appear in the toolbar with their configured\nicon and/or label, and clicking them will trigger any .click() events\nregistered on the button.\n\n", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/fileexplorer", "source_page_title": "Gradio - Fileexplorer Docs"}, {"text": "Shortcuts\n\n \n \n gradio.FileExplorer\n\nInterface String Shortcut `\"fileexplorer\"`\n\nInitialization Uses default values\n\n", "heading1": "Shortcuts", "source_page_url": "https://gradio.app/docs/gradio/fileexplorer", "source_page_title": "Gradio - Fileexplorer 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 FileExplorer 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 FileExplorer.change(fn, \u00b7\u00b7\u00b7)\n\nTriggered when the value of the FileExplorer 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 FileExplorer.input(fn, \u00b7\u00b7\u00b7)\n\nThis listener is triggered when the user changes the value of the\nFileExplorer.\n\n \n \n FileExplorer.select(fn, \u00b7\u00b7\u00b7)\n\nEvent listener for when the user selects or deselects the FileExplorer. Uses\nevent data gradio.SelectData to carry `value` referring to the label of the\nFileExplorer, and `selected` to refer to state of the FileExplorer. See\n for more details.\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[Comp", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/fileexplorer", "source_page_title": "Gradio - Fileexplorer Docs"}, {"text": "text] | 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 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 queu", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/fileexplorer", "source_page_title": "Gradio - Fileexplorer Docs"}, {"text": "lt `= 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\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 al", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/fileexplorer", "source_page_title": "Gradio - Fileexplorer Docs"}, {"text": " 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 the Gradio client libraries), or \"undocumented\" (hidden\nfrom API docs but callable by clients and via gr.load). If fn is None,\napi_visibility will automatically 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", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/fileexplorer", "source_page_title": "Gradio - Fileexplorer Docs"}, {"text": "ique 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/fileexplorer", "source_page_title": "Gradio - Fileexplorer Docs"}, {"text": "When gr.EventData or one of its subclasses is added as a type hint to an\nargument of a prediction function, a gr.EventData object will automatically be\npassed as the value of that argument. The attributes of this object contains\ninformation about the event that triggered the listener. The gr.EventData\nobject itself contains a `.target` attribute that refers to the component that\ntriggered the event, while subclasses of gr.EventData contains additional\nattributes that are different for each class. \n\n", "heading1": "Description", "source_page_url": "https://gradio.app/docs/gradio/eventdata", "source_page_title": "Gradio - Eventdata 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(value, evt: gr.EventData):\n return f\"The {evt.target} component was selected, and its value was {value}.\"\n \n table.select(on_select, table, statement)\n gallery.select(on_select, gallery, statement)\n textbox.select(on_select, textbox, statement)\n \n demo.launch()\n\n", "heading1": "Example Usage", "source_page_url": "https://gradio.app/docs/gradio/eventdata", "source_page_title": "Gradio - Eventdata Docs"}, {"text": "Parameters \u25bc\n\n\n \n \n target: Block | None\n\nThe component object that triggered the event. Can be used to distinguish\nmultiple components bound to the same listener.\n\n", "heading1": "Attributes", "source_page_url": "https://gradio.app/docs/gradio/eventdata", "source_page_title": "Gradio - Eventdata Docs"}, {"text": "gallery_selectionstictactoe\n\n[Blocks And Event Listeners](../../guides/blocks-and-event-listeners/)\n\n", "heading1": "Demos", "source_page_url": "https://gradio.app/docs/gradio/eventdata", "source_page_title": "Gradio - Eventdata Docs"}, {"text": "Creates a component allows users to upload or view 3D Model files (.obj,\n.glb, .stl, .gltf, .splat, or .ply). \n\n", "heading1": "Description", "source_page_url": "https://gradio.app/docs/gradio/model3d", "source_page_title": "Gradio - Model3D Docs"}, {"text": "**Using Model3D as an input component.**\n\nHow Model3D will pass its value to your function:\n\nType: `str | None`\n\nPasses the uploaded file as a `str` filepath to the function.\n\nExample Code\n\n \n \n \n import gradio as gr\n \n def predict(\n value: str | None\n ):\n process value from the Model3D component\n return \"prediction\"\n \n interface = gr.Interface(predict, gr.Model3D(), gr.Textbox())\n interface.launch()\n \n \n\n \n\n**Using Model3D as an output component**\n\nHow Model3D expects you to return a value:\n\nType: `str | Path | None`\n\nExpects function to return a `str` or `pathlib.Path` filepath of type (.obj,\n.glb, .stl, or .gltf)\n\nExample Code\n\n \n \n \n import gradio as gr\n \n def predict(text) -> str | Path | None\n process value to return to the Model3D component\n return value\n \n interface = gr.Interface(predict, gr.Textbox(), gr.Model3D())\n interface.launch()\n \n \n\n", "heading1": "Behavior", "source_page_url": "https://gradio.app/docs/gradio/model3d", "source_page_title": "Gradio - Model3D Docs"}, {"text": "Parameters \u25bc\n\n\n \n \n value: str | Callable | None\n\ndefault `= None`\n\npath to (.obj, .glb, .stl, .gltf, .splat, or .ply) file to show in model3D\nviewer. If a function is provided, the function will be called each time the\napp loads to set the initial value of this component.\n\n\n \n \n display_mode: Literal['solid', 'point_cloud', 'wireframe'] | None\n\ndefault `= None`\n\nthe display mode of the 3D model in the scene. Can be \"solid\" (which renders\nthe model as a solid object), \"point_cloud\", or \"wireframe\". For .splat, or\n.ply files, this parameter is ignored, as those files can only be rendered as\nsolid objects.\n\n\n \n \n clear_color: tuple[float, float, float, float] | None\n\ndefault `= None`\n\nbackground color of scene, should be a tuple of 4 floats between 0 and 1\nrepresenting RGBA values.\n\n\n \n \n camera_position: tuple[int | float | None, int | float | None, int | float | None]\n\ndefault `= (None, None, None)`\n\ninitial camera position of scene, provided as a tuple of `(alpha, beta,\nradius)`. Each value is optional. If provided, `alpha` and `beta` should be in\ndegrees reflecting the angular position along the longitudinal and latitudinal\naxes, respectively. Radius corresponds to the distance from the center of the\nobject to the camera.\n\n\n \n \n zoom_speed: float\n\ndefault `= 1`\n\nthe speed of zooming in and out of the scene when the cursor wheel is rotated\nor when screen is pinched on a mobile device. Should be a positive float,\nincrease this value to make zooming faster, decrease to make it slower.\nAffects the wheelPrecision property of the camera.\n\n\n \n \n pan_speed: float\n\ndefault `= 1`\n\nthe speed of panning the scene when the cursor is dragged or when the screen\nis dragged on a mobile device. Should be a positive float, increase this value\nto make panning faster, decrease to make it slower. Affects the panSensibility\nproperty of the camera.\n\n\n \n \n height: int | str | None\n\ndefault `= None`\n\nThe height of the model3D c", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/model3d", "source_page_title": "Gradio - Model3D Docs"}, {"text": "his value\nto make panning faster, decrease to make it slower. Affects the panSensibility\nproperty of the camera.\n\n\n \n \n height: int | str | None\n\ndefault `= None`\n\nThe height of the model3D component, specified in pixels if a number is\npassed, or in CSS units if a string is passed.\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 show_label: bool | None\n\ndefault `= None`\n\nif True, will display label.\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 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 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\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 |", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/model3d", "source_page_title": "Gradio - Model3D Docs"}, {"text": "reen 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 a file; if False, can only be used to\ndisplay files. 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\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\n \n \n buttons: list[Button] | None\n\ndefault `= None`\n\nA list of gr.Button() instances to", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/model3d", "source_page_title": "Gradio - Model3D Docs"}, {"text": "he user or an event listener) instead of re-rendered based on the values\nprovided during constructor.\n\n\n \n \n buttons: list[Button] | None\n\ndefault `= None`\n\nA list of gr.Button() instances to show in the top right corner of the\ncomponent. Custom buttons will appear in the toolbar with their configured\nicon and/or label, and clicking them will trigger any .click() events\nregistered on the button.\n\n", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/model3d", "source_page_title": "Gradio - Model3D Docs"}, {"text": "Shortcuts\n\n \n \n gradio.Model3D\n\nInterface String Shortcut `\"model3d\"`\n\nInitialization Uses default values\n\n", "heading1": "Shortcuts", "source_page_url": "https://gradio.app/docs/gradio/model3d", "source_page_title": "Gradio - Model3D 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 Model3D 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 Model3D.change(fn, \u00b7\u00b7\u00b7)\n\nTriggered when the value of the Model3D 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 Model3D.upload(fn, \u00b7\u00b7\u00b7)\n\nThis listener is triggered when the user uploads a file into the Model3D.\n\n \n \n Model3D.edit(fn, \u00b7\u00b7\u00b7)\n\nThis listener is triggered when the user edits the Model3D (e.g. image) using\nthe built-in editor.\n\n \n \n Model3D.clear(fn, \u00b7\u00b7\u00b7)\n\nThis listener is triggered when the user clears the Model3D using the clear\nbutton for the component.\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", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/model3d", "source_page_title": "Gradio - Model3D Docs"}, {"text": "tion 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 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, t", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/model3d", "source_page_title": "Gradio - Model3D Docs"}, {"text": "d.\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\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 | ", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/model3d", "source_page_title": "Gradio - Model3D Docs"}, {"text": "ubmissions 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 the Gradio client libraries), or \"undocumented\" (hidden\nfrom API docs but callable by clients and via gr.load). If fn is None,\napi_visibility will automatically 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 pr", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/model3d", "source_page_title": "Gradio - Model3D Docs"}, {"text": "ies 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[How To Use 3D Model Component](../../guides/how-to-use-3D-model-component/)\n\n", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/model3d", "source_page_title": "Gradio - Model3D Docs"}, {"text": "Creates a plot component to display various kinds of plots (matplotlib,\nplotly, altair, or bokeh plots are supported). As this component does not\naccept user input, it is rarely used as an input component. \n\n", "heading1": "Description", "source_page_url": "https://gradio.app/docs/gradio/plot", "source_page_title": "Gradio - Plot Docs"}, {"text": "**Using Plot as an input component.**\n\nHow Plot will pass its value to your function:\n\nType: `PlotData | None`\n\n(Rarely used) passes the data displayed in the plot as an PlotData dataclass,\nwhich includes the plot information as a JSON string, as well as the type of\nchart and the plotting library.\n\nExample Code\n\n \n \n \n import gradio as gr\n \n def predict(\n value: PlotData | None\n ):\n process value from the Plot component\n return \"prediction\"\n \n interface = gr.Interface(predict, gr.Plot(), gr.Textbox())\n interface.launch()\n \n \n\n \n\n**Using Plot as an output component**\n\nHow Plot expects you to return a value:\n\nType: `Any`\n\nExpects plot data in one of these formats: a matplotlib.Figure, bokeh.Model,\nplotly.Figure, or altair.Chart object.\n\nExample Code\n\n \n \n \n import gradio as gr\n \n def predict(text) -> Any\n process value to return to the Plot component\n return value\n \n interface = gr.Interface(predict, gr.Textbox(), gr.Plot())\n interface.launch()\n \n \n\n", "heading1": "Behavior", "source_page_url": "https://gradio.app/docs/gradio/plot", "source_page_title": "Gradio - Plot Docs"}, {"text": "Parameters \u25bc\n\n\n \n \n value: Any | None\n\ndefault `= None`\n\nOptionally, supply a default plot object to display, must be a matplotlib,\nplotly, altair, or bokeh figure, or a callable. If a function is provided, the\nfunction will be called each time the app loads to set the initial value of\nthis component.\n\n\n \n \n format: str\n\ndefault `= \"webp\"`\n\nFile format in which to send matplotlib plots to the front end, such as 'jpg'\nor 'png'.\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.\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 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\n\ndefault `= 160`\n\nminimum pixel width, will wrap if not sufficient screen space to satisfy this\nvalue. If a cert", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/plot", "source_page_title": "Gradio - Plot Docs"}, {"text": "o top-level Components\nin Blocks where fill_height=True.\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 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 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\n \n \n buttons: list[Button] | None\n\ndefault `= None`\n\nA list of gr.Button() instances to show in the top right corner of the\ncomponent. Custom buttons will appear in the toolba", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/plot", "source_page_title": "Gradio - Plot Docs"}, {"text": " constructor.\n\n\n \n \n buttons: list[Button] | None\n\ndefault `= None`\n\nA list of gr.Button() instances to show in the top right corner of the\ncomponent. Custom buttons will appear in the toolbar with their configured\nicon and/or label, and clicking them will trigger any .click() events\nregistered on the button.\n\n", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/plot", "source_page_title": "Gradio - Plot Docs"}, {"text": "Shortcuts\n\n \n \n gradio.Plot\n\nInterface String Shortcut `\"plot\"`\n\nInitialization Uses default values\n\n", "heading1": "Shortcuts", "source_page_url": "https://gradio.app/docs/gradio/plot", "source_page_title": "Gradio - Plot Docs"}, {"text": "blocks_kinematicsstock_forecast\n\n", "heading1": "Demos", "source_page_url": "https://gradio.app/docs/gradio/plot", "source_page_title": "Gradio - Plot 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 Plot 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 Plot.change(fn, \u00b7\u00b7\u00b7)\n\nTriggered when the value of the Plot 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\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", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/plot", "source_page_title": "Gradio - Plot Docs"}, {"text": "PI 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 (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:", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/plot", "source_page_title": "Gradio - Plot Docs"}, {"text": "he 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: int | None | Literal['default']\n\ndefault `= \"default\"`\n\nIf set, this is the maximum number of this event that can be running\nsimultaneously. Can ", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/plot", "source_page_title": "Gradio - Plot Docs"}, {"text": " 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 the Gradio client libraries), or \"undocumented\" (hidden\nfrom API docs but callable by clients and via gr.load). If fn is None,\napi_visibility will automatically 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[Plot Component For Maps](../../guides/plot-component-for-maps/)\n\n", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/plot", "source_page_title": "Gradio - Plot Docs"}, {"text": "ould return a\n`gr.validate()` for each input value.\n\n[Plot Component For Maps](../../guides/plot-component-for-maps/)\n\n", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/plot", "source_page_title": "Gradio - Plot Docs"}, {"text": "Server is the Gradio API engine exposed on a FastAPI application (Server\nmode). It inherits from FastAPI, so all standard FastAPI methods (.get(),\n.post(), .add_middleware(), .include_router(), etc.) work directly on this\ninstance. \nNew methods added on top of FastAPI: api(): Decorator to register a Gradio API\nendpoint with queue, SSE streaming, and concurrency control. mcp: Namespace\nwith .tool(), .resource(), and .prompt() decorators to tag functions with MCP\nmetadata. launch(): Creates an internal Blocks, registers deferred API\nendpoints, and starts the server. \n\n", "heading1": "Description", "source_page_url": "https://gradio.app/docs/gradio/server", "source_page_title": "Gradio - Server Docs"}, {"text": "from gradio import Server\n \n app = Server()\n \n @app.api(name=\"hello\")\n def hello(name: str) -> str:\n return f\"Hello {name}\"\n \n @app.get(\"/\")\n def root():\n return {\"message\": \"Hello World\"}\n \n app.launch()\n\n", "heading1": "Example Usage", "source_page_url": "https://gradio.app/docs/gradio/server", "source_page_title": "Gradio - Server Docs"}, {"text": "Parameters \u25bc\n\n\n \n \n debug: bool\n\ndefault `= False`\n\nEnable debug mode for detailed error tracebacks.\n\n\n \n \n title: str\n\ndefault `= \"FastAPI\"`\n\nThe title of the API, shown in the OpenAPI docs.\n\n\n \n \n summary: str | None\n\ndefault `= None`\n\nA short summary of the API.\n\n\n \n \n description: str\n\ndefault `= \"\"`\n\nA longer description of the API. Supports Markdown.\n\n\n \n \n version: str\n\ndefault `= \"0.1.0\"`\n\nThe version of the API.\n\n\n \n \n openapi_url: str | None\n\ndefault `= \"/openapi.json\"`\n\nThe URL path for the OpenAPI schema. Set to None to disable.\n\n\n \n \n openapi_tags: list[dict[str, Any]] | None\n\ndefault `= None`\n\nTags for organizing endpoints in the OpenAPI docs.\n\n\n \n \n servers: list[dict[str, Any]] | None\n\ndefault `= None`\n\nServer URLs for the OpenAPI schema.\n\n\n \n \n dependencies: Any\n\ndefault `= None`\n\nGlobal dependencies applied to all routes.\n\n\n \n \n default_response_class: Any\n\ndefault `= None`\n\nThe default response class for routes.\n\n\n \n \n redirect_slashes: bool\n\ndefault `= True`\n\nWhether to redirect trailing slashes.\n\n\n \n \n docs_url: str | None\n\ndefault `= \"/docs\"`\n\nThe URL path for the Swagger UI docs. Set to None to disable.\n\n\n \n \n redoc_url: str | None\n\ndefault `= \"/redoc\"`\n\nThe URL path for the ReDoc docs. Set to None to disable.\n\n\n \n \n middleware: Any\n\ndefault `= None`\n\nList of middleware to add to the server.\n\n\n \n \n exception_handlers: Any\n\ndefault `= None`\n\nCustom exception handlers.\n\n\n \n \n on_startup: Any\n\ndefault `= None`\n\nList of startup event handlers. Prefer lifespan instead.\n\n\n \n \n on_shutdown: Any\n\ndefault `= None`\n\nList of shutdown event handlers. Prefer lifespan instead.\n\n\n \n \n lifespan: Any\n\ndefault `= None`\n\nAn async context manager for startup/shutdown lifecycle.\n\n\n \n \n terms_of_service: str | None\n\ndefault `= None`\n\nURL to the terms of service.\n\n\n \n \n contact: dict[str, ", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/server", "source_page_title": "Gradio - Server Docs"}, {"text": "ault `= None`\n\nAn async context manager for startup/shutdown lifecycle.\n\n\n \n \n terms_of_service: str | None\n\ndefault `= None`\n\nURL to the terms of service.\n\n\n \n \n contact: dict[str, Any] | None\n\ndefault `= None`\n\nContact information dict for the API.\n\n\n \n \n license_info: dict[str, Any] | None\n\ndefault `= None`\n\nLicense information dict for the API.\n\n\n \n \n root_path: str\n\ndefault `= \"\"`\n\nA path prefix for the app when behind a proxy.\n\n\n \n \n root_path_in_servers: bool\n\ndefault `= True`\n\nWhether to include root_path in the OpenAPI servers field.\n\n\n \n \n responses: dict[int | str, dict[str, Any]] | None\n\ndefault `= None`\n\nAdditional responses for the OpenAPI schema.\n\n\n \n \n callbacks: Any\n\ndefault `= None`\n\nOpenAPI callback definitions.\n\n\n \n \n webhooks: Any\n\ndefault `= None`\n\nOpenAPI webhook definitions.\n\n\n \n \n deprecated: bool | None\n\ndefault `= None`\n\nMark all routes as deprecated.\n\n\n \n \n include_in_schema: bool\n\ndefault `= True`\n\nWhether to include all routes in the OpenAPI schema.\n\n\n \n \n generate_unique_id_function: Any\n\ndefault `= None`\n\nCustom function to generate unique operation IDs.\n\n\n \n \n separate_input_output_schemas: bool\n\ndefault `= True`\n\nWhether to generate separate input/output schemas.\n\n\n \n \n extra: Any\n\n", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/server", "source_page_title": "Gradio - Server Docs"}, {"text": "server_app\n\n", "heading1": "Demos", "source_page_url": "https://gradio.app/docs/gradio/server", "source_page_title": "Gradio - Server Docs"}, {"text": "", "heading1": "Methods", "source_page_url": "https://gradio.app/docs/gradio/server", "source_page_title": "Gradio - Server 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.Server.api(\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": "api", "source_page_url": "https://gradio.app/docs/gradio/server", "source_page_title": "Gradio - Server 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\nDecorator to register a function as a Gradio API endpoint.
Goes through\nGradio's queue with concurrency control and SSE streaming.\n\nParameters \u25bc\n\n\n \n \n fn: Callable | None\n\ndefault `= None`\n\n\n \n \n name: str | None\n\ndefault `= None`\n\n\n \n \n description: str | None\n\ndefault `= None`\n\n\n \n \n concurrency_limit: int | None | Literal['default']\n\ndefault `= \"default\"`\n\n\n \n \n concurrency_id: str | None\n\ndefault `= None`\n\n\n \n \n queue: bool\n\ndefault `= Tru", "heading1": "api", "source_page_url": "https://gradio.app/docs/gradio/server", "source_page_title": "Gradio - Server Docs"}, {"text": "None`\n\n\n \n \n concurrency_limit: int | None | Literal['default']\n\ndefault `= \"default\"`\n\n\n \n \n concurrency_id: str | None\n\ndefault `= None`\n\n\n \n \n queue: bool\n\ndefault `= True`\n\n\n \n \n batch: bool\n\ndefault `= False`\n\n\n \n \n max_batch_size: int\n\ndefault `= 4`\n\n\n \n \n api_visibility: Literal['public', 'private', 'undocumented']\n\ndefault `= \"public\"`\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", "heading1": "api", "source_page_url": "https://gradio.app/docs/gradio/server", "source_page_title": "Gradio - Server 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.Server.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/server", "source_page_title": "Gradio - Server 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\nLaunch the Gradio API server (Server mode).
Parameters match\n``Blocks.launch()``; see that method for full descriptions.
\n\nParameters \u25bc\n\n\n \n \n inline: bool | None\n\ndefault `= None`\n\n\n \n \n inbrowser: bool\n\ndefault `= False`\n\n\n \n \n share: bool | None\n\ndefault `= None`\n\n\n \n \n debug: bool\n\ndefault `= False`\n\n\n \n \n max_threads: int\n\ndefault `= 40`\n\n\n \n \n auth: Callable[[str, str], bool] | tuple[str, str] | list[tuple[str, str]] | None\n\ndefaul", "heading1": "launch", "source_page_url": "https://gradio.app/docs/gradio/server", "source_page_title": "Gradio - Server Docs"}, {"text": "\n \n \n debug: bool\n\ndefault `= False`\n\n\n \n \n max_threads: int\n\ndefault `= 40`\n\n\n \n \n auth: Callable[[str, str], bool] | tuple[str, str] | list[tuple[str, str]] | None\n\ndefault `= None`\n\n\n \n \n auth_message: str | None\n\ndefault `= None`\n\n\n \n \n prevent_thread_lock: bool\n\ndefault `= False`\n\n\n \n \n show_error: bool\n\ndefault `= False`\n\n\n \n \n server_name: str | None\n\ndefault `= None`\n\n\n \n \n server_port: int | None\n\ndefault `= None`\n\n\n \n \n height: int\n\ndefault `= 500`\n\n\n \n \n width: int | str\n\ndefault `= \"100%\"`\n\n\n \n \n favicon_path: str | Path | None\n\ndefault `= None`\n\n\n \n \n ssl_keyfile: str | None\n\ndefault `= None`\n\n\n \n \n ssl_certfile: str | None\n\ndefault `= None`\n\n\n \n \n ssl_keyfile_password: str | None\n\ndefault `= None`\n\n\n \n \n ssl_verify: bool\n\ndefault `= True`\n\n\n \n \n quiet: bool\n\ndefault `= False`\n\n\n \n \n footer_links: list[Literal['api', 'gradio', 'settings'] | dict[str, str]] | None\n\ndefault `= None`\n\n\n \n \n allowed_paths: list[str] | None\n\ndefault `= None`\n\n\n \n \n blocked_paths: list[str] | None\n\ndefault `= None`\n\n\n \n \n root_path: str | None\n\ndefault `= None`\n\n\n \n \n app_kwargs: dict[str, Any] | None\n\ndefault `= None`\n\n\n \n \n state_session_capacity: int\n\ndefault `= 10000`\n\n\n \n \n share_server_address: str | None\n\ndefault `= None`\n\n\n \n \n share_server_protocol: Literal['http', 'https'] | None\n\ndefault `= None`\n\n\n \n \n share_server_tls_certificate: str | None\n\ndefault `= None`\n\n\n \n \n auth_dependency: Callable[[fastapi.Request], str | None] | None\n\ndefault `= None`\n\n\n \n \n max_file_size: str | int | None\n\ndefault `= None`\n\n\n \n \n enable_monitoring: bool | None\n\ndefault `= None`\n\n\n \n \n strict_cors: bool\n\ndefault `= True`\n\n\n \n \n node_server_name: str | None\n\ndefault `= None`\n\n\n \n \n node_port: int | None\n\ndefault", "heading1": "launch", "source_page_url": "https://gradio.app/docs/gradio/server", "source_page_title": "Gradio - Server Docs"}, {"text": "itoring: bool | None\n\ndefault `= None`\n\n\n \n \n strict_cors: bool\n\ndefault `= True`\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\n\n \n \n pwa: bool | None\n\ndefault `= None`\n\n\n \n \n mcp_server: bool | None\n\ndefault `= None`\n\n\n \n \n i18n: I18n | None\n\ndefault `= None`\n\n\n \n \n theme: Theme | str | None\n\ndefault `= None`\n\n\n \n \n css: str | None\n\ndefault `= None`\n\n\n \n \n css_paths: str | Path | list[str | Path] | None\n\ndefault `= None`\n\n\n \n \n js: str | Literal[True] | None\n\ndefault `= None`\n\n\n \n \n head: str | None\n\ndefault `= None`\n\n\n \n \n head_paths: str | Path | list[str | Path] | None\n\ndefault `= None`\n\n\n \n \n num_workers: int | None\n\ndefault `= None`\n\n[Server Mode](../../guides/server-mode/)\n\n", "heading1": "launch", "source_page_url": "https://gradio.app/docs/gradio/server", "source_page_title": "Gradio - Server 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.Server.api(\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": "api", "source_page_url": "https://gradio.app/docs/gradio/server", "source_page_title": "Gradio - Server 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\nDecorator to register a function as a Gradio API endpoint.
Goes through\nGradio's queue with concurrency control and SSE streaming.\n\nParameters \u25bc\n\n\n \n \n fn: Callable | None\n\ndefault `= None`\n\n\n \n \n name: str | None\n\ndefault `= None`\n\n\n \n \n description: str | None\n\ndefault `= None`\n\n\n \n \n concurrency_limit: int | None | Literal['default']\n\ndefault `= \"default\"`\n\n\n \n \n concurrency_id: str | None\n\ndefault `= None`\n\n\n \n \n queue: bool\n\ndefault `= Tru", "heading1": "api", "source_page_url": "https://gradio.app/docs/gradio/server", "source_page_title": "Gradio - Server Docs"}, {"text": "None`\n\n\n \n \n concurrency_limit: int | None | Literal['default']\n\ndefault `= \"default\"`\n\n\n \n \n concurrency_id: str | None\n\ndefault `= None`\n\n\n \n \n queue: bool\n\ndefault `= True`\n\n\n \n \n batch: bool\n\ndefault `= False`\n\n\n \n \n max_batch_size: int\n\ndefault `= 4`\n\n\n \n \n api_visibility: Literal['public', 'private', 'undocumented']\n\ndefault `= \"public\"`\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", "heading1": "api", "source_page_url": "https://gradio.app/docs/gradio/server", "source_page_title": "Gradio - Server 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.Server.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/server", "source_page_title": "Gradio - Server 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\nLaunch the Gradio API server (Server mode).
Parameters match\n``Blocks.launch()``; see that method for full descriptions.
\n\nParameters \u25bc\n\n\n \n \n inline: bool | None\n\ndefault `= None`\n\n\n \n \n inbrowser: bool\n\ndefault `= False`\n\n\n \n \n share: bool | None\n\ndefault `= None`\n\n\n \n \n debug: bool\n\ndefault `= False`\n\n\n \n \n max_threads: int\n\ndefault `= 40`\n\n\n \n \n auth: Callable[[str, str], bool] | tuple[str, str] | list[tuple[str, str]] | None\n\ndefaul", "heading1": "launch", "source_page_url": "https://gradio.app/docs/gradio/server", "source_page_title": "Gradio - Server Docs"}, {"text": "\n \n \n debug: bool\n\ndefault `= False`\n\n\n \n \n max_threads: int\n\ndefault `= 40`\n\n\n \n \n auth: Callable[[str, str], bool] | tuple[str, str] | list[tuple[str, str]] | None\n\ndefault `= None`\n\n\n \n \n auth_message: str | None\n\ndefault `= None`\n\n\n \n \n prevent_thread_lock: bool\n\ndefault `= False`\n\n\n \n \n show_error: bool\n\ndefault `= False`\n\n\n \n \n server_name: str | None\n\ndefault `= None`\n\n\n \n \n server_port: int | None\n\ndefault `= None`\n\n\n \n \n height: int\n\ndefault `= 500`\n\n\n \n \n width: int | str\n\ndefault `= \"100%\"`\n\n\n \n \n favicon_path: str | Path | None\n\ndefault `= None`\n\n\n \n \n ssl_keyfile: str | None\n\ndefault `= None`\n\n\n \n \n ssl_certfile: str | None\n\ndefault `= None`\n\n\n \n \n ssl_keyfile_password: str | None\n\ndefault `= None`\n\n\n \n \n ssl_verify: bool\n\ndefault `= True`\n\n\n \n \n quiet: bool\n\ndefault `= False`\n\n\n \n \n footer_links: list[Literal['api', 'gradio', 'settings'] | dict[str, str]] | None\n\ndefault `= None`\n\n\n \n \n allowed_paths: list[str] | None\n\ndefault `= None`\n\n\n \n \n blocked_paths: list[str] | None\n\ndefault `= None`\n\n\n \n \n root_path: str | None\n\ndefault `= None`\n\n\n \n \n app_kwargs: dict[str, Any] | None\n\ndefault `= None`\n\n\n \n \n state_session_capacity: int\n\ndefault `= 10000`\n\n\n \n \n share_server_address: str | None\n\ndefault `= None`\n\n\n \n \n share_server_protocol: Literal['http', 'https'] | None\n\ndefault `= None`\n\n\n \n \n share_server_tls_certificate: str | None\n\ndefault `= None`\n\n\n \n \n auth_dependency: Callable[[fastapi.Request], str | None] | None\n\ndefault `= None`\n\n\n \n \n max_file_size: str | int | None\n\ndefault `= None`\n\n\n \n \n enable_monitoring: bool | None\n\ndefault `= None`\n\n\n \n \n strict_cors: bool\n\ndefault `= True`\n\n\n \n \n node_server_name: str | None\n\ndefault `= None`\n\n\n \n \n node_port: int | None\n\ndefault", "heading1": "launch", "source_page_url": "https://gradio.app/docs/gradio/server", "source_page_title": "Gradio - Server Docs"}, {"text": "itoring: bool | None\n\ndefault `= None`\n\n\n \n \n strict_cors: bool\n\ndefault `= True`\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\n\n \n \n pwa: bool | None\n\ndefault `= None`\n\n\n \n \n mcp_server: bool | None\n\ndefault `= None`\n\n\n \n \n i18n: I18n | None\n\ndefault `= None`\n\n\n \n \n theme: Theme | str | None\n\ndefault `= None`\n\n\n \n \n css: str | None\n\ndefault `= None`\n\n\n \n \n css_paths: str | Path | list[str | Path] | None\n\ndefault `= None`\n\n\n \n \n js: str | Literal[True] | None\n\ndefault `= None`\n\n\n \n \n head: str | None\n\ndefault `= None`\n\n\n \n \n head_paths: str | Path | list[str | Path] | None\n\ndefault `= None`\n\n\n \n \n num_workers: int | None\n\ndefault `= None`\n\n", "heading1": "launch", "source_page_url": "https://gradio.app/docs/gradio/server", "source_page_title": "Gradio - Server Docs"}, {"text": "Creates an image component that can be used to upload images (as an input)\nor display images (as an output).\n\n", "heading1": "Description", "source_page_url": "https://gradio.app/docs/gradio/simpleimage", "source_page_title": "Gradio - Simpleimage Docs"}, {"text": "**Using SimpleImage as an input component.**\n\nHow SimpleImage will pass its value to your function:\n\nType: `str | None`\n\nA `str` containing the path to the image.\n\nExample Code\n\n \n \n \n import gradio as gr\n \n def predict(\n value: str | None\n ):\n process value from the SimpleImage component\n return \"prediction\"\n \n interface = gr.Interface(predict, gr.SimpleImage(), gr.Textbox())\n interface.launch()\n \n \n\n \n\n**Using SimpleImage as an output component**\n\nHow SimpleImage expects you to return a value:\n\nType: `str | Path | None`\n\nExpects a `str` or `pathlib.Path` object containing the path to the image.\n\nExample Code\n\n \n \n \n import gradio as gr\n \n def predict(text) -> str | Path | None\n process value to return to the SimpleImage component\n return value\n \n interface = gr.Interface(predict, gr.Textbox(), gr.SimpleImage())\n interface.launch()\n \n \n\n", "heading1": "Behavior", "source_page_url": "https://gradio.app/docs/gradio/simpleimage", "source_page_title": "Gradio - Simpleimage Docs"}, {"text": "Parameters \u25bc\n\n\n \n \n value: str | None\n\ndefault `= None`\n\nA path or URL for the default value that SimpleImage component is going to\ntake. If a function is provided, the function will be called each time the app\nloads to set the initial value of this component.\n\n\n \n \n label: str | I18nData | None\n\ndefault `= None`\n\nthe label for this component, displayed above the component if `show_label` is\n`True` and is also used as the header if there are a table of examples for\nthis component. If None and used in a `gr.Interface`, the label will be the\nname of the parameter this component corresponds 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.\n\n\n \n \n show_label: bool | None\n\ndefault `= None`\n\nif True, will display label.\n\n\n \n \n show_download_button: bool\n\ndefault `= True`\n\nIf True, will display button to download image.\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 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\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", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/simpleimage", "source_page_title": "Gradio - Simpleimage Docs"}, {"text": "ll_height=True.\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 image; if False, can only be\nused to display images. 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\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", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/simpleimage", "source_page_title": "Gradio - Simpleimage Docs"}, {"text": " 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/simpleimage", "source_page_title": "Gradio - Simpleimage Docs"}, {"text": "Shortcuts\n\n \n \n gradio.SimpleImage\n\nInterface String Shortcut `\"simpleimage\"`\n\nInitialization Uses default values\n\n", "heading1": "Shortcuts", "source_page_url": "https://gradio.app/docs/gradio/simpleimage", "source_page_title": "Gradio - Simpleimage 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 SimpleImage 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 SimpleImage.clear(fn, \u00b7\u00b7\u00b7)\n\nThis listener is triggered when the user clears the SimpleImage using the\nclear button for the component.\n\n \n \n SimpleImage.change(fn, \u00b7\u00b7\u00b7)\n\nTriggered when the value of the SimpleImage 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 SimpleImage.upload(fn, \u00b7\u00b7\u00b7)\n\nThis listener is triggered when the user uploads a file into the SimpleImage.\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 ", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/simpleimage", "source_page_title": "Gradio - Simpleimage Docs"}, {"text": "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 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 e", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/simpleimage", "source_page_title": "Gradio - Simpleimage Docs"}, {"text": "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\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 argumen", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/simpleimage", "source_page_title": "Gradio - Simpleimage Docs"}, {"text": "d 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 the Gradio client libraries), or \"undocumented\" (hidden\nfrom API docs but callable by clients and via gr.load). If fn is None,\napi_visibility will automatically 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", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/simpleimage", "source_page_title": "Gradio - Simpleimage Docs"}, {"text": "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/simpleimage", "source_page_title": "Gradio - Simpleimage Docs"}, {"text": "Load a chat interface from an OpenAI API chat compatible endpoint.\n\n", "heading1": "Description", "source_page_url": "https://gradio.app/docs/gradio/load_chat", "source_page_title": "Gradio - Load_Chat Docs"}, {"text": "import gradio as gr\n demo = gr.load_chat(\"http://localhost:11434/v1\", model=\"deepseek-r1\")\n demo.launch()\n\n", "heading1": "Example Usage", "source_page_url": "https://gradio.app/docs/gradio/load_chat", "source_page_title": "Gradio - Load_Chat Docs"}, {"text": "Parameters \u25bc\n\n\n \n \n base_url: str\n\nThe base URL of the endpoint, e.g. \"http://localhost:11434/v1/\"\n\n\n \n \n model: str\n\nThe name of the model you are loading, e.g. \"llama3.2\"\n\n\n \n \n token: str | None\n\ndefault `= None`\n\nThe API token or a placeholder string if you are using a local model, e.g.\n\"ollama\"\n\n\n \n \n file_types: Literal['text_encoded', 'image'] | list[Literal['text_encoded', 'image']] | None\n\ndefault `= \"text_encoded\"`\n\nThe file types allowed to be uploaded by the user. \"text_encoded\" allows\nuploading any text-encoded file (which is simply appended to the prompt), and\n\"image\" adds image upload support. Set to None to disable file uploads.\n\n\n \n \n system_message: str | None\n\ndefault `= None`\n\nThe system message to use for the conversation, if any.\n\n\n \n \n streaming: bool\n\ndefault `= True`\n\nWhether the response should be streamed.\n\n\n \n \n kwargs: \n\nAdditional keyword arguments to pass into ChatInterface for customization.\n\n[Creating a Chatbot Fast](../../guides/creating-a-chatbot-fast)\n\n", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/load_chat", "source_page_title": "Gradio - Load_Chat 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 the Gradio client libraries), or \"undocumented\" (hidden\nfrom API docs but callable by clients and via gr.load). If fn is None,\napi_visibility will automatically 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 ", "heading1": "expand", "source_page_url": "https://gradio.app/docs/gradio/sidebar", "source_page_title": "Gradio - Sidebar Docs"}, {"text": "oad). If fn is None,\napi_visibility will automatically 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 the Gradio client libraries), or \"undocumented\" (hidden\nfrom API docs but callable by clients and via gr.load). If fn is None,\napi_visibility will automatically 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 ", "heading1": "collapse", "source_page_url": "https://gradio.app/docs/gradio/sidebar", "source_page_title": "Gradio - Sidebar Docs"}, {"text": "r.load). If fn is None,\napi_visibility will automatically 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 the Gradio client libraries), or \"undocumented\" (hidden\nfrom API docs but callable by clients and via gr.load). If fn is None,\napi_visibility will automatically 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 ", "heading1": "expand", "source_page_url": "https://gradio.app/docs/gradio/sidebar", "source_page_title": "Gradio - Sidebar Docs"}, {"text": "oad). If fn is None,\napi_visibility will automatically 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 the Gradio client libraries), or \"undocumented\" (hidden\nfrom API docs but callable by clients and via gr.load). If fn is None,\napi_visibility will automatically 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 ", "heading1": "collapse", "source_page_url": "https://gradio.app/docs/gradio/sidebar", "source_page_title": "Gradio - Sidebar Docs"}, {"text": "r.load). If fn is None,\napi_visibility will automatically 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": "A TabbedInterface is created by providing a list of Interfaces or Blocks,\neach of which gets rendered in a separate tab. Only the components from the\nInterface/Blocks will be rendered in the tab. \n\n", "heading1": "Description", "source_page_url": "https://gradio.app/docs/gradio/tabbedinterface", "source_page_title": "Gradio - Tabbedinterface Docs"}, {"text": "Parameters \u25bc\n\n\n \n \n interface_list: list[Blocks]\n\nA list of Interfaces (or Blocks) to be rendered in the tabs.\n\n\n \n \n tab_names: list[str] | None\n\ndefault `= None`\n\nA list of tab names. If None, the tab names will be \"Tab 1\", \"Tab 2\", etc.\n\n\n \n \n title: str | None\n\ndefault `= None`\n\nThe tab title to display when this demo is opened in a browser window.\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", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/tabbedinterface", "source_page_title": "Gradio - Tabbedinterface Docs"}, {"text": "tabbed_interface_lite\n\n", "heading1": "Demos", "source_page_url": "https://gradio.app/docs/gradio/tabbedinterface", "source_page_title": "Gradio - Tabbedinterface Docs"}, {"text": "Creates a Dialogue component for displaying or collecting multi-speaker\nconversations. This component can be used as input to allow users to enter\ndialogue involving multiple speakers, or as output to display diarized speech,\nsuch as the result of a transcription or speaker identification model. Each\nmessage can be associated with a specific speaker, making it suitable for use\ncases like conversations, interviews, or meetings. \n\n", "heading1": "Description", "source_page_url": "https://gradio.app/docs/gradio/dialogue", "source_page_title": "Gradio - Dialogue Docs"}, {"text": "**Using Dialogue as an input component.**\n\nHow Dialogue will pass its value to your function:\n\nType: `str | list[dict[str, str]]`\n\nReturns the dialogue as a string or list of dictionaries.\n\nExample Code\n\n \n \n \n import gradio as gr\n \n def predict(\n value: str | list[dict[str, str]]\n ):\n process value from the Dialogue component\n return \"prediction\"\n \n interface = gr.Interface(predict, gr.Dialogue(), gr.Textbox())\n interface.launch()\n \n \n\n \n\n**Using Dialogue as an output component**\n\nHow Dialogue expects you to return a value:\n\nType: `list[dict[str, str]] | str | None`\n\nExpects a string or a list of dictionaries of dialogue lines, where each\ndictionary contains 'speaker' and 'text' keys, or a string.\n\nExample Code\n\n \n \n \n import gradio as gr\n \n def predict(text) -> list[dict[str, str]] | str | None\n process value to return to the Dialogue component\n return value\n \n interface = gr.Interface(predict, gr.Textbox(), gr.Dialogue())\n interface.launch()\n \n \n\n", "heading1": "Behavior", "source_page_url": "https://gradio.app/docs/gradio/dialogue", "source_page_title": "Gradio - Dialogue Docs"}, {"text": "Parameters \u25bc\n\n\n \n \n value: list[dict[str, str]] | Callable | None\n\ndefault `= None`\n\nValue of the dialogue. It is a list of dictionaries, each containing a\n'speaker' key and a 'text' key. If a function is provided, the function will\nbe called each time the app loads to set the initial value of this component.\n\n\n \n \n type: Literal['list', 'text']\n\ndefault `= \"text\"`\n\nThe type of the component, either \"list\" for a multi-speaker dialogue\nconsisting of dictionaries with 'speaker' and 'text' keys or \"text\" for a\nsingle text input. Defaults to \"text\".\n\n\n \n \n speakers: list[str] | None\n\ndefault `= None`\n\nThe different speakers allowed in the dialogue. If `None` or an empty list, no\nspeakers will be displayed. Instead, the component will be a standard textarea\nthat optionally supports `tags` autocompletion.\n\n\n \n \n formatter: Callable | None\n\ndefault `= None`\n\nA function that formats the dialogue line dictionary, e.g. {\"speaker\":\n\"Speaker 1\", \"text\": \"Hello, how are you?\"} into a string, e.g. \"Speaker 1:\nHello, how are you?\". This function is run on user input and the resulting\nstring is passed into the prediction function.\n\n\n \n \n unformatter: Callable | None\n\ndefault `= None`\n\nA function that parses a formatted dialogue string back into a dialogue line\ndictionary. Should take a single string line and return a dictionary with\n'speaker' and 'text' keys. If not provided, the default unformatter will\nattempt to parse the default formatter pattern.\n\n\n \n \n tags: list[str] | None\n\ndefault `= None`\n\nThe different tags allowed in the dialogue. Tags are displayed in an\nautocomplete menu below the input textbox when the user starts typing `:`. Use\nthe exact tag name expected by the AI model or inference function.\n\n\n \n \n separator: str\n\ndefault `= \" \"`\n\nThe separator between the different dialogue lines used to join the formatted\ndialogue lines into a single string. It should be unambiguous. For example, a\nnewline character", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/dialogue", "source_page_title": "Gradio - Dialogue Docs"}, {"text": "tor: str\n\ndefault `= \" \"`\n\nThe separator between the different dialogue lines used to join the formatted\ndialogue lines into a single string. It should be unambiguous. For example, a\nnewline character or tab character.\n\n\n \n \n color_map: dict[str, str] | None\n\ndefault `= None`\n\nA dictionary mapping speaker names to colors. The colors may be specified as\nhex codes or by their names. For example: {\"Speaker 1\": \"red\", \"Speaker 2\":\n\"FFEE22\"}. If not provided, default colors will be assigned to speakers. This\nis only used if `interactive` is False.\n\n\n \n \n label: str | None\n\ndefault `= \"Dialogue\"`\n\nthe label for this component, displayed above the component if `show_label` is\n`True` and is also used as the header if there are a table of examples for\nthis component. If None and used in a `gr.Interface`, the label will be the\nname of the parameter this component corresponds to.\n\n\n \n \n info: str | None\n\ndefault `= \"Type colon (:) in the dialogue line to see the available tags\"`\n\n\n \n \n placeholder: str | None\n\ndefault `= None`\n\nplaceholder hint to provide behind textarea.\n\n\n \n \n show_label: bool | None\n\ndefault `= None`\n\nif True, will display the label. If False, the copy button is hidden as well\nas well as the 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 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\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 respec", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/dialogue", "source_page_title": "Gradio - Dialogue Docs"}, {"text": "um 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 be rendered as an editable textbox; if False, editing will be\ndisabled. If not provided, this is inferred based on whether the component is\nused 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\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 autofocus: bool\n\ndefault `= False`\n\nIf True, will focus on the textbox when the page loads. Use this carefully, as\nit can cause usability issues for sighted and non-sighted users.\n\n\n \n \n autoscroll: bool\n\ndefault `= True`\n\nIf True, will automatically scroll to the bottom of the textbox when the value\nchanges, unless the user scrolls up. If False, will not scroll to the bottom\nof the textbox when the value changes.\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 | None\n\ndefault `= None`\n\nif assigned, will be used to assume identity across a re-render. Components\nthat have the same key across a re-render will have their value preserved.\n\n\n \n \n max_lines: int | None\n\ndefault `= None`\n\nmaximum number of lines allo", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/dialogue", "source_page_title": "Gradio - Dialogue Docs"}, {"text": "identity across a re-render. Components\nthat have the same key across a re-render will have their value preserved.\n\n\n \n \n max_lines: int | None\n\ndefault `= None`\n\nmaximum number of lines allowed in the dialogue.\n\n\n \n \n buttons: list[Literal['copy'] | Button] | None\n\ndefault `= None`\n\nA list of buttons to show for the component. Valid options are \"copy\" or a\ngr.Button() instance. The \"copy\" button allows the user to copy the text in\nthe textbox. Custom gr.Button() instances will appear in the toolbar with\ntheir configured icon and/or label, and clicking them will trigger any\n.click() events registered on the button. By default, no buttons are shown.\n\n\n \n \n submit_btn: str | bool | None\n\ndefault `= False`\n\nIf False, will not show a submit button. If True, will show a submit button\nwith an icon. If a string, will use that string as the submit button text.\n\n\n \n \n ui_mode: Literal['dialogue', 'text', 'both']\n\ndefault `= \"both\"`\n\nDetermines the user interface mode of the component. Can be \"dialogue\"\n(displays dialogue lines), \"text\" (displays a single text input), or \"both\"\n(displays both dialogue lines and a text input). Defaults to \"both\".\n\n", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/dialogue", "source_page_title": "Gradio - Dialogue Docs"}, {"text": "Shortcuts\n\n \n \n gradio.Dialogue\n\nInterface String Shortcut `\"dialogue\"`\n\nInitialization Uses default values\n\n", "heading1": "Shortcuts", "source_page_url": "https://gradio.app/docs/gradio/dialogue", "source_page_title": "Gradio - Dialogue Docs"}, {"text": "dia_dialogue_demo\n\n", "heading1": "Demos", "source_page_url": "https://gradio.app/docs/gradio/dialogue", "source_page_title": "Gradio - Dialogue 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 Dialogue 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 Dialogue.change(fn, \u00b7\u00b7\u00b7)\n\nTriggered when the value of the Dialogue 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 Dialogue.input(fn, \u00b7\u00b7\u00b7)\n\nThis listener is triggered when the user changes the value of the Dialogue.\n\n \n \n Dialogue.submit(fn, \u00b7\u00b7\u00b7)\n\nThis listener is triggered when the user presses the Enter key while the\nDialogue is focused.\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 | No", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/dialogue", "source_page_title": "Gradio - Dialogue Docs"}, {"text": "et[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 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 shou", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/dialogue", "source_page_title": "Gradio - Dialogue Docs"}, {"text": "pp.\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\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 o", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/dialogue", "source_page_title": "Gradio - Dialogue Docs"}, {"text": "fter 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 the Gradio client libraries), or \"undocumented\" (hidden\nfrom API docs but callable by clients and via gr.load). If fn is None,\napi_visibility will automatically 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", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/dialogue", "source_page_title": "Gradio - Dialogue Docs"}, {"text": "nal 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/dialogue", "source_page_title": "Gradio - Dialogue Docs"}, {"text": "Creates a button that can be assigned arbitrary .click() events. The value\n(label) of the button can be used as an input to the function (rarely used) or\nset via the output of a function.\n\n", "heading1": "Description", "source_page_url": "https://gradio.app/docs/gradio/button", "source_page_title": "Gradio - Button Docs"}, {"text": "**Using Button as an input component.**\n\nHow Button will pass its value to your function:\n\nType: `str | None`\n\n(Rarely used) the `str` corresponding to the button label when the button is\nclicked\n\nExample Code\n\n \n \n \n import gradio as gr\n \n def predict(\n value: str | None\n ):\n process value from the Button component\n return \"prediction\"\n \n interface = gr.Interface(predict, gr.Button(), gr.Textbox())\n interface.launch()\n \n \n\n \n\n**Using Button as an output component**\n\nHow Button expects you to return a value:\n\nType: `str | None`\n\nstring corresponding to the button label\n\nExample Code\n\n \n \n \n import gradio as gr\n \n def predict(text) -> str | None\n process value to return to the Button component\n return value\n \n interface = gr.Interface(predict, gr.Textbox(), gr.Button())\n interface.launch()\n \n \n\n", "heading1": "Behavior", "source_page_url": "https://gradio.app/docs/gradio/button", "source_page_title": "Gradio - Button Docs"}, {"text": "Parameters \u25bc\n\n\n \n \n value: str | I18nData | Callable\n\ndefault `= \"Run\"`\n\ndefault text for the button to display. If a function is provided, the\nfunction will be called each time the app loads to set the initial value of\nthis component.\n\n\n \n \n every: Timer | float | None\n\ndefault `= None`\n\ncontinuously 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', 'huggingface']\n\ndefault `= \"secondary\"`\n\nsets the background and text color of the button. Use 'primary' for main call-\nto-action buttons, 'secondary' for a more subdued style, 'stop' for a stop\nbutton, 'huggingface' for a black background with white text, consistent with\nHugging Face's button styles.\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 | Path | 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 link: str | None\n\ndefault `= None`\n\nURL to open when the button is clicked. If None, no link will be used.\n\n\n \n \n link_target: Literal['_self', '_blank', '_parent', '_top']\n\ndefault `= \"_self\"`\n\ndetermines where to open the linked URL. \"_self\" (default, same tab), \"_blank\"\n(new tab), \"_parent\" (parent frame), \"_top\" (top frame).\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 in", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/button", "source_page_title": "Gradio - Button Docs"}, {"text": "iteral['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 interactive: bool\n\ndefault `= True`\n\nif False, the Button 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\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 sp", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/button", "source_page_title": "Gradio - Button Docs"}, {"text": "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 value results in this Component being narrower than\nmin_width, the min_width parameter will be respected first.\n\n", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/button", "source_page_title": "Gradio - Button Docs"}, {"text": "Shortcuts\n\n \n \n gradio.Button\n\nInterface String Shortcut `\"button\"`\n\nInitialization Uses default values\n\n \n \n gradio.ClearButton\n\nInterface String Shortcut `\"clearbutton\"`\n\nInitialization Uses default values\n\n \n \n gradio.DeepLinkButton\n\nInterface String Shortcut `\"deeplinkbutton\"`\n\nInitialization Uses default values\n\n \n \n gradio.DuplicateButton\n\nInterface String Shortcut `\"duplicatebutton\"`\n\nInitialization Uses default values\n\n \n \n gradio.LoginButton\n\nInterface String Shortcut `\"loginbutton\"`\n\nInitialization Uses default values\n\n", "heading1": "Shortcuts", "source_page_url": "https://gradio.app/docs/gradio/button", "source_page_title": "Gradio - Button 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 Button 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 Button.click(fn, \u00b7\u00b7\u00b7)\n\nTriggered when the Button 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 with the given\ndescription.", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/button", "source_page_title": "Gradio - Button Docs"}, {"text": " 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 preprocessing of component data be", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/button", "source_page_title": "Gradio - Button Docs"}, {"text": "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\n`Blocks.queue()`, which", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/button", "source_page_title": "Gradio - Button Docs"}, {"text": "y_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 the Gradio client libraries), or \"undocumented\" (hidden\nfrom API docs but callable by clients and via gr.load). If fn is None,\napi_visibility will automatically 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/button", "source_page_title": "Gradio - Button Docs"}, {"text": "A base class for defining methods that all input/output components should\nhave.\n\n", "heading1": "Description", "source_page_url": "https://gradio.app/docs/gradio/state", "source_page_title": "Gradio - State Docs"}, {"text": "**Using State as an input component.**\n\nHow State will pass its value to your function:\n\nType: `Any`\n\nPasses a value of arbitrary type through.\n\nExample Code\n\n \n \n \n import gradio as gr\n \n def predict(\n value: Any\n ):\n process value from the State component\n return \"prediction\"\n \n interface = gr.Interface(predict, gr.State(), gr.Textbox())\n interface.launch()\n \n \n\n \n\n**Using State as an output component**\n\nHow State expects you to return a value:\n\nType: `Any`\n\nExpects a value of arbitrary type, as long as it can be deepcopied.\n\nExample Code\n\n \n \n \n import gradio as gr\n \n def predict(text) -> Any\n process value to return to the State component\n return value\n \n interface = gr.Interface(predict, gr.Textbox(), gr.State())\n interface.launch()\n \n \n\n", "heading1": "Behavior", "source_page_url": "https://gradio.app/docs/gradio/state", "source_page_title": "Gradio - State Docs"}, {"text": "Parameters \u25bc\n\n\n \n \n value: Any\n\ndefault `= None`\n\nthe initial value (of arbitrary type) of the state. The provided argument is\ndeepcopied. If a callable is provided, the function will be called whenever\nthe app loads to set the initial value of the state.\n\n\n \n \n render: bool\n\ndefault `= True`\n\nshould always be True, is included for consistency with other components.\n\n\n \n \n time_to_live: int | float | None\n\ndefault `= None`\n\nthe number of seconds the state should be stored for after it is created or\nupdated. If None, the state will be stored indefinitely. Gradio automatically\ndeletes state variables after a user closes the browser tab or refreshes the\npage, so this is useful for clearing state for potentially long running\nsessions.\n\n\n \n \n delete_callback: Callable[[Any], None] | None\n\ndefault `= None`\n\na function that is called when the state is deleted. The function should take\nthe state value as an argument.\n\n", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/state", "source_page_title": "Gradio - State 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 State 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 State.change(fn, \u00b7\u00b7\u00b7)\n\nTriggered when the value of the State 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\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.", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/state", "source_page_title": "Gradio - State Docs"}, {"text": "e 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 (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_si", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/state", "source_page_title": "Gradio - State Docs"}, {"text": ". 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: int | None | Literal['default']\n\ndefault `= \"default\"`\n\nIf set, this is the maximum number of this event that can be running\nsimultaneously. C", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/state", "source_page_title": "Gradio - State Docs"}, {"text": "for 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 the Gradio client libraries), or \"undocumented\" (hidden\nfrom API docs but callable by clients and via gr.load). If fn is None,\napi_visibility will automatically 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/state", "source_page_title": "Gradio - State Docs"}, {"text": " should return a\n`gr.validate()` for each input value.\n\n", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/state", "source_page_title": "Gradio - State Docs"}, {"text": "Creates an image component that can be used to upload images (as an input)\nor display images (as an output). \n\n", "heading1": "Description", "source_page_url": "https://gradio.app/docs/gradio/imageslider", "source_page_title": "Gradio - Imageslider Docs"}, {"text": "**Using ImageSlider as an input component.**\n\nHow ImageSlider will pass its value to your function:\n\nType: `image_tuple | None`\n\nPasses the uploaded image as a tuple of `numpy.array`, `PIL.Image` or `str`\nfilepath depending on `type`.\n\nExample Code\n\n \n \n \n import gradio as gr\n \n def predict(\n value: image_tuple | None\n ):\n process value from the ImageSlider component\n return \"prediction\"\n \n interface = gr.Interface(predict, gr.ImageSlider(), gr.Textbox())\n interface.launch()\n \n \n\n \n\n**Using ImageSlider as an output component**\n\nHow ImageSlider expects you to return a value:\n\nType: `tuple[np.ndarray | PIL.Image.Image | str | Path | None, np.ndarray | PIL.Image.Image | str | Path | None] | None`\n\nExpects a tuple of `numpy.array`, `PIL.Image`, or `str` or `pathlib.Path`\nfilepath to an image which is displayed.\n\nExample Code\n\n \n \n \n import gradio as gr\n \n def predict(text) -> tuple[np.ndarray | PIL.Image.Image | str | Path | None, np.ndarray | PIL.Image.Image | str | Path | None] | None\n process value to return to the ImageSlider component\n return value\n \n interface = gr.Interface(predict, gr.Textbox(), gr.ImageSlider())\n interface.launch()\n \n \n\n", "heading1": "Behavior", "source_page_url": "https://gradio.app/docs/gradio/imageslider", "source_page_title": "Gradio - Imageslider Docs"}, {"text": "Parameters \u25bc\n\n\n \n \n value: image_tuple | Callable | None\n\ndefault `= None`\n\nA tuple of PIL Image, numpy array, path or URL for the default value that\nImageSlider component is going to take, this pair of images should be of equal\nsize. If a function is provided, the function will be called each time the app\nloads to set the initial value of this component.\n\n\n \n \n format: str\n\ndefault `= \"webp\"`\n\nFile format (e.g. \"png\" or \"gif\"). Used to save image if it does not already\nhave a valid format (e.g. if the image is being returned to the frontend as a\nnumpy array or PIL Image). The format should be supported by the PIL library.\nApplies both when this component is used as an input or output. This parameter\nhas no effect on SVG files.\n\n\n \n \n height: int | str | None\n\ndefault `= None`\n\nThe height of the component, specified in pixels if a number is passed, or in\nCSS units if a string is passed. This has no effect on the preprocessed tuple\nof image file or numpy array, but will affect the displayed image.\n\n\n \n \n width: int | str | None\n\ndefault `= None`\n\nThe width of the component, specified in pixels if a number is passed, or in\nCSS units if a string is passed. This has no effect on the preprocessed tuple\nof image file or numpy array, but will affect the displayed image.\n\n\n \n \n image_mode: Literal['1', 'L', 'P', 'RGB', 'RGBA', 'CMYK', 'YCbCr', 'LAB', 'HSV', 'I', 'F'] | None\n\ndefault `= \"RGB\"`\n\nThe pixel format and color depth that the image should be loaded and\npreprocessed as. \"RGB\" will load the image as a color image, or \"L\" as black-\nand-white. See https://pillow.readthedocs.io/en/stable/handbook/concepts.html\nfor other supported image modes and their meaning. This parameter has no\neffect on SVG or GIF files. If set to None, the image_mode will be inferred\nfrom the image file types (e.g. \"RGBA\" for a .png image, \"RGB\" in most other\ncases).\n\n\n \n \n type: Literal['numpy', 'pil', 'filepath']\n\ndefault `= \"numpy\"`\n\nThe for", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/imageslider", "source_page_title": "Gradio - Imageslider Docs"}, {"text": "image_mode will be inferred\nfrom the image file types (e.g. \"RGBA\" for a .png image, \"RGB\" in most other\ncases).\n\n\n \n \n type: Literal['numpy', 'pil', 'filepath']\n\ndefault `= \"numpy\"`\n\nThe format the images are converted to before being passed into the prediction\nfunction. \"numpy\" converts the images to numpy arrays with shape (height,\nwidth, 3) and values from 0 to 255, \"pil\" converts the images to PIL image\nobjects, \"filepath\" passes str paths to temporary files containing the images.\nTo support animated GIFs in input, the `type` should be set to \"filepath\" or\n\"pil\". To support SVGs, the `type` should be set to \"filepath\".\n\n\n \n \n label: str | 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.\n\n\n \n \n show_label: bool | None\n\ndefault `= None`\n\nif True, will display label.\n\n\n \n \n buttons: list[Literal['download', 'fullscreen'] | Button] | None\n\ndefault `= None`\n\nA list of buttons to show in the top right corner of the component. Valid\noptions are \"download\", \"fullscreen\", or a gr.Button() instance. The\n\"download\" button allows the user to download the image. The \"fullscreen\"\nbutton allows the user to view the image in fullscreen mode. Custom\ngr.Button() instances will appear in the toolbar w", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/imageslider", "source_page_title": "Gradio - Imageslider Docs"}, {"text": "ce. The\n\"download\" button allows the user to download the image. The \"fullscreen\"\nbutton allows the user to view the image in fullscreen mode. 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, all of the built-in buttons are shown.\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 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\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 image; if False, can only be\nused to display images. 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\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 `= T", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/imageslider", "source_page_title": "Gradio - Imageslider Docs"}, {"text": "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\n \n \n slider_position: float\n\ndefault `= 50`\n\nThe position of the slider as a percentage of the width of the image, between\n0 and 100.\n\n\n \n \n max_height: int\n\ndefault `= 500`\n\nThe maximum height of the image.\n\n", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/imageslider", "source_page_title": "Gradio - Imageslider Docs"}, {"text": "Shortcuts\n\n \n \n gradio.ImageSlider\n\nInterface String Shortcut `\"imageslider\"`\n\nInitialization Uses default values\n\n", "heading1": "Shortcuts", "source_page_url": "https://gradio.app/docs/gradio/imageslider", "source_page_title": "Gradio - Imageslider Docs"}, {"text": "imageslider\n\n", "heading1": "Demos", "source_page_url": "https://gradio.app/docs/gradio/imageslider", "source_page_title": "Gradio - Imageslider 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 ImageSlider 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 ImageSlider.clear(fn, \u00b7\u00b7\u00b7)\n\nThis listener is triggered when the user clears the ImageSlider using the\nclear button for the component.\n\n \n \n ImageSlider.change(fn, \u00b7\u00b7\u00b7)\n\nTriggered when the value of the ImageSlider 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 ImageSlider.stream(fn, \u00b7\u00b7\u00b7)\n\nThis listener is triggered when the user streams the ImageSlider.\n\n \n \n ImageSlider.select(fn, \u00b7\u00b7\u00b7)\n\nEvent listener for when the user selects or deselects the ImageSlider. Uses\nevent data gradio.SelectData to carry `value` referring to the label of the\nImageSlider, and `selected` to refer to state of the ImageSlider. See\n for more details.\n\n \n \n ImageSlider.upload(fn, \u00b7\u00b7\u00b7)\n\nThis listener is triggered when the user uploads a file into the ImageSlider.\n\n \n \n ImageSlider.input(fn, \u00b7\u00b7\u00b7)\n\nThis listener is triggered when the user changes the value of the ImageSlider.\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 e", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/imageslider", "source_page_title": "Gradio - Imageslider Docs"}, {"text": "red. 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 animation at all\n\n\n \n \n show_progress_on: Component | list[Component] | None\n\ndefault `= None`\n\nComp", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/imageslider", "source_page_title": "Gradio - Imageslider Docs"}, {"text": "e 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 generators that are iterating) will be cancelled, but\nfunctions that are currently running will be allow", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/imageslider", "source_page_title": "Gradio - Imageslider Docs"}, {"text": "nt\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 the Gradio client libraries), or \"undocumented\" (hidden\nfrom API docs but callable by clients and via gr.load). If fn is None,\napi_visibility will automatically be set to \"private\".\n\n\n \n \n time_li", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/imageslider", "source_page_title": "Gradio - Imageslider Docs"}, {"text": "radio client libraries), or \"undocumented\" (hidden\nfrom API docs but callable by clients and via gr.load). If fn is None,\napi_visibility will automatically 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/imageslider", "source_page_title": "Gradio - Imageslider Docs"}, {"text": "The FileData class is a subclass of the GradioModel class that represents a\nfile object within a Gradio interface. It is used to store file data and\nmetadata when a file is uploaded. \n\n", "heading1": "Description", "source_page_url": "https://gradio.app/docs/gradio/filedata", "source_page_title": "Gradio - Filedata Docs"}, {"text": "from gradio_client import Client, FileData, handle_file\n \n def get_url_on_server(data: FileData):\n print(data['url'])\n \n client = Client(\"gradio/gif_maker_main\", download_files=False)\n job = client.submit([handle_file(\"./cheetah.jpg\")], api_name=\"/predict\")\n data = job.result()\n video: FileData = data['video']\n \n get_url_on_server(video)\n\n", "heading1": "Example Usage", "source_page_url": "https://gradio.app/docs/gradio/filedata", "source_page_title": "Gradio - Filedata Docs"}, {"text": "Parameters \u25bc\n\n\n \n \n path: str\n\nThe server file path where the file is stored.\n\n\n \n \n url: Optional[str]\n\nThe normalized server URL pointing to the file.\n\n\n \n \n size: Optional[int]\n\nThe size of the file in bytes.\n\n\n \n \n orig_name: Optional[str]\n\nThe original filename before upload.\n\n\n \n \n mime_type: Optional[str]\n\nThe MIME type of the file.\n\n\n \n \n is_stream: bool\n\nIndicates whether the file is a stream.\n\n\n \n \n meta: dict\n\nAdditional metadata used internally (should not be changed).\n\n", "heading1": "Attributes", "source_page_url": "https://gradio.app/docs/gradio/filedata", "source_page_title": "Gradio - Filedata 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 the Gradio client libraries), or \"undocumented\" (hidden\nfrom API docs but callable by clients and vi", "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 the Gradio client libraries), or \"undocumented\" (hidden\nfrom API docs but callable by clients and via gr.load). If fn is None,\napi_visibility will automatically 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 the Gradio client libraries), or \"undocumented\" (hidden\nfrom API docs but callable by clients and vi", "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 the Gradio client libraries), or \"undocumented\" (hidden\nfrom API docs but callable by clients and via gr.load). If fn is None,\napi_visibility will automatically 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": "Creates a chatbot that displays user-submitted messages and responses.\nSupports a subset of Markdown including bold, italics, code, tables. Also\nsupports audio/video/image files, which are displayed in the Chatbot, and\nother kinds of files which are displayed as links. This component is usually\nused as an output component. \n\n", "heading1": "Description", "source_page_url": "https://gradio.app/docs/gradio/chatbot", "source_page_title": "Gradio - Chatbot Docs"}, {"text": "The Chatbot component accepts a list of messages, where each message is a\ndictionary with `role` and `content` keys. This format is compatible with the\nmessage format expected by most LLM APIs (OpenAI, Claude, HuggingChat, etc.),\nmaking it easy to pipe model outputs directly into the component.\n\nThe `role` key should be either `'user'` or `'assistant'`, and the `content`\nkey can be a string (rendered as markdown/HTML) or a Gradio component (useful\nfor displaying files, images, plots, and other media).\n\nAs an example:\n\n \n \n import gradio as gr\n \n history = [\n {\"role\": \"assistant\", \"content\": \"I am happy to provide you that report and plot.\"},\n {\"role\": \"assistant\", \"content\": gr.Plot(value=make_plot_from_file('quaterly_sales.txt'))}\n ]\n \n with gr.Blocks() as demo:\n gr.Chatbot(history)\n \n demo.launch()\n\nFor convenience, you can use the `ChatMessage` dataclass so that your text\neditor can give you autocomplete hints and typechecks.\n\n \n \n import gradio as gr\n \n history = [\n gr.ChatMessage(role=\"assistant\", content=\"How can I help you?\"),\n gr.ChatMessage(role=\"user\", content=\"Can you make me a plot of quarterly sales?\"),\n gr.ChatMessage(role=\"assistant\", content=\"I am happy to provide you that report and plot.\")\n ]\n \n with gr.Blocks() as demo:\n gr.Chatbot(history)\n \n demo.launch()\n\n", "heading1": "Behavior", "source_page_url": "https://gradio.app/docs/gradio/chatbot", "source_page_title": "Gradio - Chatbot Docs"}, {"text": "Parameters \u25bc\n\n\n \n \n value: list[MessageDict | Message] | Callable | None\n\ndefault `= None`\n\nDefault list of messages to show in chatbot, where each message is of the\nformat {\"role\": \"user\", \"content\": \"Help me.\"}. Role can be one of \"user\",\n\"assistant\", or \"system\". Content should be either text, or media passed as a\nGradio component, e.g. {\"content\": gr.Image(\"lion.jpg\")}. If a function is\nprovided, the function will be called each time the app loads to set the\ninitial value of this component.\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.\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 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\n\ndefault `= 160`\n\nminimum pixel width, will wrap if ", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/chatbot", "source_page_title": "Gradio - Chatbot Docs"}, {"text": "ide\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\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 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 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 autoscroll: bool\n\ndefault `= True`\n\nIf True, will automatically scroll to the bottom of the textbox when the value\nchanges, unless the user scrolls up. If False, will not scroll to the bottom\nof the textbox when the value changes.\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 hav", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/chatbot", "source_page_title": "Gradio - Chatbot Docs"}, {"text": "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 height: int | str | None\n\ndefault `= 400`\n\nThe height of the component, specified in pixels if a number is passed, or in\nCSS units if a string is passed. If messages exceed the height, the component\nwill scroll.\n\n\n \n \n resizable: bool\n\ndefault `= False`\n\nIf True, the user of the Gradio app can resize the chatbot by dragging the\nbottom right corner.\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 messages exceed the height,\nthe component will scroll. If messages are shorter than the height, the\ncomponent will shrink to fit the content. Will not have any effect if `height`\nis set and is smaller than `max_height`.\n\n\n \n \n min_height: int | str | None\n\ndefault `= None`\n\nThe minimum height of the component, specified in pixels if a number is\npassed, or in CSS units if a string is passed. If messages exceed the height,\nthe component will expand to fit the content. Will not have any effect if\n`height` is set and is larger than `min_height`.\n\n\n \n \n editable: Literal['user', 'all'] | None\n\ndefault `= None`\n\nAllows user to edit messages in the chatbot. If set to \"user\", allows editing\nof user messages. If set to \"all\", allows editing of assistant messages as\nwell.\n\n\n \n \n latex_delimiters: list[dict[str, str | bool]] | None\n\ndefault `= None`\n\nA list of dicts of the form {\"left\": open delimiter (str), \"right\": close\ndelimiter (str), \"display\": whether to display in newline (bool)} that will be\nused to render LaTeX expressions. If not provided, `latex_delimiters` is set\nto `[{ \"", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/chatbot", "source_page_title": "Gradio - Chatbot Docs"}, {"text": "pen delimiter (str), \"right\": close\ndelimiter (str), \"display\": whether to display in newline (bool)} that will be\nused to render LaTeX expressions. If not provided, `latex_delimiters` is set\nto `[{ \"left\": \"$$\", \"right\": \"$$\", \"display\": True }]`, so only expressions\nenclosed in $$ delimiters will be rendered as LaTeX, and in a new line. Pass\nin an empty list to disable LaTeX rendering. For more information, see the\n[KaTeX documentation](https://katex.org/docs/autorender.html).\n\n\n \n \n rtl: bool\n\ndefault `= False`\n\nIf True, sets the direction of the rendered text to right-to-left. Default is\nFalse, which renders text left-to-right.\n\n\n \n \n buttons: list[Literal['share', 'copy', 'copy_all'] | Button] | None\n\ndefault `= None`\n\nA list of buttons to show in the top right corner of the component. Valid\noptions are \"share\", \"copy\", \"copy_all\", or a gr.Button() instance. The\n\"share\" button allows the user to share outputs to Hugging Face Spaces\nDiscussions. The \"copy\" button makes a copy button appear next to each\nindividual chatbot message. The \"copy_all\" button appears at the component\nlevel and allows the user to copy all chatbot messages. Custom gr.Button()\ninstances will appear in the toolbar with their configured icon and/or label,\nand clicking them will trigger any .click() events registered on the button.\nBy default, \"share\" and \"copy_all\" buttons are shown.\n\n\n \n \n watermark: str | None\n\ndefault `= None`\n\nIf provided, this text will be appended to the end of messages copied from the\nchatbot, after a blank line. Useful for indicating that the message is\ngenerated by an AI model.\n\n\n \n \n avatar_images: tuple[str | Path | None, str | Path | None] | None\n\ndefault `= None`\n\nTuple of two avatar image paths or URLs for user and bot (in that order). Pass\nNone for either the user or bot image to skip. Must be within the working\ndirectory of the Gradio app or an external URL.\n\n\n \n \n sanitize_html: bool\n\ndefault `= True`\n\nIf False, w", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/chatbot", "source_page_title": "Gradio - Chatbot Docs"}, {"text": "rder). Pass\nNone for either the user or bot image to skip. Must be within the working\ndirectory of the Gradio app or an external URL.\n\n\n \n \n sanitize_html: bool\n\ndefault `= True`\n\nIf False, will disable HTML sanitization for chatbot messages. This is not\nrecommended, as it can lead to security vulnerabilities.\n\n\n \n \n render_markdown: bool\n\ndefault `= True`\n\nIf False, will disable Markdown rendering for chatbot messages.\n\n\n \n \n feedback_options: list[str] | tuple[str, ...] | None\n\ndefault `= ('Like', 'Dislike')`\n\nA list of strings representing the feedback options that will be displayed to\nthe user. The exact case-sensitive strings \"Like\" and \"Dislike\" will render as\nthumb icons, but any other choices will appear under a separate flag icon.\n\n\n \n \n feedback_value: list[str | None] | None\n\ndefault `= None`\n\nA list of strings representing the feedback state for entire chat. Only works\nwhen type=\"messages\". Each entry in the list corresponds to that assistant\nmessage, in order, and the value is the feedback given (e.g. \"Like\",\n\"Dislike\", or any custom feedback option) or None if no feedback was given for\nthat message.\n\n\n \n \n line_breaks: bool\n\ndefault `= True`\n\nIf True (default), will enable Github-flavored Markdown line breaks in chatbot\nmessages. If False, single new lines will be ignored. Only applies if\n`render_markdown` is True.\n\n\n \n \n layout: Literal['panel', 'bubble'] | None\n\ndefault `= None`\n\nIf \"panel\", will display the chatbot in a llm style layout. If \"bubble\", will\ndisplay the chatbot with message bubbles, with the user and bot messages on\nalterating sides. Will default to \"bubble\".\n\n\n \n \n placeholder: str | None\n\ndefault `= None`\n\na placeholder message to display in the chatbot when it is empty. Centered\nvertically and horizontally in the Chatbot. Supports Markdown and HTML. If\nNone, no placeholder is displayed.\n\n\n \n \n examples: list[ExampleMessage] | None\n\ndefault `= None`\n\nA list of ex", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/chatbot", "source_page_title": "Gradio - Chatbot Docs"}, {"text": "ered\nvertically and horizontally in the Chatbot. Supports Markdown and HTML. If\nNone, no placeholder is displayed.\n\n\n \n \n examples: list[ExampleMessage] | None\n\ndefault `= None`\n\nA list of example messages to display in the chatbot before any user/assistant\nmessages are shown. Each example should be a dictionary with an optional\n\"text\" key representing the message that should be populated in the Chatbot\nwhen clicked, an optional \"files\" key, whose value should be a list of files\nto populate in the Chatbot, an optional \"icon\" key, whose value should be a\nfilepath or URL to an image to display in the example box, and an optional\n\"display_text\" key, whose value should be the text to display in the example\nbox. If \"display_text\" is not provided, the value of \"text\" will be displayed.\n\n\n \n \n allow_file_downloads: bool\n\ndefault `= True`\n\nIf True, will show a download button for chatbot messages that contain media.\nDefaults to True.\n\n\n \n \n group_consecutive_messages: bool\n\ndefault `= True`\n\nIf True, will display consecutive messages from the same role in the same\nbubble. If False, will display each message in a separate bubble. Defaults to\nTrue.\n\n\n \n \n allow_tags: list[str] | bool\n\ndefault `= True`\n\nIf a list of tags is provided, these tags will be preserved in the output\nchatbot messages, even if `sanitize_html` is `True`. For example, if this list\nis [\"thinking\"], the tags `` and `` will not be removed.\nIf True, all custom tags (non-standard HTML tags) will be preserved. If False,\nno tags will be preserved. Default value is 'True'.\n\n\n \n \n reasoning_tags: list[tuple[str, str]] | None\n\ndefault `= None`\n\nIf provided, a list of tuples of (open_tag, close_tag) strings. Any text\nbetween these tags will be extracted and displayed in a separate collapsible\nmessage with metadata={\"title\": \"Reasoning\"}. For example, [(\"\",\n\"\")] will extract content between and tags.\nEach th", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/chatbot", "source_page_title": "Gradio - Chatbot Docs"}, {"text": "and displayed in a separate collapsible\nmessage with metadata={\"title\": \"Reasoning\"}. For example, [(\"\",\n\"\")] will extract content between and tags.\nEach thinking block will be displayed as a separate collapsible message before\nthe main response. If None (default), no automatic extraction is performed.\n\n\n \n \n like_user_message: bool\n\ndefault `= False`\n\nIf True, will show like/dislike buttons for user messages as well. Defaults to\nFalse.\n\n", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/chatbot", "source_page_title": "Gradio - Chatbot Docs"}, {"text": "Shortcuts\n\n \n \n gradio.Chatbot\n\nInterface String Shortcut `\"chatbot\"`\n\nInitialization Uses default values\n\n", "heading1": "Shortcuts", "source_page_url": "https://gradio.app/docs/gradio/chatbot", "source_page_title": "Gradio - Chatbot Docs"}, {"text": "**Displaying Thoughts/Tool Usage**\n\nYou can provide additional metadata regarding any tools used to generate the\nresponse. This is useful for displaying the thought process of LLM agents. For\nexample,\n\n \n \n def generate_response(history):\n history.append(\n ChatMessage(role=\"assistant\",\n content=\"The weather API says it is 20 degrees Celcius in New York.\",\n metadata={\"title\": \"\ud83d\udee0\ufe0f Used tool Weather API\"})\n )\n return history\n\nWould be displayed as following:\n\n![Gradio chatbot tool display](https://github.com/user-\nattachments/assets/c1514bc9-bc29-4af1-8c3f-cd4a7c2b217f)\n\nYou can also specify metadata with a plain python dictionary,\n\n \n \n def generate_response(history):\n history.append(\n dict(role=\"assistant\",\n content=\"The weather API says it is 20 degrees Celcius in New York.\",\n metadata={\"title\": \"\ud83d\udee0\ufe0f Used tool Weather API\"})\n )\n return history\n\n**Using Gradio Components Inside`gr.Chatbot`**\n\nThe `Chatbot` component supports using many of the core Gradio components\n(such as `gr.Image`, `gr.Plot`, `gr.Audio`, and `gr.HTML`) inside of the\nchatbot. Simply include one of these components as the `content` of a message.\nHere\u2019s an example:\n\n \n \n import gradio as gr\n \n def load():\n return [\n {\"role\": \"user\", \"content\": \"Can you show me some media?\"},\n {\"role\": \"assistant\", \"content\": \"Here's an audio clip:\"},\n {\"role\": \"assistant\", \"content\": gr.Audio(\"https://github.com/gradio-app/gradio/raw/main/gradio/media_assets/audio/audio_sample.wav\")},\n {\"role\": \"assistant\", \"content\": \"And here's a video:\"},\n {\"role\": \"assistant\", \"content\": gr.Video(\"https://github.com/gradio-app/gradio/raw/main/gradio/media_assets/videos/world.mp4\")}\n ]\n \n with gr.Blocks() as demo:\n chatbot = gr.Chatbot()\n button = gr.Button(\"Load ", "heading1": "Examples", "source_page_url": "https://gradio.app/docs/gradio/chatbot", "source_page_title": "Gradio - Chatbot Docs"}, {"text": "deo(\"https://github.com/gradio-app/gradio/raw/main/gradio/media_assets/videos/world.mp4\")}\n ]\n \n with gr.Blocks() as demo:\n chatbot = gr.Chatbot()\n button = gr.Button(\"Load audio and video\")\n button.click(load, None, chatbot)\n \n demo.launch()\n\n", "heading1": "Examples", "source_page_url": "https://gradio.app/docs/gradio/chatbot", "source_page_title": "Gradio - Chatbot Docs"}, {"text": "chatbot_simplechatbot_streamingchatbot_with_toolschatbot_core_components\n\n", "heading1": "Demos", "source_page_url": "https://gradio.app/docs/gradio/chatbot", "source_page_title": "Gradio - Chatbot 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 Chatbot 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 Chatbot.change(fn, \u00b7\u00b7\u00b7)\n\nTriggered when the value of the Chatbot 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 Chatbot.select(fn, \u00b7\u00b7\u00b7)\n\nEvent listener for when the user selects or deselects the Chatbot. Uses event\ndata gradio.SelectData to carry `value` referring to the label of the Chatbot,\nand `selected` to refer to state of the Chatbot. See\n for more details.\n\n \n \n Chatbot.like(fn, \u00b7\u00b7\u00b7)\n\nThis listener is triggered when the user likes/dislikes from within the\nChatbot. This event has EventData of type gradio.LikeData that carries\ninformation, accessible through LikeData.index and LikeData.value. See\nEventData documentation on how to use this event data.\n\n \n \n Chatbot.retry(fn, \u00b7\u00b7\u00b7)\n\nThis listener is triggered when the user clicks the retry button in the\nchatbot message.\n\n \n \n Chatbot.undo(fn, \u00b7\u00b7\u00b7)\n\nThis listener is triggered when the user clicks the undo button in the chatbot\nmessage.\n\n \n \n Chatbot.example_select(fn, \u00b7\u00b7\u00b7)\n\nThis listener is triggered when the user clicks on an example from within the\nChatbot. This event has SelectData of type gradio.SelectData that carries\ninformation, accessible through SelectData.index and SelectData.value. See\nSelectData documentation on how to use this event data.\n\n \n ", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/chatbot", "source_page_title": "Gradio - Chatbot Docs"}, {"text": "s event has SelectData of type gradio.SelectData that carries\ninformation, accessible through SelectData.index and SelectData.value. See\nSelectData documentation on how to use this event data.\n\n \n \n Chatbot.option_select(fn, \u00b7\u00b7\u00b7)\n\nThis listener is triggered when the user clicks on an option from within the\nChatbot. This event has SelectData of type gradio.SelectData that carries\ninformation, accessible through SelectData.index and SelectData.value. See\nSelectData documentation on how to use this event data.\n\n \n \n Chatbot.clear(fn, \u00b7\u00b7\u00b7)\n\nThis listener is triggered when the user clears the Chatbot using the clear\nbutton for the component.\n\n \n \n Chatbot.copy(fn, \u00b7\u00b7\u00b7)\n\nThis listener is triggered when the user copies content from the Chatbot. Uses\nevent data gradio.CopyData to carry information about the copied content. See\nEventData documentation on how to use this event data\n\n \n \n Chatbot.edit(fn, \u00b7\u00b7\u00b7)\n\nThis listener is triggered when the user edits the Chatbot (e.g. image) using\nthe built-in editor.\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_", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/chatbot", "source_page_title": "Gradio - Chatbot Docs"}, {"text": "ckContext] | 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 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. ", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/chatbot", "source_page_title": "Gradio - Chatbot Docs"}, {"text": "f 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\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\nmetho", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/chatbot", "source_page_title": "Gradio - Chatbot Docs"}, {"text": "d 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 the Gradio client libraries), or \"undocumented\" (hidden\nfrom API docs but callable by clients and via gr.load). If fn is None,\napi_visibility will automatically 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 ", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/chatbot", "source_page_title": "Gradio - Chatbot Docs"}, {"text": "= 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/chatbot", "source_page_title": "Gradio - Chatbot Docs"}, {"text": "", "heading1": "Helper Classes", "source_page_url": "https://gradio.app/docs/gradio/chatbot", "source_page_title": "Gradio - Chatbot Docs"}, {"text": "gradio.ChatMessage(\u00b7\u00b7\u00b7)\n\nDescription\n\nA dataclass that represents a message in the Chatbot component (with\ntype=\"messages\"). The only required field is `content`. The value of\n`gr.Chatbot` is a list of these dataclasses.\n\nParameters \u25bc\n\n\n \n \n content: MessageContent | list[MessageContent]\n\nThe content of the message. Can be a string, a file dict, a gradio component,\nor a list of these types to group these messages together.\n\n\n \n \n role: Literal['user', 'assistant', 'system']\n\ndefault `= \"assistant\"`\n\nThe role of the message, which determines the alignment of the message in the\nchatbot. Can be \"user\", \"assistant\", or \"system\". Defaults to \"assistant\".\n\n\n \n \n metadata: MetadataDict\n\ndefault `= _HAS_DEFAULT_FACTORY_CLASS()`\n\nThe metadata of the message, which is used to display intermediate thoughts /\ntool usage. Should be a dictionary with the following keys: \"title\" (required\nto display the thought), and optionally: \"id\" and \"parent_id\" (to nest\nthoughts), \"duration\" (to display the duration of the thought), \"status\" (to\ndisplay the status of the thought).\n\n\n \n \n options: list[OptionDict]\n\ndefault `= _HAS_DEFAULT_FACTORY_CLASS()`\n\nThe options of the message. A list of Option objects, which are dictionaries\nwith the following keys: \"label\" (the text to display in the option), and\noptionally \"value\" (the value to return when the option is selected if\ndifferent from the label).\n\n", "heading1": "ChatMessage", "source_page_url": "https://gradio.app/docs/gradio/chatbot", "source_page_title": "Gradio - Chatbot Docs"}, {"text": "A typed dictionary to represent metadata for a message in the Chatbot\ncomponent. An instance of this dictionary is used for the `metadata` field in\na ChatMessage when the chat message should be displayed as a thought.\n\nKeys \u25bc\n\n\n \n \n title: str\n\nThe title of the 'thought' message. Only required field.\n\n\n \n \n id: int | str\n\nThe ID of the message. Only used for nested thoughts. Nested thoughts can be\nnested by setting the parent_id to the id of the parent thought.\n\n\n \n \n parent_id: int | str\n\nThe ID of the parent message. Only used for nested thoughts.\n\n\n \n \n log: str\n\nA string message to display next to the thought title in a subdued font.\n\n\n \n \n duration: float\n\nThe duration of the message in seconds. Appears next to the thought title in a\nsubdued font inside a parentheses.\n\n\n \n \n status: Literal['pending', 'done']\n\nif set to `'pending'`, a spinner appears next to the thought title and the\naccordion is initialized open. If `status` is `'done'`, the thought accordion\nis initialized closed. If `status` is not provided, the thought accordion is\ninitialized open and no spinner is displayed.\n\n", "heading1": "MetadataDict", "source_page_url": "https://gradio.app/docs/gradio/chatbot", "source_page_title": "Gradio - Chatbot Docs"}, {"text": "A typed dictionary to represent an option in a ChatMessage. A list of these\ndictionaries is used for the `options` field in a ChatMessage.\n\nKeys \u25bc\n\n\n \n \n value: str\n\nThe value to return when the option is selected.\n\n\n \n \n label: str\n\nThe text to display in the option, if different from the value.\n\n[Chatbot Specific Events](../../guides/chatbot-specific-\nevents/)[Conversational Chatbot](../../guides/conversational-\nchatbot/)[Creating A Chatbot Fast](../../guides/creating-a-chatbot-\nfast/)[Creating A Custom Chatbot With Blocks](../../guides/creating-a-custom-\nchatbot-with-blocks/)[Agents And Tool Usage](../../guides/agents-and-tool-\nusage/)\n\n", "heading1": "OptionDict", "source_page_url": "https://gradio.app/docs/gradio/chatbot", "source_page_title": "Gradio - Chatbot Docs"}, {"text": "This class is a wrapper over the Dataset component and can be used to\ncreate Examples for Blocks / Interfaces. Populates the Dataset component with\nexamples and assigns event listener so that clicking on an example populates\nthe input/output components. Optionally handles example caching for fast\ninference. \n\n", "heading1": "Description", "source_page_url": "https://gradio.app/docs/gradio/examples", "source_page_title": "Gradio - Examples Docs"}, {"text": "Parameters \u25bc\n\n\n \n \n examples: list[Any] | list[list[Any]] | str\n\nexample inputs that can be clicked to populate specific components. Should be\nnested list, in which the outer list consists of samples and each inner list\nconsists of an input corresponding to each input component. A string path to a\ndirectory of examples can also be provided but it should be within the\ndirectory with the python file running the gradio app. If there are multiple\ninput components and a directory is provided, a log.csv file must be present\nin the directory to link corresponding inputs.\n\n\n \n \n inputs: Component | list[Component]\n\nthe component or list of components corresponding to the examples\n\n\n \n \n outputs: Component | list[Component] | None\n\ndefault `= None`\n\noptionally, provide the component or list of components corresponding to the\noutput of the examples. Required if `cache_examples` is not False.\n\n\n \n \n fn: Callable | None\n\ndefault `= None`\n\noptionally, provide the function to run to generate the outputs corresponding\nto the examples. Required if `cache_examples` is not False. Also required if\n`run_on_click` is True.\n\n\n \n \n cache_examples: bool | None\n\ndefault `= None`\n\nIf True, caches examples in the server for fast runtime in examples. If\n\"lazy\", then examples are cached (for all users of the app) after their first\nuse (by any user of the app). If None, will use the GRADIO_CACHE_EXAMPLES\nenvironment variable, which should be either \"true\" or \"false\". In HuggingFace\nSpaces, this parameter is True (as long as `fn` and `outputs` are also\nprovided). The default option otherwise is False. Note that examples are\ncached separately from Gradio's queue() so certain features, such as\ngr.Progress(), gr.Info(), gr.Warning(), etc. will not be displayed in Gradio's\nUI for cached examples.\n\n\n \n \n cache_mode: Literal['eager', 'lazy'] | None\n\ndefault `= None`\n\nif \"lazy\", examples are cached after their first use. If \"eager\", all examples\nare ", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/examples", "source_page_title": "Gradio - Examples Docs"}, {"text": "d in Gradio's\nUI for cached examples.\n\n\n \n \n cache_mode: Literal['eager', 'lazy'] | None\n\ndefault `= None`\n\nif \"lazy\", examples are cached after their first use. If \"eager\", all examples\nare cached at app launch. If None, will use the GRADIO_CACHE_MODE environment\nvariable if defined, or default to \"eager\".\n\n\n \n \n examples_per_page: int\n\ndefault `= 10`\n\nhow many examples to show per page.\n\n\n \n \n label: str | I18nData | None\n\ndefault `= \"Examples\"`\n\nthe label to use for the examples component (by default, \"Examples\")\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.\n\n\n \n \n run_on_click: bool\n\ndefault `= False`\n\nif cache_examples is False, clicking on an example does not run the function\nwhen an example is clicked. Set this to True to run the function when an\nexample is clicked. Has no effect if cache_examples is True.\n\n\n \n \n preprocess: bool\n\ndefault `= True`\n\nif True, preprocesses the example input before running the prediction function\nand caching the output. Only applies if `cache_examples` is not False.\n\n\n \n \n postprocess: bool\n\ndefault `= True`\n\nif True, postprocesses the example output after running the prediction\nfunction and before caching. Only applies if `cache_examples` is not False.\n\n\n \n \n api_visibility: Literal['public', 'private', 'undocumented']\n\ndefault `= \"undocumented\"`\n\nControls the visibility of the event associated with clicking on the examples.\nCan be \"public\" (shown in API docs and callable), \"private\" (hidden from API\ndocs and not callable by the Gradio client libraries), or \"undocumented\"\n(hidden from API docs but callable).\n\n\n \n \n api_name: str | None\n\ndefault `= \"load_example\"`\n\nDefines how the event associated with clicking on the examples appears in the\nAPI docs. Can be a string or None. If set to a string, the endpoint will be\nexposed in the API docs with the given name. If None, a", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/examples", "source_page_title": "Gradio - Examples Docs"}, {"text": "ow the event associated with clicking on the examples appears in the\nAPI docs. Can be a string or None. If set to a string, the endpoint will be\nexposed in the API docs with the given name. If None, an auto-generated name\nwill be used.\n\n\n \n \n api_description: str | None | Literal[False]\n\ndefault `= None`\n\nDescription of the event associated with clicking on the examples in the API\ndocs. Can be a string, None, or False. If set to a string, the endpoint will\nbe exposed in the API docs with the given description. If None, the function's\ndocstring will be used as the API endpoint description. If False, then no\ndescription will be displayed in the API docs.\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. Used only if\ncache_examples is not False.\n\n\n \n \n example_labels: list[str] | None\n\ndefault `= None`\n\nA list of labels for each example. If provided, the length of this list should\nbe the same as the number of examples, and these labels will be used in the UI\ninstead of rendering the example values.\n\n\n \n \n visible: bool | Literal['hidden']\n\ndefault `= True`\n\nIf False, the examples component will be hidden in the UI.\n\n\n \n \n preload: int | Literal[False]\n\ndefault `= 0`\n\nIf an integer is provided (and examples are being cached eagerly and none of\nthe input components have a developer-provided `value`), the example at that\nindex in the examples list will be preloaded when the Gradio app is first\nloaded. If False, no example will be preloaded.\n\n", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/examples", "source_page_title": "Gradio - Examples Docs"}, {"text": "Parameters \u25bc\n\n\n \n \n dataset: gradio.Dataset\n\nThe `gr.Dataset` component corresponding to this Examples object.\n\n\n \n \n load_input_event: gradio.events.Dependency\n\nThe Gradio event that populates the input values when the examples are\nclicked. You can attach a `.then()` or a `.success()` to this event to trigger\nsubsequent events to fire after this event.\n\n\n \n \n cache_event: gradio.events.Dependency | None\n\nThe Gradio event that populates the cached output values when the examples are\nclicked. You can attach a `.then()` or a `.success()` to this event to trigger\nsubsequent events to fire after this event. This event is `None` if\n`cache_examples` if False, and is the same as `load_input_event` if\n`cache_examples` is `'lazy'`.\n\n", "heading1": "Attributes", "source_page_url": "https://gradio.app/docs/gradio/examples", "source_page_title": "Gradio - Examples Docs"}, {"text": "**Updating Examples**\n\nIn this demo, we show how to update the examples by updating the samples of\nthe underlying dataset. Note that this only works if `cache_examples=False` as\nupdating the underlying dataset does not update the cache.\n\n \n \n import gradio as gr\n \n def update_examples(country):\n if country == \"USA\":\n return gr.Dataset(samples=[[\"Chicago\"], [\"Little Rock\"], [\"San Francisco\"]])\n else:\n return gr.Dataset(samples=[[\"Islamabad\"], [\"Karachi\"], [\"Lahore\"]])\n \n with gr.Blocks() as demo:\n dropdown = gr.Dropdown(label=\"Country\", choices=[\"USA\", \"Pakistan\"], value=\"USA\")\n textbox = gr.Textbox()\n examples = gr.Examples([[\"Chicago\"], [\"Little Rock\"], [\"San Francisco\"]], textbox)\n dropdown.change(update_examples, dropdown, examples.dataset)\n \n demo.launch()\n\n", "heading1": "Examples", "source_page_url": "https://gradio.app/docs/gradio/examples", "source_page_title": "Gradio - Examples Docs"}, {"text": "calculator_blocks\n\n", "heading1": "Demos", "source_page_url": "https://gradio.app/docs/gradio/examples", "source_page_title": "Gradio - Examples Docs"}, {"text": "The render decorator allows Gradio Blocks apps to have dynamic layouts, so\nthat the components and event listeners in your app can change depending on\ncustom logic. Attaching a @gr.render decorator to a function will cause the\nfunction to be re-run whenever the inputs are changed (or specified triggers\nare activated). The function contains the components and event listeners that\nwill update based on the inputs. With render, you can: \n\\- Show or hide components \n\\- Change text or layout \n\\- Create components based on what users enter \nThe basic usage of @gr.render is as follows: \n1\\. Create a function and attach the @gr.render decorator to it. \n2\\. Add the input components to the `inputs=` argument of @gr.render, and\ncreate a corresponding argument in your function for each component. \n3\\. Add all components inside the function that you want to update based on\nthe inputs. Any event listeners that use these components should also be\ninside this function. \n\n", "heading1": "Description", "source_page_url": "https://gradio.app/docs/gradio/render", "source_page_title": "Gradio - Render Docs"}, {"text": "import gradio as gr\n \n with gr.Blocks() as demo:\n textbox = gr.Textbox(label=\"Enter text\")\n \n @gr.render(inputs=textbox)\n def show_message(text):\n if not text:\n gr.Markdown(\"Please enter some text.\")\n else:\n gr.Markdown(f\"You entered: {text}\")\n \n demo.launch()\n\n", "heading1": "Example Usage", "source_page_url": "https://gradio.app/docs/gradio/render", "source_page_title": "Gradio - Render Docs"}, {"text": "Parameters \u25bc\n\n\n \n \n inputs: list[Component] | Component | 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 triggers: list[Trigger] | Trigger | None\n\ndefault `= None`\n\nList of triggers to listen to, e.g. [btn.click, number.change]. If None, will\nlisten to changes to any inputs.\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 trigger_mode: Literal['once', 'multiple', 'always_last'] | None\n\ndefault `= \"always_last\"`\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 concurrency_limit: int | None | Literal['default']\n\ndefault `= None`\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 show_progress: Literal['full', 'minimal', 'hidden']\n\ndefault `= \"full\"`\n\n[Dynamic Apps with the Render Decorator](../../guides/dynamic-apps-with-\nrender-decorator/)\n\n", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/render", "source_page_title": "Gradio - Render Docs"}, {"text": "Gradio includes pre-built components that can be used as inputs or outputs\nin your Interface or Blocks with a single line of code. Components include\npreprocessing steps that convert user data submitted through browser to\nsomething that be can used by a Python function, and postprocessing steps to\nconvert values returned by a Python function into something that can be\ndisplayed in a browser.\n\nConsider an example with three inputs (Textbox, Number, and Image) and two\noutputs (Number and Gallery), below is a diagram of what our preprocessing\nwill send to the function and what our postprocessing will require from it.\n\n![](/_app/immutable/assets/dataflow.FNuRzshD.svg)\n\n", "heading1": "Introduction", "source_page_url": "https://gradio.app/docs/gradio/introduction", "source_page_title": "Gradio - Introduction Docs"}, {"text": "Components also come with certain events that they support. These are\nmethods that are triggered with user actions. Below is a table showing which\nevents are supported for each component. All events are also listed (with\nparameters) in the component\u2019s docs.\n\n| preview_close| stop| select| submit| delete| load| blur| pause_recording|\npreview_open| end| start_recording| change| stop_recording| play| key_up|\npause| edit| clear| focus| apply| undo| collapse| stream| retry| upload|\nexample_select| input| release| double_click| expand| download| copy| tick|\nlike| click| option_select \n---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|--- \n[Button](button)| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715|\n\u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715 \n[AnnotatedImage](annotatedimage)| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715|\n\u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715 \n[Audio](audio)| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2713| \u2713| \u2713| \u2713| \u2715| \u2713| \u2715| \u2713| \u2715| \u2715| \u2715|\n\u2715| \u2713| \u2715| \u2713| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715 \n[BrowserState](browserstate)| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715|\n\u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715 \n[Chatbot](chatbot)| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2713| \u2713| \u2715|\n\u2715| \u2713| \u2715| \u2715| \u2713| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2713| \u2715| \u2713 \n[Checkbox](checkbox)| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715|\n\u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715 \n[CheckboxGroup](checkboxgroup)| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715|\n\u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715 \n[ClearButton](clearbutton)| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715|\n\u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715 \n[Code](code)| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715|\n\u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715 \n[ColorPicker](colorpicker)| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715", "heading1": "Events", "source_page_url": "https://gradio.app/docs/gradio/introduction", "source_page_title": "Gradio - Introduction Docs"}, {"text": "| \u2715| \u2713| \u2715 \n[Code](code)| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715|\n\u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715 \n[ColorPicker](colorpicker)| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715|\n\u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715 \n[Dataframe](dataframe)| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715|\n\u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715 \n[Dataset](dataset)| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715|\n\u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715 \n[DateTime](datetime)| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715|\n\u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715 \n[DeepLinkButton](deeplinkbutton)| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715|\n\u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715 \n[Dialogue](dialogue)| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715|\n\u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715 \n[DownloadButton](downloadbutton)| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715|\n\u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715 \n[Dropdown](dropdown)| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2713|\n\u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715 \n[DuplicateButton](duplicatebutton)| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715|\n\u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715 \n[File](file)| \u2715| \u2715| \u2713| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715|\n\u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715 \n[FileExplorer](fileexplorer)| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715|\n\u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715 \n[ImageEditor](imageeditor)| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715|\n\u2713| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715 \n[Gallery](gallery)| \u2713| \u2715| \u2713| \u2715| \u2713| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715|\n\u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715 \n[HighlightedText](highlightedtext)| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715|\n\u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| ", "heading1": "Events", "source_page_url": "https://gradio.app/docs/gradio/introduction", "source_page_title": "Gradio - Introduction Docs"}, {"text": " \u2713| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715|\n\u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715 \n[HighlightedText](highlightedtext)| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715|\n\u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715 \n[HTML](html)| \u2715| \u2713| \u2713| \u2713| \u2713| \u2713| \u2713| \u2713| \u2715| \u2713| \u2713| \u2713| \u2713| \u2713| \u2713| \u2713| \u2713| \u2713| \u2713| \u2713| \u2713|\n\u2713| \u2713| \u2713| \u2713| \u2713| \u2713| \u2713| \u2713| \u2713| \u2713| \u2713| \u2713| \u2713| \u2713| \u2713 \n[Image](image)| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715|\n\u2715| \u2713| \u2715| \u2713| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715 \n[ImageSlider](imageslider)| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715|\n\u2713| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2713| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715 \n[JSON](json)| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715|\n\u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715 \n[Label](label)| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715|\n\u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715 \n[LoginButton](loginbutton)| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715|\n\u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715 \n[Markdown](markdown)| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715|\n\u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715 \n[Model3D](model3d)| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2713| \u2713| \u2715|\n\u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715 \n[Textbox](textbox)| \u2715| \u2713| \u2713| \u2713| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713|\n\u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715 \n[MultimodalTextbox](multimodaltextbox)| \u2715| \u2713| \u2713| \u2713| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715|\n\u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715 \n[BarPlot](barplot)| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715|\n\u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715 \n[LinePlot](lineplot)| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715|\n\u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715 \n[ScatterPlot](scatterplot)| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715|\n\u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715 \n[Navbar](navbar)| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715", "heading1": "Events", "source_page_url": "https://gradio.app/docs/gradio/introduction", "source_page_title": "Gradio - Introduction Docs"}, {"text": "ScatterPlot](scatterplot)| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715|\n\u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715 \n[Navbar](navbar)| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715|\n\u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715 \n[Number](number)| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715|\n\u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715 \n[ParamViewer](paramviewer)| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715|\n\u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715 \n[Plot](plot)| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715|\n\u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715 \n[Radio](radio)| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715|\n\u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715 \n[Slider](slider)| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715|\n\u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715 \n[State](state)| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715|\n\u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715 \n[Timer](timer)| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715|\n\u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715 \n[UploadButton](uploadbutton)| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715|\n\u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715 \n[Video](video)| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2713| \u2713| \u2713| \u2713| \u2715| \u2713| \u2715| \u2713| \u2715| \u2715| \u2715|\n\u2715| \u2715| \u2715| \u2713| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715 \n[SimpleImage](simpleimage)| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715|\n\u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2713| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715| \u2715\n\n", "heading1": "Events", "source_page_url": "https://gradio.app/docs/gradio/introduction", "source_page_title": "Gradio - Introduction Docs"}, {"text": "Used to create an upload button, when clicked allows a user to upload files\nthat satisfy the specified file type or generic files (if file_type not set). \n\n", "heading1": "Description", "source_page_url": "https://gradio.app/docs/gradio/uploadbutton", "source_page_title": "Gradio - Uploadbutton Docs"}, {"text": "**Using UploadButton as an input component.**\n\nHow UploadButton will pass its value to your function:\n\nType: `bytes | str | list[bytes] | list[str] | None`\n\nPasses the file as a `str` or `bytes` object, or a list of `str` or list of\n`bytes` objects, depending on `type` and `file_count`.\n\nExample Code\n\n \n \n \n import gradio as gr\n \n def predict(\n value: bytes | str | list[bytes] | list[str] | None\n ):\n process value from the UploadButton component\n return \"prediction\"\n \n interface = gr.Interface(predict, gr.UploadButton(), gr.Textbox())\n interface.launch()\n \n \n\n \n\n**Using UploadButton as an output component**\n\nHow UploadButton expects you to return a value:\n\nType: `str | list[str] | None`\n\nExpects a `str` filepath or URL, or a `list[str]` of filepaths/URLs.\n\nExample Code\n\n \n \n \n import gradio as gr\n \n def predict(text) -> str | list[str] | None\n process value to return to the UploadButton component\n return value\n \n interface = gr.Interface(predict, gr.Textbox(), gr.UploadButton())\n interface.launch()\n \n \n\n", "heading1": "Behavior", "source_page_url": "https://gradio.app/docs/gradio/uploadbutton", "source_page_title": "Gradio - Uploadbutton Docs"}, {"text": "Parameters \u25bc\n\n\n \n \n label: str\n\ndefault `= \"Upload a File\"`\n\nText to display on the button. Defaults to \"Upload a File\".\n\n\n \n \n value: str | I18nData | list[str] | Callable | None\n\ndefault `= None`\n\nFile or list of files to upload by default.\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 value results in this Component being narrower than\nmin_widt", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/uploadbutton", "source_page_title": "Gradio - Uploadbutton Docs"}, {"text": "idth: 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\n \n \n type: Literal['filepath', 'binary']\n\ndefault `= \"filepath\"`\n\nType of value to be returned by component. \"file\" returns a temporary file\nobject with the same base name as the uploaded file, whose full path can be\nretrieved by file_obj.name, \"binary\" returns an bytes object.\n\n\n \n \n file_count: Literal['single', 'multiple', 'directory']\n\n", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/uploadbutton", "source_page_title": "Gradio - Uploadbutton Docs"}, {"text": "h the same base name as the uploaded file, whose full path can be\nretrieved by file_obj.name, \"binary\" returns an bytes object.\n\n\n \n \n file_count: Literal['single', 'multiple', 'directory']\n\ndefault `= \"single\"`\n\nif single, allows user to upload one file. If \"multiple\", user uploads\nmultiple files. If \"directory\", user uploads all files in selected directory.\nReturn type will be list for each file in case of \"multiple\" or \"directory\".\n\n\n \n \n file_types: list[str] | None\n\ndefault `= None`\n\nList of type of files to be uploaded. \"file\" allows any file to be uploaded,\n\"image\" allows only image files to be uploaded, \"audio\" allows only audio\nfiles to be uploaded, \"video\" allows only video files to be uploaded, \"text\"\nallows only text files to be uploaded.\n\n", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/uploadbutton", "source_page_title": "Gradio - Uploadbutton Docs"}, {"text": "Shortcuts\n\n \n \n gradio.UploadButton\n\nInterface String Shortcut `\"uploadbutton\"`\n\nInitialization Uses default values\n\n", "heading1": "Shortcuts", "source_page_url": "https://gradio.app/docs/gradio/uploadbutton", "source_page_title": "Gradio - Uploadbutton Docs"}, {"text": "upload_and_downloadupload_button\n\n", "heading1": "Demos", "source_page_url": "https://gradio.app/docs/gradio/uploadbutton", "source_page_title": "Gradio - Uploadbutton 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 UploadButton 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 UploadButton.click(fn, \u00b7\u00b7\u00b7)\n\nTriggered when the UploadButton is clicked.\n\n \n \n UploadButton.upload(fn, \u00b7\u00b7\u00b7)\n\nThis listener is triggered when the user uploads a file into the UploadButton.\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 t", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/uploadbutton", "source_page_title": "Gradio - Uploadbutton Docs"}, {"text": "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 (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 que", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/uploadbutton", "source_page_title": "Gradio - Uploadbutton Docs"}, {"text": "onent), 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: 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 simultane", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/uploadbutton", "source_page_title": "Gradio - Uploadbutton Docs"}, {"text": "t `= \"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 the Gradio client libraries), or \"undocumented\" (hidden\nfrom API docs but callable by clients and via gr.load). If fn is None,\napi_visibility will automatically 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/uploadbutton", "source_page_title": "Gradio - Uploadbutton Docs"}, {"text": "Special component that ticks at regular intervals when active. It is not\nvisible, and only used to trigger events at a regular interval through the\n`tick` event listener. \n\n", "heading1": "Description", "source_page_url": "https://gradio.app/docs/gradio/timer", "source_page_title": "Gradio - Timer Docs"}, {"text": "**Using Timer as an input component.**\n\nHow Timer will pass its value to your function:\n\nType: `float | None`\n\nThe interval of the timer as a float.\n\nExample Code\n\n \n \n \n import gradio as gr\n \n def predict(\n value: float | None\n ):\n process value from the Timer component\n return \"prediction\"\n \n interface = gr.Interface(predict, gr.Timer(), gr.Textbox())\n interface.launch()\n \n \n\n \n\n**Using Timer as an output component**\n\nHow Timer expects you to return a value:\n\nType: `float | None`\n\nThe interval of the timer as a float or None.\n\nExample Code\n\n \n \n \n import gradio as gr\n \n def predict(text) -> float | None\n process value to return to the Timer component\n return value\n \n interface = gr.Interface(predict, gr.Textbox(), gr.Timer())\n interface.launch()\n \n \n\n", "heading1": "Behavior", "source_page_url": "https://gradio.app/docs/gradio/timer", "source_page_title": "Gradio - Timer Docs"}, {"text": "Parameters \u25bc\n\n\n \n \n value: float\n\ndefault `= 1`\n\nInterval in seconds between each tick.\n\n\n \n \n active: bool\n\ndefault `= True`\n\nWhether the timer is active.\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", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/timer", "source_page_title": "Gradio - Timer Docs"}, {"text": "Shortcuts\n\n \n \n gradio.Timer\n\nInterface String Shortcut `\"timer\"`\n\nInitialization Uses default values\n\n", "heading1": "Shortcuts", "source_page_url": "https://gradio.app/docs/gradio/timer", "source_page_title": "Gradio - Timer 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 Timer 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 Timer.tick(fn, \u00b7\u00b7\u00b7)\n\nThis listener is triggered at regular intervals defined by the Timer.\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 doc", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/timer", "source_page_title": "Gradio - Timer Docs"}, {"text": " \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 `= \"hidden\"`\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 pre", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/timer", "source_page_title": "Gradio - Timer Docs"}, {"text": "\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: 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` param", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/timer", "source_page_title": "Gradio - Timer Docs"}, {"text": "t 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 the Gradio client libraries), or \"undocumented\" (hidden\nfrom API docs but callable by clients and via gr.load). If fn is None,\napi_visibility will automatically 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[More Blocks Features](../../guides/more-blocks-features/)[Time\nPlots](../../guides/time-plots/)\n\n", "heading1": "Event Listeners", "source_page_url": "https://gradio.app/docs/gradio/timer", "source_page_title": "Gradio - Timer 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": "The gr.EditData class is a subclass of gr.Event data that specifically\ncarries information about the `.edit()` event. When gr.EditData is added as a\ntype hint to an argument of an event listener method, a gr.EditData 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/editdata", "source_page_title": "Gradio - Editdata Docs"}, {"text": "import gradio as gr\n \n def edit(edit_data: gr.EditData, history: list[gr.MessageDict]):\n history_up_to_edit = history[:edit_data.index]\n history_up_to_edit[-1] = edit_data.value\n return history_up_to_edit\n \n with gr.Blocks() as demo:\n chatbot = gr.Chatbot()\n chatbot.undo(edit, chatbot, chatbot)\n demo.launch()\n\n", "heading1": "Example Usage", "source_page_url": "https://gradio.app/docs/gradio/editdata", "source_page_title": "Gradio - Editdata Docs"}, {"text": "Parameters \u25bc\n\n\n \n \n index: int | tuple[int, int]\n\nThe index of the message that was edited.\n\n\n \n \n previous_value: Any\n\nThe previous content of the message that was edited.\n\n\n \n \n value: Any\n\nThe new content of the message that was edited.\n\n[Chatbot Specific Events](../../guides/chatbot-specific-events/)\n\n", "heading1": "Attributes", "source_page_url": "https://gradio.app/docs/gradio/editdata", "source_page_title": "Gradio - Editdata Docs"}, {"text": "Column is a layout element within Blocks that renders all children\nvertically. The widths of columns can be set through the `scale` and\n`min_width` parameters. If a certain scale results in a column narrower than\nmin_width, the min_width parameter will win.\n\n", "heading1": "Description", "source_page_url": "https://gradio.app/docs/gradio/column", "source_page_title": "Gradio - Column Docs"}, {"text": "with gr.Blocks() as demo:\n with gr.Row():\n with gr.Column(scale=1):\n text1 = gr.Textbox()\n text2 = gr.Textbox()\n with gr.Column(scale=4):\n btn1 = gr.Button(\"Button 1\")\n btn2 = gr.Button(\"Button 2\")\n\n", "heading1": "Example Usage", "source_page_url": "https://gradio.app/docs/gradio/column", "source_page_title": "Gradio - Column Docs"}, {"text": "Parameters \u25bc\n\n\n \n \n scale: int\n\ndefault `= 1`\n\nrelative width compared to adjacent Columns. For example, if Column A has\nscale=2, and Column B has scale=1, A will be twice as wide as B.\n\n\n \n \n min_width: int\n\ndefault `= 320`\n\nminimum pixel width of Column, will wrap if not sufficient screen space to\nsatisfy this value. If a certain scale value results in a column narrower than\nmin_width, the min_width parameter will be respected first.\n\n\n \n \n variant: Literal['default', 'panel', 'compact']\n\ndefault `= \"default\"`\n\ncolumn type, 'default' (no background), 'panel' (gray background color and\nrounded corners), or 'compact' (rounded corners and no internal gap).\n\n\n \n \n visible: bool | Literal['hidden']\n\ndefault `= True`\n\nIf False, column will be hidden.\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, 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 show_progress: bool\n\ndefault `= False`\n\nIf True, shows progress animation when being updated.\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", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/column", "source_page_title": "Gradio - Column Docs"}, {"text": "ved_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[Controlling Layout](../../guides/controlling-layout/)\n\n", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/column", "source_page_title": "Gradio - Column Docs"}, {"text": "Accordion is a layout element which can be toggled to show/hide the\ncontained content.\n\n", "heading1": "Description", "source_page_url": "https://gradio.app/docs/gradio/accordion", "source_page_title": "Gradio - Accordion Docs"}, {"text": "with gr.Accordion(\"See Details\"):\n gr.Markdown(\"lorem ipsum\")\n\n", "heading1": "Example Usage", "source_page_url": "https://gradio.app/docs/gradio/accordion", "source_page_title": "Gradio - Accordion Docs"}, {"text": "Parameters \u25bc\n\n\n \n \n label: str | I18nData | None\n\ndefault `= None`\n\nname of accordion section.\n\n\n \n \n open: bool\n\ndefault `= True`\n\nif True, accordion 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 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/accordion", "source_page_title": "Gradio - Accordion Docs"}, {"text": "", "heading1": "Methods", "source_page_url": "https://gradio.app/docs/gradio/accordion", "source_page_title": "Gradio - Accordion 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.Accordion.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.", "heading1": "expand", "source_page_url": "https://gradio.app/docs/gradio/accordion", "source_page_title": "Gradio - Accordion 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 Accordion 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", "heading1": "expand", "source_page_url": "https://gradio.app/docs/gradio/accordion", "source_page_title": "Gradio - Accordion Docs"}, {"text": "onds 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 an", "heading1": "expand", "source_page_url": "https://gradio.app/docs/gradio/accordion", "source_page_title": "Gradio - Accordion Docs"}, {"text": "ion 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\nde", "heading1": "expand", "source_page_url": "https://gradio.app/docs/gradio/accordion", "source_page_title": "Gradio - Accordion Docs"}, {"text": "enerators 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 the Gradio client libraries), or \"undocumented\" (hidden\nfrom API docs but callable by clients and via gr.load). If fn is None,\napi_visibility will automatically 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 ", "heading1": "expand", "source_page_url": "https://gradio.app/docs/gradio/accordion", "source_page_title": "Gradio - Accordion Docs"}, {"text": "gr.load). If fn is None,\napi_visibility will automatically 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/accordion", "source_page_title": "Gradio - Accordion 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.Accordion.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,%20In", "heading1": "collapse", "source_page_url": "https://gradio.app/docs/gradio/accordion", "source_page_title": "Gradio - Accordion Docs"}, {"text": "%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\nThis listener is triggered when the Accordion 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: Compon", "heading1": "collapse", "source_page_url": "https://gradio.app/docs/gradio/accordion", "source_page_title": "Gradio - Accordion Docs"}, {"text": "esponds 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", "heading1": "collapse", "source_page_url": "https://gradio.app/docs/gradio/accordion", "source_page_title": "Gradio - Accordion Docs"}, {"text": "mation 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", "heading1": "collapse", "source_page_url": "https://gradio.app/docs/gradio/accordion", "source_page_title": "Gradio - Accordion Docs"}, {"text": "r 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 the Gradio client libraries), or \"undocumented\" (hidden\nfrom API docs but callable by clients and via gr.load). If fn is None,\napi_visibility will automatically 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", "heading1": "collapse", "source_page_url": "https://gradio.app/docs/gradio/accordion", "source_page_title": "Gradio - Accordion Docs"}, {"text": "ia gr.load). If fn is None,\napi_visibility will automatically 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/accordion", "source_page_title": "Gradio - Accordion 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.Accordion.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.", "heading1": "expand", "source_page_url": "https://gradio.app/docs/gradio/accordion", "source_page_title": "Gradio - Accordion 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 Accordion 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", "heading1": "expand", "source_page_url": "https://gradio.app/docs/gradio/accordion", "source_page_title": "Gradio - Accordion Docs"}, {"text": "onds 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 an", "heading1": "expand", "source_page_url": "https://gradio.app/docs/gradio/accordion", "source_page_title": "Gradio - Accordion Docs"}, {"text": "ion 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\nde", "heading1": "expand", "source_page_url": "https://gradio.app/docs/gradio/accordion", "source_page_title": "Gradio - Accordion Docs"}, {"text": "enerators 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 the Gradio client libraries), or \"undocumented\" (hidden\nfrom API docs but callable by clients and via gr.load). If fn is None,\napi_visibility will automatically 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 ", "heading1": "expand", "source_page_url": "https://gradio.app/docs/gradio/accordion", "source_page_title": "Gradio - Accordion Docs"}, {"text": "gr.load). If fn is None,\napi_visibility will automatically 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/accordion", "source_page_title": "Gradio - Accordion 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.Accordion.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,%20In", "heading1": "collapse", "source_page_url": "https://gradio.app/docs/gradio/accordion", "source_page_title": "Gradio - Accordion Docs"}, {"text": "%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\nThis listener is triggered when the Accordion 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: Compon", "heading1": "collapse", "source_page_url": "https://gradio.app/docs/gradio/accordion", "source_page_title": "Gradio - Accordion Docs"}, {"text": "esponds 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", "heading1": "collapse", "source_page_url": "https://gradio.app/docs/gradio/accordion", "source_page_title": "Gradio - Accordion Docs"}, {"text": "mation 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", "heading1": "collapse", "source_page_url": "https://gradio.app/docs/gradio/accordion", "source_page_title": "Gradio - Accordion Docs"}, {"text": "r 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 the Gradio client libraries), or \"undocumented\" (hidden\nfrom API docs but callable by clients and via gr.load). If fn is None,\napi_visibility will automatically 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", "heading1": "collapse", "source_page_url": "https://gradio.app/docs/gradio/accordion", "source_page_title": "Gradio - Accordion Docs"}, {"text": "ia gr.load). If fn is None,\napi_visibility will automatically 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/accordion", "source_page_title": "Gradio - Accordion Docs"}, {"text": "Creates a component with arbitrary HTML. Can include CSS and JavaScript to\ncreate highly customized and interactive components.\n\n", "heading1": "Description", "source_page_url": "https://gradio.app/docs/gradio/html", "source_page_title": "Gradio - Html Docs"}, {"text": "**Using HTML as an input component.**\n\nHow HTML will pass its value to your function:\n\nType: `str | None`\n\n(Rarely used) passes the HTML as a `str`.\n\nExample Code\n\n \n \n \n import gradio as gr\n \n def predict(\n value: str | None\n ):\n process value from the HTML component\n return \"prediction\"\n \n interface = gr.Interface(predict, gr.HTML(), gr.Textbox())\n interface.launch()\n \n \n\n \n\n**Using HTML as an output component**\n\nHow HTML expects you to return a value:\n\nType: `str | None`\n\nExpects a `str` consisting of valid HTML.\n\nExample Code\n\n \n \n \n import gradio as gr\n \n def predict(text) -> str | None\n process value to return to the HTML component\n return value\n \n interface = gr.Interface(predict, gr.Textbox(), gr.HTML())\n interface.launch()\n \n \n\n", "heading1": "Behavior", "source_page_url": "https://gradio.app/docs/gradio/html", "source_page_title": "Gradio - Html Docs"}, {"text": "Parameters \u25bc\n\n\n \n \n value: Any | Callable | None\n\ndefault `= None`\n\nThe HTML content in the ${value} tag in the html_template. For example, if\nhtml_template=\"

${value}

\" and value=\"Hello, world!\", the component will\nrender as `\"

Hello, world!

\"`.\n\n\n \n \n label: str | I18nData | None\n\ndefault `= None`\n\nThe label for this component. Is used as the header if there are a table of\nexamples for this component. If None and used in a `gr.Interface`, the label\nwill be the name of the parameter this component is assigned to.\n\n\n \n \n html_template: str\n\ndefault `= \"${value}\"`\n\nA string representing the HTML template for this component as a JS template\nstring and Handlebars template. The `${value}` tag will be replaced with the\n`value` parameter, and all other tags will be filled in with the values from\n`props`. This element can have children when used in a `with gr.HTML(...):`\ncontext, and the children will be rendered to replace `@children` substring,\nwhich cannot be nested inside any HTML tags.\n\n\n \n \n css_template: str\n\ndefault `= \"\"`\n\nA string representing the CSS template for this component as a JS template\nstring and Handlebars template. The CSS will be automatically scoped to this\ncomponent, and rules outside a block will target the component's root element.\nThe `${value}` tag will be replaced with the `value` parameter, and all other\ntags will be filled in with the values from `props`.\n\n\n \n \n js_on_load: str | None\n\ndefault `= \"element.addEventListener('click', function() { trigger('click')\n});\"`\n\nA string representing the JavaScript code that will be executed when the\ncomponent is loaded. The `element` variable refers to the HTML element of this\ncomponent, and can be used to access children such as\n`element.querySelector()`. The `trigger` function can be used to trigger\nevents, such as `trigger('click')`. The value and other props can be edited\nthrough `props`, e.g. `props.value = \"new value\"` which will re-render th", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/html", "source_page_title": "Gradio - Html Docs"}, {"text": "()`. The `trigger` function can be used to trigger\nevents, such as `trigger('click')`. The value and other props can be edited\nthrough `props`, e.g. `props.value = \"new value\"` which will re-render the\nHTML template. If `server_functions` is provided, a `server` object is also\navailable in `js_on_load`, where each function is accessible as an async\nmethod, e.g. `server.list_files(path).then(files => ...)` or `const files =\nawait server.list_files(path)`. The `upload` async function can be used to\nupload a JavaScript `File` object to the Gradio server, returning a dictionary\nwith `path` (the server-side file path) and `url` (the public URL to access\nthe file), e.g. `const { path, url } = await upload(file)`. The `watch`\nfunction can be used to observe prop changes when the component is an output\nto a Python event listener: `watch('value', () => { ... })` runs the callback\nafter the template re-renders whenever `value` changes, or `watch(['value',\n'color'], () => { ... })` to watch multiple props.`.\n\n\n \n \n apply_default_css: bool\n\ndefault `= True`\n\nIf True, default Gradio CSS styles will be applied to the HTML component.\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 show_label: bool\n\ndefault `= False`\n\nIf True, the label will be displayed. If False, the label will be hidden.\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 e", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/html", "source_page_title": "Gradio - Html Docs"}, {"text": "\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 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\n \n \n min_height: int | None\n\ndefault `= None`\n\nThe minimum height of the component, specified in pixels if a number is\npassed, or in CSS units if a string is passed. If HTML content exceeds the\nheight, the component will expand to fit the content.\n\n\n \n \n max_height: int | 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 component will scroll.\n\n\n \n \n ", "heading1": "Initialization", "source_page_url": "https://gradio.app/docs/gradio/html", "source_page_title": "Gradio - Html Docs"}, {"text": "`= 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 component will scroll.\n\n\n \n \n container: bool\n\ndefault `= False`\n\nIf True, the HTML component will be displayed in a container. Default is\nFalse.\n\n\n \n \n padding: bool\n\ndefault `= False`\n\nIf True, the HTML component will have a certain padding (set by the `--block-\npadding` CSS variable) in all directions. Default is False.\n\n\n \n \n autoscroll: bool\n\ndefault `= False`\n\nIf True, will automatically scroll to the bottom of the component when the\ncontent changes, unless the user has scrolled up. If False, will not scroll to\nthe bottom when the content changes.\n\n\n \n \n buttons: list[Button] | None\n\ndefault `= None`\n\nA list of gr.Button() instances to show in the top right corner of the\ncomponent. Custom buttons will appear in the toolbar with their configured\nicon and/or label, and clicking them will trigger any .click() events\nregistered on the button.\n\n\n \n \n head: str | None\n\ndefault `= None`\n\nA raw HTML string to inject into the document `` before `js_on_load`\nruns. Typically used for `\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": "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": "Before using Custom Components, make sure you have Python 3.10+, Node.js v18+, npm 9+, and Gradio 4.0+ (preferably Gradio 5.0+) installed.\n\n", "heading1": "What do I need to install before using Custom Components?", "source_page_url": "https://gradio.app/guides/frequently-asked-questions", "source_page_title": "Custom Components - Frequently Asked Questions Guide"}, {"text": "Custom components built with Gradio 5.0 should be compatible with Gradio 4.0. If you built your custom component in Gradio 4.0 you will have to rebuild your component to be compatible with Gradio 5.0. Simply follow these steps:\n1. Update the `@gradio/preview` package. `cd` into the `frontend` directory and run `npm update`.\n2. Modify the `dependencies` key in `pyproject.toml` to pin the maximum allowed Gradio version at version 5, e.g. `dependencies = [\"gradio>=4.0,<6.0\"]`.\n3. Run the build and publish commands\n\n", "heading1": "Are custom components compatible between Gradio 4.0 and 5.0?", "source_page_url": "https://gradio.app/guides/frequently-asked-questions", "source_page_title": "Custom Components - Frequently Asked Questions Guide"}, {"text": "Run `gradio cc show` to see the list of built-in templates.\nYou can also start off from other's custom components!\nSimply `git clone` their repository and make your modifications.\n\n", "heading1": "What templates can I use to create my custom component?", "source_page_url": "https://gradio.app/guides/frequently-asked-questions", "source_page_title": "Custom Components - Frequently Asked Questions Guide"}, {"text": "When you run `gradio cc dev`, a development server will load and run a Gradio app of your choosing.\nThis is like when you run `python .py`, however the `gradio` command will hot reload so you can instantly see your changes. \n\n", "heading1": "What is the development server?", "source_page_url": "https://gradio.app/guides/frequently-asked-questions", "source_page_title": "Custom Components - Frequently Asked Questions Guide"}, {"text": "**1. Check your terminal and browser console**\n\nMake sure there are no syntax errors or other obvious problems in your code. Exceptions triggered from python will be displayed in the terminal. Exceptions from javascript will be displayed in the browser console and/or the terminal.\n\n**2. Are you developing on Windows?**\n\nChrome on Windows will block the local compiled svelte files for security reasons. We recommend developing your custom component in the windows subsystem for linux (WSL) while the team looks at this issue.\n\n**3. Inspect the window.__GRADIO_CC__ variable**\n\nIn the browser console, print the `window.__GRADIO__CC` variable (just type it into the console). If it is an empty object, that means\nthat the CLI could not find your custom component source code. Typically, this happens when the custom component is installed in a different virtual environment than the one used to run the dev command. Please use the `--python-path` and `gradio-path` CLI arguments to specify the path of the python and gradio executables for the environment your component is installed in. For example, if you are using a virtualenv located at `/Users/mary/venv`, pass in `/Users/mary/bin/python` and `/Users/mary/bin/gradio` respectively.\n\nIf the `window.__GRADIO__CC` variable is not empty (see below for an example), then the dev server should be working correctly. \n\n![](https://gradio-builds.s3.amazonaws.com/demo-files/gradio_CC_DEV.png)\n\n**4. Make sure you are using a virtual environment**\nIt is highly recommended you use a virtual environment to prevent conflicts with other python dependencies installed in your system.\n\n\n", "heading1": "The development server didn't work for me", "source_page_url": "https://gradio.app/guides/frequently-asked-questions", "source_page_title": "Custom Components - Frequently Asked Questions Guide"}, {"text": "No! You can start off from an existing gradio component as a template, see the [five minute guide](./custom-components-in-five-minutes).\nYou can also start from an existing custom component if you'd like to tweak it further. Once you find the source code of a custom component you like, clone the code to your computer and run `gradio cc install`. Then you can run the development server to make changes.If you run into any issues, contact the author of the component by opening an issue in their repository. The [gallery](https://www.gradio.app/custom-components/gallery) is a good place to look for published components. For example, to start from the [PDF component](https://www.gradio.app/custom-components/gallery?id=freddyaboulton%2Fgradio_pdf), clone the space with `git clone https://huggingface.co/spaces/freddyaboulton/gradio_pdf`, `cd` into the `src` directory, and run `gradio cc install`.\n\n\n", "heading1": "Do I always need to start my component from scratch?", "source_page_url": "https://gradio.app/guides/frequently-asked-questions", "source_page_title": "Custom Components - Frequently Asked Questions Guide"}, {"text": "You can develop and build your custom component without hosting or connecting to HuggingFace.\nIf you would like to share your component with the gradio community, it is recommended to publish your package to PyPi and host a demo on HuggingFace so that anyone can install it or try it out.\n\n", "heading1": "Do I need to host my custom component on HuggingFace Spaces?", "source_page_url": "https://gradio.app/guides/frequently-asked-questions", "source_page_title": "Custom Components - Frequently Asked Questions Guide"}, {"text": "You must implement the `preprocess`, `postprocess`, `example_payload`, and `example_value` methods. If your component does not use a data model, you must also define the `api_info`, `flag`, and `read_from_flag` methods. Read more in the [backend guide](./backend).\n\n", "heading1": "What methods are mandatory for implementing a custom component in Gradio?", "source_page_url": "https://gradio.app/guides/frequently-asked-questions", "source_page_title": "Custom Components - Frequently Asked Questions Guide"}, {"text": "A `data_model` defines the expected data format for your component, simplifying the component development process and self-documenting your code. It streamlines API usage and example caching.\n\n", "heading1": "What is the purpose of a `data_model` in Gradio custom components?", "source_page_url": "https://gradio.app/guides/frequently-asked-questions", "source_page_title": "Custom Components - Frequently Asked Questions Guide"}, {"text": "Utilizing `FileData` is crucial for components that expect file uploads. It ensures secure file handling, automatic caching, and streamlined client library functionality.\n\n", "heading1": "Why is it important to use `FileData` for components dealing with file uploads?", "source_page_url": "https://gradio.app/guides/frequently-asked-questions", "source_page_title": "Custom Components - Frequently Asked Questions Guide"}, {"text": "You can define event triggers in the `EVENTS` class attribute by listing the desired event names, which automatically adds corresponding methods to your component.\n\n", "heading1": "How can I add event triggers to my custom Gradio component?", "source_page_url": "https://gradio.app/guides/frequently-asked-questions", "source_page_title": "Custom Components - Frequently Asked Questions Guide"}, {"text": "Yes, it is possible to create custom components without a `data_model`, but you are going to have to manually implement `api_info`, `flag`, and `read_from_flag` methods.\n\n", "heading1": "Can I implement a custom Gradio component without defining a `data_model`?", "source_page_url": "https://gradio.app/guides/frequently-asked-questions", "source_page_title": "Custom Components - Frequently Asked Questions Guide"}, {"text": "We have prepared this [collection](https://huggingface.co/collections/gradio/custom-components-65497a761c5192d981710b12) of custom components on the HuggingFace Hub that you can use to get started!\n\n", "heading1": "Are there sample custom components I can learn from?", "source_page_url": "https://gradio.app/guides/frequently-asked-questions", "source_page_title": "Custom Components - Frequently Asked Questions Guide"}, {"text": "We're working on creating a gallery to make it really easy to discover new custom components.\nIn the meantime, you can search for HuggingFace Spaces that are tagged as a `gradio-custom-component` [here](https://huggingface.co/search/full-text?q=gradio-custom-component&type=space)", "heading1": "How can I find custom components created by the Gradio community?", "source_page_url": "https://gradio.app/guides/frequently-asked-questions", "source_page_title": "Custom Components - Frequently Asked Questions 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 `\n", "heading1": "Sharing Themes", "source_page_url": "https://gradio.app/guides/theming-guide", "source_page_title": "Other Tutorials - Theming Guide Guide"}, {"text": "Let\u2019s start with a simple example of integrating a C++ program into a Gradio app. Suppose we have the following C++ program that adds two numbers:\n\n```cpp\n// add.cpp\ninclude \n\nint main() {\n double a, b;\n std::cin >> a >> b;\n std::cout << a + b << std::endl;\n return 0;\n}\n```\n\nThis program reads two numbers from standard input, adds them, and outputs the result.\n\nWe can build a Gradio interface around this C++ program using Python's `subprocess` module. Here\u2019s the corresponding Python code:\n\n```python\nimport gradio as gr\nimport subprocess\n\ndef add_numbers(a, b):\n process = subprocess.Popen(\n ['./add'], \n stdin=subprocess.PIPE, \n stdout=subprocess.PIPE, \n stderr=subprocess.PIPE\n )\n output, error = process.communicate(input=f\"{a} {b}\\n\".encode())\n \n if error:\n return f\"Error: {error.decode()}\"\n return float(output.decode().strip())\n\ndemo = gr.Interface(\n fn=add_numbers, \n inputs=[gr.Number(label=\"Number 1\"), gr.Number(label=\"Number 2\")], \n outputs=gr.Textbox(label=\"Result\")\n)\n\ndemo.launch()\n```\n\nHere, `subprocess.Popen` is used to execute the compiled C++ program (`add`), pass the input values, and capture the output. You can compile the C++ program by running:\n\n```bash\ng++ -o add add.cpp\n```\n\nThis example shows how easy it is to call C++ from Python using `subprocess` and build a Gradio interface around it.\n\n", "heading1": "Using Gradio with C++", "source_page_url": "https://gradio.app/guides/using-gradio-in-other-programming-languages", "source_page_title": "Other Tutorials - Using Gradio In Other Programming Languages Guide"}, {"text": "Now, let\u2019s move to another example: calling a Rust program to apply a sepia filter to an image. The Rust code could look something like this:\n\n```rust\n// sepia.rs\nextern crate image;\n\nuse image::{GenericImageView, ImageBuffer, Rgba};\n\nfn sepia_filter(input: &str, output: &str) {\n let img = image::open(input).unwrap();\n let (width, height) = img.dimensions();\n let mut img_buf = ImageBuffer::new(width, height);\n\n for (x, y, pixel) in img.pixels() {\n let (r, g, b, a) = (pixel[0] as f32, pixel[1] as f32, pixel[2] as f32, pixel[3]);\n let tr = (0.393 * r + 0.769 * g + 0.189 * b).min(255.0);\n let tg = (0.349 * r + 0.686 * g + 0.168 * b).min(255.0);\n let tb = (0.272 * r + 0.534 * g + 0.131 * b).min(255.0);\n img_buf.put_pixel(x, y, Rgba([tr as u8, tg as u8, tb as u8, a]));\n }\n\n img_buf.save(output).unwrap();\n}\n\nfn main() {\n let args: Vec = std::env::args().collect();\n if args.len() != 3 {\n eprintln!(\"Usage: sepia \");\n return;\n }\n sepia_filter(&args[1], &args[2]);\n}\n```\n\nThis Rust program applies a sepia filter to an image. It takes two command-line arguments: the input image path and the output image path. You can compile this program using:\n\n```bash\ncargo build --release\n```\n\nNow, we can call this Rust program from Python and use Gradio to build the interface:\n\n```python\nimport gradio as gr\nimport subprocess\n\ndef apply_sepia(input_path):\n output_path = \"output.png\"\n \n process = subprocess.Popen(\n ['./target/release/sepia', input_path, output_path], \n stdout=subprocess.PIPE, \n stderr=subprocess.PIPE\n )\n process.wait()\n \n return output_path\n\ndemo = gr.Interface(\n fn=apply_sepia, \n inputs=gr.Image(type=\"filepath\", label=\"Input Image\"), \n outputs=gr.Image(label=\"Sepia Image\")\n)\n\ndemo.launch()\n```\n\nHere, when a user uploads an image and clicks submit, Gradio calls the Rust binary (`sepia`) to process the image, and re", "heading1": "Using Gradio with Rust", "source_page_url": "https://gradio.app/guides/using-gradio-in-other-programming-languages", "source_page_title": "Other Tutorials - Using Gradio In Other Programming Languages Guide"}, {"text": "nput Image\"), \n outputs=gr.Image(label=\"Sepia Image\")\n)\n\ndemo.launch()\n```\n\nHere, when a user uploads an image and clicks submit, Gradio calls the Rust binary (`sepia`) to process the image, and returns the sepia-filtered output to Gradio.\n\nThis setup showcases how you can integrate performance-critical or specialized code written in Rust into a Gradio interface.\n\n", "heading1": "Using Gradio with Rust", "source_page_url": "https://gradio.app/guides/using-gradio-in-other-programming-languages", "source_page_title": "Other Tutorials - Using Gradio In Other Programming Languages Guide"}, {"text": "Integrating Gradio with R is particularly straightforward thanks to the `reticulate` package, which allows you to run Python code directly in R. Let\u2019s walk through an example of using Gradio in R. \n\n**Installation**\n\nFirst, you need to install the `reticulate` package in R:\n\n```r\ninstall.packages(\"reticulate\")\n```\n\n\nOnce installed, you can use the package to run Gradio directly from within an R script.\n\n\n```r\nlibrary(reticulate)\n\npy_install(\"gradio\", pip = TRUE)\n\ngr <- import(\"gradio\") import gradio as gr\n```\n\n**Building a Gradio Application**\n\nWith gradio installed and imported, we now have access to gradio's app building methods. Let's build a simple app for an R function that returns a greeting\n\n```r\ngreeting <- \\(name) paste(\"Hello\", name)\n\napp <- gr$Interface(\n fn = greeting,\n inputs = gr$Text(label = \"Name\"),\n outputs = gr$Text(label = \"Greeting\"),\n title = \"Hello! &128515 &128075\"\n)\n\napp$launch(server_name = \"localhost\", \n server_port = as.integer(3000))\n```\n\nCredit to [@IfeanyiIdiaye](https://github.com/Ifeanyi55) for contributing this section. You can see more examples [here](https://github.com/Ifeanyi55/Gradio-in-R/tree/main/Code), including using Gradio Blocks to build a machine learning application in R.\n", "heading1": "Using Gradio with R (via `reticulate`)", "source_page_url": "https://gradio.app/guides/using-gradio-in-other-programming-languages", "source_page_title": "Other Tutorials - Using Gradio In Other Programming Languages Guide"}, {"text": "**[OpenAPI](https://www.openapis.org/)** is a widely adopted standard for describing RESTful APIs in a machine-readable format, typically as a JSON file. \n\nYou can create a Gradio UI from an OpenAPI Spec **in 1 line of Python**, instantly generating an interactive web interface for any API, making it accessible for demos, testing, or sharing with non-developers, without writing custom frontend code.\n\n", "heading1": "Introduction", "source_page_url": "https://gradio.app/guides/from-openapi-spec", "source_page_title": "Other Tutorials - From Openapi Spec Guide"}, {"text": "Gradio now provides a convenient function, `gr.load_openapi`, that can automatically generate a Gradio app from an OpenAPI v3 specification. This function parses the spec, creates UI components for each endpoint and parameter, and lets you interact with the API directly from your browser.\n\nHere's a minimal example:\n\n```python\nimport gradio as gr\n\ndemo = gr.load_openapi(\n openapi_spec=\"https://petstore3.swagger.io/api/v3/openapi.json\",\n base_url=\"https://petstore3.swagger.io/api/v3\",\n paths=[\"/pet.*\"],\n methods=[\"get\", \"post\"],\n)\n\ndemo.launch()\n```\n\n**Parameters:**\n- **openapi_spec**: URL, file path, or Python dictionary containing the OpenAPI v3 spec (JSON format only).\n- **base_url**: The base URL for the API endpoints (e.g., `https://api.example.com/v1`).\n- **paths** (optional): List of endpoint path patterns (supports regex) to include. If not set, all paths are included.\n- **methods** (optional): List of HTTP methods (e.g., `[\"get\", \"post\"]`) to include. If not set, all methods are included.\n\nThe generated app will display a sidebar with available endpoints and create interactive forms for each operation, letting you make API calls and view responses in real time.\n\n", "heading1": "How it works", "source_page_url": "https://gradio.app/guides/from-openapi-spec", "source_page_title": "Other Tutorials - From Openapi Spec Guide"}, {"text": "Once your Gradio app is running, you can share the URL with others so they can try out the API through a friendly web interface\u2014no code required. For even more power, you can launch the app as an MCP (Model Control Protocol) server using [Gradio's MCP integration](https://www.gradio.app/guides/building-mcp-server-with-gradio), enabling programmatic access and orchestration of your API via the MCP ecosystem. This makes it easy to build, share, and automate API workflows with minimal effort.\n\n", "heading1": "Next steps", "source_page_url": "https://gradio.app/guides/from-openapi-spec", "source_page_title": "Other Tutorials - From Openapi Spec Guide"}, {"text": "A virtual environment in Python is a self-contained directory that holds a Python installation for a particular version of Python, along with a number of additional packages. This environment is isolated from the main Python installation and other virtual environments. Each environment can have its own independent set of installed Python packages, which allows you to maintain different versions of libraries for different projects without conflicts.\n\n\nUsing virtual environments ensures that you can work on multiple Python projects on the same machine without any conflicts. This is particularly useful when different projects require different versions of the same library. It also simplifies dependency management and enhances reproducibility, as you can easily share the requirements of your project with others.\n\n\n", "heading1": "Virtual Environments", "source_page_url": "https://gradio.app/guides/installing-gradio-in-a-virtual-environment", "source_page_title": "Other Tutorials - Installing Gradio In A Virtual Environment Guide"}, {"text": "To install Gradio on a Windows system in a virtual environment, follow these steps:\n\n1. **Install Python**: Ensure you have Python 3.10 or higher installed. You can download it from [python.org](https://www.python.org/). You can verify the installation by running `python --version` or `python3 --version` in Command Prompt.\n\n\n2. **Create a Virtual Environment**:\n Open Command Prompt and navigate to your project directory. Then create a virtual environment using the following command:\n\n ```bash\n python -m venv gradio-env\n ```\n\n This command creates a new directory `gradio-env` in your project folder, containing a fresh Python installation.\n\n3. **Activate the Virtual Environment**:\n To activate the virtual environment, run:\n\n ```bash\n .\\gradio-env\\Scripts\\activate\n ```\n\n Your command prompt should now indicate that you are working inside `gradio-env`. Note: you can choose a different name than `gradio-env` for your virtual environment in this step.\n\n\n4. **Install Gradio**:\n Now, you can install Gradio using pip:\n\n ```bash\n pip install gradio\n ```\n\n5. **Verification**:\n To verify the installation, run `python` and then type:\n\n ```python\n import gradio as gr\n print(gr.__version__)\n ```\n\n This will display the installed version of Gradio.\n\n", "heading1": "Installing Gradio on Windows", "source_page_url": "https://gradio.app/guides/installing-gradio-in-a-virtual-environment", "source_page_title": "Other Tutorials - Installing Gradio In A Virtual Environment Guide"}, {"text": "The installation steps on MacOS and Linux are similar to Windows but with some differences in commands.\n\n1. **Install Python**:\n Python usually comes pre-installed on MacOS and most Linux distributions. You can verify the installation by running `python --version` in the terminal (note that depending on how Python is installed, you might have to use `python3` instead of `python` throughout these steps). \n \n Ensure you have Python 3.10 or higher installed. If you do not have it installed, you can download it from [python.org](https://www.python.org/). \n\n2. **Create a Virtual Environment**:\n Open Terminal and navigate to your project directory. Then create a virtual environment using:\n\n ```bash\n python -m venv gradio-env\n ```\n\n Note: you can choose a different name than `gradio-env` for your virtual environment in this step.\n\n3. **Activate the Virtual Environment**:\n To activate the virtual environment on MacOS/Linux, use:\n\n ```bash\n source gradio-env/bin/activate\n ```\n\n4. **Install Gradio**:\n With the virtual environment activated, install Gradio using pip:\n\n ```bash\n pip install gradio\n ```\n\n5. **Verification**:\n To verify the installation, run `python` and then type:\n\n ```python\n import gradio as gr\n print(gr.__version__)\n ```\n\n This will display the installed version of Gradio.\n\nBy following these steps, you can successfully install Gradio in a virtual environment on your operating system, ensuring a clean and managed workspace for your Python projects.", "heading1": "Installing Gradio on MacOS/Linux", "source_page_url": "https://gradio.app/guides/installing-gradio-in-a-virtual-environment", "source_page_title": "Other Tutorials - Installing Gradio In A Virtual Environment Guide"}, {"text": "First of all, we need some data to visualize. Following this [excellent guide](https://supabase.com/blog/loading-data-supabase-python), we'll create fake commerce data and put it in Supabase.\n\n1\\. Start by creating a new project in Supabase. Once you're logged in, click the \"New Project\" button\n\n2\\. Give your project a name and database password. You can also choose a pricing plan (for our purposes, the Free Tier is sufficient!)\n\n3\\. You'll be presented with your API keys while the database spins up (can take up to 2 minutes).\n\n4\\. Click on \"Table Editor\" (the table icon) in the left pane to create a new table. We'll create a single table called `Product`, with the following schema:\n\n
\n\n\n\n\n\n
product_idint8
inventory_countint8
pricefloat8
product_namevarchar
\n
\n\n5\\. Click Save to save the table schema.\n\nOur table is now ready!\n\n", "heading1": "Create a table in Supabase", "source_page_url": "https://gradio.app/guides/creating-a-dashboard-from-supabase-data", "source_page_title": "Other Tutorials - Creating A Dashboard From Supabase Data Guide"}, {"text": "The next step is to write data to a Supabase dataset. We will use the Supabase Python library to do this.\n\n6\\. Install `supabase` by running the following command in your terminal:\n\n```bash\npip install supabase\n```\n\n7\\. Get your project URL and API key. Click the Settings (gear icon) on the left pane and click 'API'. The URL is listed in the Project URL box, while the API key is listed in Project API keys (with the tags `service_role`, `secret`)\n\n8\\. Now, run the following Python script to write some fake data to the table (note you have to put the values of `SUPABASE_URL` and `SUPABASE_SECRET_KEY` from step 7):\n\n```python\nimport supabase\n\nInitialize the Supabase client\nclient = supabase.create_client('SUPABASE_URL', 'SUPABASE_SECRET_KEY')\n\nDefine the data to write\nimport random\n\nmain_list = []\nfor i in range(10):\n value = {'product_id': i,\n 'product_name': f\"Item {i}\",\n 'inventory_count': random.randint(1, 100),\n 'price': random.random()*100\n }\n main_list.append(value)\n\nWrite the data to the table\ndata = client.table('Product').insert(main_list).execute()\n```\n\nReturn to your Supabase dashboard and refresh the page, you should now see 10 rows populated in the `Product` table!\n\n", "heading1": "Write data to Supabase", "source_page_url": "https://gradio.app/guides/creating-a-dashboard-from-supabase-data", "source_page_title": "Other Tutorials - Creating A Dashboard From Supabase Data Guide"}, {"text": "Finally, we will read the data from the Supabase dataset using the same `supabase` Python library and create a realtime dashboard using `gradio`.\n\nNote: We repeat certain steps in this section (like creating the Supabase client) in case you did not go through the previous sections. As described in Step 7, you will need the project URL and API Key for your database.\n\n9\\. Write a function that loads the data from the `Product` table and returns it as a pandas Dataframe:\n\n```python\nimport supabase\nimport pandas as pd\n\nclient = supabase.create_client('SUPABASE_URL', 'SUPABASE_SECRET_KEY')\n\ndef read_data():\n response = client.table('Product').select(\"*\").execute()\n df = pd.DataFrame(response.data)\n return df\n```\n\n10\\. Create a small Gradio Dashboard with 2 Barplots that plots the prices and inventories of all of the items every minute and updates in real-time:\n\n```python\nimport gradio as gr\n\nwith gr.Blocks() as dashboard:\n with gr.Row():\n gr.BarPlot(read_data, x=\"product_id\", y=\"price\", title=\"Prices\", every=gr.Timer(60))\n gr.BarPlot(read_data, x=\"product_id\", y=\"inventory_count\", title=\"Inventory\", every=gr.Timer(60))\n\ndashboard.queue().launch()\n```\n\nNotice that by passing in a function to `gr.BarPlot()`, we have the BarPlot query the database as soon as the web app loads (and then again every 60 seconds because of the `every` parameter). Your final dashboard should look something like this:\n\n\n\n", "heading1": "Visualize the Data in a Real-Time Gradio Dashboard", "source_page_url": "https://gradio.app/guides/creating-a-dashboard-from-supabase-data", "source_page_title": "Other Tutorials - Creating A Dashboard From Supabase Data Guide"}, {"text": "That's it! In this tutorial, you learned how to write data to a Supabase dataset, and then read that data and plot the results as bar plots. If you update the data in the Supabase database, you'll notice that the Gradio dashboard will update within a minute.\n\nTry adding more plots and visualizations to this example (or with a different dataset) to build a more complex dashboard!\n", "heading1": "Conclusion", "source_page_url": "https://gradio.app/guides/creating-a-dashboard-from-supabase-data", "source_page_title": "Other Tutorials - Creating A Dashboard From Supabase Data Guide"}, {"text": "Data visualization is a crucial aspect of data analysis and machine learning. The Gradio `DataFrame` component is a popular way to display tabular data within a web application. \n\nBut what if you want to stylize the table of data? What if you want to add background colors, partially highlight cells, or change the display precision of numbers? This Guide is for you!\n\n\n\nLet's dive in!\n\n**Prerequisites**: We'll be using the `gradio.Blocks` class in our examples.\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\n", "heading1": "Introduction", "source_page_url": "https://gradio.app/guides/styling-the-gradio-dataframe", "source_page_title": "Other Tutorials - Styling The Gradio Dataframe Guide"}, {"text": "The Gradio `DataFrame` component now supports values of the type `Styler` from the `pandas` class. This allows us to reuse the rich existing API and documentation of the `Styler` class instead of inventing a new style format on our own. Here's a complete example of how it looks:\n\n```python\nimport pandas as pd \nimport gradio as gr\n\nCreating a sample dataframe\ndf = pd.DataFrame({\n \"A\" : [14, 4, 5, 4, 1], \n \"B\" : [5, 2, 54, 3, 2], \n \"C\" : [20, 20, 7, 3, 8], \n \"D\" : [14, 3, 6, 2, 6], \n \"E\" : [23, 45, 64, 32, 23]\n}) \n\nApplying style to highlight the maximum value in each row\nstyler = df.style.highlight_max(color = 'lightgreen', axis = 0)\n\nDisplaying the styled dataframe in Gradio\nwith gr.Blocks() as demo:\n gr.DataFrame(styler)\n \ndemo.launch()\n```\n\nThe Styler class can be used to apply conditional formatting and styling to dataframes, making them more visually appealing and interpretable. You can highlight certain values, apply gradients, or even use custom CSS to style the DataFrame. The Styler object is applied to a DataFrame and it returns a new object with the relevant styling properties, which can then be previewed directly, or rendered dynamically in a Gradio interface.\n\nTo read more about the Styler object, read the official `pandas` documentation at: https://pandas.pydata.org/docs/user_guide/style.html\n\nBelow, we'll explore a few examples:\n\nHighlighting Cells\n\nOk, so let's revisit the previous example. We start by creating a `pd.DataFrame` object and then highlight the highest value in each row with a light green color:\n\n```python\nimport pandas as pd \n\nCreating a sample dataframe\ndf = pd.DataFrame({\n \"A\" : [14, 4, 5, 4, 1], \n \"B\" : [5, 2, 54, 3, 2], \n \"C\" : [20, 20, 7, 3, 8], \n \"D\" : [14, 3, 6, 2, 6], \n \"E\" : [23, 45, 64, 32, 23]\n}) \n\nApplying style to highlight the maximum value in each row\nstyler = df.style.highlight_max(color = 'lightgreen', axis = 0)\n```\n\nNow, we simply pass this object into the Gradio `DataFra", "heading1": "The Pandas `Styler`", "source_page_url": "https://gradio.app/guides/styling-the-gradio-dataframe", "source_page_title": "Other Tutorials - Styling The Gradio Dataframe Guide"}, {"text": ", 32, 23]\n}) \n\nApplying style to highlight the maximum value in each row\nstyler = df.style.highlight_max(color = 'lightgreen', axis = 0)\n```\n\nNow, we simply pass this object into the Gradio `DataFrame` and we can visualize our colorful table of data in 4 lines of python:\n\n```python\nimport gradio as gr\n\nwith gr.Blocks() as demo:\n gr.Dataframe(styler)\n \ndemo.launch()\n```\n\nHere's how it looks:\n\n![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/df-highlight.png)\n\nFont Colors\n\nApart from highlighting cells, you might want to color specific text within the cells. Here's how you can change text colors for certain columns:\n\n```python\nimport pandas as pd \nimport gradio as gr\n\nCreating a sample dataframe\ndf = pd.DataFrame({\n \"A\" : [14, 4, 5, 4, 1], \n \"B\" : [5, 2, 54, 3, 2], \n \"C\" : [20, 20, 7, 3, 8], \n \"D\" : [14, 3, 6, 2, 6], \n \"E\" : [23, 45, 64, 32, 23]\n}) \n\nFunction to apply text color\ndef highlight_cols(x): \n df = x.copy() \n df.loc[:, :] = 'color: purple'\n df[['B', 'C', 'E']] = 'color: green'\n return df \n\nApplying the style function\ns = df.style.apply(highlight_cols, axis = None)\n\nDisplaying the styled dataframe in Gradio\nwith gr.Blocks() as demo:\n gr.DataFrame(s)\n \ndemo.launch()\n```\n\nIn this script, we define a custom function highlight_cols that changes the text color to purple for all cells, but overrides this for columns B, C, and E with green. Here's how it looks:\n\n![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/df-color.png)\n\nDisplay Precision \n\nSometimes, the data you are dealing with might have long floating numbers, and you may want to display only a fixed number of decimals for simplicity. The pandas Styler object allows you to format the precision of numbers displayed. Here's how you can do this:\n\n```python\nimport pandas as pd\nimport gradio as gr\n\nCreating a sample dataframe with floating numbers\ndf = pd.DataFrame({\n \"A\" : [14.12345, 4.", "heading1": "The Pandas `Styler`", "source_page_url": "https://gradio.app/guides/styling-the-gradio-dataframe", "source_page_title": "Other Tutorials - Styling The Gradio Dataframe Guide"}, {"text": "on of numbers displayed. Here's how you can do this:\n\n```python\nimport pandas as pd\nimport gradio as gr\n\nCreating a sample dataframe with floating numbers\ndf = pd.DataFrame({\n \"A\" : [14.12345, 4.23456, 5.34567, 4.45678, 1.56789], \n \"B\" : [5.67891, 2.78912, 54.89123, 3.91234, 2.12345], \n ... other columns\n}) \n\nSetting the precision of numbers to 2 decimal places\ns = df.style.format(\"{:.2f}\")\n\nDisplaying the styled dataframe in Gradio\nwith gr.Blocks() as demo:\n gr.DataFrame(s)\n \ndemo.launch()\n```\n\nIn this script, the format method of the Styler object is used to set the precision of numbers to two decimal places. Much cleaner now:\n\n![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/df-precision.png)\n\n\n\n", "heading1": "The Pandas `Styler`", "source_page_url": "https://gradio.app/guides/styling-the-gradio-dataframe", "source_page_title": "Other Tutorials - Styling The Gradio Dataframe Guide"}, {"text": "So far, we've been restricting ourselves to styling that is supported by the Pandas `Styler` class. But what if you want to create custom styles like partially highlighting cells based on their values:\n\n![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio-guides/dataframe_custom_styling.png)\n\n\nThis isn't possible with `Styler`, but you can do this by creating your own **`styling`** array, which is a 2D array the same size and shape as your data. Each element in this list should be a CSS style string (e.g. `\"background-color: green\"`) that applies to the `` element containing the cell value (or an empty string if no custom CSS should be applied). Similarly, you can create a **`display_value`** array which controls the value that is displayed in each cell (which can be different the underlying value which is the one that is used for searching/sorting).\n\nHere's the complete code for how to can use custom styling with `gr.Dataframe` as in the screenshot above:\n\n$code_dataframe_custom_styling\n\n\n", "heading1": "Custom Styling", "source_page_url": "https://gradio.app/guides/styling-the-gradio-dataframe", "source_page_title": "Other Tutorials - Styling The Gradio Dataframe Guide"}, {"text": "One thing to keep in mind is that the gradio `DataFrame` component only accepts custom styling objects when it is non-interactive (i.e. in \"static\" mode). If the `DataFrame` component is interactive, then the styling information is ignored and instead the raw table values are shown instead. \n\nThe `DataFrame` component is by default non-interactive, unless it is used as an input to an event. In which case, you can force the component to be non-interactive by setting the `interactive` prop like this:\n\n```python\nc = gr.DataFrame(styler, interactive=False)\n```\n\n", "heading1": "Note about Interactivity", "source_page_url": "https://gradio.app/guides/styling-the-gradio-dataframe", "source_page_title": "Other Tutorials - Styling The Gradio Dataframe Guide"}, {"text": "This is just a taste of what's possible using the `gradio.DataFrame` component with the `Styler` class from `pandas`. Try it out and let us know what you think!", "heading1": "Conclusion \ud83c\udf89", "source_page_url": "https://gradio.app/guides/styling-the-gradio-dataframe", "source_page_title": "Other Tutorials - Styling The Gradio Dataframe Guide"}, {"text": "Make sure you have Gradio installed along with a recent version of `huggingface_hub`:\n\n```bash\npip install --upgrade gradio huggingface_hub\n```\n\n> `huggingface_hub >= 1.4.0` is required for the skills command.\n\n", "heading1": "Prerequisites", "source_page_url": "https://gradio.app/guides/Gradio-skills-for-ai-coding-assistants", "source_page_title": "Other Tutorials - Gradio Skills For Ai Coding Assistants Guide"}, {"text": "The general Gradio skill gives your assistant comprehensive knowledge of the Gradio API \u2014 components, event listeners, layout patterns, and working examples.\n\nTo install, pass the flag for your assistant:\n\n```bash\ngradio skills add --cursor or --claude, --codex, --opencode\n```\n\nThis downloads two files (`SKILL.md` and `examples.md`) into a central location (`.agents/skills/gradio/`) and creates **symlinks** from each assistant's skills directory (e.g., `.claude/skills/gradio/` for Claude Code) pointing to the central copy. This avoids duplicating files when you install for multiple assistants.\n\n", "heading1": "Installing the General Gradio Skill", "source_page_url": "https://gradio.app/guides/Gradio-skills-for-ai-coding-assistants", "source_page_title": "Other Tutorials - Gradio Skills For Ai Coding Assistants Guide"}, {"text": "By default, skills are installed **locally** in your current project directory. This means the assistant only has Gradio knowledge when working in that project.\n\nTo install **globally** (user-level, available in all projects):\n\n```bash\ngradio skills add --claude --global\n```\n\nOr using the short flag:\n\n```bash\ngradio skills add --claude -g\n```\n\n", "heading1": "Project-Level vs. Global Installation", "source_page_url": "https://gradio.app/guides/Gradio-skills-for-ai-coding-assistants", "source_page_title": "Other Tutorials - Gradio Skills For Ai Coding Assistants Guide"}, {"text": "One of the most powerful features is generating a skill for any public HuggingFace Space. This gives your assistant full knowledge of that Space's API \u2014 endpoints, parameters, return types, and ready-to-use code snippets.\n\n```bash\ngradio skills add abidlabs/english-translator --claude\n```\n\nThis connects to the Space, extracts its API schema, and generates a `SKILL.md` file with:\n\n- A description of each API endpoint\n- Parameter names, types, defaults, and whether they're required\n- Return value types\n- Code snippets in Python, JavaScript, and cURL\n\nFor private Spaces, set your Hugging Face token:\n\n```bash\nexport HF_TOKEN=hf_xxxxx\ngradio skills add my-org/private-space --claude\n```\n\n\n\n", "heading1": "Generating a Skill for a Specific HuggingFace Space", "source_page_url": "https://gradio.app/guides/Gradio-skills-for-ai-coding-assistants", "source_page_title": "Other Tutorials - Gradio Skills For Ai Coding Assistants Guide"}, {"text": "If a skill is already installed, the command will exit with an error. To overwrite it:\n\n```bash\ngradio skills add --claude --force\n```\n\n", "heading1": "Overwriting Existing Skills", "source_page_url": "https://gradio.app/guides/Gradio-skills-for-ai-coding-assistants", "source_page_title": "Other Tutorials - Gradio Skills For Ai Coding Assistants Guide"}, {"text": "General Gradio Skill\n\n| File | Contents |\n|------|----------|\n| `SKILL.md` | Core API reference \u2014 component signatures, event listeners, layout patterns, ChatInterface, and links to detailed guides |\n| `examples.md` | Complete working Gradio apps covering common patterns (forms, chatbots, streaming, image processing, etc.) |\n\nSpace-Specific Skill\n\n| File | Contents |\n|------|----------|\n| `SKILL.md` | Auto-generated API reference for the Space's endpoints, with code snippets in Python, JavaScript, and cURL |\n\n", "heading1": "What Gets Installed", "source_page_url": "https://gradio.app/guides/Gradio-skills-for-ai-coding-assistants", "source_page_title": "Other Tutorials - Gradio Skills For Ai Coding Assistants Guide"}, {"text": "Here's a typical workflow using skills with Claude Code:\n\n1. **Install the skill** in your project:\n ```bash\n cd my-project\n gradio skills add --claude\n ```\n\n2. **Start Claude Code** and ask it to build a Gradio app:\n ```\n > Build me a Gradio app with an image input that applies a sepia filter\n and displays the result\n ```\n\n Claude Code now has full knowledge of `gr.Image`, `gr.Interface`, event listeners, and can write correct, idiomatic Gradio code.\n\n3. **Add a Space skill** if you want to integrate with an existing Space:\n ```bash\n gradio skills add abidlabs/english-translator --claude\n ```\n\n Now you can ask:\n ```\n > Use the english-translator Space API to add a translation feature\n to my app\n ```\n\n", "heading1": "Example Workflow", "source_page_url": "https://gradio.app/guides/Gradio-skills-for-ai-coding-assistants", "source_page_title": "Other Tutorials - Gradio Skills For Ai Coding Assistants Guide"}, {"text": "Gradio features [blocks](https://www.gradio.app/docs/blocks) to easily layout applications. To use this feature, you need to stack or nest layout components and create a hierarchy with them. This isn't difficult to implement and maintain for small projects, but after the project gets more complex, this component hierarchy becomes difficult to maintain and reuse.\n\nIn this guide, we are going to explore how we can wrap the layout classes to create more maintainable and easy-to-read applications without sacrificing flexibility.\n\n", "heading1": "Introduction", "source_page_url": "https://gradio.app/guides/wrapping-layouts", "source_page_title": "Other Tutorials - Wrapping Layouts Guide"}, {"text": "We are going to follow the implementation from this Huggingface Space example:\n\n\n\n\n", "heading1": "Example", "source_page_url": "https://gradio.app/guides/wrapping-layouts", "source_page_title": "Other Tutorials - Wrapping Layouts Guide"}, {"text": "The wrapping utility has two important classes. The first one is the ```LayoutBase``` class and the other one is the ```Application``` class.\n\nWe are going to look at the ```render``` and ```attach_event``` functions of them for brevity. You can look at the full implementation from [the example code](https://huggingface.co/spaces/WoWoWoWololo/wrapping-layouts/blob/main/app.py).\n\nSo let's start with the ```LayoutBase``` class.\n\nLayoutBase Class\n\n1. Render Function\n\n Let's look at the ```render``` function in the ```LayoutBase``` class:\n\n```python\nother LayoutBase implementations\n\ndef render(self) -> None:\n with self.main_layout:\n for renderable in self.renderables:\n renderable.render()\n\n self.main_layout.render()\n```\nThis is a little confusing at first but if you consider the default implementation you can understand it easily.\nLet's look at an example:\n\nIn the default implementation, this is what we're doing:\n\n```python\nwith Row():\n left_textbox = Textbox(value=\"left_textbox\")\n right_textbox = Textbox(value=\"right_textbox\")\n```\n\nNow, pay attention to the Textbox variables. These variables' ```render``` parameter is true by default. So as we use the ```with``` syntax and create these variables, they are calling the ```render``` function under the ```with``` syntax.\n\nWe know the render function is called in the constructor with the implementation from the ```gradio.blocks.Block``` class:\n\n```python\nclass Block:\n constructor parameters are omitted for brevity\n def __init__(self, ...):\n other assign functions \n\n if render:\n self.render()\n```\n\nSo our implementation looks like this:\n\n```python\nself.main_layout -> Row()\nwith self.main_layout:\n left_textbox.render()\n right_textbox.render()\n```\n\nWhat this means is by calling the components' render functions under the ```with``` syntax, we are actually simulating the default implementation.\n\nSo now let's consider two nested ```with```s to see ho", "heading1": "Implementation", "source_page_url": "https://gradio.app/guides/wrapping-layouts", "source_page_title": "Other Tutorials - Wrapping Layouts Guide"}, {"text": "at this means is by calling the components' render functions under the ```with``` syntax, we are actually simulating the default implementation.\n\nSo now let's consider two nested ```with```s to see how the outer one works. For this, let's expand our example with the ```Tab``` component:\n\n```python\nwith Tab():\n with Row():\n first_textbox = Textbox(value=\"first_textbox\")\n second_textbox = Textbox(value=\"second_textbox\")\n```\n\nPay attention to the Row and Tab components this time. We have created the Textbox variables above and added them to Row with the ```with``` syntax. Now we need to add the Row component to the Tab component. You can see that the Row component is created with default parameters, so its render parameter is true, that's why the render function is going to be executed under the Tab component's ```with``` syntax.\n\nTo mimic this implementation, we need to call the ```render``` function of the ```main_layout``` variable after the ```with``` syntax of the ```main_layout``` variable.\n\nSo the implementation looks like this:\n\n```python\nwith tab_main_layout:\n with row_main_layout:\n first_textbox.render()\n second_textbox.render()\n\n row_main_layout.render()\n\ntab_main_layout.render()\n```\n\nThe default implementation and our implementation are the same, but we are using the render function ourselves. So it requires a little work.\n\nNow, let's take a look at the ```attach_event``` function.\n\n2. Attach Event Function\n\n The function is left as not implemented because it is specific to the class, so each class has to implement its `attach_event` function.\n\n```python\n other LayoutBase implementations\n\n def attach_event(self, block_dict: Dict[str, Block]) -> None:\n raise NotImplementedError\n```\n\nCheck out the ```block_dict``` variable in the ```Application``` class's ```attach_event``` function.\n\nApplication Class\n\n1. Render Function\n\n```python\n other Application implementations\n\n def _render(self):\n ", "heading1": "Implementation", "source_page_url": "https://gradio.app/guides/wrapping-layouts", "source_page_title": "Other Tutorials - Wrapping Layouts Guide"}, {"text": "ct``` variable in the ```Application``` class's ```attach_event``` function.\n\nApplication Class\n\n1. Render Function\n\n```python\n other Application implementations\n\n def _render(self):\n with self.app:\n for child in self.children:\n child.render()\n\n self.app.render()\n```\n\nFrom the explanation of the ```LayoutBase``` class's ```render``` function, we can understand the ```child.render``` part.\n\nSo let's look at the bottom part, why are we calling the ```app``` variable's ```render``` function? It's important to call this function because if we look at the implementation in the ```gradio.blocks.Blocks``` class, we can see that it is adding the components and event functions into the root component. To put it another way, it is creating and structuring the gradio application.\n\n2. Attach Event Function\n\n Let's see how we can attach events to components:\n\n```python\n other Application implementations\n\n def _attach_event(self):\n block_dict: Dict[str, Block] = {}\n\n for child in self.children:\n block_dict.update(child.global_children_dict)\n\n with self.app:\n for child in self.children:\n try:\n child.attach_event(block_dict=block_dict)\n except NotImplementedError:\n print(f\"{child.name}'s attach_event is not implemented\")\n```\n\nYou can see why the ```global_children_list``` is used in the ```LayoutBase``` class from the example code. With this, all the components in the application are gathered into one dictionary, so the component can access all the components with their names.\n\nThe ```with``` syntax is used here again to attach events to components. If we look at the ```__exit__``` function in the ```gradio.blocks.Blocks``` class, we can see that it is calling the ```attach_load_events``` function which is used for setting event triggers to components. So we have to use the ```with``` syntax to trigger the ```_", "heading1": "Implementation", "source_page_url": "https://gradio.app/guides/wrapping-layouts", "source_page_title": "Other Tutorials - Wrapping Layouts Guide"}, {"text": "Blocks``` class, we can see that it is calling the ```attach_load_events``` function which is used for setting event triggers to components. So we have to use the ```with``` syntax to trigger the ```__exit__``` function.\n\nOf course, we can call ```attach_load_events``` without using the ```with``` syntax, but the function needs a ```Context.root_block```, and it is set in the ```__enter__``` function. So we used the ```with``` syntax here rather than calling the function ourselves.\n\n", "heading1": "Implementation", "source_page_url": "https://gradio.app/guides/wrapping-layouts", "source_page_title": "Other Tutorials - Wrapping Layouts Guide"}, {"text": "In this guide, we saw\n\n- How we can wrap the layouts\n- How components are rendered\n- How we can structure our application with wrapped layout classes\n\nBecause the classes used in this guide are used for demonstration purposes, they may still not be totally optimized or modular. But that would make the guide much longer!\n\nI hope this guide helps you gain another view of the layout classes and gives you an idea about how you can use them for your needs. See the full implementation of our example [here](https://huggingface.co/spaces/WoWoWoWololo/wrapping-layouts/blob/main/app.py).\n", "heading1": "Conclusion", "source_page_url": "https://gradio.app/guides/wrapping-layouts", "source_page_title": "Other Tutorials - Wrapping Layouts Guide"}, {"text": "In this Guide, we'll walk you through:\n\n- Introduction of Gradio, and Hugging Face Spaces, and Wandb\n- How to setup a Gradio demo using the Wandb integration for JoJoGAN\n- How to contribute your own Gradio demos after tracking your experiments on wandb to the Wandb organization on Hugging Face\n\n\n", "heading1": "Introduction", "source_page_url": "https://gradio.app/guides/Gradio-and-Wandb-Integration", "source_page_title": "Other Tutorials - Gradio And Wandb Integration Guide"}, {"text": "Weights and Biases (W&B) allows data scientists and machine learning scientists to track their machine learning experiments at every stage, from training to production. Any metric can be aggregated over samples and shown in panels in a customizable and searchable dashboard, like below:\n\n\"Screen\n\n", "heading1": "What is Wandb?", "source_page_url": "https://gradio.app/guides/Gradio-and-Wandb-Integration", "source_page_title": "Other Tutorials - Gradio And Wandb Integration Guide"}, {"text": "Gradio\n\nGradio lets users demo their machine learning models as a web app, all in a few lines of Python. Gradio wraps any Python function (such as a machine learning model's inference function) into a user interface and the demos can be launched inside jupyter notebooks, colab notebooks, as well as embedded in your own website and hosted on Hugging Face Spaces for free.\n\nGet started [here](https://gradio.app/getting_started)\n\nHugging Face Spaces\n\nHugging Face Spaces is a free hosting option for Gradio demos. Spaces comes with 3 SDK options: Gradio, Streamlit and Static HTML demos. Spaces can be public or private and the workflow is similar to github repos. There are over 2000+ spaces currently on Hugging Face. Learn more about spaces [here](https://huggingface.co/spaces/launch).\n\n", "heading1": "What are Hugging Face Spaces & Gradio?", "source_page_url": "https://gradio.app/guides/Gradio-and-Wandb-Integration", "source_page_title": "Other Tutorials - Gradio And Wandb Integration Guide"}, {"text": "Now, let's walk you through how to do this on your own. We'll make the assumption that you're new to W&B and Gradio for the purposes of this tutorial.\n\nLet's get started!\n\n1. Create a W&B account\n\n Follow [these quick instructions](https://app.wandb.ai/login) to create your free account if you don\u2019t have one already. It shouldn't take more than a couple minutes. Once you're done (or if you've already got an account), next, we'll run a quick colab.\n\n2. Open Colab Install Gradio and W&B\n\n We'll be following along with the colab provided in the JoJoGAN repo with some minor modifications to use Wandb and Gradio more effectively.\n\n [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/mchong6/JoJoGAN/blob/main/stylize.ipynb)\n\n Install Gradio and Wandb at the top:\n\n ```sh\n pip install gradio wandb\n ```\n\n3. Finetune StyleGAN and W&B experiment tracking\n\n This next step will open a W&B dashboard to track your experiments and a gradio panel showing pretrained models to choose from a drop down menu from a Gradio Demo hosted on Huggingface Spaces. Here's the code you need for that:\n\n ```python\n alpha = 1.0\n alpha = 1-alpha\n\n preserve_color = True\n num_iter = 100\n log_interval = 50\n\n samples = []\n column_names = [\"Reference (y)\", \"Style Code(w)\", \"Real Face Image(x)\"]\n\n wandb.init(project=\"JoJoGAN\")\n config = wandb.config\n config.num_iter = num_iter\n config.preserve_color = preserve_color\n wandb.log(\n {\"Style reference\": [wandb.Image(transforms.ToPILImage()(target_im))]},\n step=0)\n\n load discriminator for perceptual loss\n discriminator = Discriminator(1024, 2).eval().to(device)\n ckpt = torch.load('models/stylegan2-ffhq-config-f.pt', map_location=lambda storage, loc: storage)\n discriminator.load_state_dict(ckpt[\"d\"], strict=False)\n\n reset generator\n del generator\n generator = deepcopy(original_generator)\n\n g_optim = optim.Adam(generator.parameters(),", "heading1": "Setting up a Gradio Demo for JoJoGAN", "source_page_url": "https://gradio.app/guides/Gradio-and-Wandb-Integration", "source_page_title": "Other Tutorials - Gradio And Wandb Integration Guide"}, {"text": ": storage)\n discriminator.load_state_dict(ckpt[\"d\"], strict=False)\n\n reset generator\n del generator\n generator = deepcopy(original_generator)\n\n g_optim = optim.Adam(generator.parameters(), lr=2e-3, betas=(0, 0.99))\n\n Which layers to swap for generating a family of plausible real images -> fake image\n if preserve_color:\n id_swap = [9,11,15,16,17]\n else:\n id_swap = list(range(7, generator.n_latent))\n\n for idx in tqdm(range(num_iter)):\n mean_w = generator.get_latent(torch.randn([latents.size(0), latent_dim]).to(device)).unsqueeze(1).repeat(1, generator.n_latent, 1)\n in_latent = latents.clone()\n in_latent[:, id_swap] = alpha*latents[:, id_swap] + (1-alpha)*mean_w[:, id_swap]\n\n img = generator(in_latent, input_is_latent=True)\n\n with torch.no_grad():\n real_feat = discriminator(targets)\n fake_feat = discriminator(img)\n\n loss = sum([F.l1_loss(a, b) for a, b in zip(fake_feat, real_feat)])/len(fake_feat)\n\n wandb.log({\"loss\": loss}, step=idx)\n if idx % log_interval == 0:\n generator.eval()\n my_sample = generator(my_w, input_is_latent=True)\n generator.train()\n my_sample = transforms.ToPILImage()(utils.make_grid(my_sample, normalize=True, range=(-1, 1)))\n wandb.log(\n {\"Current stylization\": [wandb.Image(my_sample)]},\n step=idx)\n table_data = [\n wandb.Image(transforms.ToPILImage()(target_im)),\n wandb.Image(img),\n wandb.Image(my_sample),\n ]\n samples.append(table_data)\n\n g_optim.zero_grad()\n loss.backward()\n g_optim.step()\n\n out_table = wandb.Table(data=samples, columns=column_names)\n wandb.log({\"Current Samples\": out_table})\n ```\n4. Save, Download, and Load Model\n\n Here's how to save and download your model.\n\n ```python\n from PIL import Image\n import torch\n torch.backends.cudnn.benchmark = True\n from torchvision impor", "heading1": "Setting up a Gradio Demo for JoJoGAN", "source_page_url": "https://gradio.app/guides/Gradio-and-Wandb-Integration", "source_page_title": "Other Tutorials - Gradio And Wandb Integration Guide"}, {"text": "ave, Download, and Load Model\n\n Here's how to save and download your model.\n\n ```python\n from PIL import Image\n import torch\n torch.backends.cudnn.benchmark = True\n from torchvision import transforms, utils\n from util import *\n import math\n import random\n import numpy as np\n from torch import nn, autograd, optim\n from torch.nn import functional as F\n from tqdm import tqdm\n import lpips\n from model import *\n from e4e_projection import projection as e4e_projection\n \n from copy import deepcopy\n import imageio\n \n import os\n import sys\n import torchvision.transforms as transforms\n from argparse import Namespace\n from e4e.models.psp import pSp\n from util import *\n from huggingface_hub import hf_hub_download\n from google.colab import files\n \n torch.save({\"g\": generator.state_dict()}, \"your-model-name.pt\")\n \n files.download('your-model-name.pt')\n \n latent_dim = 512\n device=\"cuda\"\n model_path_s = hf_hub_download(repo_id=\"akhaliq/jojogan-stylegan2-ffhq-config-f\", filename=\"stylegan2-ffhq-config-f.pt\")\n original_generator = Generator(1024, latent_dim, 8, 2).to(device)\n ckpt = torch.load(model_path_s, map_location=lambda storage, loc: storage)\n original_generator.load_state_dict(ckpt[\"g_ema\"], strict=False)\n mean_latent = original_generator.mean_latent(10000)\n \n generator = deepcopy(original_generator)\n \n ckpt = torch.load(\"/content/JoJoGAN/your-model-name.pt\", map_location=lambda storage, loc: storage)\n generator.load_state_dict(ckpt[\"g\"], strict=False)\n generator.eval()\n \n plt.rcParams['figure.dpi'] = 150\n \n transform = transforms.Compose(\n [\n transforms.Resize((1024, 1024)),\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\n ]\n )\n \n def inference(img):\n img.save('out.jpg')\n aligned_face = align_face('out.jpg')\n \n my_w = e4e_projection(aligned_face, \"out.pt\", device).unsqueeze(0)", "heading1": "Setting up a Gradio Demo for JoJoGAN", "source_page_url": "https://gradio.app/guides/Gradio-and-Wandb-Integration", "source_page_title": "Other Tutorials - Gradio And Wandb Integration Guide"}, {"text": ".5, 0.5)),\n ]\n )\n \n def inference(img):\n img.save('out.jpg')\n aligned_face = align_face('out.jpg')\n \n my_w = e4e_projection(aligned_face, \"out.pt\", device).unsqueeze(0)\n with torch.no_grad():\n my_sample = generator(my_w, input_is_latent=True)\n \n npimage = my_sample[0].cpu().permute(1, 2, 0).detach().numpy()\n imageio.imwrite('filename.jpeg', npimage)\n return 'filename.jpeg'\n ````\n\n5. Build a Gradio Demo\n\n ```python\n import gradio as gr\n \n title = \"JoJoGAN\"\n description = \"Gradio Demo for JoJoGAN: One Shot Face Stylization. To use it, simply upload your image, or click one of the examples to load them. Read more at the links below.\"\n \n demo = gr.Interface(\n inference,\n gr.Image(type=\"pil\"),\n gr.Image(type=\"file\"),\n title=title,\n description=description\n )\n \n demo.launch(share=True)\n ```\n\n6. Integrate Gradio into your W&B Dashboard\n\n The last step\u2014integrating your Gradio demo with your W&B dashboard\u2014is just one extra line:\n\n ```python\n demo.integrate(wandb=wandb)\n ```\n\n Once you call integrate, a demo will be created and you can integrate it into your dashboard or report.\n\n Outside of W&B with Web components, using the `gradio-app` tags, anyone can embed Gradio demos on HF spaces directly into their blogs, websites, documentation, etc.:\n \n ```html\n \n ```\n\n7. (Optional) Embed W&B plots in your Gradio App\n\n It's also possible to embed W&B plots within Gradio apps. To do so, you can create a W&B Report of your plots and\n embed them within your Gradio app within a `gr.HTML` block.\n\n The Report will need to be public and you will need to wrap the URL within an iFrame like this:\n\n ```python\n import gradio as gr\n \n def wandb_report(url):\n iframe = f'\n\nIf you are permanently hosting your Gradio application, you can embed the UI using the Gradio Panel Extended custom Panel.\n\nGo to your Comet Project page, and head over to the Panels tab. Click the `+ Add` button to bring up the Panels search page.\n\n\"adding-panels\"\n\nNext, search for Gradio Panel Extended in the Public Panels section and click `Add`.\n\n\"gradio-panel-extended\"\n\nOnce you have added your Panel, click `Edit` to access to the Panel Options page and paste in the URL of your Gradio application.\n\n![Edit-Gradio-Panel-Options](https://user-images.githubusercontent.com/7529846/214573001-23814b5a-ca65-4ace-a8a5-b27cdda70f7a.gif)\n\n\"Edit-Gradio-Panel-URL\"\n\n", "heading1": "2. Embedding Gradio Applications directly into your Comet Projects", "source_page_url": "https://gradio.app/guides/Gradio-and-Comet", "source_page_title": "Other Tutorials - Gradio And Comet Guide"}, {"text": "\n\nYou can also embed Gradio Applications that are hosted on Hugging Faces Spaces into your Comet Projects using the Hugging Face Spaces Panel.\n\nGo to your Comet Project page, and head over to the Panels tab. Click the `+ Add` button to bring up the Panels search page. Next, search for the Hugging Face Spaces Panel in the Public Panels section and click `Add`.\n\n\"huggingface-spaces-panel\"\n\nOnce you have added your Panel, click Edit to access to the Panel Options page and paste in the path of your Hugging Face Space e.g. `pytorch/ResNet`\n\n\"Edit-HF-Space\"\n\n", "heading1": "3. Embedding Hugging Face Spaces directly into your Comet Projects", "source_page_url": "https://gradio.app/guides/Gradio-and-Comet", "source_page_title": "Other Tutorials - Gradio And Comet Guide"}, {"text": "\n\n[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/comet-ml/comet-examples/blob/master/integrations/model-evaluation/gradio/notebooks/Logging_Model_Inferences_with_Comet_and_Gradio.ipynb)\n\nIn the previous examples, we demonstrated the various ways in which you can interact with a Gradio application through the Comet UI. Additionally, you can also log model inferences, such as SHAP plots, from your Gradio application to Comet.\n\nIn the following snippet, we're going to log inferences from a Text Generation model. We can persist an Experiment across multiple inference calls using Gradio's [State](https://www.gradio.app/docs/state) object. This will allow you to log multiple inferences from a model to a single Experiment.\n\n```python\nimport comet_ml\nimport gradio as gr\nimport shap\nimport torch\nfrom transformers import AutoModelForCausalLM, AutoTokenizer\n\nif torch.cuda.is_available():\n device = \"cuda\"\nelse:\n device = \"cpu\"\n\nMODEL_NAME = \"gpt2\"\n\nmodel = AutoModelForCausalLM.from_pretrained(MODEL_NAME)\n\nset model decoder to true\nmodel.config.is_decoder = True\nset text-generation params under task_specific_params\nmodel.config.task_specific_params[\"text-generation\"] = {\n \"do_sample\": True,\n \"max_length\": 50,\n \"temperature\": 0.7,\n \"top_k\": 50,\n \"no_repeat_ngram_size\": 2,\n}\nmodel = model.to(device)\n\ntokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)\nexplainer = shap.Explainer(model, tokenizer)\n\n\ndef start_experiment():\n \"\"\"Returns an APIExperiment object that is thread safe\n and can be used to log inferences to a single Experiment\n \"\"\"\n try:\n api = comet_ml.API()\n workspace = api.get_default_", "heading1": "4. Logging Model Inferences to Comet", "source_page_url": "https://gradio.app/guides/Gradio-and-Comet", "source_page_title": "Other Tutorials - Gradio And Comet Guide"}, {"text": " \"\"\"Returns an APIExperiment object that is thread safe\n and can be used to log inferences to a single Experiment\n \"\"\"\n try:\n api = comet_ml.API()\n workspace = api.get_default_workspace()\n project_name = comet_ml.config.get_config()[\"comet.project_name\"]\n\n experiment = comet_ml.APIExperiment(\n workspace=workspace, project_name=project_name\n )\n experiment.log_other(\"Created from\", \"gradio-inference\")\n\n message = f\"Started Experiment: [{experiment.name}]({experiment.url})\"\n\n return (experiment, message)\n\n except Exception as e:\n return None, None\n\n\ndef predict(text, state, message):\n experiment = state\n\n shap_values = explainer([text])\n plot = shap.plots.text(shap_values, display=False)\n\n if experiment is not None:\n experiment.log_other(\"message\", message)\n experiment.log_html(plot)\n\n return plot\n\n\nwith gr.Blocks() as demo:\n start_experiment_btn = gr.Button(\"Start New Experiment\")\n experiment_status = gr.Markdown()\n\n Log a message to the Experiment to provide more context\n experiment_message = gr.Textbox(label=\"Experiment Message\")\n experiment = gr.State()\n\n input_text = gr.Textbox(label=\"Input Text\", lines=5, interactive=True)\n submit_btn = gr.Button(\"Submit\")\n\n output = gr.HTML(interactive=True)\n\n start_experiment_btn.click(\n start_experiment, outputs=[experiment, experiment_status]\n )\n submit_btn.click(\n predict, inputs=[input_text, experiment, experiment_message], outputs=[output]\n )\n```\n\nInferences from this snippet will be saved in the HTML tab of your experiment.\n\n\n\n", "heading1": "4. Logging Model Inferences to Comet", "source_page_url": "https://gradio.app/guides/Gradio-and-Comet", "source_page_title": "Other Tutorials - Gradio And Comet Guide"}, {"text": "887c-065aca14dd30.mp4\">\n\n\n", "heading1": "4. Logging Model Inferences to Comet", "source_page_url": "https://gradio.app/guides/Gradio-and-Comet", "source_page_title": "Other Tutorials - Gradio And Comet Guide"}, {"text": "We hope you found this guide useful and that it provides some inspiration to help you build awesome model evaluation workflows with Comet and Gradio.\n\n", "heading1": "Conclusion", "source_page_url": "https://gradio.app/guides/Gradio-and-Comet", "source_page_title": "Other Tutorials - Gradio And Comet Guide"}, {"text": "- Create an account on Hugging Face [here](https://huggingface.co/join).\n- Add Gradio Demo under your username, see this [course](https://huggingface.co/course/chapter9/4?fw=pt) for setting up Gradio Demo on Hugging Face.\n- Request to join the Comet organization [here](https://huggingface.co/Comet).\n\n", "heading1": "How to contribute Gradio demos on HF spaces on the Comet organization", "source_page_url": "https://gradio.app/guides/Gradio-and-Comet", "source_page_title": "Other Tutorials - Gradio And Comet Guide"}, {"text": "- [Comet Documentation](https://www.comet.com/docs/v2/?utm_source=gradio&utm_medium=referral&utm_campaign=gradio-integration&utm_content=gradio-docs)\n", "heading1": "Additional Resources", "source_page_url": "https://gradio.app/guides/Gradio-and-Comet", "source_page_title": "Other Tutorials - Gradio And Comet Guide"}, {"text": "Building a dashboard from a public Google Sheet is very easy, thanks to the [`pandas` library](https://pandas.pydata.org/):\n\n1\\. Get the URL of the Google Sheets that you want to use. To do this, simply go to the Google Sheets, click on the \"Share\" button in the top-right corner, and then click on the \"Get shareable link\" button. This will give you a URL that looks something like this:\n\n```html\nhttps://docs.google.com/spreadsheets/d/1UoKzzRzOCt-FXLLqDKLbryEKEgllGAQUEJ5qtmmQwpU/editgid=0\n```\n\n2\\. Now, let's modify this URL and then use it to read the data from the Google Sheets into a Pandas DataFrame. (In the code below, replace the `URL` variable with the URL of your public Google Sheet):\n\n```python\nimport pandas as pd\n\nURL = \"https://docs.google.com/spreadsheets/d/1UoKzzRzOCt-FXLLqDKLbryEKEgllGAQUEJ5qtmmQwpU/editgid=0\"\ncsv_url = URL.replace('/editgid=', '/export?format=csv&gid=')\n\ndef get_data():\n return pd.read_csv(csv_url)\n```\n\n3\\. The data query is a function, which means that it's easy to display it real-time using the `gr.DataFrame` component, or plot it real-time using the `gr.LinePlot` component (of course, depending on the data, a different plot may be appropriate). To do this, just pass the function into the respective components, and set the `every` parameter based on how frequently (in seconds) you would like the component to refresh. Here's the Gradio code:\n\n```python\nimport gradio as gr\n\nwith gr.Blocks() as demo:\n gr.Markdown(\"\ud83d\udcc8 Real-Time Line Plot\")\n with gr.Row():\n with gr.Column():\n gr.DataFrame(get_data, every=gr.Timer(5))\n with gr.Column():\n gr.LinePlot(get_data, every=gr.Timer(5), x=\"Date\", y=\"Sales\", y_title=\"Sales ($ millions)\", overlay_point=True, width=500, height=500)\n\ndemo.queue().launch() Run the demo with queuing enabled\n```\n\nAnd that's it! You have a dashboard that refreshes every 5 seconds, pulling the data from your Google Sheet.\n\n", "heading1": "Public Google Sheets", "source_page_url": "https://gradio.app/guides/creating-a-realtime-dashboard-from-google-sheets", "source_page_title": "Other Tutorials - Creating A Realtime Dashboard From Google Sheets Guide"}, {"text": "For private Google Sheets, the process requires a little more work, but not that much! The key difference is that now, you must authenticate yourself to authorize access to the private Google Sheets.\n\nAuthentication\n\nTo authenticate yourself, obtain credentials from Google Cloud. Here's [how to set up google cloud credentials](https://developers.google.com/workspace/guides/create-credentials):\n\n1\\. First, log in to your Google Cloud account and go to the Google Cloud Console (https://console.cloud.google.com/)\n\n2\\. In the Cloud Console, click on the hamburger menu in the top-left corner and select \"APIs & Services\" from the menu. If you do not have an existing project, you will need to create one.\n\n3\\. Then, click the \"+ Enabled APIs & services\" button, which allows you to enable specific services for your project. Search for \"Google Sheets API\", click on it, and click the \"Enable\" button. If you see the \"Manage\" button, then Google Sheets is already enabled, and you're all set.\n\n4\\. In the APIs & Services menu, click on the \"Credentials\" tab and then click on the \"Create credentials\" button.\n\n5\\. In the \"Create credentials\" dialog, select \"Service account key\" as the type of credentials to create, and give it a name. **Note down the email of the service account**\n\n6\\. After selecting the service account, select the \"JSON\" key type and then click on the \"Create\" button. This will download the JSON key file containing your credentials to your computer. It will look something like this:\n\n```json\n{\n\t\"type\": \"service_account\",\n\t\"project_id\": \"your project\",\n\t\"private_key_id\": \"your private key id\",\n\t\"private_key\": \"private key\",\n\t\"client_email\": \"email\",\n\t\"client_id\": \"client id\",\n\t\"auth_uri\": \"https://accounts.google.com/o/oauth2/auth\",\n\t\"token_uri\": \"https://accounts.google.com/o/oauth2/token\",\n\t\"auth_provider_x509_cert_url\": \"https://www.googleapis.com/oauth2/v1/certs\",\n\t\"client_x509_cert_url\": \"https://www.googleapis.com/robot/v1/metadata/x509/email_id\"\n}\n```\n\n", "heading1": "Private Google Sheets", "source_page_url": "https://gradio.app/guides/creating-a-realtime-dashboard-from-google-sheets", "source_page_title": "Other Tutorials - Creating A Realtime Dashboard From Google Sheets Guide"}, {"text": "google.com/o/oauth2/token\",\n\t\"auth_provider_x509_cert_url\": \"https://www.googleapis.com/oauth2/v1/certs\",\n\t\"client_x509_cert_url\": \"https://www.googleapis.com/robot/v1/metadata/x509/email_id\"\n}\n```\n\nQuerying\n\nOnce you have the credentials `.json` file, you can use the following steps to query your Google Sheet:\n\n1\\. Click on the \"Share\" button in the top-right corner of the Google Sheet. Share the Google Sheets with the email address of the service from Step 5 of authentication subsection (this step is important!). Then click on the \"Get shareable link\" button. This will give you a URL that looks something like this:\n\n```html\nhttps://docs.google.com/spreadsheets/d/1UoKzzRzOCt-FXLLqDKLbryEKEgllGAQUEJ5qtmmQwpU/editgid=0\n```\n\n2\\. Install the [`gspread` library](https://docs.gspread.org/en/v5.7.0/), which makes it easy to work with the [Google Sheets API](https://developers.google.com/sheets/api/guides/concepts) in Python by running in the terminal: `pip install gspread`\n\n3\\. Write a function to load the data from the Google Sheet, like this (replace the `URL` variable with the URL of your private Google Sheet):\n\n```python\nimport gspread\nimport pandas as pd\n\nAuthenticate with Google and get the sheet\nURL = 'https://docs.google.com/spreadsheets/d/1_91Vps76SKOdDQ8cFxZQdgjTJiz23375sAT7vPvaj4k/editgid=0'\n\ngc = gspread.service_account(\"path/to/key.json\")\nsh = gc.open_by_url(URL)\nworksheet = sh.sheet1\n\ndef get_data():\n values = worksheet.get_all_values()\n df = pd.DataFrame(values[1:], columns=values[0])\n return df\n\n```\n\n4\\. The data query is a function, which means that it's easy to display it real-time using the `gr.DataFrame` component, or plot it real-time using the `gr.LinePlot` component (of course, depending on the data, a different plot may be appropriate). To do this, we just pass the function into the respective components, and set the `every` parameter based on how frequently (in seconds) we would like the component to refresh. Here's the Gradio cod", "heading1": "Private Google Sheets", "source_page_url": "https://gradio.app/guides/creating-a-realtime-dashboard-from-google-sheets", "source_page_title": "Other Tutorials - Creating A Realtime Dashboard From Google Sheets Guide"}, {"text": ". To do this, we just pass the function into the respective components, and set the `every` parameter based on how frequently (in seconds) we would like the component to refresh. Here's the Gradio code:\n\n```python\nimport gradio as gr\n\nwith gr.Blocks() as demo:\n gr.Markdown(\"\ud83d\udcc8 Real-Time Line Plot\")\n with gr.Row():\n with gr.Column():\n gr.DataFrame(get_data, every=gr.Timer(5))\n with gr.Column():\n gr.LinePlot(get_data, every=gr.Timer(5), x=\"Date\", y=\"Sales\", y_title=\"Sales ($ millions)\", overlay_point=True, width=500, height=500)\n\ndemo.queue().launch() Run the demo with queuing enabled\n```\n\nYou now have a Dashboard that refreshes every 5 seconds, pulling the data from your Google Sheet.\n\n", "heading1": "Private Google Sheets", "source_page_url": "https://gradio.app/guides/creating-a-realtime-dashboard-from-google-sheets", "source_page_title": "Other Tutorials - Creating A Realtime Dashboard From Google Sheets Guide"}, {"text": "And that's all there is to it! With just a few lines of code, you can use `gradio` and other libraries to read data from a public or private Google Sheet and then display and plot the data in a real-time dashboard.\n", "heading1": "Conclusion", "source_page_url": "https://gradio.app/guides/creating-a-realtime-dashboard-from-google-sheets", "source_page_title": "Other Tutorials - Creating A Realtime Dashboard From Google Sheets Guide"}, {"text": "When you demo a machine learning model, you might want to collect data from users who try the model, particularly data points in which the model is not behaving as expected. Capturing these \"hard\" data points is valuable because it allows you to improve your machine learning model and make it more reliable and robust.\n\nGradio simplifies the collection of this data by including a **Flag** button with every `Interface`. This allows a user or tester to easily send data back to the machine where the demo is running. In this Guide, we discuss more about how to use the flagging feature, both with `gradio.Interface` as well as with `gradio.Blocks`.\n\n", "heading1": "Introduction", "source_page_url": "https://gradio.app/guides/using-flagging", "source_page_title": "Other Tutorials - Using Flagging Guide"}, {"text": "Flagging with Gradio's `Interface` is especially easy. By default, underneath the output components, there is a button marked **Flag**. When a user testing your model sees input with interesting output, they can click the flag button to send the input and output data back to the machine where the demo is running. The sample is saved to a CSV log file (by default). If the demo involves images, audio, video, or other types of files, these are saved separately in a parallel directory and the paths to these files are saved in the CSV file.\n\nThere are [four parameters](https://gradio.app/docs/interfaceinitialization) in `gradio.Interface` that control how flagging works. We will go over them in greater detail.\n\n- `flagging_mode`: this parameter can be set to either `\"manual\"` (default), `\"auto\"`, or `\"never\"`.\n - `manual`: users will see a button to flag, and samples are only flagged when the button is clicked.\n - `auto`: users will not see a button to flag, but every sample will be flagged automatically.\n - `never`: users will not see a button to flag, and no sample will be flagged.\n- `flagging_options`: this parameter can be either `None` (default) or a list of strings.\n - If `None`, then the user simply clicks on the **Flag** button and no additional options are shown.\n - If a list of strings are provided, then the user sees several buttons, corresponding to each of the strings that are provided. For example, if the value of this parameter is `[\"Incorrect\", \"Ambiguous\"]`, then buttons labeled **Flag as Incorrect** and **Flag as Ambiguous** appear. This only applies if `flagging_mode` is `\"manual\"`.\n - The chosen option is then logged along with the input and output.\n- `flagging_dir`: this parameter takes a string.\n - It represents what to name the directory where flagged data is stored.\n- `flagging_callback`: this parameter takes an instance of a subclass of the `FlaggingCallback` class\n - Using this parameter allows you to write custom code that gets run whe", "heading1": "The **Flag** button in `gradio.Interface`", "source_page_url": "https://gradio.app/guides/using-flagging", "source_page_title": "Other Tutorials - Using Flagging Guide"}, {"text": "flagged data is stored.\n- `flagging_callback`: this parameter takes an instance of a subclass of the `FlaggingCallback` class\n - Using this parameter allows you to write custom code that gets run when the flag button is clicked\n - By default, this is set to an instance of `gr.JSONLogger`\n\n", "heading1": "The **Flag** button in `gradio.Interface`", "source_page_url": "https://gradio.app/guides/using-flagging", "source_page_title": "Other Tutorials - Using Flagging Guide"}, {"text": "Within the directory provided by the `flagging_dir` argument, a JSON file will log the flagged data.\n\nHere's an example: The code below creates the calculator interface embedded below it:\n\n```python\nimport gradio as gr\n\n\ndef calculator(num1, operation, num2):\n if operation == \"add\":\n return num1 + num2\n elif operation == \"subtract\":\n return num1 - num2\n elif operation == \"multiply\":\n return num1 * num2\n elif operation == \"divide\":\n return num1 / num2\n\n\niface = gr.Interface(\n calculator,\n [\"number\", gr.Radio([\"add\", \"subtract\", \"multiply\", \"divide\"]), \"number\"],\n \"number\",\n flagging_mode=\"manual\"\n)\n\niface.launch()\n```\n\n\n\nWhen you click the flag button above, the directory where the interface was launched will include a new flagged subfolder, with a csv file inside it. This csv file includes all the data that was flagged.\n\n```directory\n+-- flagged/\n| +-- logs.csv\n```\n\n_flagged/logs.csv_\n\n```csv\nnum1,operation,num2,Output,timestamp\n5,add,7,12,2022-01-31 11:40:51.093412\n6,subtract,1.5,4.5,2022-01-31 03:25:32.023542\n```\n\nIf the interface involves file data, such as for Image and Audio components, folders will be created to store those flagged data as well. For example an `image` input to `image` output interface will create the following structure.\n\n```directory\n+-- flagged/\n| +-- logs.csv\n| +-- image/\n| | +-- 0.png\n| | +-- 1.png\n| +-- Output/\n| | +-- 0.png\n| | +-- 1.png\n```\n\n_flagged/logs.csv_\n\n```csv\nim,Output timestamp\nim/0.png,Output/0.png,2022-02-04 19:49:58.026963\nim/1.png,Output/1.png,2022-02-02 10:40:51.093412\n```\n\nIf you wish for the user to provide a reason for flagging, you can pass a list of strings to the `flagging_options` argument of Interface. Users will have to select one of these choices when flagging, and the option will be saved as an additional column to the CSV.\n\nIf we go back to the calculator example, the fo", "heading1": "What happens to flagged data?", "source_page_url": "https://gradio.app/guides/using-flagging", "source_page_title": "Other Tutorials - Using Flagging Guide"}, {"text": "` argument of Interface. Users will have to select one of these choices when flagging, and the option will be saved as an additional column to the CSV.\n\nIf we go back to the calculator example, the following code will create the interface embedded below it.\n\n```python\niface = gr.Interface(\n calculator,\n [\"number\", gr.Radio([\"add\", \"subtract\", \"multiply\", \"divide\"]), \"number\"],\n \"number\",\n flagging_mode=\"manual\",\n flagging_options=[\"wrong sign\", \"off by one\", \"other\"]\n)\n\niface.launch()\n```\n\n\n\nWhen users click the flag button, the csv file will now include a column indicating the selected option.\n\n_flagged/logs.csv_\n\n```csv\nnum1,operation,num2,Output,flag,timestamp\n5,add,7,-12,wrong sign,2022-02-04 11:40:51.093412\n6,subtract,1.5,3.5,off by one,2022-02-04 11:42:32.062512\n```\n\n", "heading1": "What happens to flagged data?", "source_page_url": "https://gradio.app/guides/using-flagging", "source_page_title": "Other Tutorials - Using Flagging Guide"}, {"text": "What about if you are using `gradio.Blocks`? On one hand, you have even more flexibility\nwith Blocks -- you can write whatever Python code you want to run when a button is clicked,\nand assign that using the built-in events in Blocks.\n\nAt the same time, you might want to use an existing `FlaggingCallback` to avoid writing extra code.\nThis requires two steps:\n\n1. You have to run your callback's `.setup()` somewhere in the code prior to the\n first time you flag data\n2. When the flagging button is clicked, then you trigger the callback's `.flag()` method,\n making sure to collect the arguments correctly and disabling the typical preprocessing.\n\nHere is an example with an image sepia filter Blocks demo that lets you flag\ndata using the default `CSVLogger`:\n\n$code_blocks_flag\n$demo_blocks_flag\n\n", "heading1": "Flagging with Blocks", "source_page_url": "https://gradio.app/guides/using-flagging", "source_page_title": "Other Tutorials - Using Flagging Guide"}, {"text": "Important Note: please make sure your users understand when the data they submit is being saved, and what you plan on doing with it. This is especially important when you use `flagging_mode=auto` (when all of the data submitted through the demo is being flagged)\n\nThat's all! Happy building :)\n", "heading1": "Privacy", "source_page_url": "https://gradio.app/guides/using-flagging", "source_page_title": "Other Tutorials - Using Flagging Guide"}, {"text": "Add `@gr.cache` to any function to automatically cache its results. The decorator hashes inputs by their content \u2014 two different numpy arrays with the same pixel values will produce a cache hit. Cache hits bypass the Gradio queue entirely.\n\n```python\nimport gradio as gr\n\n@gr.cache\ndef classify(image):\n return model.predict(image)\n```\n\nGenerators\n\nFor generator functions, `@gr.cache` caches **all yielded values** and replays them on a hit. This is particularly important for streaming media (`gr.Audio` or `gr.Video` with `streaming=True`) where each yield is a chunk of the output:\n\n```python\n@gr.cache\ndef stream_response(prompt):\n response = \"\"\n for token in model.generate(prompt):\n response += token\n yield response\n```\n\nAsync\n\nAsync functions and async generators work identically:\n\n```python\n@gr.cache\nasync def transcribe(audio):\n return await model.transcribe(audio)\n```\n\nParameters\n\nThe behavior of `@gr.cache()` can be customized with a few parameters, most notably the `key`:\n\n```python\n@gr.cache(\n key=lambda kw: kw[\"prompt\"], only cache based on prompt, ignore temperature\n max_size=256, max entries (LRU eviction), default 128\n max_memory=\"512mb\", max memory before eviction\n per_session=True, isolate cache per user session\n)\ndef generate(prompt, temperature=0.7):\n return llm(prompt, temperature=temperature)\n```\n\n- **`key`** \u2014 function that takes the kwargs dict and returns what to hash. Useful for ignoring parameters like temperature or seed.\n- **`max_size`** \u2014 maximum number of entries. LRU eviction when full. Default 128. Set to 0 for unlimited.\n- **`max_memory`** \u2014 maximum memory usage. Accepts strings like `\"512mb\"`, `\"2gb\"` or raw bytes. LRU eviction when exceeded.\n- **`per_session`** \u2014 when `True`, each user session gets an isolated cache namespace. Prevents one user's cached results from being served to another, clears that session's entries when the client ", "heading1": "Automatic caching with `@gr.cache`", "source_page_url": "https://gradio.app/guides/caching", "source_page_title": "Additional Features - Caching Guide"}, {"text": ".\n- **`per_session`** \u2014 when `True`, each user session gets an isolated cache namespace. Prevents one user's cached results from being served to another, clears that session's entries when the client disconnects, and still applies `max_size` and `max_memory` to the shared cache store across all sessions.\n\n\nAccess the cache programmatically via `fn.cache`:\n\n```python\ngenerate.cache.clear()\nprint(len(generate.cache))\n```\n\nWhen a queued event is served from `@gr.cache`, Gradio shows a small `from cache` timing badge in the UI which appears temporarily in the relevant output components.\n\nCaching intermediate helper calls\n\nYou can also apply `gr.cache()` to a callable at runtime to cache an intermediate step inside a larger Gradio callback:\n\n```python\ndef embed(text):\n return embedding_model(text)\n\ndef predict(text):\n embedding = gr.cache(embed, per_session=True)(text)\n return rerank(embedding)\n```\n\nThis is especially useful when only part of your function is deterministic or reusable. Runtime `gr.cache(fn)(...)` uses the same cache store for repeated calls to that helper and shows the same `used cache` badge as `gr.Cache()` (see below) when a hit is reused during a request.\n\n`gr.cache()` must wrap a callable. If you accidentally write `gr.cache(fn(...))`, Gradio raises an error and tells you to use `gr.cache(fn)(...)` instead.\n\n", "heading1": "Automatic caching with `@gr.cache`", "source_page_url": "https://gradio.app/guides/caching", "source_page_title": "Additional Features - Caching Guide"}, {"text": "For full control over what gets cached and when, use `gr.Cache()` as an injectable parameter (like `gr.Progress`). Gradio injects the same instance on every call, giving you a thread-safe `get`/`set` interface:\n\n```python\ndef my_function(prompt, c=gr.Cache()):\n hit = c.get(prompt)\n if hit is not None:\n return hit[\"result\"]\n result = expensive_computation(prompt)\n c.set(prompt, result=result)\n return result\n```\n\nIf a queued function gets a successful hit from `c.get(...)`, Gradio also shows a timing badge in the UI. This badge says `used cache` instead of `from cache`, because the request still ran, but part of its work was reused from `gr.Cache()`.\n\nA minimal example is available in the [`gr.Cache()` manual cache demo](https://github.com/gradio-app/gradio/blob/main/demo/cache_manual_demo/run.py).\n\nWhy use `gr.Cache()` over a plain dict?\n\n- **Thread-safe** \u2014 built-in locking for concurrent requests\n- **LRU eviction** + **memory limits** \u2014 bounded memory usage (`max_size`, `max_memory`)\n- **Per-session isolation** \u2014 `gr.Cache(per_session=True)` partitions the cache by user session, prevents data leakage between users, clears that session's entries when the client disconnects, and still applies `max_size` and `max_memory` across the combined cache entries of all sessions\n- **Content-aware keys** \u2014 numpy arrays, PIL images, DataFrames all work as cache keys\n\nKV Cache Example\n\nYou can cache arbitrary intermediate state, not just function outputs. Here's how to cache transformer KV states for prefix reuse:\n\n```python\ndef generate(prompt, c=gr.Cache(per_session=True)):\n best_key = None\n best_len = 0\n for cached_key in c.keys():\n if prompt.startswith(cached_key) and len(cached_key) > best_len:\n best_key = cached_key\n best_len = len(cached_key)\n\n if best_key:\n past_kv = c.get(best_key)[\"kv\"]\n output = model.generate(prompt, past_key_values=past_kv)\n else:\n output = model.generate(p", "heading1": "Manual cache control with `gr.Cache()`", "source_page_url": "https://gradio.app/guides/caching", "source_page_title": "Additional Features - Caching Guide"}, {"text": " best_len = len(cached_key)\n\n if best_key:\n past_kv = c.get(best_key)[\"kv\"]\n output = model.generate(prompt, past_key_values=past_kv)\n else:\n output = model.generate(prompt)\n\n c.set(prompt, kv=model.past_key_values)\n return output.text\n```\n\nFor a full runnable version, see the [`gr.Cache()` KV cache demo](https://github.com/gradio-app/gradio/blob/main/demo/cache_kv_demo/run.py).\n\n\n", "heading1": "Manual cache control with `gr.Cache()`", "source_page_url": "https://gradio.app/guides/caching", "source_page_title": "Additional Features - Caching Guide"}, {"text": "`@gr.cache` is most useful for **deterministic** functions where the same input always produces the same output: image classification, audio transcription, embedding computation, structured data extraction.\n\nIt is less useful for **non-deterministic** functions like text generation or image generation, where users might want different outputs even for the same input. For those, `gr.Cache()` with manual control may be more appropriate as you can cache intermediate state (like KV caches) without caching the output completely.\n\n\n", "heading1": "When to use caching", "source_page_url": "https://gradio.app/guides/caching", "source_page_title": "Additional Features - Caching Guide"}, {"text": "Take a look at these complete examples and then build your own Gradio app with caching!\n\n- [`@gr.cache()` function types demo](https://github.com/gradio-app/gradio/blob/main/demo/cache_demo/run.py) - sync, async, generator, and async generator caching\n- [`gr.Cache()` manual cache demo](https://github.com/gradio-app/gradio/blob/main/demo/cache_manual_demo/run.py) - normalized manual cache keys with explicit `get` / `set`\n- [`gr.Cache()` KV cache demo](https://github.com/gradio-app/gradio/blob/main/demo/cache_kv_demo/run.py) - transformer prefix reuse with cached KV state\n", "heading1": "Next steps", "source_page_url": "https://gradio.app/guides/caching", "source_page_title": "Additional Features - Caching 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": "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": "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. 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": "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": "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": "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\n24. `GRADIO_NUM_WORKERS`\n\n- **Description**: Number of multiple workers to launch in the background", "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\n24. `GRADIO_NUM_WORKERS`\n\n- **Description**: Number of multiple workers to launch in the background to offload traffic for file I/O and static assets from the main Gradio server. Only works when SSR mode is set.\n- **Default**: not set.\n- **Options**: Any positive integer.\n- **Example**:\n ```sh\n export GRADIO_NUM_WORKERS=4\n ```\n\n25. `GRADIO_HEARTBEAT_INTERVAL`\n\n- **Description**: Sets the interval, in seconds, between heartbeats that keep a client session alive. When a client disconnects, this heartbeat is used to trigger `unload` events and clean up session state. Lowering this value can help detect disconnections faster in environments such as Kubernetes, where the default interval can delay session cleanup.\n- **Default**: `15`\n- **Example**:\n ```sh\n export GRADIO_HEARTBEAT_INTERVAL=5\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": "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": "**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 hidden from API docs and not callable by the Gradio client libraries (e.g. `gradio_client` or `@gradio/client`). Note: this does **not** block direct HTTP requests to the endpoint \u2014 it should not be relied upon as a security measure.\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**Hiding endpoints from client libraries**\n\nIf you want to hide an API endpoint from the API docs and prevent it from being called by the Gradio client libraries, set `api_visibility=\"private\"`:\n\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. However, the underlying HTTP endpoint is still accessible \u2014 this setting should not be relied upon for security.\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 ad", "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": "\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.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": "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": "Gradio themes are the easiest way to customize the look and feel of your app. You can choose from a variety of themes, or create your own. To do so, pass the `theme=` kwarg to the `launch()` method of the `Blocks` constructor. For example:\n\n```python\nwith gr.Blocks() as demo:\n ... your code here\ndemo.launch(theme=gr.themes.Glass())\n ...\n```\n\nGradio comes with a set of prebuilt themes which you can load from `gr.themes.*`. You can extend these themes or create your own themes from scratch - see the [Theming guide](/guides/theming-guide) for more details.\n\nFor additional styling ability, you can pass any CSS to your app as a string using the `css=` kwarg in the `launch()` method. You can also pass a pathlib.Path to a css file or a list of such paths to the `css_paths=` kwarg in the `launch()` method.\n\n**Warning**: The use of query selectors in custom JS and CSS is _not_ guaranteed to work across Gradio versions that bind to Gradio's own HTML elements as the Gradio HTML DOM may change. We recommend using query selectors sparingly.\n\nThe base class for the Gradio app is `gradio-container`, so here's an example that changes the background color of the Gradio app:\n\n```python\nwith gr.Blocks() as demo:\n ... your code here\ndemo.launch(css=\".gradio-container {background-color: red}\")\n ...\n```\n\nIf you'd like to reference external files in your css, preface the file path (which can be a relative or absolute path) with `\"/gradio_api/file=\"`, for example:\n\n```python\nwith gr.Blocks() as demo:\n ... your code here\ndemo.launch(css=\".gradio-container {background: url('/gradio_api/file=clouds.jpg')}\")\n ...\n```\n\nNote: By default, most files in the host machine are not accessible to users running the Gradio app. As a result, you should make sure that any referenced files (such as `clouds.jpg` here) are either URLs or [allowed paths, as described here](/main/guides/file-access).\n\n\n", "heading1": "Adding custom CSS to your demo", "source_page_url": "https://gradio.app/guides/custom-CSS-and-JS", "source_page_title": "Building With Blocks - Custom Css And Js Guide"}, {"text": "You can `elem_id` to add an HTML element `id` to any component, and `elem_classes` to add a class or list of classes. This will allow you to select elements more easily with CSS. This approach is also more likely to be stable across Gradio versions as built-in class names or ids may change (however, as mentioned in the warning above, we cannot guarantee complete compatibility between Gradio versions if you use custom CSS as the DOM elements may themselves change).\n\n```python\ncss = \"\"\"\nwarning {background-color: FFCCCB}\n.feedback textarea {font-size: 24px !important}\n\"\"\"\n\nwith gr.Blocks() as demo:\n box1 = gr.Textbox(value=\"Good Job\", elem_classes=\"feedback\")\n box2 = gr.Textbox(value=\"Failure\", elem_id=\"warning\", elem_classes=\"feedback\")\ndemo.launch(css=css)\n```\n\nThe CSS `warning` ruleset will only target the second Textbox, while the `.feedback` ruleset will target both. Note that when targeting classes, you might need to put the `!important` selector to override the default Gradio styles.\n\n", "heading1": "The `elem_id` and `elem_classes` Arguments", "source_page_url": "https://gradio.app/guides/custom-CSS-and-JS", "source_page_title": "Building With Blocks - Custom Css And Js Guide"}, {"text": "There are 3 ways to add javascript code to your Gradio demo:\n\n1. You can add JavaScript code as a string to the `js` parameter of the `Blocks` or `Interface` initializer. This will run the JavaScript code when the demo is first loaded.\n\nBelow is an example of adding custom js to show an animated welcome message when the demo first loads.\n\n$code_blocks_js_load\n$demo_blocks_js_load\n\n\n2. When using `Blocks` and event listeners, events have a `js` argument that can take a JavaScript function as a string and treat it just like a Python event listener function. You can pass both a JavaScript function and a Python function (in which case the JavaScript function is run first) or only Javascript (and set the Python `fn` to `None`). Take a look at the code below:\n \n$code_blocks_js_methods\n$demo_blocks_js_methods\n\n3. Lastly, you can add JavaScript code to the `head` param of the `Blocks` initializer. This will add the code to the head of the HTML document. For example, you can add Google Analytics to your demo like so:\n\n\n```python\nhead = f\"\"\"\n\n\n\"\"\"\n\nwith gr.Blocks() as demo:\n gr.HTML(\"

My App

\")\n\ndemo.launch(head=head)\n```\n\nThe `head` parameter accepts any HTML tags you would normally insert into the `` of a page. For example, you can also include `` tags to `head` in order to update the social sharing preview for your Gradio app like this:\n\n```py\nimport gradio as gr\n\ncustom_head = \"\"\"\n\nSample App\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n\"\"\"\n\nwith gr.Blocks(title=\"My App\") as demo:\n gr.HTML(\"

My App

\")\n\ndemo.launch(head=custom_head)\n```\n\n\n\nNote that injecting custom JS can affect browser behavior and accessibility (e.g. keyboard shortcuts may be lead to unexpected behavior if your Gradio app is embedded in another webpage). You should test your interface across different browsers and be mindful of how scripts may interact with browser defaults. Here's an example where pressing `Shift + s` triggers the `click` event of a specific `Button` component if the browser focus is _not_ on an input component (e.g. `Textbox` component):\n\n```python\nimport gradio as gr\n\nshortcut_js = \"\"\"\n\n\"\"\"\n\nwith gr.Blocks() as demo:\n action_button = gr.Button(value=\"Name\", elem_id=\"my_btn\")\n textbox = gr.Textbox()\n action_button.click(lambda : \"button pressed\", None, textbox)\n \ndemo.launch(head=shortcut_js)\n```\n\n", "heading1": "Adding custom JavaScript to your demo", "source_page_url": "https://gradio.app/guides/custom-CSS-and-JS", "source_page_title": "Building With Blocks - Custom Css And Js Guide"}, {"text": "Take a look at the demo below.\n\n$code_hello_blocks\n$demo_hello_blocks\n\n- First, note the `with gr.Blocks() as demo:` clause. The Blocks app code will be contained within this clause.\n- Next come the Components. These are the same Components used in `Interface`. However, instead of being passed to some constructor, Components are automatically added to the Blocks as they are created within the `with` clause.\n- Finally, the `click()` event listener. Event listeners define the data flow within the app. In the example above, the listener ties the two Textboxes together. The Textbox `name` acts as the input and Textbox `output` acts as the output to the `greet` method. This dataflow is triggered when the Button `greet_btn` is clicked. Like an Interface, an event listener can take multiple inputs or outputs.\n\nYou can also attach event listeners using decorators - skip the `fn` argument and assign `inputs` and `outputs` directly:\n\n$code_hello_blocks_decorator\n\n", "heading1": "Blocks Structure", "source_page_url": "https://gradio.app/guides/blocks-and-event-listeners", "source_page_title": "Building With Blocks - Blocks And Event Listeners Guide"}, {"text": "In the example above, you'll notice that you are able to edit Textbox `name`, but not Textbox `output`. This is because any Component that acts as an input to an event listener is made interactive. However, since Textbox `output` acts only as an output, Gradio determines that it should not be made interactive. You can override the default behavior and directly configure the interactivity of a Component with the boolean `interactive` keyword argument, e.g. `gr.Textbox(interactive=True)`.\n\n```python\noutput = gr.Textbox(label=\"Output\", interactive=True)\n```\n\n_Note_: What happens if a Gradio component is neither an input nor an output? If a component is constructed with a default value, then it is presumed to be displaying content and is rendered non-interactive. Otherwise, it is rendered interactive. Again, this behavior can be overridden by specifying a value for the `interactive` argument.\n\n", "heading1": "Event Listeners and Interactivity", "source_page_url": "https://gradio.app/guides/blocks-and-event-listeners", "source_page_title": "Building With Blocks - Blocks And Event Listeners Guide"}, {"text": "Take a look at the demo below:\n\n$code_blocks_hello\n$demo_blocks_hello\n\nInstead of being triggered by a click, the `welcome` function is triggered by typing in the Textbox `inp`. This is due to the `change()` event listener. Different Components support different event listeners. For example, the `Video` Component supports a `play()` event listener, triggered when a user presses play. See the [Docs](http://gradio.app/docscomponents) for the event listeners for each Component.\n\n", "heading1": "Types of Event Listeners", "source_page_url": "https://gradio.app/guides/blocks-and-event-listeners", "source_page_title": "Building With Blocks - Blocks And Event Listeners Guide"}, {"text": "A Blocks app is not limited to a single data flow the way Interfaces are. Take a look at the demo below:\n\n$code_reversible_flow\n$demo_reversible_flow\n\nNote that `num1` can act as input to `num2`, and also vice-versa! As your apps get more complex, you will have many data flows connecting various Components.\n\nHere's an example of a \"multi-step\" demo, where the output of one model (a speech-to-text model) gets fed into the next model (a sentiment classifier).\n\n$code_blocks_speech_text_sentiment\n$demo_blocks_speech_text_sentiment\n\n", "heading1": "Multiple Data Flows", "source_page_url": "https://gradio.app/guides/blocks-and-event-listeners", "source_page_title": "Building With Blocks - Blocks And Event Listeners Guide"}, {"text": "The event listeners you've seen so far have a single input component. If you'd like to have multiple input components pass data to the function, you have two options on how the function can accept input component values:\n\n1. as a list of arguments, or\n2. as a single dictionary of values, keyed by the component\n\nLet's see an example of each:\n$code_calculator_list_and_dict\n\nBoth `add()` and `sub()` take `a` and `b` as inputs. However, the syntax is different between these listeners.\n\n1. To the `add_btn` listener, we pass the inputs as a list. The function `add()` takes each of these inputs as arguments. The value of `a` maps to the argument `num1`, and the value of `b` maps to the argument `num2`.\n2. To the `sub_btn` listener, we pass the inputs as a set (note the curly brackets!). When you pass a set, the function `sub()` receives a single dictionary argument `data`, where the keys are the input components and the values are the values of those components.\n\nIt is a matter of preference which syntax you prefer! For functions with many input components, option 2 may be easier to manage.\n\n$demo_calculator_list_and_dict\n\n", "heading1": "Function Input List vs Set", "source_page_url": "https://gradio.app/guides/blocks-and-event-listeners", "source_page_title": "Building With Blocks - Blocks And Event Listeners Guide"}, {"text": "Similarly, you may return values for multiple output components either as:\n\n1. a list of values, or\n2. a dictionary keyed by the component\n\nLet's first see an example of (1), where we set the values of two output components by returning two values:\n\n```python\nwith gr.Blocks() as demo:\n food_box = gr.Number(value=10, label=\"Food Count\")\n status_box = gr.Textbox()\n\n def eat(food):\n if food > 0:\n return food - 1, \"full\"\n else:\n return 0, \"hungry\"\n\n gr.Button(\"Eat\").click(\n fn=eat,\n inputs=food_box,\n outputs=[food_box, status_box]\n )\n```\n\nAbove, each return statement returns two values corresponding to `food_box` and `status_box`, respectively.\n\n**Note:** if your event listener has a single output component, you should **not** return it as a single-item list. This will not work, since Gradio does not know whether to interpret that outer list as part of your return value. You should instead just return that value directly.\n\nNow, let's see option (2). Instead of returning a list of values corresponding to each output component in order, you can also return a dictionary, with the key corresponding to the output component and the value as the new value. This also allows you to skip updating some output components.\n\n```python\nwith gr.Blocks() as demo:\n food_box = gr.Number(value=10, label=\"Food Count\")\n status_box = gr.Textbox()\n\n def eat(food):\n if food > 0:\n return {food_box: food - 1, status_box: \"full\"}\n else:\n return {status_box: \"hungry\"}\n\n gr.Button(\"Eat\").click(\n fn=eat,\n inputs=food_box,\n outputs=[food_box, status_box]\n )\n```\n\nNotice how when there is no food, we only update the `status_box` element. We skipped updating the `food_box` component.\n\nDictionary returns are helpful when an event listener affects many components on return, or conditionally affects outputs and not others.\n\nKeep in mind that with dictionary returns,", "heading1": "Function Return List vs Dict", "source_page_url": "https://gradio.app/guides/blocks-and-event-listeners", "source_page_title": "Building With Blocks - Blocks And Event Listeners Guide"}, {"text": "d_box` component.\n\nDictionary returns are helpful when an event listener affects many components on return, or conditionally affects outputs and not others.\n\nKeep in mind that with dictionary returns, we still need to specify the possible outputs in the event listener.\n\n", "heading1": "Function Return List vs Dict", "source_page_url": "https://gradio.app/guides/blocks-and-event-listeners", "source_page_title": "Building With Blocks - Blocks And Event Listeners Guide"}, {"text": "The return value of an event listener function is usually the updated value of the corresponding output Component. Sometimes we want to update the configuration of the Component as well, such as the visibility. In this case, we return a new Component, setting the properties we want to change.\n\n$code_blocks_essay_simple\n$demo_blocks_essay_simple\n\nSee how we can configure the Textbox itself through a new `gr.Textbox()` method. The `value=` argument can still be used to update the value along with Component configuration. Any arguments we do not set will preserve their previous values.\n\n", "heading1": "Updating Component Configurations", "source_page_url": "https://gradio.app/guides/blocks-and-event-listeners", "source_page_title": "Building With Blocks - Blocks And Event Listeners Guide"}, {"text": "In some cases, you may want to leave a component's value unchanged. Gradio includes a special function, `gr.skip()`, which can be returned from your function. Returning this function will keep the output component (or components') values as is. Let us illustrate with an example:\n\n$code_skip\n$demo_skip\n\nNote the difference between returning `None` (which generally resets a component's value to an empty state) versus returning `gr.skip()`, which leaves the component value unchanged.\n\nTip: if you have multiple output components, and you want to leave all of their values unchanged, you can just return a single `gr.skip()` instead of returning a tuple of skips, one for each element.\n\n", "heading1": "Not Changing a Component's Value", "source_page_url": "https://gradio.app/guides/blocks-and-event-listeners", "source_page_title": "Building With Blocks - Blocks And Event Listeners Guide"}, {"text": "You can also run events consecutively by using the `then` method of an event listener. This will run an event after the previous event has finished running. This is useful for running events that update components in multiple steps.\n\nFor example, in the chatbot example below, we first update the chatbot with the user message immediately, and then update the chatbot with the computer response after a simulated delay.\n\n$code_chatbot_consecutive\n$demo_chatbot_consecutive\n\nThe `.then()` method of an event listener executes the subsequent event regardless of whether the previous event raised any errors. If you'd like to only run subsequent events if the previous event executed successfully, use the `.success()` method, which takes the same arguments as `.then()`. Conversely, if you'd like to only run subsequent events if the previous event failed (i.e., raised an error), use the `.failure()` method. This is particularly useful for error handling workflows, such as displaying error messages or restoring previous states when an operation fails.\n\n", "heading1": "Running Events Consecutively", "source_page_url": "https://gradio.app/guides/blocks-and-event-listeners", "source_page_title": "Building With Blocks - Blocks And Event Listeners Guide"}, {"text": "Often times, you may want to bind multiple triggers to the same function. For example, you may want to allow a user to click a submit button, or press enter to submit a form. You can do this using the `gr.on` method and passing a list of triggers to the `trigger`.\n\n$code_on_listener_basic\n$demo_on_listener_basic\n\nYou can use decorator syntax as well:\n\n$code_on_listener_decorator\n\nYou can use `gr.on` to create \"live\" events by binding to the `change` event of components that implement it. If you do not specify any triggers, the function will automatically bind to all `change` event of all input components that include a `change` event (for example `gr.Textbox` has a `change` event whereas `gr.Button` does not).\n\n$code_on_listener_live\n$demo_on_listener_live\n\nYou can follow `gr.on` with `.then`, just like any regular event listener. This handy method should save you from having to write a lot of repetitive code!\n\n", "heading1": "Binding Multiple Triggers to a Function", "source_page_url": "https://gradio.app/guides/blocks-and-event-listeners", "source_page_title": "Building With Blocks - Blocks And Event Listeners Guide"}, {"text": "If you want to set a Component's value to always be a function of the value of other Components, you can use the following shorthand:\n\n```python\nwith gr.Blocks() as demo:\n num1 = gr.Number()\n num2 = gr.Number()\n product = gr.Number(lambda a, b: a * b, inputs=[num1, num2])\n```\n\nThis functionally the same as:\n```python\nwith gr.Blocks() as demo:\n num1 = gr.Number()\n num2 = gr.Number()\n product = gr.Number()\n\n gr.on(\n [num1.change, num2.change, demo.load], \n lambda a, b: a * b, \n inputs=[num1, num2], \n outputs=product\n )\n```\n", "heading1": "Binding a Component Value Directly to a Function of Other Components", "source_page_url": "https://gradio.app/guides/blocks-and-event-listeners", "source_page_title": "Building With Blocks - Blocks And Event Listeners Guide"}, {"text": "Global state in Gradio apps is very simple: any variable created outside of a function is shared globally between all users.\n\nThis makes managing global state very simple and without the need for external services. For example, in this application, the `visitor_count` variable is shared between all users\n\n```py\nimport gradio as gr\n\nShared between all users\nvisitor_count = 0\n\ndef increment_counter():\n global visitor_count\n visitor_count += 1\n return visitor_count\n\nwith gr.Blocks() as demo: \n number = gr.Textbox(label=\"Total Visitors\", value=\"Counting...\")\n demo.load(increment_counter, inputs=None, outputs=number)\n\ndemo.launch()\n```\n\nThis means that any time you do _not_ want to share a value between users, you should declare it _within_ a function. But what if you need to share values between function calls, e.g. a chat history? In that case, you should use one of the subsequent approaches to manage state.\n\n", "heading1": "Global State", "source_page_url": "https://gradio.app/guides/state-in-blocks", "source_page_title": "Building With Blocks - State In Blocks Guide"}, {"text": "Gradio supports session state, where data persists across multiple submits within a page session. To reiterate, session data is _not_ shared between different users of your model, and does _not_ persist if a user refreshes the page to reload the Gradio app. To store data in a session state, you need to do three things:\n\n1. Create a `gr.State()` object. If there is a default value to this stateful object, pass that into the constructor. Note that `gr.State` objects must be [deepcopy-able](https://docs.python.org/3/library/copy.html), otherwise you will need to use a different approach as described below.\n2. In the event listener, put the `State` object as an input and output as needed.\n3. In the event listener function, add the variable to the input parameters and the return value.\n\nLet's take a look at a simple example. We have a simple checkout app below where you add items to a cart. You can also see the size of the cart.\n\n$code_simple_state\n\nNotice how we do this with state:\n\n1. We store the cart items in a `gr.State()` object, initialized here to be an empty list.\n2. When adding items to the cart, the event listener uses the cart as both input and output - it returns the updated cart with all the items inside. \n3. We can attach a `.change` listener to cart, that uses the state variable as input as well.\n\nYou can think of `gr.State` as an invisible Gradio component that can store any kind of value. Here, `cart` is not visible in the frontend but is used for calculations.\n\nThe `.change` listener for a state variable triggers after any event listener changes the value of a state variable. If the state variable holds a sequence (like a `list`, `set`, or `dict`), a change is triggered if any of the elements inside change. If it holds an object or primitive, a change is triggered if the **hash** of the value changes. So if you define a custom class and create a `gr.State` variable that is an instance of that class, make sure that the the class includes a sensible `__", "heading1": "Session State", "source_page_url": "https://gradio.app/guides/state-in-blocks", "source_page_title": "Building With Blocks - State In Blocks Guide"}, {"text": "riggered if the **hash** of the value changes. So if you define a custom class and create a `gr.State` variable that is an instance of that class, make sure that the the class includes a sensible `__hash__` implementation.\n\nThe value of a session State variable is cleared when the user refreshes the page. The value is stored on in the app backend for 60 minutes after the user closes the tab (this can be configured by the `delete_cache` parameter in `gr.Blocks`).\n\nLearn more about `State` in the [docs](https://gradio.app/docs/gradio/state).\n\n**What about objects that cannot be deepcopied?**\n\nAs mentioned earlier, the value stored in `gr.State` must be [deepcopy-able](https://docs.python.org/3/library/copy.html). If you are working with a complex object that cannot be deepcopied, you can take a different approach to manually read the user's `session_hash` and store a global `dictionary` with instances of your object for each user. Here's how you would do that:\n\n```py\nimport gradio as gr\n\nclass NonDeepCopyable:\n def __init__(self):\n from threading import Lock\n self.counter = 0\n self.lock = Lock() Lock objects cannot be deepcopied\n \n def increment(self):\n with self.lock:\n self.counter += 1\n return self.counter\n\nGlobal dictionary to store user-specific instances\ninstances = {}\n\ndef initialize_instance(request: gr.Request):\n instances[request.session_hash] = NonDeepCopyable()\n return \"Session initialized!\"\n\ndef cleanup_instance(request: gr.Request):\n if request.session_hash in instances:\n del instances[request.session_hash]\n\ndef increment_counter(request: gr.Request):\n if request.session_hash in instances:\n instance = instances[request.session_hash]\n return instance.increment()\n return \"Error: Session not initialized\"\n\nwith gr.Blocks() as demo:\n output = gr.Textbox(label=\"Status\")\n counter = gr.Number(label=\"Counter Value\")\n increment_btn = gr.Button(\"Increment Co", "heading1": "Session State", "source_page_url": "https://gradio.app/guides/state-in-blocks", "source_page_title": "Building With Blocks - State In Blocks Guide"}, {"text": " return \"Error: Session not initialized\"\n\nwith gr.Blocks() as demo:\n output = gr.Textbox(label=\"Status\")\n counter = gr.Number(label=\"Counter Value\")\n increment_btn = gr.Button(\"Increment Counter\")\n increment_btn.click(increment_counter, inputs=None, outputs=counter)\n \n Initialize instance when page loads\n demo.load(initialize_instance, inputs=None, outputs=output) \n Clean up instance when page is closed/refreshed\n demo.unload(cleanup_instance) \n\ndemo.launch()\n```\n\n", "heading1": "Session State", "source_page_url": "https://gradio.app/guides/state-in-blocks", "source_page_title": "Building With Blocks - State In Blocks Guide"}, {"text": "Gradio also supports browser state, where data persists in the browser's localStorage even after the page is refreshed or closed. This is useful for storing user preferences, settings, API keys, or other data that should persist across sessions. To use local state:\n\n1. Create a `gr.BrowserState` object. You can optionally provide an initial default value and a key to identify the data in the browser's localStorage.\n2. Use it like a regular `gr.State` component in event listeners as inputs and outputs.\n\nHere's a simple example that saves a user's username and password across sessions:\n\n$code_browserstate\n\nNote: The value stored in `gr.BrowserState` does not persist if the Grado app is restarted. To persist it, you can hardcode specific values of `storage_key` and `secret` in the `gr.BrowserState` component and restart the Gradio app on the same server name and server port. However, this should only be done if you are running trusted Gradio apps, as in principle, this can allow one Gradio app to access localStorage data that was created by a different Gradio app.\n", "heading1": "Browser State", "source_page_url": "https://gradio.app/guides/state-in-blocks", "source_page_title": "Building With Blocks - State In Blocks Guide"}, {"text": "Elements within a `with gr.Row` clause will all be displayed horizontally. For example, to display two Buttons side by side:\n\n```python\nwith gr.Blocks() as demo:\n with gr.Row():\n btn1 = gr.Button(\"Button 1\")\n btn2 = gr.Button(\"Button 2\")\n```\n\nYou can set every element in a Row to have the same height. Configure this with the `equal_height` argument.\n\n```python\nwith gr.Blocks() as demo:\n with gr.Row(equal_height=True):\n textbox = gr.Textbox()\n btn2 = gr.Button(\"Button 2\")\n```\n\nThe widths of elements in a Row can be controlled via a combination of `scale` and `min_width` arguments that are present in every Component.\n\n- `scale` is an integer that defines how an element will take up space in a Row. If scale is set to `0`, the element will not expand to take up space. If scale is set to `1` or greater, the element will expand. Multiple elements in a row will expand proportional to their scale. Below, `btn2` will expand twice as much as `btn1`, while `btn0` will not expand at all:\n\n```python\nwith gr.Blocks() as demo:\n with gr.Row():\n btn0 = gr.Button(\"Button 0\", scale=0)\n btn1 = gr.Button(\"Button 1\", scale=1)\n btn2 = gr.Button(\"Button 2\", scale=2)\n```\n\n- `min_width` will set the minimum width the element will take. The Row will wrap if there isn't sufficient space to satisfy all `min_width` values.\n\nLearn more about Rows in the [docs](https://gradio.app/docs/row).\n\n", "heading1": "Rows", "source_page_url": "https://gradio.app/guides/controlling-layout", "source_page_title": "Building With Blocks - Controlling Layout Guide"}, {"text": "Components within a Column will be placed vertically atop each other. Since the vertical layout is the default layout for Blocks apps anyway, to be useful, Columns are usually nested within Rows. For example:\n\n$code_rows_and_columns\n$demo_rows_and_columns\n\nSee how the first column has two Textboxes arranged vertically. The second column has an Image and Button arranged vertically. Notice how the relative widths of the two columns is set by the `scale` parameter. The column with twice the `scale` value takes up twice the width.\n\nLearn more about Columns in the [docs](https://gradio.app/docs/column).\n\nFill Browser Height / Width\n\nTo make an app take the full width of the browser by removing the side padding, use `gr.Blocks(fill_width=True)`. \n\nTo make top level Components expand to take the full height of the browser, use `fill_height` and apply scale to the expanding Components.\n\n```python\nimport gradio as gr\n\nwith gr.Blocks(fill_height=True) as demo:\n gr.Chatbot(scale=1)\n gr.Textbox(scale=0)\n```\n\n", "heading1": "Columns and Nesting", "source_page_url": "https://gradio.app/guides/controlling-layout", "source_page_title": "Building With Blocks - Controlling Layout Guide"}, {"text": "Some components support setting height and width. These parameters accept either a number (interpreted as pixels) or a string. Using a string allows the direct application of any CSS unit to the encapsulating Block element.\n\nBelow is an example illustrating the use of viewport width (vw):\n\n```python\nimport gradio as gr\n\nwith gr.Blocks() as demo:\n im = gr.ImageEditor(width=\"50vw\")\n\ndemo.launch()\n```\n\n", "heading1": "Dimensions", "source_page_url": "https://gradio.app/guides/controlling-layout", "source_page_title": "Building With Blocks - Controlling Layout Guide"}, {"text": "You can also create Tabs using the `with gr.Tab('tab_name'):` clause. Any component created inside of a `with gr.Tab('tab_name'):` context appears in that tab. Consecutive Tab clauses are grouped together so that a single tab can be selected at one time, and only the components within that Tab's context are shown.\n\nFor example:\n\n$code_blocks_flipper\n$demo_blocks_flipper\n\nAlso note the `gr.Accordion('label')` in this example. The Accordion is a layout that can be toggled open or closed. Like `Tabs`, it is a layout element that can selectively hide or show content. Any components that are defined inside of a `with gr.Accordion('label'):` will be hidden or shown when the accordion's toggle icon is clicked.\n\nLearn more about [Tabs](https://gradio.app/docs/tab) and [Accordions](https://gradio.app/docs/accordion) in the docs.\n\n", "heading1": "Tabs and Accordions", "source_page_url": "https://gradio.app/guides/controlling-layout", "source_page_title": "Building With Blocks - Controlling Layout Guide"}, {"text": "The sidebar is a collapsible panel that renders child components on the left side of the screen and can be expanded or collapsed.\n\nFor example:\n\n$code_blocks_sidebar\n\nLearn more about [Sidebar](https://gradio.app/docs/gradio/sidebar) in the docs.\n\n\n", "heading1": "Sidebar", "source_page_url": "https://gradio.app/guides/controlling-layout", "source_page_title": "Building With Blocks - Controlling Layout Guide"}, {"text": "In order to provide a guided set of ordered steps, a controlled workflow, you can use the `Walkthrough` component with accompanying `Step` components.\n\nThe `Walkthrough` component has a visual style and user experience tailored for this usecase.\n\nAuthoring this component is very similar to `Tab`, except it is the app developers responsibility to progress through each step, by setting the appropriate ID for the parent `Walkthrough` which should correspond to an ID provided to an indvidual `Step`. \n\n$demo_walkthrough\n\nLearn more about [Walkthrough](https://gradio.app/docs/gradio/walkthrough) in the docs.\n\n\n", "heading1": "Multi-step walkthroughs", "source_page_url": "https://gradio.app/guides/controlling-layout", "source_page_title": "Building With Blocks - Controlling Layout Guide"}, {"text": "Both Components and Layout elements have a `visible` argument that can set initially and also updated. Setting `gr.Column(visible=...)` on a Column can be used to show or hide a set of Components.\n\n$code_blocks_form\n$demo_blocks_form\n\n", "heading1": "Visibility", "source_page_url": "https://gradio.app/guides/controlling-layout", "source_page_title": "Building With Blocks - Controlling Layout Guide"}, {"text": "In some cases, you might want to define components before you actually render them in your UI. For instance, you might want to show an examples section using `gr.Examples` above the corresponding `gr.Textbox` input. Since `gr.Examples` requires as a parameter the input component object, you will need to first define the input component, but then render it later, after you have defined the `gr.Examples` object.\n\nThe solution to this is to define the `gr.Textbox` outside of the `gr.Blocks()` scope and use the component's `.render()` method wherever you'd like it placed in the UI.\n\nHere's a full code example:\n\n```python\ninput_textbox = gr.Textbox()\n\nwith gr.Blocks() as demo:\n gr.Examples([\"hello\", \"bonjour\", \"merhaba\"], input_textbox)\n input_textbox.render()\n```\n\nSimilarly, if you have already defined a component in a Gradio app, but wish to unrender it so that you can define in a different part of your application, then you can call the `.unrender()` method. In the following example, the `Textbox` will appear in the third column:\n\n```py\nimport gradio as gr\n\nwith gr.Blocks() as demo:\n with gr.Row():\n with gr.Column():\n gr.Markdown(\"Row 1\")\n textbox = gr.Textbox()\n with gr.Column():\n gr.Markdown(\"Row 2\")\n textbox.unrender()\n with gr.Column():\n gr.Markdown(\"Row 3\")\n textbox.render()\n\ndemo.launch()\n```\n\n", "heading1": "Defining and Rendering Components Separately", "source_page_url": "https://gradio.app/guides/controlling-layout", "source_page_title": "Building With Blocks - Controlling Layout Guide"}, {"text": "The `gr.HTML` component can also be used to create custom input components by triggering events. You will provide `js_on_load`, javascript code that runs when the component loads. The code has access to the `trigger` function to trigger events that Gradio can listen to, and the object `props` which has access to all the props of the component, including `value`.\n\n$code_star_rating_events\n$demo_star_rating_events\n\nTake a look at the `js_on_load` code above. We add click event listeners to each star image to update the value via `props.value` when a star is clicked. This also re-renders the template to show the updated value. We also add a click event listener to the submit button that triggers the `submit` event. In our app, we listen to this trigger to run a function that outputs the `value` of the star rating.\n\nThe `js_on_load` scope also includes an `upload` async function that lets you upload a JavaScript `File` object directly to the Gradio server. It returns a dictionary with `path` (the server-side file path) and `url` (the public URL to access the file).\n\n```js\nconst { path, url } = await upload(file);\n```\n\nHere is an example of a custom file-upload widget built with `gr.HTML`:\n\n$code_html_upload\n$demo_html_upload\n\nYou can update any other props of the component via `props.`, and trigger events via `trigger('')`. The trigger event can also be send event data, e.g.\n\n```js\ntrigger('event_name', { key: value, count: 123 });\n```\n\nThis event data will be accessible the Python event listener functions via gr.EventData.\n\n```python\ndef handle_event(evt: gr.EventData):\n print(evt.key)\n print(evt.count)\n\nstar_rating.event(fn=handle_event, inputs=[], outputs=[])\n```\n\nKeep in mind that event listeners attached in `js_on_load` are only attached once when the component is first rendered. If your component creates new elements dynamically that need event listeners, attach the event listener to a parent element that exists when the component load", "heading1": "Triggering Events and Custom Input Components", "source_page_url": "https://gradio.app/guides/custom-HTML-components", "source_page_title": "Building With Blocks - Custom Html Components Guide"}, {"text": "ce when the component is first rendered. If your component creates new elements dynamically that need event listeners, attach the event listener to a parent element that exists when the component loads, and check for the target. For example:\n\n```js\nelement.addEventListener('click', (e) =>\n if (e.target && e.target.matches('.child-element')) {\n props.value = e.target.dataset.value;\n }\n);\n```\n\nYou can trigger an event with any name. As long as the event name appears enclosed in quotes in your `js_on_load` string, you can attach a Python listener using `component.do_something(fn, ...)`.\n\n", "heading1": "Triggering Events and Custom Input Components", "source_page_url": "https://gradio.app/guides/custom-HTML-components", "source_page_title": "Building With Blocks - Custom Html Components Guide"}, {"text": "The `watch` function, available inside `js_on_load`, lets you run a callback whenever specific props change when the component is an output to a Python event listener. Read current values directly from `props` inside the callback.\n\n```js\n// Watch a single prop\nwatch('value', () => {\n console.log('value is now:', props.value);\n});\n\n// Watch multiple props\nwatch(['value', 'color'], () => {\n console.log('value or color changed');\n});\n```\n\n", "heading1": "Watching Props with `watch`", "source_page_url": "https://gradio.app/guides/custom-HTML-components", "source_page_title": "Building With Blocks - Custom Html Components Guide"}, {"text": "The `head` parameter lets you load external JavaScript or CSS libraries directly on the component. The `head` content is injected and loaded **before** `js_on_load` runs, so your code can immediately use the library.\n\n```python\ngr.HTML(\n value=[30, 70, 45, 90, 60],\n html_template=\"\",\n js_on_load=\"\"\"\n new Chart(element.querySelector('chart'), {\n type: 'bar',\n data: {\n labels: props.value.map((_, i) => 'Item ' + (i + 1)),\n datasets: [{ label: 'Values', data: props.value }]\n }\n });\n \"\"\",\n head='',\n)\n```\n\n", "heading1": "Loading Third-Party Scripts with `head`", "source_page_url": "https://gradio.app/guides/custom-HTML-components", "source_page_title": "Building With Blocks - Custom Html Components Guide"}, {"text": "You can call Python functions directly from your `js_on_load` code using the `server_functions` parameter. Pass a list of Python functions to `server_functions`, and they become available as async methods on a `server` object inside `js_on_load`.\n\n$code_html_server_functions\n$demo_html_server_functions\n\n\n", "heading1": "Server Functions", "source_page_url": "https://gradio.app/guides/custom-HTML-components", "source_page_title": "Building With Blocks - Custom Html Components Guide"}, {"text": "If you are reusing the same HTML component in multiple places, you can create a custom component class by subclassing `gr.HTML` and setting default values for the templates and other arguments. Here's an example of creating a reusable StarRating component.\n\n$code_star_rating_component\n$demo_star_rating_component\n\nNote: Gradio requires all components to accept certain arguments, such as `render`. You do not need\nto handle these arguments, but you do need to accept them in your component constructor and pass\nthem to the parent `gr.HTML` class. Otherwise, your component may not behave correctly. The easiest\nway is to add `**kwargs` to your `__init__` method and pass it to `super().__init__()`, just like in the code example above.\n\nWe've created several custom HTML components as reusable components as examples you can reference in [this directory](https://github.com/gradio-app/gradio/tree/main/gradio/components/custom_html_components).\n\n\n", "heading1": "Component Classes", "source_page_url": "https://gradio.app/guides/custom-HTML-components", "source_page_title": "Building With Blocks - Custom Html Components Guide"}, {"text": "The `gr.HTML` component can also be used as a container for other Gradio components using the `@children` placeholder. This allows you to create custom layouts with HTML/CSS. \n\nThe `@children` must be at the top-level of the `html_template`. Since children cannot be nested inside the template, target the parent element directly with your CSS and JavaScript if you need to style or interact with the container of the children.\n\nHere's a basic example:\n\n$code_html_children\n$demo_html_children\n\nIn this example, the `@children` placeholder marks where the child components (the Name and Email textboxes) will be rendered. Notice how in the `css_template` we target the parent element to style the container div that wraps the children.\n\n\nAPI / MCP support\n\nTo make your custom HTML component work with Gradio's built-in support for API and MCP (Model Context Protocol) usage, you need to define how its data should be serialized. There are two ways to do this:\n\n**Option 1: Define an `api_info()` method**\n\nAdd an `api_info()` method that returns a JSON schema dictionary describing your component's data format. This is what we do in the StarRating class above.\n\n**Option 2: Define a Pydantic data model**\n\nFor more complex data structures, you can define a Pydantic model that inherits from `GradioModel` or `GradioRootModel`:\n\n```python\nfrom gradio.data_classes import GradioModel, GradioRootModel\n\nclass MyComponentData(GradioModel):\n items: List[str]\n count: int\n\nclass MyComponent(gr.HTML):\n data_model = MyComponentData\n```\n\nUse `GradioModel` when your data is a dictionary with named fields, or `GradioRootModel` when your data is a simple type (string, list, etc.) that doesn't need to be wrapped in a dictionary. By defining a `data_model`, your component automatically implements API methods.\n\n", "heading1": "Embedding Components in HTML", "source_page_url": "https://gradio.app/guides/custom-HTML-components", "source_page_title": "Building With Blocks - Custom Html Components Guide"}, {"text": "Once you've built a custom HTML component, you can share it with the community by pushing it to the [HTML Components Gallery](https://www.gradio.app/custom-components/html-gallery). The gallery lets anyone browse, interact with, and copy the Python code for community-contributed components.\n\nCall `push_to_hub` on any `gr.HTML` instance or subclass:\n\n```python\nstar_rating = StarRating()\nstar_rating.push_to_hub(\n name=\"Star Rating\",\n description=\"Interactive 5-star rating with click-to-rate\",\n author=\"your-hf-username\",\n tags=[\"input\", \"rating\"],\n repo_url=\"https://github.com/your-username/your-repo\",\n)\n```\n\nThis opens a pull request on the gallery's HuggingFace dataset repo. Once approved, your component will appear in the gallery for others to discover and use.\n\nTip: The `push_to_hub` method has a `head` parameter that deserves special attention. If your component uses an external library loaded via the `head` parameter of `launch` (e.g. `head=''`), pass the same `head` string to `push_to_hub` so that the gallery can load those scripts when rendering your component.\n\nAuthentication\n\nYou need a HuggingFace **write token** to push components. Either pass it directly:\n\n```python\nstar_rating.push_to_hub(..., token=\"hf_xxxxx\")\n```\n\nOr log in beforehand with the HuggingFace CLI, and the cached token will be used automatically:\n\n```bash\nhuggingface-cli login\n```\n\n", "heading1": "Sharing Components with `push_to_hub`", "source_page_url": "https://gradio.app/guides/custom-HTML-components", "source_page_title": "Building With Blocks - Custom Html Components Guide"}, {"text": "Keep in mind that using `gr.HTML` to create custom components involves injecting raw HTML and JavaScript into your Gradio app. Be cautious about using untrusted user input into `html_template` and `js_on_load`, as this could lead to cross-site scripting (XSS) vulnerabilities. \n\nYou should also expect that any Python event listeners that take your `gr.HTML` component as input could have any arbitrary value passed to them, not just the values you expect the frontend to be able to set for `value`. Sanitize and validate user input appropriately in public applications.\n\n", "heading1": "Security Considerations", "source_page_url": "https://gradio.app/guides/custom-HTML-components", "source_page_title": "Building With Blocks - Custom Html Components Guide"}, {"text": "- Browse the [HTML Components Gallery](https://www.gradio.app/custom-components/html-gallery) to see what the community has built and copy components into your own apps.\n- Check out more examples in [this directory](https://github.com/gradio-app/gradio/tree/main/gradio/components/custom_html_components).\n- Share your own components with `push_to_hub` to help others!", "heading1": "Next Steps", "source_page_url": "https://gradio.app/guides/custom-HTML-components", "source_page_title": "Building With Blocks - Custom Html Components Guide"}, {"text": "In the example below, we will create a variable number of Textboxes. When the user edits the input Textbox, we create a Textbox for each letter in the input. Try it out below:\n\n$code_render_split_simple\n$demo_render_split_simple\n\nSee how we can now create a variable number of Textboxes using our custom logic - in this case, a simple `for` loop. The `@gr.render` decorator enables this with the following steps:\n\n1. Create a function and attach the @gr.render decorator to it.\n2. Add the input components to the `inputs=` argument of @gr.render, and create a corresponding argument in your function for each component. This function will automatically re-run on any change to a component.\n3. Add all components inside the function that you want to render based on the inputs.\n\nNow whenever the inputs change, the function re-runs, and replaces the components created from the previous function run with the latest run. Pretty straightforward! Let's add a little more complexity to this app:\n\n$code_render_split\n$demo_render_split\n\nBy default, `@gr.render` re-runs are triggered by the `.load` listener to the app and the `.change` listener to any input component provided. We can override this by explicitly setting the triggers in the decorator, as we have in this app to only trigger on `input_text.submit` instead. \nIf you are setting custom triggers, and you also want an automatic render at the start of the app, make sure to add `demo.load` to your list of triggers.\n\n", "heading1": "Dynamic Number of Components", "source_page_url": "https://gradio.app/guides/dynamic-apps-with-render-decorator", "source_page_title": "Building With Blocks - Dynamic Apps With Render Decorator Guide"}, {"text": "If you're creating components, you probably want to attach event listeners to them as well. Let's take a look at an example that takes in a variable number of Textbox as input, and merges all the text into a single box.\n\n$code_render_merge_simple\n$demo_render_merge_simple\n\nLet's take a look at what's happening here:\n\n1. The state variable `text_count` is keeping track of the number of Textboxes to create. By clicking on the Add button, we increase `text_count` which triggers the render decorator.\n2. Note that in every single Textbox we create in the render function, we explicitly set a `key=` argument. This key allows us to preserve the value of this Component between re-renders. If you type in a value in a textbox, and then click the Add button, all the Textboxes re-render, but their values aren't cleared because the `key=` maintains the the value of a Component across a render.\n3. We've stored the Textboxes created in a list, and provide this list as input to the merge button event listener. Note that **all event listeners that use Components created inside a render function must also be defined inside that render function**. The event listener can still reference Components outside the render function, as we do here by referencing `merge_btn` and `output` which are both defined outside the render function.\n\nJust as with Components, whenever a function re-renders, the event listeners created from the previous render are cleared and the new event listeners from the latest run are attached. \n\nThis allows us to create highly customizable and complex interactions! \n\n", "heading1": "Dynamic Event Listeners", "source_page_url": "https://gradio.app/guides/dynamic-apps-with-render-decorator", "source_page_title": "Building With Blocks - Dynamic Apps With Render Decorator Guide"}, {"text": "The `key=` argument tells Gradio that a component being created in a render function corresponds to the same logical component as in the previous render.\n\nThis allows Gradio to reuse the existing browser element instead of destroying and recreating it on every render. It also preserves the user's entered value across re-renders when the same keyed component is recreated.\n\nIf your component is nested inside layout items like `gr.Row`, make sure those containers are keyed consistently as well, because parent keys must also match.\n\nYou can also key event listeners, for example `button.click(key=...)`, when the same listener is recreated with the same inputs and outputs across renders. This helps Gradio keep the listener associated with the correct component instances and can prevent issues when events finish processing after a re-render.\n\n", "heading1": "Closer Look at `keys=` parameter", "source_page_url": "https://gradio.app/guides/dynamic-apps-with-render-decorator", "source_page_title": "Building With Blocks - Dynamic Apps With Render Decorator Guide"}, {"text": "Let's look at two examples that use all the features above. First, try out the to-do list app below: \n\n$code_todo_list\n$demo_todo_list\n\nNote that almost the entire app is inside a single `gr.render` that reacts to the tasks `gr.State` variable. This variable is a nested list, which presents some complexity. If you design a `gr.render` to react to a list or dict structure, ensure you do the following:\n\n1. Any event listener that modifies a state variable in a manner that should trigger a re-render must set the state variable as an output. This lets Gradio know to check if the variable has changed behind the scenes. \n2. In a `gr.render`, if a variable in a loop is used inside an event listener function, that variable should be \"frozen\" via setting it to itself as a default argument in the function header. See how we have `task=task` in both `mark_done` and `delete`. This freezes the variable to its \"loop-time\" value.\n\nLet's take a look at one last example that uses everything we learned. Below is an audio mixer. Provide multiple audio tracks and mix them together.\n\n$code_audio_mixer\n$demo_audio_mixer\n\nTwo things to note in this app:\n1. Here we provide `key=` to all the components! We need to do this so that if we add another track after setting the values for an existing track, our input values to the existing track do not get reset on re-render.\n2. When there are lots of components of different types and arbitrary counts passed to an event listener, it is easier to use the set and dictionary notation for inputs rather than list notation. Above, we make one large set of all the input `gr.Audio` and `gr.Slider` components when we pass the inputs to the `merge` function. In the function body we query the component values as a dict.\n\nThe `gr.render` expands gradio capabilities extensively - see what you can make out of it! \n", "heading1": "Putting it Together", "source_page_url": "https://gradio.app/guides/dynamic-apps-with-render-decorator", "source_page_title": "Building With Blocks - Dynamic Apps With Render Decorator Guide"}, {"text": "**Prerequisite**: Gradio requires [Python 3.10 or higher](https://www.python.org/downloads/).\n\n\nWe recommend installing Gradio using `pip`, which is included by default in Python. Run this in your terminal or command prompt:\n\n```bash\npip install --upgrade gradio\n```\n\n\nTip: It is best to install Gradio in a virtual environment. Detailed installation instructions for all common operating systems are provided here. \n\n", "heading1": "Installation", "source_page_url": "https://gradio.app/guides/quickstart", "source_page_title": "Getting Started - Quickstart Guide"}, {"text": "You can run Gradio in your favorite code editor, Jupyter notebook, Google Colab, or anywhere else you write Python. Let's write your first Gradio app:\n\n\n$code_hello_world_4\n\n\nTip: We shorten the imported name from gradio to gr. This is a widely adopted convention for better readability of code. \n\nNow, run your code. If you've written the Python code in a file named `app.py`, then you would run `python app.py` from the terminal.\n\nThe demo below will open in a browser on [http://localhost:7860](http://localhost:7860) if running from a file. If you are running within a notebook, the demo will appear embedded within the notebook.\n\n$demo_hello_world_4\n\nType your name in the textbox on the left, drag the slider, and then press the Submit button. You should see a friendly greeting on the right.\n\nTip: When developing locally, you can run your Gradio app in hot reload mode, which automatically reloads the Gradio app whenever you make changes to the file. To do this, simply type in gradio before the name of the file instead of python. In the example above, you would type: `gradio app.py` in your terminal. You can also enable vibe mode by using the --vibe flag, e.g. gradio --vibe app.py, which provides an in-browser chat that can be used to write or edit your Gradio app using natural language. Learn more in the Hot Reloading Guide.\n\n\n**Understanding the `Interface` Class**\n\nYou'll notice that in order to make your first demo, you created an instance of the `gr.Interface` class. The `Interface` class is designed to create demos for machine learning models which accept one or more inputs, and return one or more outputs. \n\nThe `Interface` class has three core arguments:\n\n- `fn`: the function to wrap a user interface (UI) around\n- `inputs`: the Gradio component(s) to use for the input. The num", "heading1": "Building Your First Demo", "source_page_url": "https://gradio.app/guides/quickstart", "source_page_title": "Getting Started - Quickstart Guide"}, {"text": "turn one or more outputs. \n\nThe `Interface` class has three core arguments:\n\n- `fn`: the function to wrap a user interface (UI) around\n- `inputs`: the Gradio component(s) to use for the input. The number of components should match the number of arguments in your function.\n- `outputs`: the Gradio component(s) to use for the output. The number of components should match the number of return values from your function.\n\nThe `fn` argument is very flexible -- you can pass *any* Python function that you want to wrap with a UI. In the example above, we saw a relatively simple function, but the function could be anything from a music generator to a tax calculator to the prediction function of a pretrained machine learning model.\n\nThe `inputs` and `outputs` arguments take one or more Gradio components. As we'll see, Gradio includes more than [30 built-in components](https://www.gradio.app/docs/gradio/introduction) (such as the `gr.Textbox()`, `gr.Image()`, and `gr.HTML()` components) that are designed for machine learning applications. \n\nTip: For the `inputs` and `outputs` arguments, you can pass in the name of these components as a string (`\"textbox\"`) or an instance of the class (`gr.Textbox()`).\n\nIf your function accepts more than one argument, as is the case above, pass a list of input components to `inputs`, with each input component corresponding to one of the arguments of the function, in order. The same holds true if your function returns more than one value: simply pass in a list of components to `outputs`. This flexibility makes the `Interface` class a very powerful way to create demos.\n\nWe'll dive deeper into the `gr.Interface` on our series on [building Interfaces](https://www.gradio.app/main/guides/the-interface-class).\n\n", "heading1": "Building Your First Demo", "source_page_url": "https://gradio.app/guides/quickstart", "source_page_title": "Getting Started - Quickstart Guide"}, {"text": "What good is a beautiful demo if you can't share it? Gradio lets you easily share a machine learning demo without having to worry about the hassle of hosting on a web server. Simply set `share=True` in `launch()`, and a publicly accessible URL will be created for your demo. Let's revisit our example demo, but change the last line as follows:\n\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\nWhen you run this code, a public URL will be generated for your demo in a matter of seconds, something like:\n\n\ud83d\udc49   `https://a23dsf231adb.gradio.live`\n\nNow, anyone around the world can try your Gradio demo from their browser, while the machine learning model and all computation continues to run locally on your computer.\n\nTo learn more about sharing your demo, read our dedicated guide on [sharing your Gradio application](https://www.gradio.app/guides/sharing-your-app).\n\n\n", "heading1": "Sharing Your Demo", "source_page_url": "https://gradio.app/guides/quickstart", "source_page_title": "Getting Started - Quickstart Guide"}, {"text": "So far, we've been discussing the `Interface` class, which is a high-level class that lets you build demos quickly with Gradio. But what else does Gradio include?\n\nCustom Demos with `gr.Blocks`\n\nGradio offers a low-level approach for designing web apps with more customizable layouts and data flows with the `gr.Blocks` class. Blocks supports things like controlling where components appear on the page, handling multiple data flows and more complex interactions (e.g. outputs can serve as inputs to other functions), and updating properties/visibility of components based on user interaction \u2014 still all in Python. \n\nYou can build very custom and complex applications using `gr.Blocks()`. For example, the popular image generation [Automatic1111 Web UI](https://github.com/AUTOMATIC1111/stable-diffusion-webui) is built using Gradio Blocks. We dive deeper into the `gr.Blocks` on our series on [building with Blocks](https://www.gradio.app/guides/blocks-and-event-listeners).\n\nChatbots with `gr.ChatInterface`\n\nGradio includes another high-level class, `gr.ChatInterface`, which is specifically designed to create Chatbot UIs. Similar to `Interface`, you supply a function and Gradio creates a fully working Chatbot UI. If you're interested in creating a chatbot, you can jump straight to [our dedicated guide on `gr.ChatInterface`](https://www.gradio.app/guides/creating-a-chatbot-fast).\n\nThe Gradio Python & JavaScript Ecosystem\n\nThat's the gist of the core `gradio` Python library, but Gradio is actually so much more! It's an entire ecosystem of Python and JavaScript libraries that let you build machine learning applications, or query them programmatically, in Python or JavaScript. Here are other related parts of the Gradio ecosystem:\n\n* [Gradio Python Client](https://www.gradio.app/guides/getting-started-with-the-python-client) (`gradio_client`): query any Gradio app programmatically in Python.\n* [Gradio JavaScript Client](https://www.gradio.app/guides/getting-started-with-", "heading1": "An Overview of Gradio", "source_page_url": "https://gradio.app/guides/quickstart", "source_page_title": "Getting Started - Quickstart Guide"}, {"text": ".app/guides/getting-started-with-the-python-client) (`gradio_client`): query any Gradio app programmatically in Python.\n* [Gradio JavaScript Client](https://www.gradio.app/guides/getting-started-with-the-js-client) (`@gradio/client`): query any Gradio app programmatically in JavaScript.\n* [Hugging Face Spaces](https://huggingface.co/spaces): the most popular place to host Gradio applications \u2014 for free!\n* [Server mode](https://www.gradio.app/guides/server-mode) (`gradio.Server`): build a completely custom frontend using only Gradio's backend (queue, streaming, MCP, ZeroGPU, and Spaces hosting included).\n\n", "heading1": "An Overview of Gradio", "source_page_url": "https://gradio.app/guides/quickstart", "source_page_title": "Getting Started - Quickstart Guide"}, {"text": "Keep learning about Gradio sequentially using the Gradio Guides, which include explanations as well as example code and embedded interactive demos. Next up: [let's dive deeper into the Interface class](https://www.gradio.app/guides/the-interface-class).\n\nOr, if you already know the basics and are looking for something specific, you can search the more [technical API documentation](https://www.gradio.app/docs/).\n", "heading1": "What's Next?", "source_page_url": "https://gradio.app/guides/quickstart", "source_page_title": "Getting Started - Quickstart Guide"}, {"text": "An MCP (Model Control Protocol) server is a standardized way to expose tools so that they can be used by LLMs. A tool can provide an LLM functionality that it does not have natively, such as the ability to generate images or calculate the prime factors of a number. \n\n", "heading1": "What is an MCP Server?", "source_page_url": "https://gradio.app/guides/building-mcp-server-with-gradio", "source_page_title": "Mcp - Building Mcp Server With Gradio Guide"}, {"text": "LLMs are famously not great at counting the number of letters in a word (e.g. the number of \"r\"-s in \"strawberry\"). But what if we equip them with a tool to help? Let's start by writing a simple Gradio app that counts the number of letters in a word or phrase:\n\n$code_letter_counter\n\nNotice that we have: (1) included a detailed docstring for our function, and (2) set `mcp_server=True` in `.launch()`. This is all that's needed for your Gradio app to serve as an MCP server! Now, when you run this app, it will:\n\n1. Start the regular Gradio web interface\n2. Start the MCP server\n3. Print the MCP server URL in the console\n\nThe MCP server will be accessible at:\n```\nhttp://your-server:port/gradio_api/mcp/\n```\n\nGradio automatically converts the `letter_counter` function into an MCP tool that can be used by LLMs. The docstring of the function and the type hints of arguments will be used to generate the description of the tool and its parameters. The name of the function will be used as the name of your tool. Any initial values you provide to your input components (e.g. \"strawberry\" and \"r\" in the `gr.Textbox` components above) will be used as the default values if your LLM doesn't specify a value for that particular input parameter.\n\nNow, all you need to do is add this URL endpoint to your MCP Client (e.g. Claude Desktop, Cursor, or Cline), which typically means pasting this config in the settings:\n\n```\n{\n \"mcpServers\": {\n \"gradio\": {\n \"url\": \"http://your-server:port/gradio_api/mcp/\"\n }\n }\n}\n```\n\n(By the way, you can find the exact config to copy-paste by going to the \"View API\" link in the footer of your Gradio app, and then clicking on \"MCP\").\n\n![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio-guides/view-api-mcp.png)\n\n", "heading1": "Example: Counting Letters in a Word", "source_page_url": "https://gradio.app/guides/building-mcp-server-with-gradio", "source_page_title": "Mcp - Building Mcp Server With Gradio Guide"}, {"text": "1. **Tool Conversion**: Each API endpoint in your Gradio app is automatically converted into an MCP tool with a corresponding name, description, and input schema. To view the tools and schemas, visit http://your-server:port/gradio_api/mcp/schema or go to the \"View API\" link in the footer of your Gradio app, and then click on \"MCP\".\n\n\n2. **Environment variable support**. There are two ways to enable the MCP server functionality:\n\n* Using the `mcp_server` parameter, as shown above:\n ```python\n demo.launch(mcp_server=True)\n ```\n\n* Using environment variables:\n ```bash\n export GRADIO_MCP_SERVER=True\n ```\n\n3. **File Handling**: The Gradio MCP server automatically handles file data conversions, including:\n - Processing image files and returning them in the correct format\n - Managing temporary file storage\n\n By default, the Gradio MCP server accepts input images and files as full URLs (\"http://...\" or \"https:/...\"). For convenience, an additional STDIO-based MCP server is also generated, which can be used to upload files to any remote Gradio app and which returns a URL that can be used for subsequent tool calls.\n\n4. **Hosted MCP Servers on \udb40\udc20\ud83e\udd17 Spaces**: You can publish your Gradio application for free on Hugging Face Spaces, which will allow you to have a free hosted MCP server. Here's an example of such a Space: https://huggingface.co/spaces/abidlabs/mcp-tools. Notice that you can add this config to your MCP Client to start using the tools from this Space immediately:\n\n```\n{\n \"mcpServers\": {\n \"gradio\": {\n \"url\": \"https://abidlabs-mcp-tools.hf.space/gradio_api/mcp/\"\n }\n }\n}\n```\n\n\n\nTip: To minimize latency and increase throughput by as much as 10 times, set queue=False in the event handlers of your Gradio app. However, this disables progress notifications so its recommended that l", "heading1": "Key features of the Gradio <> MCP Integration", "source_page_url": "https://gradio.app/guides/building-mcp-server-with-gradio", "source_page_title": "Mcp - Building Mcp Server With Gradio Guide"}, {"text": "p: To minimize latency and increase throughput by as much as 10 times, set queue=False in the event handlers of your Gradio app. However, this disables progress notifications so its recommended that long running events set queue=True\n\n", "heading1": "Key features of the Gradio <> MCP Integration", "source_page_url": "https://gradio.app/guides/building-mcp-server-with-gradio", "source_page_title": "Mcp - Building Mcp Server With Gradio Guide"}, {"text": "If there's an existing Space that you'd like to use an MCP server, you'll need to do three things:\n\n1. First, [duplicate the Space](https://huggingface.co/docs/hub/en/spaces-more-ways-to-createduplicating-a-space) if it is not your own Space. This will allow you to make changes to the app. If the Space requires a GPU, set the hardware of the duplicated Space to be same as the original Space. You can make it either a public Space or a private Space, since it is possible to use either as an MCP server, as described below.\n2. Then, add docstrings to the functions that you'd like the LLM to be able to call as a tool. The docstring should be in the same format as the example code above.\n3. Finally, add `mcp_server=True` in `.launch()`.\n\nThat's it!\n\n", "heading1": "Converting an Existing Space", "source_page_url": "https://gradio.app/guides/building-mcp-server-with-gradio", "source_page_title": "Mcp - Building Mcp Server With Gradio Guide"}, {"text": "You can use either a public Space or a private Space as an MCP server. If you'd like to use a private Space as an MCP server (or a ZeroGPU Space with your own quota), then you will need to provide your [Hugging Face token](https://huggingface.co/settings/token) when you make your request. To do this, simply add it as a header in your config like this:\n\n```\n{\n \"mcpServers\": {\n \"gradio\": {\n \"url\": \"https://abidlabs-mcp-tools.hf.space/gradio_api/mcp/\",\n \"headers\": {\n \"Authorization\": \"Bearer \"\n }\n }\n }\n}\n```\n\n", "heading1": "Private Spaces", "source_page_url": "https://gradio.app/guides/building-mcp-server-with-gradio", "source_page_title": "Mcp - Building Mcp Server With Gradio Guide"}, {"text": "You may wish to authenticate users more precisely or let them provide other kinds of credentials or tokens in order to provide a custom experience for different users. \n\nGradio allows you to access the underlying `starlette.Request` that has made the tool call, which means that you can access headers, originating IP address, or any other information that is part of the network request. To do this, simply add a parameter in your function of the type `gr.Request`, and Gradio will automatically inject the request object as the parameter.\n\nHere's an example:\n\n```py\nimport gradio as gr\n\ndef echo_headers(x, request: gr.Request):\n return str(dict(request.headers))\n\ngr.Interface(echo_headers, \"textbox\", \"textbox\").launch(mcp_server=True)\n```\n\nThis MCP server will simply ignore the user's input and echo back all of the headers from a user's request. One can build more complex apps using the same idea. See the [docs on `gr.Request`](https://www.gradio.app/main/docs/gradio/request) for more information (note that only the core Starlette attributes of the `gr.Request` object will be present, attributes such as Gradio's `.session_hash` will not be present).\n\nUsing the gr.Header class\n\nA common pattern in MCP server development is to use authentication headers to call services on behalf of your users. Instead of using a `gr.Request` object like in the example above, you can use a `gr.Header` argument. Gradio will automatically extract that header from the incoming request (if it exists) and pass it to your function.\n\nIn the example below, the `X-API-Token` header is extracted from the incoming request and passed in as the `x_api_token` argument to `make_api_request_on_behalf_of_user`.\n\nThe benefit of using `gr.Header` is that the MCP connection docs will automatically display the headers you need to supply when connecting to the server! See the image below:\n\n```python\nimport gradio as gr\n\ndef make_api_request_on_behalf_of_user(prompt: str, x_api_token: gr.Header):\n \"\"\"M", "heading1": "Authentication and Credentials", "source_page_url": "https://gradio.app/guides/building-mcp-server-with-gradio", "source_page_title": "Mcp - Building Mcp Server With Gradio Guide"}, {"text": "the headers you need to supply when connecting to the server! See the image below:\n\n```python\nimport gradio as gr\n\ndef make_api_request_on_behalf_of_user(prompt: str, x_api_token: gr.Header):\n \"\"\"Make a request to everyone's favorite API.\n Args:\n prompt: The prompt to send to the API.\n Returns:\n The response from the API.\n Raises:\n AssertionError: If the API token is not valid.\n \"\"\"\n return \"Hello from the API\" if not x_api_token else \"Hello from the API with token!\"\n\n\ndemo = gr.Interface(\n make_api_request_on_behalf_of_user,\n [\n gr.Textbox(label=\"Prompt\"),\n ],\n gr.Textbox(label=\"Response\"),\n)\n\ndemo.launch(mcp_server=True)\n```\n\n![MCP Header Connection Page](https://github.com/user-attachments/assets/e264eedf-a91a-476b-880d-5be0d5934134)\n\nSending Progress Updates\n\nThe Gradio MCP server automatically sends progress updates to your MCP Client based on the queue in the Gradio application. If you'd like to send custom progress updates, you can do so using the same mechanism as you would use to display progress updates in the UI of your Gradio app: by using the `gr.Progress` class!\n\nHere's an example of how to do this:\n\n$code_mcp_progress\n\n[Here are the docs](https://www.gradio.app/docs/gradio/progress) for the `gr.Progress` class, which can also automatically track `tqdm` calls.\n\nNote: by default, progress notifications are enabled for all MCP tools, even if the corresponding Gradio functions do not include a `gr.Progress`. However, this can add some overhead to the MCP tool (typically ~500ms). To disable progress notification, you can set `queue=False` in your Gradio event handler to skip the overhead related to subscribing to the queue's progress updates.\n\n\n", "heading1": "Authentication and Credentials", "source_page_url": "https://gradio.app/guides/building-mcp-server-with-gradio", "source_page_title": "Mcp - Building Mcp Server With Gradio Guide"}, {"text": "Gradio automatically sets the tool name based on the name of your function, and the description from the docstring of your function. But you may want to change how the description appears to your LLM. You can do this by using the `api_description` parameter in `Interface`, `ChatInterface`, or any event listener. This parameter takes three different kinds of values:\n\n* `None` (default): the tool description is automatically created from the docstring of the function (or its parent's docstring if it does not have a docstring but inherits from a method that does.)\n* `False`: no tool description appears to the LLM.\n* `str`: an arbitrary string to use as the tool description.\n\nIn addition to modifying the tool descriptions, you can also toggle which tools appear to the LLM. You can do this by setting the `show_api` parameter, which is by default `True`. Setting it to `False` hides the endpoint from the API docs and from the MCP server. If you expose multiple tools, users of your app will also be able to toggle which tools they'd like to add to their MCP server by checking boxes in the \"view MCP or API\" panel.\n\nHere's an example that shows the `api_description` and `show_api` parameters in actions:\n\n$code_mcp_tools\n\n\n\n", "heading1": "Modifying Tool Descriptions", "source_page_url": "https://gradio.app/guides/building-mcp-server-with-gradio", "source_page_title": "Mcp - Building Mcp Server With Gradio Guide"}, {"text": "In addition to tools (which execute functions generally and are the default for any function exposed through the Gradio MCP integration), MCP supports two other important primitives: **resources** (for exposing data) and **prompts** (for defining reusable templates). Gradio provides decorators to easily create MCP servers with all three capabilities.\n\n\nCreating MCP Resources\n\nUse the `@gr.mcp.resource` decorator on any function to expose data through your Gradio app. Resources can be static (always available at a fixed URI) or templated (with parameters in the URI).\n\n$code_mcp_resources_and_prompts\n\nIn this example:\n- The `get_greeting` function is exposed as a resource with a URI template `greeting://{name}`\n- When an MCP client requests `greeting://Alice`, it receives \"Hello, Alice!\"\n- Resources can also return images and other types of files or binary data. In order to return non-text data, you should specify the `mime_type` parameter in `@gr.mcp.resource()` and return a Base64 string from your function.\n\nCreating MCP Prompts \n\nPrompts help standardize how users interact with your tools. They're especially useful for complex workflows that require specific formatting or multiple steps.\n\nThe `greet_user` function in the example above is decorated with `@gr.mcp.prompt()`, which:\n- Makes it available as a prompt template in MCP clients\n- Accepts parameters (`name` and `style`) to customize the output\n- Returns a structured prompt that guides the LLM's behavior\n\n\n", "heading1": "MCP Resources and Prompts", "source_page_url": "https://gradio.app/guides/building-mcp-server-with-gradio", "source_page_title": "Mcp - Building Mcp Server With Gradio Guide"}, {"text": "So far, all of our MCP tools, resources, or prompts have corresponded to event listeners in the UI. This works well for functions that directly update the UI, but may not work if you wish to expose a \"pure logic\" function that should return raw data (e.g. a JSON object) without directly causing a UI update.\n\nIn order to expose such an MCP tool, you can create a pure Gradio API endpoint using `gr.api` (see [full docs here](https://www.gradio.app/main/docs/gradio/api)). Here's an example of creating an MCP tool that slices a list:\n\n$code_mcp_tool_only\n\nNote that if you use this approach, your function signature must be fully typed, including the return value, as these signature are used to determine the typing information for the MCP tool.\n\n", "heading1": "Adding MCP-Only Functions", "source_page_url": "https://gradio.app/guides/building-mcp-server-with-gradio", "source_page_title": "Mcp - Building Mcp Server With Gradio Guide"}, {"text": "In some cases, you may decide not to use Gradio's built-in integration and instead manually create an FastMCP Server that calls a Gradio app. This approach is useful when you want to:\n\n- Store state / identify users between calls instead of treating every tool call completely independently\n- Start the Gradio app MCP server when a tool is called (if you are running multiple Gradio apps locally and want to save memory / GPU)\n\nThis is very doable thanks to the [Gradio Python Client](https://www.gradio.app/guides/getting-started-with-the-python-client) and the [MCP Python SDK](https://github.com/modelcontextprotocol/python-sdk)'s `FastMCP` class. Here's an example of creating a custom MCP server that connects to various Gradio apps hosted on [HuggingFace Spaces](https://huggingface.co/spaces) using the `stdio` protocol:\n\n```python\nfrom mcp.server.fastmcp import FastMCP\nfrom gradio_client import Client\nimport sys\nimport io\nimport json \n\nmcp = FastMCP(\"gradio-spaces\")\n\nclients = {}\n\ndef get_client(space_id: str) -> Client:\n \"\"\"Get or create a Gradio client for the specified space.\"\"\"\n if space_id not in clients:\n clients[space_id] = Client(space_id)\n return clients[space_id]\n\n\n@mcp.tool()\nasync def generate_image(prompt: str, space_id: str = \"ysharma/SanaSprint\") -> str:\n \"\"\"Generate an image using Flux.\n \n Args:\n prompt: Text prompt describing the image to generate\n space_id: HuggingFace Space ID to use \n \"\"\"\n client = get_client(space_id)\n result = client.predict(\n prompt=prompt,\n model_size=\"1.6B\",\n seed=0,\n randomize_seed=True,\n width=1024,\n height=1024,\n guidance_scale=4.5,\n num_inference_steps=2,\n api_name=\"/infer\"\n )\n return result\n\n\n@mcp.tool()\nasync def run_dia_tts(prompt: str, space_id: str = \"ysharma/Dia-1.6B\") -> str:\n \"\"\"Text-to-Speech Synthesis.\n \n Args:\n prompt: Text prompt describing the co", "heading1": "Gradio with FastMCP", "source_page_url": "https://gradio.app/guides/building-mcp-server-with-gradio", "source_page_title": "Mcp - Building Mcp Server With Gradio Guide"}, {"text": "return result\n\n\n@mcp.tool()\nasync def run_dia_tts(prompt: str, space_id: str = \"ysharma/Dia-1.6B\") -> str:\n \"\"\"Text-to-Speech Synthesis.\n \n Args:\n prompt: Text prompt describing the conversation between speakers S1, S2\n space_id: HuggingFace Space ID to use \n \"\"\"\n client = get_client(space_id)\n result = client.predict(\n text_input=f\"\"\"{prompt}\"\"\",\n audio_prompt_input=None, \n max_new_tokens=3072,\n cfg_scale=3,\n temperature=1.3,\n top_p=0.95,\n cfg_filter_top_k=30,\n speed_factor=0.94,\n api_name=\"/generate_audio\"\n )\n return result\n\n\nif __name__ == \"__main__\":\n import sys\n import io\n sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')\n \n mcp.run(transport='stdio')\n```\n\nThis server exposes two tools:\n1. `run_dia_tts` - Generates a conversation for the given transcript in the form of `[S1]first-sentence. [S2]second-sentence. [S1]...`\n2. `generate_image` - Generates images using a fast text-to-image model\n\nTo use this MCP Server with Claude Desktop (as MCP Client):\n\n1. Save the code to a file (e.g., `gradio_mcp_server.py`)\n2. Install the required dependencies: `pip install mcp gradio-client`\n3. Configure Claude Desktop to use your server by editing the configuration file at `~/Library/Application Support/Claude/claude_desktop_config.json` (macOS) or `%APPDATA%\\Claude\\claude_desktop_config.json` (Windows):\n\n```json\n{\n \"mcpServers\": {\n \"gradio-spaces\": {\n \"command\": \"python\",\n \"args\": [\n \"/absolute/path/to/gradio_mcp_server.py\"\n ]\n }\n }\n}\n```\n\n4. Restart Claude Desktop\n\nNow, when you ask Claude about generating an image or transcribing audio, it can use your Gradio-powered tools to accomplish these tasks.\n\n\n", "heading1": "Gradio with FastMCP", "source_page_url": "https://gradio.app/guides/building-mcp-server-with-gradio", "source_page_title": "Mcp - Building Mcp Server With Gradio Guide"}, {"text": "use your Gradio-powered tools to accomplish these tasks.\n\n\n", "heading1": "Gradio with FastMCP", "source_page_url": "https://gradio.app/guides/building-mcp-server-with-gradio", "source_page_title": "Mcp - Building Mcp Server With Gradio Guide"}, {"text": "The MCP protocol is still in its infancy and you might see issues connecting to an MCP Server that you've built. We generally recommend using the [MCP Inspector Tool](https://github.com/modelcontextprotocol/inspector) to try connecting and debugging your MCP Server.\n\nHere are some things that may help:\n\n**1. Ensure that you've provided type hints and valid docstrings for your functions**\n\nAs mentioned earlier, Gradio reads the docstrings for your functions and the type hints of input arguments to generate the description of the tool and parameters. A valid function and docstring looks like this (note the \"Args:\" block with indented parameter names underneath):\n\n```py\ndef image_orientation(image: Image.Image) -> str:\n \"\"\"\n Returns whether image is portrait or landscape.\n\n Args:\n image (Image.Image): The image to check.\n \"\"\"\n return \"Portrait\" if image.height > image.width else \"Landscape\"\n```\n\nNote: You can preview the schema that is created for your MCP server by visiting the `http://your-server:port/gradio_api/mcp/schema` URL.\n\n**2. Try accepting input arguments as `str`**\n\nSome MCP Clients do not recognize parameters that are numeric or other complex types, but all of the MCP Clients that we've tested accept `str` input parameters. When in doubt, change your input parameter to be a `str` and then cast to a specific type in the function, as in this example:\n\n```py\ndef prime_factors(n: str):\n \"\"\"\n Compute the prime factorization of a positive integer.\n\n Args:\n n (str): The integer to factorize. Must be greater than 1.\n \"\"\"\n n_int = int(n)\n if n_int <= 1:\n raise ValueError(\"Input must be an integer greater than 1.\")\n\n factors = []\n while n_int % 2 == 0:\n factors.append(2)\n n_int //= 2\n\n divisor = 3\n while divisor * divisor <= n_int:\n while n_int % divisor == 0:\n factors.append(divisor)\n n_int //= divisor\n divisor += 2\n\n if n_int > 1:\n factors.", "heading1": "Troubleshooting your MCP Servers", "source_page_url": "https://gradio.app/guides/building-mcp-server-with-gradio", "source_page_title": "Mcp - Building Mcp Server With Gradio Guide"}, {"text": "= 3\n while divisor * divisor <= n_int:\n while n_int % divisor == 0:\n factors.append(divisor)\n n_int //= divisor\n divisor += 2\n\n if n_int > 1:\n factors.append(n_int)\n\n return factors\n```\n\n**3. Ensure that your MCP Client Supports Streamable HTTP**\n\nSome MCP Clients do not yet support streamable HTTP-based MCP Servers. In those cases, you can use a tool such as [mcp-remote](https://github.com/geelen/mcp-remote). First install [Node.js](https://nodejs.org/en/download/). Then, add the following to your own MCP Client config:\n\n```\n{\n \"mcpServers\": {\n \"gradio\": {\n \"command\": \"npx\",\n \"args\": [\n \"mcp-remote\",\n \"http://your-server:port/gradio_api/mcp/\"\n ]\n }\n }\n}\n```\n\n**4. Restart your MCP Client and MCP Server**\n\nSome MCP Clients require you to restart them every time you update the MCP configuration. Other times, if the connection between the MCP Client and servers breaks, you might need to restart the MCP server. If all else fails, try restarting both your MCP Client and MCP Servers!\n\n", "heading1": "Troubleshooting your MCP Servers", "source_page_url": "https://gradio.app/guides/building-mcp-server-with-gradio", "source_page_title": "Mcp - Building Mcp Server With Gradio Guide"}, {"text": "As of version 5.36.0, Gradio now comes with a built-in MCP server that can upload files to a running Gradio application. In the `View API` page of the server, you should see the following code snippet if any of the tools require file inputs:\n\n\n\nThe command to start the MCP server takes two arguments:\n\n- The URL (or Hugging Face space id) of the gradio application to upload the files to. In this case, `http://127.0.0.1:7860`.\n- The local directory on your computer with which the server is allowed to upload files from (``). For security, please make this directory as narrow as possible to prevent unintended file uploads.\n\nAs stated in the image, you need to install [uv](https://docs.astral.sh/uv/getting-started/installation/) (a python package manager that can run python scripts) before connecting from your MCP client. \n\nIf you have gradio installed locally and you don't want to install uv, you can replace the `uvx` command with the path to gradio binary. It should look like this:\n\n```json\n\"upload-files\": {\n \"command\": \"\",\n \"args\": [\n \"upload-mcp\",\n \"http://localhost:7860/\",\n \"/Users/freddyboulton/Pictures\"\n ]\n}\n```\n\nAfter connecting to the upload server, your LLM agent will know when to upload files for you automatically!\n\n\n\n", "heading1": "Using the File Upload MCP Server", "source_page_url": "https://gradio.app/guides/file-upload-mcp", "source_page_title": "Mcp - File Upload Mcp Guide"}, {"text": "In this guide, we've covered how you can connect to the Upload File MCP Server so that your agent can upload files before using Gradio MCP servers. Remember to set the `` as small as possible to prevent unintended file uploads!\n\n", "heading1": "Conclusion", "source_page_url": "https://gradio.app/guides/file-upload-mcp", "source_page_title": "Mcp - File Upload Mcp Guide"}, {"text": "If you're using LLMs in your workflow, adding this server will augment them with just the right context on gradio - which makes your experience a lot faster and smoother. \n\n\n\nThe server is running on Spaces and was launched entirely using Gradio, you can see all the code [here](https://huggingface.co/spaces/gradio/docs-mcp). For more on building an mcp server with gradio, see the [previous guide](./building-an-mcp-client-with-gradio). \n\n", "heading1": "Why an MCP Server?", "source_page_url": "https://gradio.app/guides/using-docs-mcp", "source_page_title": "Mcp - Using Docs Mcp Guide"}, {"text": "For clients that support streamable HTTP (e.g. Cursor, Windsurf, Cline), simply add the following configuration to your MCP config:\n\n```json\n{\n \"mcpServers\": {\n \"gradio\": {\n \"url\": \"https://gradio-docs-mcp.hf.space/gradio_api/mcp/\"\n }\n }\n}\n```\n\nWe've included step-by-step instructions for Cursor below, but you can consult the docs for Windsurf [here](https://docs.windsurf.com/windsurf/mcp), and Cline [here](https://docs.cline.bot/mcp-servers/configuring-mcp-servers) which are similar to set up. \n\n\n\nCursor \n\n1. Make sure you're using the latest version of Cursor, and go to Cursor > Settings > Cursor Settings > MCP \n2. Click on '+ Add new global MCP server' \n3. Copy paste this json into the file that opens and then save it. \n```json\n{\n \"mcpServers\": {\n \"gradio\": {\n \"url\": \"https://gradio-docs-mcp.hf.space/gradio_api/mcp/\"\n }\n }\n}\n```\n4. That's it! You should see the tools load and the status go green in the settings page. You may have to click the refresh icon or wait a few seconds. \n\n![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio-guides/cursor-mcp.png)\n\nClaude Desktop\n\n1. Since Claude Desktop only supports stdio, you will need to [install Node.js](https://nodejs.org/en/download/) to get this to work. \n2. Make sure you're using the latest version of Claude Desktop, and go to Claude > Settings > Developer > Edit Config \n3. Open the file with your favorite editor and copy paste this json, then save the file. \n```json\n{\n \"mcpServers\": {\n \"gradio\": {\n \"command\": \"npx\",\n \"args\": [\n \"mcp-remote\",\n \"https://gradio-docs-mcp.hf.space/gradio_api/mcp/\"\n ]\n }\n }\n}\n```\n4. Quit and re-open Claude Desktop, and you should be good to go. You should see it loaded in the Search and Tools icon or on the developer settings page. \n \n![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio-guides/claude-desktop-mcp.gif)\n\n", "heading1": "Installing in the Clients", "source_page_url": "https://gradio.app/guides/using-docs-mcp", "source_page_title": "Mcp - Using Docs Mcp Guide"}, {"text": "There are currently only two tools in the server: `gradio_docs_mcp_load_gradio_docs` and `gradio_docs_mcp_search_gradio_docs`. \n\n1. `gradio_docs_mcp_load_gradio_docs`: This tool takes no arguments and will load an /llms.txt style summary of Gradio's latest, full documentation. Very useful context the LLM can parse before answering questions or generating code. \n\n2. `gradio_docs_mcp_search_gradio_docs`: This tool takes a query as an argument and will run embedding search on Gradio's docs, guides, and demos to return the most useful context for the LLM to parse.", "heading1": "Tools", "source_page_url": "https://gradio.app/guides/using-docs-mcp", "source_page_title": "Mcp - Using Docs Mcp Guide"}, {"text": "The Model Context Protocol (MCP) standardizes how applications provide context to LLMs. It allows Claude to interact with external tools, like image generators, file systems, or APIs, etc.\n\n", "heading1": "What is MCP?", "source_page_url": "https://gradio.app/guides/building-an-mcp-client-with-gradio", "source_page_title": "Mcp - Building An Mcp Client With Gradio Guide"}, {"text": "- Python 3.10+\n- An Anthropic API key\n- Basic understanding of Python programming\n\n", "heading1": "Prerequisites", "source_page_url": "https://gradio.app/guides/building-an-mcp-client-with-gradio", "source_page_title": "Mcp - Building An Mcp Client With Gradio Guide"}, {"text": "First, install the required packages:\n\n```bash\npip install gradio anthropic mcp\n```\n\nCreate a `.env` file in your project directory and add your Anthropic API key:\n\n```\nANTHROPIC_API_KEY=your_api_key_here\n```\n\n", "heading1": "Setup", "source_page_url": "https://gradio.app/guides/building-an-mcp-client-with-gradio", "source_page_title": "Mcp - Building An Mcp Client With Gradio Guide"}, {"text": "The server provides tools that Claude can use. In this example, we'll create a server that generates images through [a HuggingFace space](https://huggingface.co/spaces/ysharma/SanaSprint).\n\nCreate a file named `gradio_mcp_server.py`:\n\n```python\nfrom mcp.server.fastmcp import FastMCP\nimport json\nimport sys\nimport io\nimport time\nfrom gradio_client import Client\n\nsys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')\nsys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8', errors='replace')\n\nmcp = FastMCP(\"huggingface_spaces_image_display\")\n\n@mcp.tool()\nasync def generate_image(prompt: str, width: int = 512, height: int = 512) -> str:\n \"\"\"Generate an image using SanaSprint model.\n \n Args:\n prompt: Text prompt describing the image to generate\n width: Image width (default: 512)\n height: Image height (default: 512)\n \"\"\"\n client = Client(\"https://ysharma-sanasprint.hf.space/\")\n \n try:\n result = client.predict(\n prompt,\n \"0.6B\",\n 0,\n True,\n width,\n height,\n 4.0,\n 2,\n api_name=\"/infer\"\n )\n \n if isinstance(result, list) and len(result) >= 1:\n image_data = result[0]\n if isinstance(image_data, dict) and \"url\" in image_data:\n return json.dumps({\n \"type\": \"image\",\n \"url\": image_data[\"url\"],\n \"message\": f\"Generated image for prompt: {prompt}\"\n })\n \n return json.dumps({\n \"type\": \"error\",\n \"message\": \"Failed to generate image\"\n })\n \n except Exception as e:\n return json.dumps({\n \"type\": \"error\",\n \"message\": f\"Error generating image: {str(e)}\"\n })\n\nif __name__ == \"__main__\":\n mcp.run(transport='stdio')\n```\n\nWhat this server does:\n\n1. It creates an MCP server that exposes a `gene", "heading1": "Part 1: Building the MCP Server", "source_page_url": "https://gradio.app/guides/building-an-mcp-client-with-gradio", "source_page_title": "Mcp - Building An Mcp Client With Gradio Guide"}, {"text": " \"message\": f\"Error generating image: {str(e)}\"\n })\n\nif __name__ == \"__main__\":\n mcp.run(transport='stdio')\n```\n\nWhat this server does:\n\n1. It creates an MCP server that exposes a `generate_image` tool\n2. The tool connects to the SanaSprint model hosted on HuggingFace Spaces\n3. It handles the asynchronous nature of image generation by polling for results\n4. When an image is ready, it returns the URL in a structured JSON format\n\n", "heading1": "Part 1: Building the MCP Server", "source_page_url": "https://gradio.app/guides/building-an-mcp-client-with-gradio", "source_page_title": "Mcp - Building An Mcp Client With Gradio Guide"}, {"text": "Now let's create a Gradio chat interface as MCP Client that connects Claude to our MCP server.\n\nCreate a file named `app.py`:\n\n```python\nimport asyncio\nimport os\nimport json\nfrom typing import List, Dict, Any, Union\nfrom contextlib import AsyncExitStack\n\nimport gradio as gr\nfrom gradio.components.chatbot import ChatMessage\nfrom mcp import ClientSession, StdioServerParameters\nfrom mcp.client.stdio import stdio_client\nfrom anthropic import Anthropic\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\nloop = asyncio.new_event_loop()\nasyncio.set_event_loop(loop)\n\nclass MCPClientWrapper:\n def __init__(self):\n self.session = None\n self.exit_stack = None\n self.anthropic = Anthropic()\n self.tools = []\n \n def connect(self, server_path: str) -> str:\n return loop.run_until_complete(self._connect(server_path))\n \n async def _connect(self, server_path: str) -> str:\n if self.exit_stack:\n await self.exit_stack.aclose()\n \n self.exit_stack = AsyncExitStack()\n \n is_python = server_path.endswith('.py')\n command = \"python\" if is_python else \"node\"\n \n server_params = StdioServerParameters(\n command=command,\n args=[server_path],\n env={\"PYTHONIOENCODING\": \"utf-8\", \"PYTHONUNBUFFERED\": \"1\"}\n )\n \n stdio_transport = await self.exit_stack.enter_async_context(stdio_client(server_params))\n self.stdio, self.write = stdio_transport\n \n self.session = await self.exit_stack.enter_async_context(ClientSession(self.stdio, self.write))\n await self.session.initialize()\n \n response = await self.session.list_tools()\n self.tools = [{ \n \"name\": tool.name,\n \"description\": tool.description,\n \"input_schema\": tool.inputSchema\n } for tool in response.tools]\n \n tool_names = [tool[\"name\"] for tool in self.tools]\n return f\"Connected to MCP server.", "heading1": "Part 2: Building the MCP Client with Gradio", "source_page_url": "https://gradio.app/guides/building-an-mcp-client-with-gradio", "source_page_title": "Mcp - Building An Mcp Client With Gradio Guide"}, {"text": "iption,\n \"input_schema\": tool.inputSchema\n } for tool in response.tools]\n \n tool_names = [tool[\"name\"] for tool in self.tools]\n return f\"Connected to MCP server. Available tools: {', '.join(tool_names)}\"\n \n def process_message(self, message: str, history: List[Union[Dict[str, Any], ChatMessage]]) -> tuple:\n if not self.session:\n return history + [\n {\"role\": \"user\", \"content\": message}, \n {\"role\": \"assistant\", \"content\": \"Please connect to an MCP server first.\"}\n ], gr.Textbox(value=\"\")\n \n new_messages = loop.run_until_complete(self._process_query(message, history))\n return history + [{\"role\": \"user\", \"content\": message}] + new_messages, gr.Textbox(value=\"\")\n \n async def _process_query(self, message: str, history: List[Union[Dict[str, Any], ChatMessage]]):\n claude_messages = []\n for msg in history:\n if isinstance(msg, ChatMessage):\n role, content = msg.role, msg.content\n else:\n role, content = msg.get(\"role\"), msg.get(\"content\")\n \n if role in [\"user\", \"assistant\", \"system\"]:\n claude_messages.append({\"role\": role, \"content\": content})\n \n claude_messages.append({\"role\": \"user\", \"content\": message})\n \n response = self.anthropic.messages.create(\n model=\"claude-3-5-sonnet-20241022\",\n max_tokens=1000,\n messages=claude_messages,\n tools=self.tools\n )\n\n result_messages = []\n \n for content in response.content:\n if content.type == 'text':\n result_messages.append({\n \"role\": \"assistant\", \n \"content\": content.text\n })\n \n elif content.type == 'tool_use':\n tool_name = content.name\n tool_args = content.input\n ", "heading1": "Part 2: Building the MCP Client with Gradio", "source_page_url": "https://gradio.app/guides/building-an-mcp-client-with-gradio", "source_page_title": "Mcp - Building An Mcp Client With Gradio Guide"}, {"text": "ntent\": content.text\n })\n \n elif content.type == 'tool_use':\n tool_name = content.name\n tool_args = content.input\n \n result_messages.append({\n \"role\": \"assistant\",\n \"content\": f\"I'll use the {tool_name} tool to help answer your question.\",\n \"metadata\": {\n \"title\": f\"Using tool: {tool_name}\",\n \"log\": f\"Parameters: {json.dumps(tool_args, ensure_ascii=True)}\",\n \"status\": \"pending\",\n \"id\": f\"tool_call_{tool_name}\"\n }\n })\n \n result_messages.append({\n \"role\": \"assistant\",\n \"content\": \"```json\\n\" + json.dumps(tool_args, indent=2, ensure_ascii=True) + \"\\n```\",\n \"metadata\": {\n \"parent_id\": f\"tool_call_{tool_name}\",\n \"id\": f\"params_{tool_name}\",\n \"title\": \"Tool Parameters\"\n }\n })\n \n result = await self.session.call_tool(tool_name, tool_args)\n \n if result_messages and \"metadata\" in result_messages[-2]:\n result_messages[-2][\"metadata\"][\"status\"] = \"done\"\n \n result_messages.append({\n \"role\": \"assistant\",\n \"content\": \"Here are the results from the tool:\",\n \"metadata\": {\n \"title\": f\"Tool Result for {tool_name}\",\n \"status\": \"done\",\n \"id\": f\"result_{tool_name}\"\n }\n })\n \n result_content = result.content\n if isinstance(result_content, list):\n result_content = \"\\n\".join(str(item) for item in re", "heading1": "Part 2: Building the MCP Client with Gradio", "source_page_url": "https://gradio.app/guides/building-an-mcp-client-with-gradio", "source_page_title": "Mcp - Building An Mcp Client With Gradio Guide"}, {"text": " })\n \n result_content = result.content\n if isinstance(result_content, list):\n result_content = \"\\n\".join(str(item) for item in result_content)\n \n try:\n result_json = json.loads(result_content)\n if isinstance(result_json, dict) and \"type\" in result_json:\n if result_json[\"type\"] == \"image\" and \"url\" in result_json:\n result_messages.append({\n \"role\": \"assistant\",\n \"content\": {\"path\": result_json[\"url\"], \"alt_text\": result_json.get(\"message\", \"Generated image\")},\n \"metadata\": {\n \"parent_id\": f\"result_{tool_name}\",\n \"id\": f\"image_{tool_name}\",\n \"title\": \"Generated Image\"\n }\n })\n else:\n result_messages.append({\n \"role\": \"assistant\",\n \"content\": \"```\\n\" + result_content + \"\\n```\",\n \"metadata\": {\n \"parent_id\": f\"result_{tool_name}\",\n \"id\": f\"raw_result_{tool_name}\",\n \"title\": \"Raw Output\"\n }\n })\n except:\n result_messages.append({\n \"role\": \"assistant\",\n \"content\": \"```\\n\" + result_content + \"\\n```\",\n \"metadata\": {\n \"parent_id\": f\"result_{tool_name}\",\n \"id\": f\"raw_result_{tool_name}\",\n \"title\": \"Raw Output\"\n }\n })\n ", "heading1": "Part 2: Building the MCP Client with Gradio", "source_page_url": "https://gradio.app/guides/building-an-mcp-client-with-gradio", "source_page_title": "Mcp - Building An Mcp Client With Gradio Guide"}, {"text": " \"parent_id\": f\"result_{tool_name}\",\n \"id\": f\"raw_result_{tool_name}\",\n \"title\": \"Raw Output\"\n }\n })\n \n claude_messages.append({\"role\": \"user\", \"content\": f\"Tool result for {tool_name}: {result_content}\"})\n next_response = self.anthropic.messages.create(\n model=\"claude-3-5-sonnet-20241022\",\n max_tokens=1000,\n messages=claude_messages,\n )\n \n if next_response.content and next_response.content[0].type == 'text':\n result_messages.append({\n \"role\": \"assistant\",\n \"content\": next_response.content[0].text\n })\n\n return result_messages\n\nclient = MCPClientWrapper()\n\ndef gradio_interface():\n with gr.Blocks(title=\"MCP Weather Client\") as demo:\n gr.Markdown(\"MCP Weather Assistant\")\n gr.Markdown(\"Connect to your MCP weather server and chat with the assistant\")\n \n with gr.Row(equal_height=True):\n with gr.Column(scale=4):\n server_path = gr.Textbox(\n label=\"Server Script Path\",\n placeholder=\"Enter path to server script (e.g., weather.py)\",\n value=\"gradio_mcp_server.py\"\n )\n with gr.Column(scale=1):\n connect_btn = gr.Button(\"Connect\")\n \n status = gr.Textbox(label=\"Connection Status\", interactive=False)\n \n chatbot = gr.Chatbot(\n value=[], \n height=500,\n show_copy_button=True,\n avatar_images=(\"\ud83d\udc64\", \"\ud83e\udd16\")\n )\n \n with gr.Row(equal_height=True):\n msg = gr.Textbox(\n label=\"Your Question\",\n placeholder=\"Ask about weather or alerts (e.g., What's the weather in New York?)\",\n ", "heading1": "Part 2: Building the MCP Client with Gradio", "source_page_url": "https://gradio.app/guides/building-an-mcp-client-with-gradio", "source_page_title": "Mcp - Building An Mcp Client With Gradio Guide"}, {"text": "w(equal_height=True):\n msg = gr.Textbox(\n label=\"Your Question\",\n placeholder=\"Ask about weather or alerts (e.g., What's the weather in New York?)\",\n scale=4\n )\n clear_btn = gr.Button(\"Clear Chat\", scale=1)\n \n connect_btn.click(client.connect, inputs=server_path, outputs=status)\n msg.submit(client.process_message, [msg, chatbot], [chatbot, msg])\n clear_btn.click(lambda: [], None, chatbot)\n \n return demo\n\nif __name__ == \"__main__\":\n if not os.getenv(\"ANTHROPIC_API_KEY\"):\n print(\"Warning: ANTHROPIC_API_KEY not found in environment. Please set it in your .env file.\")\n \n interface = gradio_interface()\n interface.launch(debug=True)\n```\n\nWhat this MCP Client does:\n\n- Creates a friendly Gradio chat interface for user interaction\n- Connects to the MCP server you specify\n- Handles conversation history and message formatting\n- Makes call to Claude API with tool definitions\n- Processes tool usage requests from Claude\n- Displays images and other tool outputs in the chat\n- Sends tool results back to Claude for interpretation\n\n", "heading1": "Part 2: Building the MCP Client with Gradio", "source_page_url": "https://gradio.app/guides/building-an-mcp-client-with-gradio", "source_page_title": "Mcp - Building An Mcp Client With Gradio Guide"}, {"text": "To run your MCP application:\n\n- Start a terminal window and run the MCP Client:\n ```bash\n python app.py\n ```\n- Open the Gradio interface at the URL shown (typically http://127.0.0.1:7860)\n- In the Gradio interface, you'll see a field for the MCP Server path. It should default to `gradio_mcp_server.py`.\n- Click \"Connect\" to establish the connection to the MCP server.\n- You should see a message indicating the server connection was successful.\n\n", "heading1": "Running the Application", "source_page_url": "https://gradio.app/guides/building-an-mcp-client-with-gradio", "source_page_title": "Mcp - Building An Mcp Client With Gradio Guide"}, {"text": "Now you can chat with Claude and it will be able to generate images based on your descriptions.\n\nTry prompts like:\n- \"Can you generate an image of a mountain landscape at sunset?\"\n- \"Create an image of a cool tabby cat\"\n- \"Generate a picture of a panda wearing sunglasses\"\n\nClaude will recognize these as image generation requests and automatically use the `generate_image` tool from your MCP server.\n\n\n", "heading1": "Example Usage", "source_page_url": "https://gradio.app/guides/building-an-mcp-client-with-gradio", "source_page_title": "Mcp - Building An Mcp Client With Gradio Guide"}, {"text": "Here's the high-level flow of what happens during a chat session:\n\n1. Your prompt enters the Gradio interface\n2. The client forwards your prompt to Claude\n3. Claude analyzes the prompt and decides to use the `generate_image` tool\n4. The client sends the tool call to the MCP server\n5. The server calls the external image generation API\n6. The image URL is returned to the client\n7. The client sends the image URL back to Claude\n8. Claude provides a response that references the generated image\n9. The Gradio chat interface displays both Claude's response and the image\n\n\n", "heading1": "How it Works", "source_page_url": "https://gradio.app/guides/building-an-mcp-client-with-gradio", "source_page_title": "Mcp - Building An Mcp Client With Gradio Guide"}, {"text": "Now that you have a working MCP system, here are some ideas to extend it:\n\n- Add more tools to your server\n- Improve error handling \n- Add private Huggingface Spaces with authentication for secure tool access\n- Create custom tools that connect to your own APIs or services\n- Implement streaming responses for better user experience\n\n", "heading1": "Next Steps", "source_page_url": "https://gradio.app/guides/building-an-mcp-client-with-gradio", "source_page_title": "Mcp - Building An Mcp Client With Gradio Guide"}, {"text": "Congratulations! You've successfully built an MCP Client and Server that allows Claude to generate images based on text prompts. This is just the beginning of what you can do with Gradio and MCP. This guide enables you to build complex AI applications that can use Claude or any other powerful LLM to interact with virtually any external tool or service.\n\nRead our other Guide on using [Gradio apps as MCP Servers](./building-mcp-server-with-gradio).\n", "heading1": "Conclusion", "source_page_url": "https://gradio.app/guides/building-an-mcp-client-with-gradio", "source_page_title": "Mcp - Building An Mcp Client With Gradio Guide"}, {"text": "Install the @gradio/client package to interact with Gradio APIs using Node.js version >=18.0.0 or in browser-based projects. Use npm or any compatible package manager:\n\n```bash\nnpm i @gradio/client\n```\n\nThis command adds @gradio/client to your project dependencies, allowing you to import it in your JavaScript or TypeScript files.\n\n", "heading1": "Installation via npm", "source_page_url": "https://gradio.app/guides/getting-started-with-the-js-client", "source_page_title": "Gradio Clients And Lite - Getting Started With The Js Client Guide"}, {"text": "For quick addition to your web project, you can use the jsDelivr CDN to load the latest version of @gradio/client directly into your HTML:\n\n```html\n\n```\n\nBe sure to add this to the `` of your HTML. This will install the latest version but we advise hardcoding the version in production. You can find all available versions [here](https://www.jsdelivr.com/package/npm/@gradio/client). This approach is ideal for experimental or prototying purposes, though has some limitations. A complete example would look like this:\n\n```html\n\n\n\n \n\n\n```\n\n", "heading1": "Installation via CDN", "source_page_url": "https://gradio.app/guides/getting-started-with-the-js-client", "source_page_title": "Gradio Clients And Lite - Getting Started With The Js Client Guide"}, {"text": "Start by connecting instantiating a `client` instance and connecting it to a Gradio app that is running on Hugging Face Spaces or generally anywhere on the web.\n\n", "heading1": "Connecting to a running Gradio App", "source_page_url": "https://gradio.app/guides/getting-started-with-the-js-client", "source_page_title": "Gradio Clients And Lite - Getting Started With The Js Client Guide"}, {"text": "```js\nimport { Client } from \"@gradio/client\";\n\nconst app = await Client.connect(\"abidlabs/en2fr\"); // a Space that translates from English to French\n```\n\nYou can also connect to private Spaces by passing in your HF token with the `token` property of the options parameter. You can get your HF token here: https://huggingface.co/settings/tokens\n\n```js\nimport { Client } from \"@gradio/client\";\n\nconst app = await Client.connect(\"abidlabs/my-private-space\", { token: \"hf_...\" })\n```\n\n", "heading1": "Connecting to a Hugging Face Space", "source_page_url": "https://gradio.app/guides/getting-started-with-the-js-client", "source_page_title": "Gradio Clients And Lite - Getting Started With The Js Client Guide"}, {"text": "While you can use any public Space as an API, you may get rate limited by Hugging Face if you make too many requests. For unlimited usage of a Space, simply duplicate the Space to create a private Space, and then use it to make as many requests as you'd like! You'll need to pass in your [Hugging Face token](https://huggingface.co/settings/tokens)).\n\n`Client.duplicate` is almost identical to `Client.connect`, the only difference is under the hood:\n\n```js\nimport { Client, handle_file } from \"@gradio/client\";\n\nconst response = await fetch(\n\t\"https://audio-samples.github.io/samples/mp3/blizzard_unconditional/sample-0.mp3\"\n);\nconst audio_file = await response.blob();\n\nconst app = await Client.duplicate(\"abidlabs/whisper\", { token: \"hf_...\" });\nconst transcription = await app.predict(\"/predict\", [handle_file(audio_file)]);\n```\n\nIf you have previously duplicated a Space, re-running `Client.duplicate` will _not_ create a new Space. Instead, the client will attach to the previously-created Space. So it is safe to re-run the `Client.duplicate` method multiple times with the same space.\n\n**Note:** if the original Space uses GPUs, your private Space will as well, and your Hugging Face account will get billed based on the price of the GPU. To minimize charges, your Space will automatically go to sleep after 5 minutes of inactivity. You can also set the hardware using the `hardware` and `timeout` properties of `duplicate`'s options object like this:\n\n```js\nimport { Client } from \"@gradio/client\";\n\nconst app = await Client.duplicate(\"abidlabs/whisper\", {\n\ttoken: \"hf_...\",\n\ttimeout: 60,\n\thardware: \"a10g-small\"\n});\n```\n\n", "heading1": "Duplicating a Space for private use", "source_page_url": "https://gradio.app/guides/getting-started-with-the-js-client", "source_page_title": "Gradio Clients And Lite - Getting Started With The Js Client Guide"}, {"text": "If your app is running somewhere else, just provide the full URL instead, including the \"http://\" or \"https://\". Here's an example of making predictions to a Gradio app that is running on a share URL:\n\n```js\nimport { Client } from \"@gradio/client\";\n\nconst app = Client.connect(\"https://bec81a83-5b5c-471e.gradio.live\");\n```\n\n", "heading1": "Connecting a general Gradio app", "source_page_url": "https://gradio.app/guides/getting-started-with-the-js-client", "source_page_title": "Gradio Clients And Lite - Getting Started With The Js Client Guide"}, {"text": "If the Gradio application you are connecting to [requires a username and password](/guides/sharing-your-appauthentication), then provide them as a tuple to the `auth` argument of the `Client` class:\n\n```js\nimport { Client } from \"@gradio/client\";\n\nClient.connect(\n space_name,\n { auth: [username, password] }\n)\n```\n\n\n", "heading1": "Connecting to a Gradio app with auth", "source_page_url": "https://gradio.app/guides/getting-started-with-the-js-client", "source_page_title": "Gradio Clients And Lite - Getting Started With The Js Client Guide"}, {"text": "Once you have connected to a Gradio app, you can view the APIs that are available to you by calling the `Client`'s `view_api` method.\n\nFor the Whisper Space, we can do this:\n\n```js\nimport { Client } from \"@gradio/client\";\n\nconst app = await Client.connect(\"abidlabs/whisper\");\n\nconst app_info = await app.view_api();\n\nconsole.log(app_info);\n```\n\nAnd we will see the following:\n\n```json\n{\n\t\"named_endpoints\": {\n\t\t\"/predict\": {\n\t\t\t\"parameters\": [\n\t\t\t\t{\n\t\t\t\t\t\"label\": \"text\",\n\t\t\t\t\t\"component\": \"Textbox\",\n\t\t\t\t\t\"type\": \"string\"\n\t\t\t\t}\n\t\t\t],\n\t\t\t\"returns\": [\n\t\t\t\t{\n\t\t\t\t\t\"label\": \"output\",\n\t\t\t\t\t\"component\": \"Textbox\",\n\t\t\t\t\t\"type\": \"string\"\n\t\t\t\t}\n\t\t\t]\n\t\t}\n\t},\n\t\"unnamed_endpoints\": {}\n}\n```\n\nThis shows us that we have 1 API endpoint in this space, and shows us how to use the API endpoint to make a prediction: we should call the `.predict()` method (which we will explore below), providing a parameter `input_audio` of type `string`, which is a url to a file.\n\nWe should also provide the `api_name='/predict'` argument to the `predict()` method. Although this isn't necessary if a Gradio app has only 1 named endpoint, it does allow us to call different endpoints in a single app if they are available. If an app has unnamed API endpoints, these can also be displayed by running `.view_api(all_endpoints=True)`.\n\n", "heading1": "Inspecting the API endpoints", "source_page_url": "https://gradio.app/guides/getting-started-with-the-js-client", "source_page_title": "Gradio Clients And Lite - Getting Started With The Js Client Guide"}, {"text": "As an alternative to running the `.view_api()` method, you can click on the \"Use via API\" link in the footer of the Gradio app, which shows us the same information, along with example usage. \n\n![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio-guides/view-api.png)\n\nThe View API page also includes an \"API Recorder\" that lets you interact with the Gradio UI normally and converts your interactions into the corresponding code to run with the JS Client.\n\n\n", "heading1": "The \"View API\" Page", "source_page_url": "https://gradio.app/guides/getting-started-with-the-js-client", "source_page_title": "Gradio Clients And Lite - Getting Started With The Js Client Guide"}, {"text": "The simplest way to make a prediction is simply to call the `.predict()` method with the appropriate arguments:\n\n```js\nimport { Client } from \"@gradio/client\";\n\nconst app = await Client.connect(\"abidlabs/en2fr\");\nconst result = await app.predict(\"/predict\", [\"Hello\"]);\n```\n\nIf there are multiple parameters, then you should pass them as an array to `.predict()`, like this:\n\n```js\nimport { Client } from \"@gradio/client\";\n\nconst app = await Client.connect(\"gradio/calculator\");\nconst result = await app.predict(\"/predict\", [4, \"add\", 5]);\n```\n\nFor certain inputs, such as images, you should pass in a `Buffer`, `Blob` or `File` depending on what is most convenient. In node, this would be a `Buffer` or `Blob`; in a browser environment, this would be a `Blob` or `File`.\n\n```js\nimport { Client, handle_file } from \"@gradio/client\";\n\nconst response = await fetch(\n\t\"https://audio-samples.github.io/samples/mp3/blizzard_unconditional/sample-0.mp3\"\n);\nconst audio_file = await response.blob();\n\nconst app = await Client.connect(\"abidlabs/whisper\");\nconst result = await app.predict(\"/predict\", [handle_file(audio_file)]);\n```\n\n", "heading1": "Making a prediction", "source_page_url": "https://gradio.app/guides/getting-started-with-the-js-client", "source_page_title": "Gradio Clients And Lite - Getting Started With The Js Client Guide"}, {"text": "If the API you are working with can return results over time, or you wish to access information about the status of a job, you can use the iterable interface for more flexibility. This is especially useful for iterative endpoints or generator endpoints that will produce a series of values over time as discrete responses.\n\n```js\nimport { Client } from \"@gradio/client\";\n\nfunction log_result(payload) {\n\tconst {\n\t\tdata: [translation]\n\t} = payload;\n\n\tconsole.log(`The translated result is: ${translation}`);\n}\n\nconst app = await Client.connect(\"abidlabs/en2fr\");\nconst job = app.submit(\"/predict\", [\"Hello\"]);\n\nfor await (const message of job) {\n\tlog_result(message);\n}\n```\n\n", "heading1": "Using events", "source_page_url": "https://gradio.app/guides/getting-started-with-the-js-client", "source_page_title": "Gradio Clients And Lite - Getting Started With The Js Client Guide"}, {"text": "The event interface also allows you to get the status of the running job by instantiating the client with the `events` options passing `status` and `data` as an array:\n\n\n```ts\nimport { Client } from \"@gradio/client\";\n\nconst app = await Client.connect(\"abidlabs/en2fr\", {\n\tevents: [\"status\", \"data\"]\n});\n```\n\nThis ensures that status messages are also reported to the client.\n\n`status`es are returned as an object with the following attributes: `status` (a human readbale status of the current job, `\"pending\" | \"generating\" | \"complete\" | \"error\"`), `code` (the detailed gradio code for the job), `position` (the current position of this job in the queue), `queue_size` (the total queue size), `eta` (estimated time this job will complete), `success` (a boolean representing whether the job completed successfully), and `time` ( as `Date` object detailing the time that the status was generated).\n\n```js\nimport { Client } from \"@gradio/client\";\n\nfunction log_status(status) {\n\tconsole.log(\n\t\t`The current status for this job is: ${JSON.stringify(status, null, 2)}.`\n\t);\n}\n\nconst app = await Client.connect(\"abidlabs/en2fr\", {\n\tevents: [\"status\", \"data\"]\n});\nconst job = app.submit(\"/predict\", [\"Hello\"]);\n\nfor await (const message of job) {\n\tif (message.type === \"status\") {\n\t\tlog_status(message);\n\t}\n}\n```\n\n", "heading1": "Status", "source_page_url": "https://gradio.app/guides/getting-started-with-the-js-client", "source_page_title": "Gradio Clients And Lite - Getting Started With The Js Client Guide"}, {"text": "The job instance also has a `.cancel()` method that cancels jobs that have been queued but not started. For example, if you run:\n\n```js\nimport { Client } from \"@gradio/client\";\n\nconst app = await Client.connect(\"abidlabs/en2fr\");\nconst job_one = app.submit(\"/predict\", [\"Hello\"]);\nconst job_two = app.submit(\"/predict\", [\"Friends\"]);\n\njob_one.cancel();\njob_two.cancel();\n```\n\nIf the first job has started processing, then it will not be canceled but the client will no longer listen for updates (throwing away the job). If the second job has not yet started, it will be successfully canceled and removed from the queue.\n\n", "heading1": "Cancelling Jobs", "source_page_url": "https://gradio.app/guides/getting-started-with-the-js-client", "source_page_title": "Gradio Clients And Lite - Getting Started With The Js Client Guide"}, {"text": "Some Gradio API endpoints do not return a single value, rather they return a series of values. You can listen for these values in real time using the iterable interface:\n\n```js\nimport { Client } from \"@gradio/client\";\n\nconst app = await Client.connect(\"gradio/count_generator\");\nconst job = app.submit(0, [9]);\n\nfor await (const message of job) {\n\tconsole.log(message.data);\n}\n```\n\nThis will log out the values as they are generated by the endpoint.\n\nYou can also cancel jobs that that have iterative outputs, in which case the job will finish immediately.\n\n```js\nimport { Client } from \"@gradio/client\";\n\nconst app = await Client.connect(\"gradio/count_generator\");\nconst job = app.submit(0, [9]);\n\nfor await (const message of job) {\n\tconsole.log(message.data);\n}\n\nsetTimeout(() => {\n\tjob.cancel();\n}, 3000);\n```\n", "heading1": "Generator Endpoints", "source_page_url": "https://gradio.app/guides/getting-started-with-the-js-client", "source_page_title": "Gradio Clients And Lite - Getting Started With The Js Client Guide"}, {"text": "Let's start with what seems like the most complex bit -- using machine learning to remove the music from a video.\n\nLuckily for us, there's an existing Space we can use to make this process easier: [https://huggingface.co/spaces/abidlabs/music-separation](https://huggingface.co/spaces/abidlabs/music-separation). This Space takes an audio file and produces two separate audio files: one with the instrumental music and one with all other sounds in the original clip. Perfect to use with our client!\n\nOpen a new Python file, say `main.py`, and start by importing the `Client` class from `gradio_client` and connecting it to this Space:\n\n```py\nfrom gradio_client import Client, handle_file\n\nclient = Client(\"abidlabs/music-separation\")\n\ndef acapellify(audio_path):\n result = client.predict(handle_file(audio_path), api_name=\"/predict\")\n return result[0]\n```\n\nThat's all the code that's needed -- notice that the API endpoints returns two audio files (one without the music, and one with just the music) in a list, and so we just return the first element of the list.\n\n---\n\n**Note**: since this is a public Space, there might be other users using this Space as well, which might result in a slow experience. You can duplicate this Space with your own [Hugging Face token](https://huggingface.co/settings/tokens) and create a private Space that only you have will have access to and bypass the queue. To do that, simply replace the first two lines above with:\n\n```py\nfrom gradio_client import Client\n\nclient = Client.duplicate(\"abidlabs/music-separation\", token=YOUR_HF_TOKEN)\n```\n\nEverything else remains the same!\n\n---\n\nNow, of course, we are working with video files, so we first need to extract the audio from the video files. For this, we will be using the `ffmpeg` library, which does a lot of heavy lifting when it comes to working with audio and video files. The most common way to use `ffmpeg` is through the command line, which we'll call via Python's `subprocess` module:\n\nOur video proc", "heading1": "Step 1: Write the Video Processing Function", "source_page_url": "https://gradio.app/guides/fastapi-app-with-the-gradio-client", "source_page_title": "Gradio Clients And Lite - Fastapi App With The Gradio Client Guide"}, {"text": "f heavy lifting when it comes to working with audio and video files. The most common way to use `ffmpeg` is through the command line, which we'll call via Python's `subprocess` module:\n\nOur video processing workflow will consist of three steps:\n\n1. First, we start by taking in a video filepath and extracting the audio using `ffmpeg`.\n2. Then, we pass in the audio file through the `acapellify()` function above.\n3. Finally, we combine the new audio with the original video to produce a final acapellified video.\n\nHere's the complete code in Python, which you can add to your `main.py` file:\n\n```python\nimport subprocess\n\ndef process_video(video_path):\n old_audio = os.path.basename(video_path).split(\".\")[0] + \".m4a\"\n subprocess.run(['ffmpeg', '-y', '-i', video_path, '-vn', '-acodec', 'copy', old_audio])\n\n new_audio = acapellify(old_audio)\n\n new_video = f\"acap_{video_path}\"\n subprocess.call(['ffmpeg', '-y', '-i', video_path, '-i', new_audio, '-map', '0:v', '-map', '1:a', '-c:v', 'copy', '-c:a', 'aac', '-strict', 'experimental', f\"static/{new_video}\"])\n return new_video\n```\n\nYou can read up on [ffmpeg documentation](https://ffmpeg.org/ffmpeg.html) if you'd like to understand all of the command line parameters, as they are beyond the scope of this tutorial.\n\n", "heading1": "Step 1: Write the Video Processing Function", "source_page_url": "https://gradio.app/guides/fastapi-app-with-the-gradio-client", "source_page_title": "Gradio Clients And Lite - Fastapi App With The Gradio Client Guide"}, {"text": "Next up, we'll create a simple FastAPI app. If you haven't used FastAPI before, check out [the great FastAPI docs](https://fastapi.tiangolo.com/). Otherwise, this basic template, which we add to `main.py`, will look pretty familiar:\n\n```python\nimport os\nfrom fastapi import FastAPI, File, UploadFile, Request\nfrom fastapi.responses import HTMLResponse, RedirectResponse\nfrom fastapi.staticfiles import StaticFiles\nfrom fastapi.templating import Jinja2Templates\n\napp = FastAPI()\nos.makedirs(\"static\", exist_ok=True)\napp.mount(\"/static\", StaticFiles(directory=\"static\"), name=\"static\")\ntemplates = Jinja2Templates(directory=\"templates\")\n\nvideos = []\n\n@app.get(\"/\", response_class=HTMLResponse)\nasync def home(request: Request):\n return templates.TemplateResponse(\n \"home.html\", {\"request\": request, \"videos\": videos})\n\n@app.post(\"/uploadvideo/\")\nasync def upload_video(video: UploadFile = File(...)):\n video_path = video.filename\n with open(video_path, \"wb+\") as fp:\n fp.write(video.file.read())\n\n new_video = process_video(video.filename)\n videos.append(new_video)\n return RedirectResponse(url='/', status_code=303)\n```\n\nIn this example, the FastAPI app has two routes: `/` and `/uploadvideo/`.\n\nThe `/` route returns an HTML template that displays a gallery of all uploaded videos.\n\nThe `/uploadvideo/` route accepts a `POST` request with an `UploadFile` object, which represents the uploaded video file. The video file is \"acapellified\" via the `process_video()` method, and the output video is stored in a list which stores all of the uploaded videos in memory.\n\nNote that this is a very basic example and if this were a production app, you will need to add more logic to handle file storage, user authentication, and security considerations.\n\n", "heading1": "Step 2: Create a FastAPI app (Backend Routes)", "source_page_url": "https://gradio.app/guides/fastapi-app-with-the-gradio-client", "source_page_title": "Gradio Clients And Lite - Fastapi App With The Gradio Client Guide"}, {"text": "Finally, we create the frontend of our web application. First, we create a folder called `templates` in the same directory as `main.py`. We then create a template, `home.html` inside the `templates` folder. Here is the resulting file structure:\n\n```csv\n\u251c\u2500\u2500 main.py\n\u251c\u2500\u2500 templates\n\u2502 \u2514\u2500\u2500 home.html\n```\n\nWrite the following as the contents of `home.html`:\n\n```html\n<!DOCTYPE html> <html> <head> <title>Video Gallery</title>\n<style> body { font-family: sans-serif; margin: 0; padding: 0;\nbackground-color: f5f5f5; } h1 { text-align: center; margin-top: 30px;\nmargin-bottom: 20px; } .gallery { display: flex; flex-wrap: wrap;\njustify-content: center; gap: 20px; padding: 20px; } .video { border: 2px solid\nccc; box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.2); border-radius: 5px; overflow:\nhidden; width: 300px; margin-bottom: 20px; } .video video { width: 100%; height:\n200px; } .video p { text-align: center; margin: 10px 0; } form { margin-top:\n20px; text-align: center; } input[type=\"file\"] { display: none; } .upload-btn {\ndisplay: inline-block; background-color: 3498db; color: fff; padding: 10px\n20px; font-size: 16px; border: none; border-radius: 5px; cursor: pointer; }\n.upload-btn:hover { background-color: 2980b9; } .file-name { margin-left: 10px;\n} </style> </head> <body> <h1>Video Gallery</h1> {% if videos %}\n<div class=\"gallery\"> {% for video in videos %} <div class=\"video\">\n<video controls> <source src=\"{{ url_for('static', path=video) }}\"\ntype=\"video/mp4\"> Your browser does not support the video tag. </video>\n<p>{{ video }}</p> </div> {% endfor %} </div> {% else %} <p>No\nvideos uploaded yet.</p> {% endif %} <form action=\"/uploadvideo/\"\nmethod=\"post\" enctype=\"multipart/form-data\"> <label for=\"video-upload\"\nclass=\"upload-btn\">Choose video file</label> <input type=\"file\"\nname=\"video\" id=\"video-upload\"> <span class=\"file-name\"></span> <button\ntype=\"submit\" class=\"upload-btn\">Upload</butto", "heading1": "Step 3: Create a FastAPI app (Frontend Template)", "source_page_url": "https://gradio.app/guides/fastapi-app-with-the-gradio-client", "source_page_title": "Gradio Clients And Lite - Fastapi App With The Gradio Client Guide"}, {"text": "class=\"upload-btn\">Choose video file</label> <input type=\"file\"\nname=\"video\" id=\"video-upload\"> <span class=\"file-name\"></span> <button\ntype=\"submit\" class=\"upload-btn\">Upload</button> </form> <script> //\nDisplay selected file name in the form const fileUpload =\ndocument.getElementById(\"video-upload\"); const fileName =\ndocument.querySelector(\".file-name\"); fileUpload.addEventListener(\"change\", (e)\n=> { fileName.textContent = e.target.files[0].name; }); </script> </body>\n</html>\n```\n\n", "heading1": "Step 3: Create a FastAPI app (Frontend Template)", "source_page_url": "https://gradio.app/guides/fastapi-app-with-the-gradio-client", "source_page_title": "Gradio Clients And Lite - Fastapi App With The Gradio Client Guide"}, {"text": "Finally, we are ready to run our FastAPI app, powered by the Gradio Python Client!\n\nOpen up a terminal and navigate to the directory containing `main.py`. Then run the following command in the terminal:\n\n```bash\n$ uvicorn main:app\n```\n\nYou should see an output that looks like this:\n\n```csv\nLoaded as API: https://abidlabs-music-separation.hf.space \u2714\nINFO: Started server process [1360]\nINFO: Waiting for application startup.\nINFO: Application startup complete.\nINFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)\n```\n\nAnd that's it! Start uploading videos and you'll get some \"acapellified\" videos in response (might take seconds to minutes to process depending on the length of your videos). Here's how the UI looks after uploading two videos:\n\n![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio-guides/acapellify.png)\n\nIf you'd like to learn more about how to use the Gradio Python Client in your projects, [read the dedicated Guide](/guides/getting-started-with-the-python-client/).\n", "heading1": "Step 4: Run your FastAPI app", "source_page_url": "https://gradio.app/guides/fastapi-app-with-the-gradio-client", "source_page_title": "Gradio Clients And Lite - Fastapi App With The Gradio Client Guide"}, {"text": "Use `gradio.Server` instead of `gr.Blocks` when any of the following apply:\n\n- You want a **completely custom (potentially vibe-coded) UI** (your own HTML, React, Svelte, etc.) powered by Gradio's backend\n- You want **full FastAPI control** (custom GET/POST routes, middleware, dependency injection) alongside Gradio API endpoints\n- You're building a service to **host on Spaces** with or without ZeroGPU but don't need Gradio components\n\nIf you're happy with Gradio's built-in UI components, use `gr.Blocks`, `gr.ChatInterface`, or `gr.Interface` instead.\n\n", "heading1": "When to use `gradio.Server`", "source_page_url": "https://gradio.app/guides/server-mode", "source_page_title": "Gradio Clients And Lite - Server Mode Guide"}, {"text": "`gradio.Server` is included in the main Gradio package. If you want MCP support, install the extra:\n\n```bash\npip install \"gradio[mcp]\"\n```\n\n", "heading1": "Installation", "source_page_url": "https://gradio.app/guides/server-mode", "source_page_title": "Gradio Clients And Lite - Server Mode Guide"}, {"text": "Here's the simplest possible Server mode app \u2014 a single API endpoint with no UI:\n\n```python\nfrom gradio import Server\n\napp = Server()\n\n@app.api(name=\"hello\")\ndef hello(name: str) -> str:\n return f\"Hello, {name}!\"\n\napp.launch()\n```\n\nThat's it. When you run this script, you get:\n\n- A Gradio API endpoint at `/gradio_api/call/hello` with queuing and SSE streaming\n- Auto-generated API docs at `/gradio_api/info`\n- A Python and JavaScript client that can call `/hello` by name\n\nYou can test it with the Gradio Python client:\n\n```python\nfrom gradio_client import Client\n\nclient = Client(\"http://localhost:7860\")\nresult = client.predict(\"World\", api_name=\"/hello\")\nprint(result) \"Hello, World!\"\n```\n\n", "heading1": "A Minimal Example", "source_page_url": "https://gradio.app/guides/server-mode", "source_page_title": "Gradio Clients And Lite - Server Mode Guide"}, {"text": "Since `gradio.Server` inherits from FastAPI, you can add any route directly:\n\n```python\nfrom gradio import Server\nfrom fastapi.responses import HTMLResponse\n\napp = Server()\n\n@app.api(name=\"hello\")\ndef hello(name: str) -> str:\n return f\"Hello, {name}!\"\n\n@app.get(\"/\", response_class=HTMLResponse)\nasync def homepage():\n return \"

Welcome to my API

\"\n\n@app.get(\"/health\")\nasync def health():\n return {\"status\": \"ok\"}\n\napp.launch()\n```\n\nYour custom routes take priority over Gradio's default routes. For example, your `GET /` replaces Gradio's default UI page.\n\nYou can also use all standard FastAPI features \u2014 `app.add_middleware()`, `app.include_router()`, dependency injection, exception handlers, and so on.\n\n", "heading1": "Custom Routes", "source_page_url": "https://gradio.app/guides/server-mode", "source_page_title": "Gradio Clients And Lite - Server Mode Guide"}, {"text": "To expose your API endpoints as MCP tools, add the `@app.mcp.tool()` decorator and pass `mcp_server=True` to `launch()`:\n\n```python\nfrom gradio import Server\n\napp = Server()\n\n@app.mcp.tool(name=\"hello\")\n@app.api(name=\"hello\")\ndef hello(name: str) -> str:\n \"\"\"Greet someone by name.\"\"\"\n return f\"Hello, {name}!\"\n\napp.launch(mcp_server=True)\n```\n\nThe `@app.mcp.tool()` and `@app.api()` decorators are independent \u2014 you can have API-only endpoints or MCP-only tools. Stack both when you want a function available through both.\n\n", "heading1": "MCP Tools", "source_page_url": "https://gradio.app/guides/server-mode", "source_page_title": "Gradio Clients And Lite - Server Mode Guide"}, {"text": "This example combines everything: custom HTML served at `/`, Gradio API endpoints with concurrency limits, MCP tools, and a custom REST endpoint, and two connected via [the Gradio JavaScript client](/guides/getting-started-with-the-js-client).\n\n$code_server_app\n\nRun it with:\n\n```bash\npython run.py\n```\n\nThen open `http://localhost:7860` in your browser. The custom HTML page uses the `@gradio/client` JavaScript library to call the Gradio API endpoints. Meanwhile, the same endpoints are available as MCP tools and through the REST API at `/gradio_api/call/add` and `/gradio_api/call/multiply`.\n\nNote: if your `Server` app uses ZeroGPU, you _must_ call Gradio API endpoints through `@gradio/client` from the browser. The JavaScript client forwards the Hugging Face iframe auth headers needed for ZeroGPU quota handling.\n\n", "heading1": "A Complete Example with the JavaScript Client", "source_page_url": "https://gradio.app/guides/server-mode", "source_page_title": "Gradio Clients And Lite - Server Mode Guide"}, {"text": "`app.api()` supports all of the same concurrency and streaming options as `gr.api()`:\n\n```python\n@app.api(name=\"generate\", concurrency_limit=2, stream_every=0.5)\nasync def generate(prompt: str):\n for token in model.generate(prompt):\n yield token\n```\n\nGenerator functions automatically stream results via SSE, just like in a regular Gradio app. The `concurrency_limit` parameter controls how many concurrent calls to this endpoint are allowed. By default, this is set to 1, since many ML workloads that run on GPU can only support a single user at a time. However, you can increase this, or set to `None` to use FastAPI defaults, if you are e.g. calling an external API.\n\nFor the full API reference, see the [`Server` documentation](/docs/gradio/server).\n", "heading1": "Concurrency and Streaming", "source_page_url": "https://gradio.app/guides/server-mode", "source_page_title": "Gradio Clients And Lite - Server Mode Guide"}, {"text": "What are agents?\n\nA [LangChain agent](https://docs.langchain.com/docs/components/agents/agent) is a Large Language Model (LLM) that takes user input and reports an output based on using one of many tools at its disposal.\n\nWhat is Gradio?\n\n[Gradio](https://github.com/gradio-app/gradio) is the defacto standard framework for building Machine Learning Web Applications and sharing them with the world - all with just python! \ud83d\udc0d\n\n", "heading1": "Some background", "source_page_url": "https://gradio.app/guides/gradio-and-llm-agents", "source_page_title": "Gradio Clients And Lite - Gradio And Llm Agents Guide"}, {"text": "To get started with `gradio_tools`, all you need to do is import and initialize your tools and pass them to the langchain agent!\n\nIn the following example, we import the `StableDiffusionPromptGeneratorTool` to create a good prompt for stable diffusion, the\n`StableDiffusionTool` to create an image with our improved prompt, the `ImageCaptioningTool` to caption the generated image, and\nthe `TextToVideoTool` to create a video from a prompt.\n\nWe then tell our agent to create an image of a dog riding a skateboard, but to please improve our prompt ahead of time. We also ask\nit to caption the generated image and create a video for it. The agent can decide which tool to use without us explicitly telling it.\n\n```python\nimport os\n\nif not os.getenv(\"OPENAI_API_KEY\"):\n raise ValueError(\"OPENAI_API_KEY must be set\")\n\nfrom langchain.agents import initialize_agent\nfrom langchain.llms import OpenAI\nfrom gradio_tools import (StableDiffusionTool, ImageCaptioningTool, StableDiffusionPromptGeneratorTool,\n TextToVideoTool)\n\nfrom langchain.memory import ConversationBufferMemory\n\nllm = OpenAI(temperature=0)\nmemory = ConversationBufferMemory(memory_key=\"chat_history\")\ntools = [StableDiffusionTool().langchain, ImageCaptioningTool().langchain,\n StableDiffusionPromptGeneratorTool().langchain, TextToVideoTool().langchain]\n\n\nagent = initialize_agent(tools, llm, memory=memory, agent=\"conversational-react-description\", verbose=True)\noutput = agent.run(input=(\"Please create a photo of a dog riding a skateboard \"\n \"but improve my prompt prior to using an image generator.\"\n \"Please caption the generated image and create a video for it using the improved prompt.\"))\n```\n\nYou'll note that we are using some pre-built tools that come with `gradio_tools`. Please see this [doc](https://github.com/freddyaboulton/gradio-toolsgradio-tools-gradio--llm-agents) for a complete list of the tools that come with `gradio_tools`.\nIf ", "heading1": "gradio_tools - An end-to-end example", "source_page_url": "https://gradio.app/guides/gradio-and-llm-agents", "source_page_title": "Gradio Clients And Lite - Gradio And Llm Agents Guide"}, {"text": "that come with `gradio_tools`. Please see this [doc](https://github.com/freddyaboulton/gradio-toolsgradio-tools-gradio--llm-agents) for a complete list of the tools that come with `gradio_tools`.\nIf you would like to use a tool that's not currently in `gradio_tools`, it is very easy to add your own. That's what the next section will cover.\n\n", "heading1": "gradio_tools - An end-to-end example", "source_page_url": "https://gradio.app/guides/gradio-and-llm-agents", "source_page_title": "Gradio Clients And Lite - Gradio And Llm Agents Guide"}, {"text": "The core abstraction is the `GradioTool`, which lets you define a new tool for your LLM as long as you implement a standard interface:\n\n```python\nclass GradioTool(BaseTool):\n\n def __init__(self, name: str, description: str, src: str) -> None:\n\n @abstractmethod\n def create_job(self, query: str) -> Job:\n pass\n\n @abstractmethod\n def postprocess(self, output: Tuple[Any] | Any) -> str:\n pass\n```\n\nThe requirements are:\n\n1. The name for your tool\n2. The description for your tool. This is crucial! Agents decide which tool to use based on their description. Be precise and be sure to include example of what the input and the output of the tool should look like.\n3. The url or space id, e.g. `freddyaboulton/calculator`, of the Gradio application. Based on this value, `gradio_tool` will create a [gradio client](https://github.com/gradio-app/gradio/blob/main/client/python/README.md) instance to query the upstream application via API. Be sure to click the link and learn more about the gradio client library if you are not familiar with it.\n4. create_job - Given a string, this method should parse that string and return a job from the client. Most times, this is as simple as passing the string to the `submit` function of the client. More info on creating jobs [here](https://github.com/gradio-app/gradio/blob/main/client/python/README.mdmaking-a-prediction)\n5. postprocess - Given the result of the job, convert it to a string the LLM can display to the user.\n6. _Optional_ - Some libraries, e.g. [MiniChain](https://github.com/srush/MiniChain/tree/main), may need some info about the underlying gradio input and output types used by the tool. By default, this will return gr.Textbox() but\n if you'd like to provide more accurate info, implement the `_block_input(self, gr)` and `_block_output(self, gr)` methods of the tool. The `gr` variable is the gradio module (the result of `import gradio as gr`). It will be\n automatically imported by the `GradiTool` parent", "heading1": "gradio_tools - creating your own tool", "source_page_url": "https://gradio.app/guides/gradio-and-llm-agents", "source_page_title": "Gradio Clients And Lite - Gradio And Llm Agents Guide"}, {"text": "lf, gr)` and `_block_output(self, gr)` methods of the tool. The `gr` variable is the gradio module (the result of `import gradio as gr`). It will be\n automatically imported by the `GradiTool` parent class and passed to the `_block_input` and `_block_output` methods.\n\nAnd that's it!\n\nOnce you have created your tool, open a pull request to the `gradio_tools` repo! We welcome all contributions.\n\n", "heading1": "gradio_tools - creating your own tool", "source_page_url": "https://gradio.app/guides/gradio-and-llm-agents", "source_page_title": "Gradio Clients And Lite - Gradio And Llm Agents Guide"}, {"text": "Here is the code for the StableDiffusion tool as an example:\n\n```python\nfrom gradio_tool import GradioTool\nimport os\n\nclass StableDiffusionTool(GradioTool):\n \"\"\"Tool for calling stable diffusion from llm\"\"\"\n\n def __init__(\n self,\n name=\"StableDiffusion\",\n description=(\n \"An image generator. Use this to generate images based on \"\n \"text input. Input should be a description of what the image should \"\n \"look like. The output will be a path to an image file.\"\n ),\n src=\"gradio-client-demos/stable-diffusion\",\n token=None,\n ) -> None:\n super().__init__(name, description, src, token)\n\n def create_job(self, query: str) -> Job:\n return self.client.submit(query, \"\", 9, fn_index=1)\n\n def postprocess(self, output: str) -> str:\n return [os.path.join(output, i) for i in os.listdir(output) if not i.endswith(\"json\")][0]\n\n def _block_input(self, gr) -> \"gr.components.Component\":\n return gr.Textbox()\n\n def _block_output(self, gr) -> \"gr.components.Component\":\n return gr.Image()\n```\n\nSome notes on this implementation:\n\n1. All instances of `GradioTool` have an attribute called `client` that is a pointed to the underlying [gradio client](https://github.com/gradio-app/gradio/tree/main/client/pythongradio_client-use-a-gradio-app-as-an-api----in-3-lines-of-python). That is what you should use\n in the `create_job` method.\n2. `create_job` just passes the query string to the `submit` function of the client with some other parameters hardcoded, i.e. the negative prompt string and the guidance scale. We could modify our tool to also accept these values from the input string in a subsequent version.\n3. The `postprocess` method simply returns the first image from the gallery of images created by the stable diffusion space. We use the `os` module to get the full path of the image.\n\n", "heading1": "Example tool - Stable Diffusion", "source_page_url": "https://gradio.app/guides/gradio-and-llm-agents", "source_page_title": "Gradio Clients And Lite - Gradio And Llm Agents Guide"}, {"text": "You now know how to extend the abilities of your LLM with the 1000s of gradio spaces running in the wild!\nAgain, we welcome any contributions to the [gradio_tools](https://github.com/freddyaboulton/gradio-tools) library.\nWe're excited to see the tools you all build!\n", "heading1": "Conclusion", "source_page_url": "https://gradio.app/guides/gradio-and-llm-agents", "source_page_title": "Gradio Clients And Lite - Gradio And Llm Agents Guide"}, {"text": "You generally don't need to install cURL, as it comes pre-installed on many operating systems. Run:\n\n```bash\ncurl --version\n```\n\nto confirm that `curl` is installed. If it is not already installed, you can install it by visiting https://curl.se/download.html. \n\n\n", "heading1": "Installation", "source_page_url": "https://gradio.app/guides/querying-gradio-apps-with-curl", "source_page_title": "Gradio Clients And Lite - Querying Gradio Apps With Curl Guide"}, {"text": "To query a Gradio app, you'll need its full URL. This is usually just the URL that the Gradio app is hosted on, for example: https://bec81a83-5b5c-471e.gradio.live\n\n\n**Hugging Face Spaces**\n\nHowever, if you are querying a Gradio on Hugging Face Spaces, you will need to use the URL of the embedded Gradio app, not the URL of the Space webpage. For example:\n\n```bash\n\u274c Space URL: https://huggingface.co/spaces/abidlabs/en2fr\n\u2705 Gradio app URL: https://abidlabs-en2fr.hf.space/\n```\n\nYou can get the Gradio app URL by clicking the \"view API\" link at the bottom of the page. Or, you can right-click on the page and then click on \"View Frame Source\" or the equivalent in your browser to view the URL of the embedded Gradio app.\n\nWhile you can use any public Space as an API, you may get rate limited by Hugging Face if you make too many requests. For unlimited usage of a Space, simply duplicate the Space to create a private Space,\nand then use it to make as many requests as you'd like!\n\nNote: to query private Spaces, you will need to pass in your Hugging Face (HF) token. You can get your HF token here: https://huggingface.co/settings/tokens. In this case, you will need to include an additional header in both of your `curl` calls that we'll discuss below:\n\n```bash\n-H \"Authorization: Bearer $HF_TOKEN\"\n```\n\nNow, we are ready to make the two `curl` requests.\n\n", "heading1": "Step 0: Get the URL for your Gradio App", "source_page_url": "https://gradio.app/guides/querying-gradio-apps-with-curl", "source_page_title": "Gradio Clients And Lite - Querying Gradio Apps With Curl Guide"}, {"text": "The first of the two `curl` requests is `POST` request that submits the input payload to the Gradio app. \n\nThe syntax of the `POST` request is as follows:\n\n```bash\n$ curl -X POST $URL/call/$API_NAME -H \"Content-Type: application/json\" -d '{\n \"data\": $PAYLOAD\n}'\n```\n\nHere:\n\n* `$URL` is the URL of the Gradio app as obtained in Step 0\n* `$API_NAME` is the name of the API endpoint for the event that you are running. You can get the API endpoint names by clicking the \"view API\" link at the bottom of the page.\n* `$PAYLOAD` is a valid JSON data list containing the input payload, one element for each input component.\n\nWhen you make this `POST` request successfully, you will get an event id that is printed to the terminal in this format:\n\n```bash\n>> {\"event_id\": $EVENT_ID} \n```\n\nThis `EVENT_ID` will be needed in the subsequent `curl` request to fetch the results of the prediction. \n\nHere are some examples of how to make the `POST` request\n\n**Basic Example**\n\nRevisiting the example at the beginning of the page, here is how to make the `POST` request for a simple Gradio application that takes in a single input text component:\n\n```bash\n$ curl -X POST https://abidlabs-en2fr.hf.space/call/predict -H \"Content-Type: application/json\" -d '{\n \"data\": [\"Hello, my friend.\"] \n}'\n```\n\n**Multiple Input Components**\n\nThis [Gradio demo](https://huggingface.co/spaces/gradio/hello_world_3) accepts three inputs: a string corresponding to the `gr.Textbox`, a boolean value corresponding to the `gr.Checkbox`, and a numerical value corresponding to the `gr.Slider`. Here is the `POST` request:\n\n```bash\ncurl -X POST https://gradio-hello-world-3.hf.space/call/predict -H \"Content-Type: application/json\" -d '{\n \"data\": [\"Hello\", true, 5]\n}'\n```\n\n**Private Spaces**\n\nAs mentioned earlier, if you are making a request to a private Space, you will need to pass in a [Hugging Face token](https://huggingface.co/settings/tokens) that has read access to the Space. The request will look like this:\n\n```bash\n", "heading1": "Step 1: Make a Prediction (POST)", "source_page_url": "https://gradio.app/guides/querying-gradio-apps-with-curl", "source_page_title": "Gradio Clients And Lite - Querying Gradio Apps With Curl Guide"}, {"text": "king a request to a private Space, you will need to pass in a [Hugging Face token](https://huggingface.co/settings/tokens) that has read access to the Space. The request will look like this:\n\n```bash\n$ curl -X POST https://private-space.hf.space/call/predict -H \"Content-Type: application/json\" -H \"Authorization: Bearer $HF_TOKEN\" -d '{\n \"data\": [\"Hello, my friend.\"] \n}'\n```\n\n**Files**\n\nIf you are using `curl` to query a Gradio application that requires file inputs, the files *need* to be provided as URLs, and The URL needs to be enclosed in a dictionary in this format:\n\n```bash\n{\"path\": $URL}\n```\n\nHere is an example `POST` request:\n\n```bash\n$ curl -X POST https://gradio-image-mod.hf.space/call/predict -H \"Content-Type: application/json\" -d '{\n \"data\": [{\"path\": \"https://raw.githubusercontent.com/gradio-app/gradio/main/test/test_files/bus.png\"}] \n}'\n```\n\n\n**Stateful Demos**\n\nIf your Gradio demo [persists user state](/guides/interface-state) across multiple interactions (e.g. is a chatbot), you can pass in a `session_hash` alongside the `data`. Requests with the same `session_hash` are assumed to be part of the same user session. Here's how that might look:\n\n```bash\nThese two requests will share a session\n\ncurl -X POST https://gradio-chatinterface-random-response.hf.space/call/chat -H \"Content-Type: application/json\" -d '{\n \"data\": [\"Are you sentient?\"],\n \"session_hash\": \"randomsequence1234\"\n}'\n\ncurl -X POST https://gradio-chatinterface-random-response.hf.space/call/chat -H \"Content-Type: application/json\" -d '{\n \"data\": [\"Really?\"],\n \"session_hash\": \"randomsequence1234\"\n}'\n\nThis request will be treated as a new session\n\ncurl -X POST https://gradio-chatinterface-random-response.hf.space/call/chat -H \"Content-Type: application/json\" -d '{\n \"data\": [\"Are you sentient?\"],\n \"session_hash\": \"newsequence5678\"\n}'\n```\n\n\n\n", "heading1": "Step 1: Make a Prediction (POST)", "source_page_url": "https://gradio.app/guides/querying-gradio-apps-with-curl", "source_page_title": "Gradio Clients And Lite - Querying Gradio Apps With Curl Guide"}, {"text": "ient?\"],\n \"session_hash\": \"newsequence5678\"\n}'\n```\n\n\n\n", "heading1": "Step 1: Make a Prediction (POST)", "source_page_url": "https://gradio.app/guides/querying-gradio-apps-with-curl", "source_page_title": "Gradio Clients And Lite - Querying Gradio Apps With Curl Guide"}, {"text": "Once you have received the `EVENT_ID` corresponding to your prediction, you can stream the results. Gradio stores these results in a least-recently-used cache in the Gradio app. By default, the cache can store 2,000 results (across all users and endpoints of the app). \n\nTo stream the results for your prediction, make a `GET` request with the following syntax:\n\n```bash\n$ curl -N $URL/call/$API_NAME/$EVENT_ID\n```\n\n\nTip: If you are fetching results from a private Space, include a header with your HF token like this: `-H \"Authorization: Bearer $HF_TOKEN\"` in the `GET` request.\n\nThis should produce a stream of responses in this format:\n\n```bash\nevent: ... \ndata: ...\nevent: ... \ndata: ...\n...\n```\n\nHere: `event` can be one of the following:\n* `generating`: indicating an intermediate result\n* `complete`: indicating that the prediction is complete and the final result \n* `error`: indicating that the prediction was not completed successfully\n* `heartbeat`: sent every 15 seconds to keep the request alive\n\nThe `data` is in the same format as the input payload: valid JSON data list containing the output result, one element for each output component.\n\nHere are some examples of what results you should expect if a request is completed successfully:\n\n**Basic Example**\n\nRevisiting the example at the beginning of the page, we would expect the result to look like this:\n\n```bash\nevent: complete\ndata: [\"Bonjour, mon ami.\"]\n```\n\n**Multiple Outputs**\n\nIf your endpoint returns multiple values, they will appear as elements of the `data` list:\n\n```bash\nevent: complete\ndata: [\"Good morning Hello. It is 5 degrees today\", -15.0]\n```\n\n**Streaming Example**\n\nIf your Gradio app [streams a sequence of values](/guides/streaming-outputs), then they will be streamed directly to your terminal, like this:\n\n```bash\nevent: generating\ndata: [\"Hello, w!\"]\nevent: generating\ndata: [\"Hello, wo!\"]\nevent: generating\ndata: [\"Hello, wor!\"]\nevent: generating\ndata: [\"Hello, worl!\"]\nevent: generating\ndata: [\"Hello, w", "heading1": "Step 2: GET the result", "source_page_url": "https://gradio.app/guides/querying-gradio-apps-with-curl", "source_page_title": "Gradio Clients And Lite - Querying Gradio Apps With Curl Guide"}, {"text": "```bash\nevent: generating\ndata: [\"Hello, w!\"]\nevent: generating\ndata: [\"Hello, wo!\"]\nevent: generating\ndata: [\"Hello, wor!\"]\nevent: generating\ndata: [\"Hello, worl!\"]\nevent: generating\ndata: [\"Hello, world!\"]\nevent: complete\ndata: [\"Hello, world!\"]\n```\n\n**File Example**\n\nIf your Gradio app returns a file, the file will be represented as a dictionary in this format (including potentially some additional keys):\n\n```python\n{\n \"orig_name\": \"example.jpg\",\n \"path\": \"/path/in/server.jpg\",\n \"url\": \"https:/example.com/example.jpg\",\n \"meta\": {\"_type\": \"gradio.FileData\"}\n}\n```\n\nIn your terminal, it may appear like this:\n\n```bash\nevent: complete\ndata: [{\"path\": \"/tmp/gradio/359933dc8d6cfe1b022f35e2c639e6e42c97a003/image.webp\", \"url\": \"https://gradio-image-mod.hf.space/c/file=/tmp/gradio/359933dc8d6cfe1b022f35e2c639e6e42c97a003/image.webp\", \"size\": null, \"orig_name\": \"image.webp\", \"mime_type\": null, \"is_stream\": false, \"meta\": {\"_type\": \"gradio.FileData\"}}]\n```\n\n", "heading1": "Step 2: GET the result", "source_page_url": "https://gradio.app/guides/querying-gradio-apps-with-curl", "source_page_title": "Gradio Clients And Lite - Querying Gradio Apps With Curl Guide"}, {"text": "What if your Gradio application has [authentication enabled](/guides/sharing-your-appauthentication)? In that case, you'll need to make an additional `POST` request with cURL to authenticate yourself before you make any queries. Here are the complete steps:\n\nFirst, login with a `POST` request supplying a valid username and password:\n\n```bash\ncurl -X POST $URL/login \\\n -d \"username=$USERNAME&password=$PASSWORD\" \\\n -c cookies.txt\n```\n\nIf the credentials are correct, you'll get `{\"success\":true}` in response and the cookies will be saved in `cookies.txt`.\n\nNext, you'll need to include these cookies when you make the original `POST` request, like this:\n\n```bash\n$ curl -X POST $URL/call/$API_NAME -b cookies.txt -H \"Content-Type: application/json\" -d '{\n \"data\": $PAYLOAD\n}'\n```\n\nFinally, you'll need to `GET` the results, again supplying the cookies from the file:\n\n```bash\ncurl -N $URL/call/$API_NAME/$EVENT_ID -b cookies.txt\n```\n", "heading1": "Authentication", "source_page_url": "https://gradio.app/guides/querying-gradio-apps-with-curl", "source_page_title": "Gradio Clients And Lite - Querying Gradio Apps With Curl Guide"}, {"text": "If you already have a recent version of `gradio`, then the `gradio_client` is included as a dependency. But note that this documentation reflects the latest version of the `gradio_client`, so upgrade if you're not sure!\n\nThe lightweight `gradio_client` package can be installed from pip (or pip3) and is tested to work with **Python versions 3.10 or higher**:\n\n```bash\n$ pip install --upgrade gradio_client\n```\n\n", "heading1": "Installation", "source_page_url": "https://gradio.app/guides/getting-started-with-the-python-client", "source_page_title": "Gradio Clients And Lite - Getting Started With The Python Client Guide"}, {"text": "Start by connecting instantiating a `Client` object and connecting it to a Gradio app that is running on Hugging Face Spaces.\n\n```python\nfrom gradio_client import Client\n\nclient = Client(\"abidlabs/en2fr\") a Space that translates from English to French\n```\n\nYou can also connect to private Spaces by passing in your HF token with the `token` parameter. You can get your HF token here: https://huggingface.co/settings/tokens\n\n```python\nfrom gradio_client import Client\n\nclient = Client(\"abidlabs/my-private-space\", token=\"...\")\n```\n\n\n", "heading1": "Connecting to a Gradio App on Hugging Face Spaces", "source_page_url": "https://gradio.app/guides/getting-started-with-the-python-client", "source_page_title": "Gradio Clients And Lite - Getting Started With The Python Client Guide"}, {"text": "While you can use any public Space as an API, you may get rate limited by Hugging Face if you make too many requests. For unlimited usage of a Space, simply duplicate the Space to create a private Space,\nand then use it to make as many requests as you'd like!\n\nThe `gradio_client` includes a class method: `Client.duplicate()` to make this process simple (you'll need to pass in your [Hugging Face token](https://huggingface.co/settings/tokens) or be logged in using the Hugging Face CLI):\n\n```python\nimport os\nfrom gradio_client import Client, handle_file\n\nHF_TOKEN = os.environ.get(\"HF_TOKEN\")\n\nclient = Client.duplicate(\"abidlabs/whisper\", token=HF_TOKEN)\nclient.predict(handle_file(\"audio_sample.wav\"))\n\n>> \"This is a test of the whisper speech recognition model.\"\n```\n\nIf you have previously duplicated a Space, re-running `duplicate()` will _not_ create a new Space. Instead, the Client will attach to the previously-created Space. So it is safe to re-run the `Client.duplicate()` method multiple times.\n\n**Note:** if the original Space uses GPUs, your private Space will as well, and your Hugging Face account will get billed based on the price of the GPU. To minimize charges, your Space will automatically go to sleep after 1 hour of inactivity. You can also set the hardware using the `hardware` parameter of `duplicate()`.\n\n", "heading1": "Duplicating a Space for private use", "source_page_url": "https://gradio.app/guides/getting-started-with-the-python-client", "source_page_title": "Gradio Clients And Lite - Getting Started With The Python Client Guide"}, {"text": "If your app is running somewhere else, just provide the full URL instead, including the \"http://\" or \"https://\". Here's an example of making predictions to a Gradio app that is running on a share URL:\n\n```python\nfrom gradio_client import Client\n\nclient = Client(\"https://bec81a83-5b5c-471e.gradio.live\")\n```\n\n", "heading1": "Connecting a general Gradio app", "source_page_url": "https://gradio.app/guides/getting-started-with-the-python-client", "source_page_title": "Gradio Clients And Lite - Getting Started With The Python Client Guide"}, {"text": "If the Gradio application you are connecting to [requires a username and password](/guides/sharing-your-appauthentication), then provide them as a tuple to the `auth` argument of the `Client` class:\n\n```python\nfrom gradio_client import Client\n\nClient(\n space_name,\n auth=[username, password]\n)\n```\n\n\n", "heading1": "Connecting to a Gradio app with auth", "source_page_url": "https://gradio.app/guides/getting-started-with-the-python-client", "source_page_title": "Gradio Clients And Lite - Getting Started With The Python Client Guide"}, {"text": "Once you have connected to a Gradio app, you can view the APIs that are available to you by calling the `Client.view_api()` method. For the Whisper Space, we see the following:\n\n```bash\nClient.predict() Usage Info\n---------------------------\nNamed API endpoints: 1\n\n - predict(audio, api_name=\"/predict\") -> output\n Parameters:\n - [Audio] audio: filepath (required) \n Returns:\n - [Textbox] output: str \n```\n\nWe see that we have 1 API endpoint in this space, and shows us how to use the API endpoint to make a prediction: we should call the `.predict()` method (which we will explore below), providing a parameter `input_audio` of type `str`, which is a `filepath or URL`.\n\nWe should also provide the `api_name='/predict'` argument to the `predict()` method. Although this isn't necessary if a Gradio app has only 1 named endpoint, it does allow us to call different endpoints in a single app if they are available.\n\n", "heading1": "Inspecting the API endpoints", "source_page_url": "https://gradio.app/guides/getting-started-with-the-python-client", "source_page_title": "Gradio Clients And Lite - Getting Started With The Python Client Guide"}, {"text": "As an alternative to running the `.view_api()` method, you can click on the \"Use via API\" link in the footer of the Gradio app, which shows us the same information, along with example usage. \n\n![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio-guides/view-api.png)\n\nThe View API page also includes an \"API Recorder\" that lets you interact with the Gradio UI normally and converts your interactions into the corresponding code to run with the Python Client.\n\n", "heading1": "The \"View API\" Page", "source_page_url": "https://gradio.app/guides/getting-started-with-the-python-client", "source_page_title": "Gradio Clients And Lite - Getting Started With The Python Client Guide"}, {"text": "The simplest way to make a prediction is simply to call the `.predict()` function with the appropriate arguments:\n\n```python\nfrom gradio_client import Client\n\nclient = Client(\"abidlabs/en2fr\")\nclient.predict(\"Hello\", api_name='/predict')\n\n>> Bonjour\n```\n\nIf there are multiple parameters, then you should pass them as separate arguments to `.predict()`, like this:\n\n```python\nfrom gradio_client import Client\n\nclient = Client(\"gradio/calculator\")\nclient.predict(4, \"add\", 5)\n\n>> 9.0\n```\n\nIt is recommended to provide key-word arguments instead of positional arguments:\n\n\n```python\nfrom gradio_client import Client\n\nclient = Client(\"gradio/calculator\")\nclient.predict(num1=4, operation=\"add\", num2=5)\n\n>> 9.0\n```\n\nThis allows you to take advantage of default arguments. For example, this Space includes the default value for the Slider component so you do not need to provide it when accessing it with the client.\n\n```python\nfrom gradio_client import Client\n\nclient = Client(\"abidlabs/image_generator\")\nclient.predict(text=\"an astronaut riding a camel\")\n```\n\nThe default value is the initial value of the corresponding Gradio component. If the component does not have an initial value, but if the corresponding argument in the predict function has a default value of `None`, then that parameter is also optional in the client. Of course, if you'd like to override it, you can include it as well:\n\n```python\nfrom gradio_client import Client\n\nclient = Client(\"abidlabs/image_generator\")\nclient.predict(text=\"an astronaut riding a camel\", steps=25)\n```\n\nFor providing files or URLs as inputs, you should pass in the filepath or URL to the file enclosed within `gradio_client.handle_file()`. This takes care of uploading the file to the Gradio server and ensures that the file is preprocessed correctly:\n\n```python\nfrom gradio_client import Client, handle_file\n\nclient = Client(\"abidlabs/whisper\")\nclient.predict(\n audio=handle_file(\"https://audio-samples.github.io/samples/mp3/blizzard_unconditional/s", "heading1": "Making a prediction", "source_page_url": "https://gradio.app/guides/getting-started-with-the-python-client", "source_page_title": "Gradio Clients And Lite - Getting Started With The Python Client Guide"}, {"text": "```python\nfrom gradio_client import Client, handle_file\n\nclient = Client(\"abidlabs/whisper\")\nclient.predict(\n audio=handle_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\n", "heading1": "Making a prediction", "source_page_url": "https://gradio.app/guides/getting-started-with-the-python-client", "source_page_title": "Gradio Clients And Lite - Getting Started With The Python Client Guide"}, {"text": "One should note that `.predict()` is a _blocking_ operation as it waits for the operation to complete before returning the prediction.\n\nIn many cases, you may be better off letting the job run in the background until you need the results of the prediction. You can do this by creating a `Job` instance using the `.submit()` method, and then later calling `.result()` on the job to get the result. For example:\n\n```python\nfrom gradio_client import Client\n\nclient = Client(space=\"abidlabs/en2fr\")\njob = client.submit(\"Hello\", api_name=\"/predict\") This is not blocking\n\nDo something else\n\njob.result() This is blocking\n\n>> Bonjour\n```\n\n", "heading1": "Running jobs asynchronously", "source_page_url": "https://gradio.app/guides/getting-started-with-the-python-client", "source_page_title": "Gradio Clients And Lite - Getting Started With The Python Client Guide"}, {"text": "Alternatively, one can add one or more callbacks to perform actions after the job has completed running, like this:\n\n```python\nfrom gradio_client import Client\n\ndef print_result(x):\n print(\"The translated result is: {x}\")\n\nclient = Client(space=\"abidlabs/en2fr\")\n\njob = client.submit(\"Hello\", api_name=\"/predict\", result_callbacks=[print_result])\n\nDo something else\n\n>> The translated result is: Bonjour\n\n```\n\n", "heading1": "Adding callbacks", "source_page_url": "https://gradio.app/guides/getting-started-with-the-python-client", "source_page_title": "Gradio Clients And Lite - Getting Started With The Python Client Guide"}, {"text": "The `Job` object also allows you to get the status of the running job by calling the `.status()` method. This returns a `StatusUpdate` object with the following attributes: `code` (the status code, one of a set of defined strings representing the status. See the `utils.Status` class), `rank` (the current position of this job in the queue), `queue_size` (the total queue size), `eta` (estimated time this job will complete), `success` (a boolean representing whether the job completed successfully), and `time` (the time that the status was generated).\n\n```py\nfrom gradio_client import Client\n\nclient = Client(src=\"gradio/calculator\")\njob = client.submit(5, \"add\", 4, api_name=\"/predict\")\njob.status()\n\n>> \n```\n\n_Note_: The `Job` class also has a `.done()` instance method which returns a boolean indicating whether the job has completed.\n\n", "heading1": "Status", "source_page_url": "https://gradio.app/guides/getting-started-with-the-python-client", "source_page_title": "Gradio Clients And Lite - Getting Started With The Python Client Guide"}, {"text": "The `Job` class also has a `.cancel()` instance method that cancels jobs that have been queued but not started. For example, if you run:\n\n```py\nclient = Client(\"abidlabs/whisper\")\njob1 = client.submit(handle_file(\"audio_sample1.wav\"))\njob2 = client.submit(handle_file(\"audio_sample2.wav\"))\njob1.cancel() will return False, assuming the job has started\njob2.cancel() will return True, indicating that the job has been canceled\n```\n\nIf the first job has started processing, then it will not be canceled. If the second job\nhas not yet started, it will be successfully canceled and removed from the queue.\n\n", "heading1": "Cancelling Jobs", "source_page_url": "https://gradio.app/guides/getting-started-with-the-python-client", "source_page_title": "Gradio Clients And Lite - Getting Started With The Python Client Guide"}, {"text": "Some Gradio API endpoints do not return a single value, rather they return a series of values. You can get the series of values that have been returned at any time from such a generator endpoint by running `job.outputs()`:\n\n```py\nfrom gradio_client import Client\n\nclient = Client(src=\"gradio/count_generator\")\njob = client.submit(3, api_name=\"/count\")\nwhile not job.done():\n time.sleep(0.1)\njob.outputs()\n\n>> ['0', '1', '2']\n```\n\nNote that running `job.result()` on a generator endpoint only gives you the _first_ value returned by the endpoint.\n\nThe `Job` object is also iterable, which means you can use it to display the results of a generator function as they are returned from the endpoint. Here's the equivalent example using the `Job` as a generator:\n\n```py\nfrom gradio_client import Client\n\nclient = Client(src=\"gradio/count_generator\")\njob = client.submit(3, api_name=\"/count\")\n\nfor o in job:\n print(o)\n\n>> 0\n>> 1\n>> 2\n```\n\nYou can also cancel jobs that that have iterative outputs, in which case the job will finish as soon as the current iteration finishes running.\n\n```py\nfrom gradio_client import Client\nimport time\n\nclient = Client(\"abidlabs/test-yield\")\njob = client.submit(\"abcdef\")\ntime.sleep(3)\njob.cancel() job cancels after 2 iterations\n```\n\n", "heading1": "Generator Endpoints", "source_page_url": "https://gradio.app/guides/getting-started-with-the-python-client", "source_page_title": "Gradio Clients And Lite - Getting Started With The Python Client Guide"}, {"text": "Gradio demos can include [session state](https://www.gradio.app/guides/state-in-blocks), which provides a way for demos to persist information from user interactions within a page session.\n\nFor example, consider the following demo, which maintains a list of words that a user has submitted in a `gr.State` component. When a user submits a new word, it is added to the state, and the number of previous occurrences of that word is displayed:\n\n```python\nimport gradio as gr\n\ndef count(word, list_of_words):\n return list_of_words.count(word), list_of_words + [word]\n\nwith gr.Blocks() as demo:\n words = gr.State([])\n textbox = gr.Textbox()\n number = gr.Number()\n textbox.submit(count, inputs=[textbox, words], outputs=[number, words])\n \ndemo.launch()\n```\n\nIf you were to connect this this Gradio app using the Python Client, you would notice that the API information only shows a single input and output:\n\n```csv\nClient.predict() Usage Info\n---------------------------\nNamed API endpoints: 1\n\n - predict(word, api_name=\"/count\") -> value_31\n Parameters:\n - [Textbox] word: str (required) \n Returns:\n - [Number] value_31: float \n```\n\nThat is because the Python client handles state automatically for you -- as you make a series of requests, the returned state from one request is stored internally and automatically supplied for the subsequent request. If you'd like to reset the state, you can do that by calling `Client.reset_session()`.\n", "heading1": "Demos with Session State", "source_page_url": "https://gradio.app/guides/getting-started-with-the-python-client", "source_page_title": "Gradio Clients And Lite - Getting Started With The Python Client Guide"}, {"text": "The next generation of AI user interfaces is moving towards audio-native experiences. Users will be able to speak to chatbots and receive spoken responses in return. Several models have been built under this paradigm, including GPT-4o and [mini omni](https://github.com/gpt-omni/mini-omni).\n\nIn this guide, we'll walk you through building your own conversational chat application using mini omni as an example. You can see a demo of the finished app below:\n\n\n\n", "heading1": "Introduction", "source_page_url": "https://gradio.app/guides/conversational-chatbot", "source_page_title": "Streaming - Conversational Chatbot Guide"}, {"text": "Our application will enable the following user experience:\n\n1. Users click a button to start recording their message\n2. The app detects when the user has finished speaking and stops recording\n3. The user's audio is passed to the omni model, which streams back a response\n4. After omni mini finishes speaking, the user's microphone is reactivated\n5. All previous spoken audio, from both the user and omni, is displayed in a chatbot component\n\nLet's dive into the implementation details.\n\n", "heading1": "Application Overview", "source_page_url": "https://gradio.app/guides/conversational-chatbot", "source_page_title": "Streaming - Conversational Chatbot Guide"}, {"text": "We'll stream the user's audio from their microphone to the server and determine if the user has stopped speaking on each new chunk of audio.\n\nHere's our `process_audio` function:\n\n```python\nimport numpy as np\nfrom utils import determine_pause\n\ndef process_audio(audio: tuple, state: AppState):\n if state.stream is None:\n state.stream = audio[1]\n state.sampling_rate = audio[0]\n else:\n state.stream = np.concatenate((state.stream, audio[1]))\n\n pause_detected = determine_pause(state.stream, state.sampling_rate, state)\n state.pause_detected = pause_detected\n\n if state.pause_detected and state.started_talking:\n return gr.Audio(recording=False), state\n return None, state\n```\n\nThis function takes two inputs:\n1. The current audio chunk (a tuple of `(sampling_rate, numpy array of audio)`)\n2. The current application state\n\nWe'll use the following `AppState` dataclass to manage our application state:\n\n```python\nfrom dataclasses import dataclass\n\n@dataclass\nclass AppState:\n stream: np.ndarray | None = None\n sampling_rate: int = 0\n pause_detected: bool = False\n stopped: bool = False\n conversation: list = []\n```\n\nThe function concatenates new audio chunks to the existing stream and checks if the user has stopped speaking. If a pause is detected, it returns an update to stop recording. Otherwise, it returns `None` to indicate no changes.\n\nThe implementation of the `determine_pause` function is specific to the omni-mini project and can be found [here](https://huggingface.co/spaces/gradio/omni-mini/blob/eb027808c7bfe5179b46d9352e3fa1813a45f7c3/app.pyL98).\n\n", "heading1": "Processing User Audio", "source_page_url": "https://gradio.app/guides/conversational-chatbot", "source_page_title": "Streaming - Conversational Chatbot Guide"}, {"text": "After processing the user's audio, we need to generate and stream the chatbot's response. Here's our `response` function:\n\n```python\nimport io\nimport tempfile\nfrom pydub import AudioSegment\n\ndef response(state: AppState):\n if not state.pause_detected and not state.started_talking:\n return None, AppState()\n \n audio_buffer = io.BytesIO()\n\n segment = AudioSegment(\n state.stream.tobytes(),\n frame_rate=state.sampling_rate,\n sample_width=state.stream.dtype.itemsize,\n channels=(1 if len(state.stream.shape) == 1 else state.stream.shape[1]),\n )\n segment.export(audio_buffer, format=\"wav\")\n\n with tempfile.NamedTemporaryFile(suffix=\".wav\", delete=False) as f:\n f.write(audio_buffer.getvalue())\n \n state.conversation.append({\"role\": \"user\",\n \"content\": {\"path\": f.name,\n \"mime_type\": \"audio/wav\"}})\n \n output_buffer = b\"\"\n\n for mp3_bytes in speaking(audio_buffer.getvalue()):\n output_buffer += mp3_bytes\n yield mp3_bytes, state\n\n with tempfile.NamedTemporaryFile(suffix=\".mp3\", delete=False) as f:\n f.write(output_buffer)\n \n state.conversation.append({\"role\": \"assistant\",\n \"content\": {\"path\": f.name,\n \"mime_type\": \"audio/mp3\"}})\n yield None, AppState(conversation=state.conversation)\n```\n\nThis function:\n1. Converts the user's audio to a WAV file\n2. Adds the user's message to the conversation history\n3. Generates and streams the chatbot's response using the `speaking` function\n4. Saves the chatbot's response as an MP3 file\n5. Adds the chatbot's response to the conversation history\n\nNote: The implementation of the `speaking` function is specific to the omni-mini project and can be found [here](https://huggingface.co/spaces/gradio/omni-mini/blob/main/app.pyL116).\n\n", "heading1": "Generating the Response", "source_page_url": "https://gradio.app/guides/conversational-chatbot", "source_page_title": "Streaming - Conversational Chatbot Guide"}, {"text": "Now let's put it all together using Gradio's Blocks API:\n\n```python\nimport gradio as gr\n\ndef start_recording_user(state: AppState):\n if not state.stopped:\n return gr.Audio(recording=True)\n\nwith gr.Blocks() as demo:\n with gr.Row():\n with gr.Column():\n input_audio = gr.Audio(\n label=\"Input Audio\", sources=\"microphone\", type=\"numpy\"\n )\n with gr.Column():\n chatbot = gr.Chatbot(label=\"Conversation\")\n output_audio = gr.Audio(label=\"Output Audio\", streaming=True, autoplay=True)\n state = gr.State(value=AppState())\n\n stream = input_audio.stream(\n process_audio,\n [input_audio, state],\n [input_audio, state],\n stream_every=0.5,\n time_limit=30,\n )\n respond = input_audio.stop_recording(\n response,\n [state],\n [output_audio, state]\n )\n respond.then(lambda s: s.conversation, [state], [chatbot])\n\n restart = output_audio.stop(\n start_recording_user,\n [state],\n [input_audio]\n )\n cancel = gr.Button(\"Stop Conversation\", variant=\"stop\")\n cancel.click(lambda: (AppState(stopped=True), gr.Audio(recording=False)), None,\n [state, input_audio], cancels=[respond, restart])\n\nif __name__ == \"__main__\":\n demo.launch()\n```\n\nThis setup creates a user interface with:\n- An input audio component for recording user messages\n- A chatbot component to display the conversation history\n- An output audio component for the chatbot's responses\n- A button to stop and reset the conversation\n\nThe app streams user audio in 0.5-second chunks, processes it, generates responses, and updates the conversation history accordingly.\n\n", "heading1": "Building the Gradio App", "source_page_url": "https://gradio.app/guides/conversational-chatbot", "source_page_title": "Streaming - Conversational Chatbot Guide"}, {"text": "This guide demonstrates how to build a conversational chatbot application using Gradio and the mini omni model. You can adapt this framework to create various audio-based chatbot demos. To see the full application in action, visit the Hugging Face Spaces demo: https://huggingface.co/spaces/gradio/omni-mini\n\nFeel free to experiment with different models, audio processing techniques, or user interface designs to create your own unique conversational AI experiences!", "heading1": "Conclusion", "source_page_url": "https://gradio.app/guides/conversational-chatbot", "source_page_title": "Streaming - Conversational Chatbot Guide"}, {"text": "Automatic speech recognition (ASR), the conversion of spoken speech to text, is a very important and thriving area of machine learning. ASR algorithms run on practically every smartphone, and are becoming increasingly embedded in professional workflows, such as digital assistants for nurses and doctors. Because ASR algorithms are designed to be used directly by customers and end users, it is important to validate that they are behaving as expected when confronted with a wide variety of speech patterns (different accents, pitches, and background audio conditions).\n\nUsing `gradio`, you can easily build a demo of your ASR model and share that with a testing team, or test it yourself by speaking through the microphone on your device.\n\nThis tutorial will show how to take a pretrained speech-to-text model and deploy it with a Gradio interface. We will start with a **_full-context_** model, in which the user speaks the entire audio before the prediction runs. Then we will adapt the demo to make it **_streaming_**, meaning that the audio model will convert speech as you speak. \n\nPrerequisites\n\nMake sure you have the `gradio` Python package already [installed](/getting_started). You will also need a pretrained speech recognition model. In this tutorial, we will build demos from 2 ASR libraries:\n\n- Transformers (for this, `pip install torch transformers torchaudio`)\n\nMake sure you have at least one of these installed so that you can follow along the tutorial. You will also need `ffmpeg` [installed on your system](https://www.ffmpeg.org/download.html), if you do not already have it, to process files from the microphone.\n\nHere's how to build a real time speech recognition (ASR) app:\n\n1. [Set up the Transformers ASR Model](1-set-up-the-transformers-asr-model)\n2. [Create a Full-Context ASR Demo with Transformers](2-create-a-full-context-asr-demo-with-transformers)\n3. [Create a Streaming ASR Demo with Transformers](3-create-a-streaming-asr-demo-with-transformers)\n\n", "heading1": "Introduction", "source_page_url": "https://gradio.app/guides/real-time-speech-recognition", "source_page_title": "Streaming - Real Time Speech Recognition Guide"}, {"text": "First, you will need to have an ASR model that you have either trained yourself or you will need to download a pretrained model. In this tutorial, we will start by using a pretrained ASR model from the model, `whisper`.\n\nHere is the code to load `whisper` from Hugging Face `transformers`.\n\n```python\nfrom transformers import pipeline\n\np = pipeline(\"automatic-speech-recognition\", model=\"openai/whisper-base.en\")\n```\n\nThat's it!\n\n", "heading1": "1. Set up the Transformers ASR Model", "source_page_url": "https://gradio.app/guides/real-time-speech-recognition", "source_page_title": "Streaming - Real Time Speech Recognition Guide"}, {"text": "We will start by creating a _full-context_ ASR demo, in which the user speaks the full audio before using the ASR model to run inference. This is very easy with Gradio -- we simply create a function around the `pipeline` object above.\n\nWe will use `gradio`'s built in `Audio` component, configured to take input from the user's microphone and return a filepath for the recorded audio. The output component will be a plain `Textbox`.\n\n$code_asr\n$demo_asr\n\nThe `transcribe` function takes a single parameter, `audio`, which is a numpy array of the audio the user recorded. The `pipeline` object expects this in float32 format, so we convert it first to float32, and then extract the transcribed text.\n\n", "heading1": "2. Create a Full-Context ASR Demo with Transformers", "source_page_url": "https://gradio.app/guides/real-time-speech-recognition", "source_page_title": "Streaming - Real Time Speech Recognition Guide"}, {"text": "To make this a *streaming* demo, we need to make these changes:\n\n1. Set `streaming=True` in the `Audio` component\n2. Set `live=True` in the `Interface`\n3. Add a `state` to the interface to store the recorded audio of a user\n\nTip: You can also set `time_limit` and `stream_every` parameters in the interface. The `time_limit` caps the amount of time each user's stream can take. The default is 30 seconds so users won't be able to stream audio for more than 30 seconds. The `stream_every` parameter controls how frequently data is sent to your function. By default it is 0.5 seconds.\n\nTake a look below.\n\n$code_stream_asr\n\nNotice that we now have a state variable because we need to track all the audio history. `transcribe` gets called whenever there is a new small chunk of audio, but we also need to keep track of all the audio spoken so far in the state. As the interface runs, the `transcribe` function gets called, with a record of all the previously spoken audio in the `stream` and the new chunk of audio as `new_chunk`. We return the new full audio to be stored back in its current state, and we also return the transcription. Here, we naively append the audio together and call the `transcriber` object on the entire audio. You can imagine more efficient ways of handling this, such as re-processing only the last 5 seconds of audio whenever a new chunk of audio is received. \n\n$demo_stream_asr\n\nNow the ASR model will run inference as you speak! \n", "heading1": "3. Create a Streaming ASR Demo with Transformers", "source_page_url": "https://gradio.app/guides/real-time-speech-recognition", "source_page_title": "Streaming - Real Time Speech Recognition Guide"}, {"text": "Just like the classic Magic 8 Ball, a user should ask it a question orally and then wait for a response. Under the hood, we'll use Whisper to transcribe the audio and then use an LLM to generate a magic-8-ball-style answer. Finally, we'll use Parler TTS to read the response aloud.\n\n", "heading1": "The Overview", "source_page_url": "https://gradio.app/guides/streaming-ai-generated-audio", "source_page_title": "Streaming - Streaming Ai Generated Audio Guide"}, {"text": "First let's define the UI and put placeholders for all the python logic.\n\n```python\nimport gradio as gr\n\nwith gr.Blocks() as block:\n gr.HTML(\n f\"\"\"\n

Magic 8 Ball \ud83c\udfb1

\n

Ask a question and receive wisdom

\n

Powered by Parler-TTS\n \"\"\"\n )\n with gr.Group():\n with gr.Row():\n audio_out = gr.Audio(label=\"Spoken Answer\", streaming=True, autoplay=True)\n answer = gr.Textbox(label=\"Answer\")\n state = gr.State()\n with gr.Row():\n audio_in = gr.Audio(label=\"Speak your question\", sources=\"microphone\", type=\"filepath\")\n\n audio_in.stop_recording(generate_response, audio_in, [state, answer, audio_out])\\\n .then(fn=read_response, inputs=state, outputs=[answer, audio_out])\n\nblock.launch()\n```\n\nWe're placing the output Audio and Textbox components and the input Audio component in separate rows. In order to stream the audio from the server, we'll set `streaming=True` in the output Audio component. We'll also set `autoplay=True` so that the audio plays as soon as it's ready.\nWe'll be using the Audio input component's `stop_recording` event to trigger our application's logic when a user stops recording from their microphone.\n\nWe're separating the logic into two parts. First, `generate_response` will take the recorded audio, transcribe it and generate a response with an LLM. We're going to store the response in a `gr.State` variable that then gets passed to the `read_response` function that generates the audio.\n\nWe're doing this in two parts because only `read_response` will require a GPU. Our app will run on Hugging Faces [ZeroGPU](https://huggingface.co/zero-gpu-explorers) which has time-based quotas. Since generating the response can be done with Hugging Face's Inference API, we shouldn't include that code in our GPU func", "heading1": "The UI", "source_page_url": "https://gradio.app/guides/streaming-ai-generated-audio", "source_page_title": "Streaming - Streaming Ai Generated Audio Guide"}, {"text": "GPU](https://huggingface.co/zero-gpu-explorers) which has time-based quotas. Since generating the response can be done with Hugging Face's Inference API, we shouldn't include that code in our GPU function as it will needlessly use our GPU quota.\n\n", "heading1": "The UI", "source_page_url": "https://gradio.app/guides/streaming-ai-generated-audio", "source_page_title": "Streaming - Streaming Ai Generated Audio Guide"}, {"text": "As mentioned above, we'll use [Hugging Face's Inference API](https://huggingface.co/docs/huggingface_hub/guides/inference) to transcribe the audio and generate a response from an LLM. After instantiating the client, I use the `automatic_speech_recognition` method (this automatically uses Whisper running on Hugging Face's Inference Servers) to transcribe the audio. Then I pass the question to an LLM (Mistal-7B-Instruct) to generate a response. We are prompting the LLM to act like a magic 8 ball with the system message.\n\nOur `generate_response` function will also send empty updates to the output textbox and audio components (returning `None`). \nThis is because I want the Gradio progress tracker to be displayed over the components but I don't want to display the answer until the audio is ready.\n\n\n```python\nfrom huggingface_hub import InferenceClient\n\nclient = InferenceClient(token=os.getenv(\"HF_TOKEN\"))\n\ndef generate_response(audio):\n gr.Info(\"Transcribing Audio\", duration=5)\n question = client.automatic_speech_recognition(audio).text\n\n messages = [{\"role\": \"system\", \"content\": (\"You are a magic 8 ball.\"\n \"Someone will present to you a situation or question and your job \"\n \"is to answer with a cryptic adage or proverb such as \"\n \"'curiosity killed the cat' or 'The early bird gets the worm'.\"\n \"Keep your answers short and do not include the phrase 'Magic 8 Ball' in your response. If the question does not make sense or is off-topic, say 'Foolish questions get foolish answers.'\"\n \"For example, 'Magic 8 Ball, should I get a dog?', 'A dog is ready for you but are you ready for the dog?'\")},\n {\"role\": \"user\", \"content\": f\"Magic 8 Ball please answer this question - {question}\"}]\n \n response = client.chat_completion(messages,", "heading1": "The Logic", "source_page_url": "https://gradio.app/guides/streaming-ai-generated-audio", "source_page_title": "Streaming - Streaming Ai Generated Audio Guide"}, {"text": "for you but are you ready for the dog?'\")},\n {\"role\": \"user\", \"content\": f\"Magic 8 Ball please answer this question - {question}\"}]\n \n response = client.chat_completion(messages, max_tokens=64, seed=random.randint(1, 5000),\n model=\"mistralai/Mistral-7B-Instruct-v0.3\")\n\n response = response.choices[0].message.content.replace(\"Magic 8 Ball\", \"\").replace(\":\", \"\")\n return response, None, None\n```\n\n\nNow that we have our text response, we'll read it aloud with Parler TTS. The `read_response` function will be a python generator that yields the next chunk of audio as it's ready.\n\n\nWe'll be using the [Mini v0.1](https://huggingface.co/parler-tts/parler_tts_mini_v0.1) for the feature extraction but the [Jenny fine tuned version](https://huggingface.co/parler-tts/parler-tts-mini-jenny-30H) for the voice. This is so that the voice is consistent across generations.\n\n\nStreaming audio with transformers requires a custom Streamer class. You can see the implementation [here](https://huggingface.co/spaces/gradio/magic-8-ball/blob/main/streamer.py). Additionally, we'll convert the output to bytes so that it can be streamed faster from the backend. \n\n\n```python\nfrom streamer import ParlerTTSStreamer\nfrom transformers import AutoTokenizer, AutoFeatureExtractor, set_seed\nimport numpy as np\nimport spaces\nimport torch\nfrom threading import Thread\n\n\ndevice = \"cuda:0\" if torch.cuda.is_available() else \"mps\" if torch.backends.mps.is_available() else \"cpu\"\ntorch_dtype = torch.float16 if device != \"cpu\" else torch.float32\n\nrepo_id = \"parler-tts/parler_tts_mini_v0.1\"\n\njenny_repo_id = \"ylacombe/parler-tts-mini-jenny-30H\"\n\nmodel = ParlerTTSForConditionalGeneration.from_pretrained(\n jenny_repo_id, torch_dtype=torch_dtype, low_cpu_mem_usage=True\n).to(device)\n\ntokenizer = AutoTokenizer.from_pretrained(repo_id)\nfeature_extractor = AutoFeatureExtractor.from_pretrained(repo_id)\n\nsampling_rate = model.audio_encoder.config.sampling_rate\nf", "heading1": "The Logic", "source_page_url": "https://gradio.app/guides/streaming-ai-generated-audio", "source_page_title": "Streaming - Streaming Ai Generated Audio Guide"}, {"text": "sage=True\n).to(device)\n\ntokenizer = AutoTokenizer.from_pretrained(repo_id)\nfeature_extractor = AutoFeatureExtractor.from_pretrained(repo_id)\n\nsampling_rate = model.audio_encoder.config.sampling_rate\nframe_rate = model.audio_encoder.config.frame_rate\n\n@spaces.GPU\ndef read_response(answer):\n\n play_steps_in_s = 2.0\n play_steps = int(frame_rate * play_steps_in_s)\n\n description = \"Jenny speaks at an average pace with a calm delivery in a very confined sounding environment with clear audio quality.\"\n description_tokens = tokenizer(description, return_tensors=\"pt\").to(device)\n\n streamer = ParlerTTSStreamer(model, device=device, play_steps=play_steps)\n prompt = tokenizer(answer, return_tensors=\"pt\").to(device)\n\n generation_kwargs = dict(\n input_ids=description_tokens.input_ids,\n prompt_input_ids=prompt.input_ids,\n streamer=streamer,\n do_sample=True,\n temperature=1.0,\n min_new_tokens=10,\n )\n\n set_seed(42)\n thread = Thread(target=model.generate, kwargs=generation_kwargs)\n thread.start()\n\n for new_audio in streamer:\n print(f\"Sample of length: {round(new_audio.shape[0] / sampling_rate, 2)} seconds\")\n yield answer, numpy_to_mp3(new_audio, sampling_rate=sampling_rate)\n```\n\n", "heading1": "The Logic", "source_page_url": "https://gradio.app/guides/streaming-ai-generated-audio", "source_page_title": "Streaming - Streaming Ai Generated Audio Guide"}, {"text": "You can see our final application [here](https://huggingface.co/spaces/gradio/magic-8-ball)!\n\n\n", "heading1": "Conclusion", "source_page_url": "https://gradio.app/guides/streaming-ai-generated-audio", "source_page_title": "Streaming - Streaming Ai Generated Audio Guide"}, {"text": "First, we'll install the following requirements in our system:\n\n```\nopencv-python\ntorch\ntransformers>=4.43.0\nspaces\n```\n\nThen, we'll download the model from the Hugging Face Hub:\n\n```python\nfrom transformers import RTDetrForObjectDetection, RTDetrImageProcessor\n\nimage_processor = RTDetrImageProcessor.from_pretrained(\"PekingU/rtdetr_r50vd\")\nmodel = RTDetrForObjectDetection.from_pretrained(\"PekingU/rtdetr_r50vd\").to(\"cuda\")\n```\nWe're moving the model to the GPU. We'll be deploying our model to Hugging Face Spaces and running the inference in the [free ZeroGPU cluster](https://huggingface.co/zero-gpu-explorers). \n\n\n", "heading1": "Setting up the Model", "source_page_url": "https://gradio.app/guides/object-detection-from-video", "source_page_title": "Streaming - Object Detection From Video Guide"}, {"text": "Our inference function will accept a video and a desired confidence threshold.\nObject detection models identify many objects and assign a confidence score to each object. The lower the confidence, the higher the chance of a false positive. So we will let our users set the confidence threshold.\n\nOur function will iterate over the frames in the video and run the RT-DETR model over each frame.\nWe will then draw the bounding boxes for each detected object in the frame and save the frame to a new output video.\nThe function will yield each output video in chunks of two seconds.\n\nIn order to keep inference times as low as possible on ZeroGPU (there is a time-based quota),\nwe will halve the original frames-per-second in the output video and resize the input frames to be half the original \nsize before running the model.\n\nThe code for the inference function is below - we'll go over it piece by piece.\n\n```python\nimport spaces\nimport cv2\nfrom PIL import Image\nimport torch\nimport time\nimport numpy as np\nimport uuid\n\nfrom draw_boxes import draw_bounding_boxes\n\nSUBSAMPLE = 2\n\n@spaces.GPU\ndef stream_object_detection(video, conf_threshold):\n cap = cv2.VideoCapture(video)\n\n This means we will output mp4 videos\n video_codec = cv2.VideoWriter_fourcc(*\"mp4v\") type: ignore\n fps = int(cap.get(cv2.CAP_PROP_FPS))\n\n desired_fps = fps // SUBSAMPLE\n width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) // 2\n height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) // 2\n\n iterating, frame = cap.read()\n\n n_frames = 0\n\n Use UUID to create a unique video file\n output_video_name = f\"output_{uuid.uuid4()}.mp4\"\n\n Output Video\n output_video = cv2.VideoWriter(output_video_name, video_codec, desired_fps, (width, height)) type: ignore\n batch = []\n\n while iterating:\n frame = cv2.resize( frame, (0,0), fx=0.5, fy=0.5)\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n if n_frames % SUBSAMPLE == 0:\n batch.append(frame)\n if len(batc", "heading1": "The Inference Function", "source_page_url": "https://gradio.app/guides/object-detection-from-video", "source_page_title": "Streaming - Object Detection From Video Guide"}, {"text": " frame = cv2.resize( frame, (0,0), fx=0.5, fy=0.5)\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n if n_frames % SUBSAMPLE == 0:\n batch.append(frame)\n if len(batch) == 2 * desired_fps:\n inputs = image_processor(images=batch, return_tensors=\"pt\").to(\"cuda\")\n\n with torch.no_grad():\n outputs = model(**inputs)\n\n boxes = image_processor.post_process_object_detection(\n outputs,\n target_sizes=torch.tensor([(height, width)] * len(batch)),\n threshold=conf_threshold)\n \n for i, (array, box) in enumerate(zip(batch, boxes)):\n pil_image = draw_bounding_boxes(Image.fromarray(array), box, model, conf_threshold)\n frame = np.array(pil_image)\n Convert RGB to BGR\n frame = frame[:, :, ::-1].copy()\n output_video.write(frame)\n\n batch = []\n output_video.release()\n yield output_video_name\n output_video_name = f\"output_{uuid.uuid4()}.mp4\"\n output_video = cv2.VideoWriter(output_video_name, video_codec, desired_fps, (width, height)) type: ignore\n\n iterating, frame = cap.read()\n n_frames += 1\n```\n\n1. **Reading from the Video**\n\nOne of the industry standards for creating videos in python is OpenCV so we will use it in this app.\n\nThe `cap` variable is how we will read from the input video. Whenever we call `cap.read()`, we are reading the next frame in the video.\n\nIn order to stream video in Gradio, we need to yield a different video file for each \"chunk\" of the output video.\nWe create the next video file to write to with the `output_video = cv2.VideoWriter(output_video_name, video_codec, desired_fps, (width, height))` line. The `video_codec` is how we specify the type of video file. Only \"mp4\" and \"ts\" files are supported for video sreaming at the moment.\n\n\n2. **The Inference Loop**\n\nFor each frame i", "heading1": "The Inference Function", "source_page_url": "https://gradio.app/guides/object-detection-from-video", "source_page_title": "Streaming - Object Detection From Video Guide"}, {"text": "dth, height))` line. The `video_codec` is how we specify the type of video file. Only \"mp4\" and \"ts\" files are supported for video sreaming at the moment.\n\n\n2. **The Inference Loop**\n\nFor each frame in the video, we will resize it to be half the size. OpenCV reads files in `BGR` format, so will convert to the expected `RGB` format of transfomers. That's what the first two lines of the while loop are doing. \n\nWe take every other frame and add it to a `batch` list so that the output video is half the original FPS. When the batch covers two seconds of video, we will run the model. The two second threshold was chosen to keep the processing time of each batch small enough so that video is smoothly displayed in the server while not requiring too many separate forward passes. In order for video streaming to work properly in Gradio, the batch size should be at least 1 second. \n\nWe run the forward pass of the model and then use the `post_process_object_detection` method of the model to scale the detected bounding boxes to the size of the input frame.\n\nWe make use of a custom function to draw the bounding boxes (source [here](https://huggingface.co/spaces/gradio/rt-detr-object-detection/blob/main/draw_boxes.pyL14)). We then have to convert from `RGB` to `BGR` before writing back to the output video.\n\nOnce we have finished processing the batch, we create a new output video file for the next batch.\n\n", "heading1": "The Inference Function", "source_page_url": "https://gradio.app/guides/object-detection-from-video", "source_page_title": "Streaming - Object Detection From Video Guide"}, {"text": "The UI code is pretty similar to other kinds of Gradio apps. \nWe'll use a standard two-column layout so that users can see the input and output videos side by side.\n\nIn order for streaming to work, we have to set `streaming=True` in the output video. Setting the video\nto autoplay is not necessary but it's a better experience for users.\n\n```python\nimport gradio as gr\n\nwith gr.Blocks() as app:\n gr.HTML(\n \"\"\"\n

\n Video Object Detection with RT-DETR\n

\n \"\"\")\n with gr.Row():\n with gr.Column():\n video = gr.Video(label=\"Video Source\")\n conf_threshold = gr.Slider(\n label=\"Confidence Threshold\",\n minimum=0.0,\n maximum=1.0,\n step=0.05,\n value=0.30,\n )\n with gr.Column():\n output_video = gr.Video(label=\"Processed Video\", streaming=True, autoplay=True)\n\n video.upload(\n fn=stream_object_detection,\n inputs=[video, conf_threshold],\n outputs=[output_video],\n )\n\n\n```\n\n\n", "heading1": "The Gradio Demo", "source_page_url": "https://gradio.app/guides/object-detection-from-video", "source_page_title": "Streaming - Object Detection From Video Guide"}, {"text": "You can check out our demo hosted on Hugging Face Spaces [here](https://huggingface.co/spaces/gradio/rt-detr-object-detection). \n\nIt is also embedded on this page below\n\n$demo_rt-detr-object-detection", "heading1": "Conclusion", "source_page_url": "https://gradio.app/guides/object-detection-from-video", "source_page_title": "Streaming - Object Detection From Video Guide"}, {"text": "Start by installing all the dependencies. Add the following lines to a `requirements.txt` file and run `pip install -r requirements.txt`:\n\n```bash\nopencv-python\nfastrtc\nonnxruntime-gpu\n```\n\nWe'll use the ONNX runtime to speed up YOLOv10 inference. This guide assumes you have access to a GPU. If you don't, change `onnxruntime-gpu` to `onnxruntime`. Without a GPU, the model will run slower, resulting in a laggy demo.\n\nWe'll use OpenCV for image manipulation and the [WebRTC](https://webrtc.org/) protocol to achieve near-zero latency.\n\n**Note**: If you want to deploy this app on any cloud provider, you'll need to use your Hugging Face token to connect to a TURN server. Learn more in this [guide](https://fastrtc.org/deployment/). If you're not familiar with TURN servers, consult this [guide](https://www.twilio.com/docs/stun-turn/faqfaq-what-is-nat).\n\n", "heading1": "Setting up", "source_page_url": "https://gradio.app/guides/object-detection-from-webcam-with-webrtc", "source_page_title": "Streaming - Object Detection From Webcam With Webrtc Guide"}, {"text": "We'll download the YOLOv10 model from the Hugging Face hub and instantiate a custom inference class to use this model. \n\nThe implementation of the inference class isn't covered in this guide, but you can find the source code [here](https://huggingface.co/spaces/freddyaboulton/webrtc-yolov10n/blob/main/inference.pyL9) if you're interested. This implementation borrows heavily from this [github repository](https://github.com/ibaiGorordo/ONNX-YOLOv8-Object-Detection).\n\nWe're using the `yolov10-n` variant because it has the lowest latency. See the [Performance](https://github.com/THU-MIG/yolov10?tab=readme-ov-fileperformance) section of the README in the YOLOv10 GitHub repository.\n\n```python\nfrom huggingface_hub import hf_hub_download\nfrom inference import YOLOv10\n\nmodel_file = hf_hub_download(\n repo_id=\"onnx-community/yolov10n\", filename=\"onnx/model.onnx\"\n)\n\nmodel = YOLOv10(model_file)\n\ndef detection(image, conf_threshold=0.3):\n image = cv2.resize(image, (model.input_width, model.input_height))\n new_image = model.detect_objects(image, conf_threshold)\n return new_image\n```\n\nOur inference function, `detection`, accepts a numpy array from the webcam and a desired confidence threshold. Object detection models like YOLO identify many objects and assign a confidence score to each. The lower the confidence, the higher the chance of a false positive. We'll let users adjust the confidence threshold.\n\nThe function returns a numpy array corresponding to the same input image with all detected objects in bounding boxes.\n\n", "heading1": "The Inference Function", "source_page_url": "https://gradio.app/guides/object-detection-from-webcam-with-webrtc", "source_page_title": "Streaming - Object Detection From Webcam With Webrtc Guide"}, {"text": "The Gradio demo is straightforward, but we'll implement a few specific features:\n\n1. Use the `WebRTC` custom component to ensure input and output are sent to/from the server with WebRTC. \n2. The [WebRTC](https://github.com/freddyaboulton/gradio-webrtc) component will serve as both an input and output component.\n3. Utilize the `time_limit` parameter of the `stream` event. This parameter sets a processing time for each user's stream. In a multi-user setting, such as on Spaces, we'll stop processing the current user's stream after this period and move on to the next. \n\nWe'll also apply custom CSS to center the webcam and slider on the page.\n\n```python\nimport gradio as gr\nfrom fastrtc import WebRTC\n\ncss = \"\"\".my-group {max-width: 600px !important; max-height: 600px !important;}\n .my-column {display: flex !important; justify-content: center !important; align-items: center !important;}\"\"\"\n\nwith gr.Blocks(css=css) as demo:\n gr.HTML(\n \"\"\"\n

\n YOLOv10 Webcam Stream (Powered by WebRTC \u26a1\ufe0f)\n

\n \"\"\"\n )\n with gr.Column(elem_classes=[\"my-column\"]):\n with gr.Group(elem_classes=[\"my-group\"]):\n image = WebRTC(label=\"Stream\", rtc_configuration=rtc_configuration)\n conf_threshold = gr.Slider(\n label=\"Confidence Threshold\",\n minimum=0.0,\n maximum=1.0,\n step=0.05,\n value=0.30,\n )\n\n image.stream(\n fn=detection, inputs=[image, conf_threshold], outputs=[image], time_limit=10\n )\n\nif __name__ == \"__main__\":\n demo.launch()\n```\n\n", "heading1": "The Gradio Demo", "source_page_url": "https://gradio.app/guides/object-detection-from-webcam-with-webrtc", "source_page_title": "Streaming - Object Detection From Webcam With Webrtc Guide"}, {"text": "Our app is hosted on Hugging Face Spaces [here](https://huggingface.co/spaces/freddyaboulton/webrtc-yolov10n). \n\nYou can use this app as a starting point to build real-time image applications with Gradio. Don't hesitate to open issues in the space or in the [FastRTC GitHub repo](https://github.com/gradio-app/fastrtc) if you have any questions or encounter problems.", "heading1": "Conclusion", "source_page_url": "https://gradio.app/guides/object-detection-from-webcam-with-webrtc", "source_page_title": "Streaming - Object Detection From Webcam With Webrtc Guide"}, {"text": "Modern voice applications should feel natural and responsive, moving beyond the traditional \"click-to-record\" pattern. By combining Groq's fast inference capabilities with automatic speech detection, we can create a more intuitive interaction model where users can simply start talking whenever they want to engage with the AI.\n\n> Credits: VAD and Gradio code inspired by [WillHeld's Diva-audio-chat](https://huggingface.co/spaces/WillHeld/diva-audio-chat/tree/main).\n\nIn this tutorial, you will learn how to create a multimodal Gradio and Groq app that has automatic speech detection. You can also watch the full video tutorial which includes a demo of the application:\n\n\n\n", "heading1": "Introduction", "source_page_url": "https://gradio.app/guides/automatic-voice-detection", "source_page_title": "Streaming - Automatic Voice Detection Guide"}, {"text": "Many voice apps currently work by the user clicking record, speaking, then stopping the recording. While this can be a powerful demo, the most natural mode of interaction with voice requires the app to dynamically detect when the user is speaking, so they can talk back and forth without having to continually click a record button. \n\nCreating a natural interaction with voice and text requires a dynamic and low-latency response. Thus, we need both automatic voice detection and fast inference. With @ricky0123/vad-web powering speech detection and Groq powering the LLM, both of these requirements are met. Groq provides a lightning fast response, and Gradio allows for easy creation of impressively functional apps.\n\nThis tutorial shows you how to build a calorie tracking app where you speak to an AI that automatically detects when you start and stop your response, and provides its own text response back to guide you with questions that allow it to give a calorie estimate of your last meal.\n\n", "heading1": "Background", "source_page_url": "https://gradio.app/guides/automatic-voice-detection", "source_page_title": "Streaming - Automatic Voice Detection Guide"}, {"text": "- **Gradio**: Provides the web interface and audio handling capabilities\n- **@ricky0123/vad-web**: Handles voice activity detection\n- **Groq**: Powers fast LLM inference for natural conversations\n- **Whisper**: Transcribes speech to text\n\nSetting Up the Environment\n\nFirst, let\u2019s install and import our essential libraries and set up a client for using the Groq API. Here\u2019s how to do it:\n\n`requirements.txt`\n```\ngradio\ngroq\nnumpy\nsoundfile\nlibrosa\nspaces\nxxhash\ndatasets\n```\n\n`app.py`\n```python\nimport groq\nimport gradio as gr\nimport soundfile as sf\nfrom dataclasses import dataclass, field\nimport os\n\nInitialize Groq client securely\napi_key = os.environ.get(\"GROQ_API_KEY\")\nif not api_key:\n raise ValueError(\"Please set the GROQ_API_KEY environment variable.\")\nclient = groq.Client(api_key=api_key)\n```\n\nHere, we\u2019re pulling in key libraries to interact with the Groq API, build a sleek UI with Gradio, and handle audio data. We\u2019re accessing the Groq API key securely with a key stored in an environment variable, which is a security best practice for avoiding leaking the API key.\n\n---\n\nState Management for Seamless Conversations\n\nWe need a way to keep track of our conversation history, so the chatbot remembers past interactions, and manage other states like whether recording is currently active. To do this, let\u2019s create an `AppState` class:\n\n```python\n@dataclass\nclass AppState:\n conversation: list = field(default_factory=list)\n stopped: bool = False\n model_outs: Any = None\n```\n\nOur `AppState` class is a handy tool for managing conversation history and tracking whether recording is on or off. Each instance will have its own fresh list of conversations, making sure chat history is isolated to each session. \n\n---\n\nTranscribing Audio with Whisper on Groq\n\nNext, we\u2019ll create a function to transcribe the user\u2019s audio input into text using Whisper, a powerful transcription model hosted on Groq. This transcription will also help us determine whether there\u2019s meani", "heading1": "Key Components", "source_page_url": "https://gradio.app/guides/automatic-voice-detection", "source_page_title": "Streaming - Automatic Voice Detection Guide"}, {"text": "e\u2019ll create a function to transcribe the user\u2019s audio input into text using Whisper, a powerful transcription model hosted on Groq. This transcription will also help us determine whether there\u2019s meaningful speech in the input. Here\u2019s how:\n\n```python\ndef transcribe_audio(client, file_name):\n if file_name is None:\n return None\n\n try:\n with open(file_name, \"rb\") as audio_file:\n response = client.audio.transcriptions.with_raw_response.create(\n model=\"whisper-large-v3-turbo\",\n file=(\"audio.wav\", audio_file),\n response_format=\"verbose_json\",\n )\n completion = process_whisper_response(response.parse())\n return completion\n except Exception as e:\n print(f\"Error in transcription: {e}\")\n return f\"Error in transcription: {str(e)}\"\n```\n\nThis function opens the audio file and sends it to Groq\u2019s Whisper model for transcription, requesting detailed JSON output. verbose_json is needed to get information to determine if speech was included in the audio. We also handle any potential errors so our app doesn\u2019t fully crash if there\u2019s an issue with the API request. \n\n```python\ndef process_whisper_response(completion):\n \"\"\"\n Process Whisper transcription response and return text or null based on no_speech_prob\n \n Args:\n completion: Whisper transcription response object\n \n Returns:\n str or None: Transcribed text if no_speech_prob <= 0.7, otherwise None\n \"\"\"\n if completion.segments and len(completion.segments) > 0:\n no_speech_prob = completion.segments[0].get('no_speech_prob', 0)\n print(\"No speech prob:\", no_speech_prob)\n\n if no_speech_prob > 0.7:\n return None\n \n return completion.text.strip()\n \n return None\n```\n\nWe also need to interpret the audio data response. The process_whisper_response function takes the resulting completion from Whisper and checks if the audio was j", "heading1": "Key Components", "source_page_url": "https://gradio.app/guides/automatic-voice-detection", "source_page_title": "Streaming - Automatic Voice Detection Guide"}, {"text": "ext.strip()\n \n return None\n```\n\nWe also need to interpret the audio data response. The process_whisper_response function takes the resulting completion from Whisper and checks if the audio was just background noise or had actual speaking that was transcribed. It uses a threshold of 0.7 to interpret the no_speech_prob, and will return None if there was no speech. Otherwise, it will return the text transcript of the conversational response from the human.\n\n\n---\n\nAdding Conversational Intelligence with LLM Integration\n\nOur chatbot needs to provide intelligent, friendly responses that flow naturally. We\u2019ll use a Groq-hosted Llama-3.2 for this:\n\n```python\ndef generate_chat_completion(client, history):\n messages = []\n messages.append(\n {\n \"role\": \"system\",\n \"content\": \"In conversation with the user, ask questions to estimate and provide (1) total calories, (2) protein, carbs, and fat in grams, (3) fiber and sugar content. Only ask *one question at a time*. Be conversational and natural.\",\n }\n )\n\n for message in history:\n messages.append(message)\n\n try:\n completion = client.chat.completions.create(\n model=\"llama-3.2-11b-vision-preview\",\n messages=messages,\n )\n return completion.choices[0].message.content\n except Exception as e:\n return f\"Error in generating chat completion: {str(e)}\"\n```\n\nWe\u2019re defining a system prompt to guide the chatbot\u2019s behavior, ensuring it asks one question at a time and keeps things conversational. This setup also includes error handling to ensure the app gracefully manages any issues.\n\n---\n\nVoice Activity Detection for Hands-Free Interaction\n\nTo make our chatbot hands-free, we\u2019ll add Voice Activity Detection (VAD) to automatically detect when someone starts or stops speaking. Here\u2019s how to implement it using ONNX in JavaScript:\n\n```javascript\nasync function main() {\n const script1 = document.createElement(\"script\");\n scrip", "heading1": "Key Components", "source_page_url": "https://gradio.app/guides/automatic-voice-detection", "source_page_title": "Streaming - Automatic Voice Detection Guide"}, {"text": "ly detect when someone starts or stops speaking. Here\u2019s how to implement it using ONNX in JavaScript:\n\n```javascript\nasync function main() {\n const script1 = document.createElement(\"script\");\n script1.src = \"https://cdn.jsdelivr.net/npm/onnxruntime-web@1.14.0/dist/ort.js\";\n document.head.appendChild(script1)\n const script2 = document.createElement(\"script\");\n script2.onload = async () => {\n console.log(\"vad loaded\");\n var record = document.querySelector('.record-button');\n record.textContent = \"Just Start Talking!\"\n \n const myvad = await vad.MicVAD.new({\n onSpeechStart: () => {\n var record = document.querySelector('.record-button');\n var player = document.querySelector('streaming-out')\n if (record != null && (player == null || player.paused)) {\n record.click();\n }\n },\n onSpeechEnd: (audio) => {\n var stop = document.querySelector('.stop-button');\n if (stop != null) {\n stop.click();\n }\n }\n })\n myvad.start()\n }\n script2.src = \"https://cdn.jsdelivr.net/npm/@ricky0123/vad-web@0.0.7/dist/bundle.min.js\";\n}\n```\n\nThis script loads our VAD model and sets up functions to start and stop recording automatically. When the user starts speaking, it triggers the recording, and when they stop, it ends the recording.\n\n---\n\nBuilding a User Interface with Gradio\n\nNow, let\u2019s create an intuitive and visually appealing user interface with Gradio. This interface will include an audio input for capturing voice, a chat window for displaying responses, and state management to keep things synchronized.\n\n```python\nwith gr.Blocks() as demo:\n with gr.Row():\n input_audio = gr.Audio(\n label=\"Input Audio\",\n sources=[\"microphone\"],\n type=\"numpy\",\n streaming=False,\n waveform_options=gr.WaveformOptions(waveform_color=\"B83A4B\"),\n )\n with gr.Row():\n chatbot = gr.Chatbot(label=\"Conversation\")\n state = g", "heading1": "Key Components", "source_page_url": "https://gradio.app/guides/automatic-voice-detection", "source_page_title": "Streaming - Automatic Voice Detection Guide"}, {"text": "\",\n streaming=False,\n waveform_options=gr.WaveformOptions(waveform_color=\"B83A4B\"),\n )\n with gr.Row():\n chatbot = gr.Chatbot(label=\"Conversation\")\n state = gr.State(value=AppState())\ndemo.launch(theme=theme, js=js)\n```\n\nIn this code block, we\u2019re using Gradio\u2019s `Blocks` API to create an interface with an audio input, a chat display, and an application state manager. The color customization for the waveform adds a nice visual touch.\n\n---\n\nHandling Recording and Responses\n\nFinally, let\u2019s link the recording and response components to ensure the app reacts smoothly to user inputs and provides responses in real-time.\n\n```python\n stream = input_audio.start_recording(\n process_audio,\n [input_audio, state],\n [input_audio, state],\n )\n respond = input_audio.stop_recording(\n response, [state, input_audio], [state, chatbot]\n )\n```\n\nThese lines set up event listeners for starting and stopping the recording, processing the audio input, and generating responses. By linking these events, we create a cohesive experience where users can simply talk, and the chatbot handles the rest.\n\n---\n\n", "heading1": "Key Components", "source_page_url": "https://gradio.app/guides/automatic-voice-detection", "source_page_title": "Streaming - Automatic Voice Detection Guide"}, {"text": "1. When you open the app, the VAD system automatically initializes and starts listening for speech\n2. As soon as you start talking, it triggers the recording automatically\n3. When you stop speaking, the recording ends and:\n - The audio is transcribed using Whisper\n - The transcribed text is sent to the LLM\n - The LLM generates a response about calorie tracking\n - The response is displayed in the chat interface\n4. This creates a natural back-and-forth conversation where you can simply talk about your meals and get instant feedback on nutritional content\n\nThis app demonstrates how to create a natural voice interface that feels responsive and intuitive. By combining Groq's fast inference with automatic speech detection, we've eliminated the need for manual recording controls while maintaining high-quality interactions. The result is a practical calorie tracking assistant that users can simply talk to as naturally as they would to a human nutritionist.\n\nLink to GitHub repository: [Groq Gradio Basics](https://github.com/bklieger-groq/gradio-groq-basics/tree/main/calorie-tracker)", "heading1": "Summary", "source_page_url": "https://gradio.app/guides/automatic-voice-detection", "source_page_title": "Streaming - Automatic Voice Detection Guide"}, {"text": "Gradio includes more than 30 pre-built components (as well as many [community-built _custom components_](https://www.gradio.app/custom-components/gallery)) that can be used as inputs or outputs in your demo. These components correspond to common data types in machine learning and data science, e.g. the `gr.Image` component is designed to handle input or output images, the `gr.Label` component displays classification labels and probabilities, the `gr.LinePlot` component displays line plots, and so on. \n\n", "heading1": "Gradio Components", "source_page_url": "https://gradio.app/guides/the-interface-class", "source_page_title": "Building Interfaces - The Interface Class Guide"}, {"text": "We used the default versions of the `gr.Textbox` and `gr.Slider`, but what if you want to change how the UI components look or behave?\n\nLet's say you want to customize the slider to have values from 1 to 10, with a default of 2. And you wanted to customize the output text field \u2014 you want it to be larger and have a label.\n\nIf you use the actual classes for `gr.Textbox` and `gr.Slider` instead of the string shortcuts, you have access to much more customizability through component attributes.\n\n$code_hello_world_2\n$demo_hello_world_2\n\n", "heading1": "Components Attributes", "source_page_url": "https://gradio.app/guides/the-interface-class", "source_page_title": "Building Interfaces - The Interface Class Guide"}, {"text": "Suppose you had a more complex function, with multiple outputs as well. In the example below, we define a function that takes a string, boolean, and number, and returns a string and number. \n\n$code_hello_world_3\n$demo_hello_world_3\n\nJust as each component in the `inputs` list corresponds to one of the parameters of the function, in order, each component in the `outputs` list corresponds to one of the values returned by the function, in order.\n\n", "heading1": "Multiple Input and Output Components", "source_page_url": "https://gradio.app/guides/the-interface-class", "source_page_title": "Building Interfaces - The Interface Class Guide"}, {"text": "Gradio supports many types of components, such as `Image`, `DataFrame`, `Video`, or `Label`. Let's try an image-to-image function to get a feel for these!\n\n$code_sepia_filter\n$demo_sepia_filter\n\nWhen using the `Image` component as input, your function will receive a NumPy array with the shape `(height, width, 3)`, where the last dimension represents the RGB values. We'll return an image as well in the form of a NumPy array. \n\nGradio handles the preprocessing and postprocessing to convert images to NumPy arrays and vice versa. You can also control the preprocessing performed with the `type=` keyword argument. For example, if you wanted your function to take a file path to an image instead of a NumPy array, the input `Image` component could be written as:\n\n```python\ngr.Image(type=\"filepath\")\n```\n\nYou can read more about the built-in Gradio components and how to customize them in the [Gradio docs](https://gradio.app/docs).\n\n", "heading1": "An Image Example", "source_page_url": "https://gradio.app/guides/the-interface-class", "source_page_title": "Building Interfaces - The Interface Class Guide"}, {"text": "You can provide example data that a user can easily load into `Interface`. This can be helpful to demonstrate the types of inputs the model expects, as well as to provide a way to explore your dataset in conjunction with your model. To load example data, you can provide a **nested list** to the `examples=` keyword argument of the Interface constructor. Each sublist within the outer list represents a data sample, and each element within the sublist represents an input for each input component. The format of example data for each component is specified in the [Docs](https://gradio.app/docscomponents).\n\n$code_calculator\n$demo_calculator\n\nYou can load a large dataset into the examples to browse and interact with the dataset through Gradio. The examples will be automatically paginated (you can configure this through the `examples_per_page` argument of `Interface`).\n\nContinue learning about examples in the [More On Examples](https://gradio.app/guides/more-on-examples) guide.\n\n", "heading1": "Example Inputs", "source_page_url": "https://gradio.app/guides/the-interface-class", "source_page_title": "Building Interfaces - The Interface Class Guide"}, {"text": "In the previous example, you may have noticed the `title=` and `description=` keyword arguments in the `Interface` constructor that helps users understand your app.\n\nThere are three arguments in the `Interface` constructor to specify where this content should go:\n\n- `title`: which accepts text and can display it at the very top of interface, and also becomes the page title.\n- `description`: which accepts text, markdown or HTML and places it right under the title.\n- `article`: which also accepts text, markdown or HTML and places it below the interface.\n\n![annotated](https://github.com/gradio-app/gradio/blob/main/guides/assets/annotated.png?raw=true)\n\nAnother useful keyword argument is `label=`, which is present in every `Component`. This modifies the label text at the top of each `Component`. You can also add the `info=` keyword argument to form elements like `Textbox` or `Radio` to provide further information on their usage.\n\n```python\ngr.Number(label='Age', info='In years, must be greater than 0')\n```\n\n", "heading1": "Descriptive Content", "source_page_url": "https://gradio.app/guides/the-interface-class", "source_page_title": "Building Interfaces - The Interface Class Guide"}, {"text": "If your prediction function takes many inputs, you may want to hide some of them within a collapsed accordion to avoid cluttering the UI. The `Interface` class takes an `additional_inputs` argument which is similar to `inputs` but any input components included here are not visible by default. The user must click on the accordion to show these components. The additional inputs are passed into the prediction function, in order, after the standard inputs.\n\nYou can customize the appearance of the accordion by using the optional `additional_inputs_accordion` argument, which accepts a string (in which case, it becomes the label of the accordion), or an instance of the `gr.Accordion()` class (e.g. this lets you control whether the accordion is open or closed by default).\n\nHere's an example:\n\n$code_interface_with_additional_inputs\n$demo_interface_with_additional_inputs\n\n", "heading1": "Additional Inputs within an Accordion", "source_page_url": "https://gradio.app/guides/the-interface-class", "source_page_title": "Building Interfaces - The Interface Class Guide"}, {"text": "To create a demo that has both the input and the output components, you simply need to set the values of the `inputs` and `outputs` parameter in `Interface()`. Here's an example demo of a simple image filter:\n\n$code_sepia_filter\n$demo_sepia_filter\n\n", "heading1": "Standard demos", "source_page_url": "https://gradio.app/guides/four-kinds-of-interfaces", "source_page_title": "Building Interfaces - Four Kinds Of Interfaces Guide"}, {"text": "What about demos that only contain outputs? In order to build such a demo, you simply set the value of the `inputs` parameter in `Interface()` to `None`. Here's an example demo of a mock image generation model:\n\n$code_fake_gan_no_input\n$demo_fake_gan_no_input\n\n", "heading1": "Output-only demos", "source_page_url": "https://gradio.app/guides/four-kinds-of-interfaces", "source_page_title": "Building Interfaces - Four Kinds Of Interfaces Guide"}, {"text": "Similarly, to create a demo that only contains inputs, set the value of `outputs` parameter in `Interface()` to be `None`. Here's an example demo that saves any uploaded image to disk:\n\n$code_save_file_no_output\n$demo_save_file_no_output\n\n", "heading1": "Input-only demos", "source_page_url": "https://gradio.app/guides/four-kinds-of-interfaces", "source_page_title": "Building Interfaces - Four Kinds Of Interfaces Guide"}, {"text": "A demo that has a single component as both the input and the output. It can simply be created by setting the values of the `inputs` and `outputs` parameter as the same component. Here's an example demo of a text generation model:\n\n$code_unified_demo_text_generation\n$demo_unified_demo_text_generation\n\nIt may be the case that none of the 4 cases fulfill your exact needs. In this case, you need to use the `gr.Blocks()` approach!", "heading1": "Unified demos", "source_page_url": "https://gradio.app/guides/four-kinds-of-interfaces", "source_page_title": "Building Interfaces - Four Kinds Of Interfaces Guide"}, {"text": "You can make interfaces automatically refresh by setting `live=True` in the interface. Now the interface will recalculate as soon as the user input changes.\n\n$code_calculator_live\n$demo_calculator_live\n\nNote there is no submit button, because the interface resubmits automatically on change.\n\n", "heading1": "Live Interfaces", "source_page_url": "https://gradio.app/guides/reactive-interfaces", "source_page_title": "Building Interfaces - Reactive Interfaces Guide"}, {"text": "Some components have a \"streaming\" mode, such as `Audio` component in microphone mode, or the `Image` component in webcam mode. Streaming means data is sent continuously to the backend and the `Interface` function is continuously being rerun.\n\nThe difference between `gr.Audio(source='microphone')` and `gr.Audio(source='microphone', streaming=True)`, when both are used in `gr.Interface(live=True)`, is that the first `Component` will automatically submit data and run the `Interface` function when the user stops recording, whereas the second `Component` will continuously send data and run the `Interface` function _during_ recording.\n\nHere is example code of streaming images from the webcam.\n\n$code_stream_frames\n\nStreaming can also be done in an output component. A `gr.Audio(streaming=True)` output component can take a stream of audio data yielded piece-wise by a generator function and combines them into a single audio file. For a detailed example, see our guide on performing [automatic speech recognition](/guides/real-time-speech-recognition) with Gradio.\n", "heading1": "Streaming Components", "source_page_url": "https://gradio.app/guides/reactive-interfaces", "source_page_title": "Building Interfaces - Reactive Interfaces Guide"}, {"text": "Adding examples to an Interface is as easy as providing a list of lists to the `examples`\nkeyword argument.\nEach sublist is a data sample, where each element corresponds to an input of the prediction function.\nThe inputs must be ordered in the same order as the prediction function expects them.\n\nIf your interface only has one input component, then you can provide your examples as a regular list instead of a list of lists.\n\nLoading Examples from a Directory\n\nYou can also specify a path to a directory containing your examples. If your Interface takes only a single file-type input, e.g. an image classifier, you can simply pass a directory filepath to the `examples=` argument, and the `Interface` will load the images in the directory as examples.\nIn the case of multiple inputs, this directory must\ncontain a log.csv file with the example values.\nIn the context of the calculator demo, we can set `examples='/demo/calculator/examples'` and in that directory we include the following `log.csv` file:\n\n```csv\nnum,operation,num2\n5,\"add\",3\n4,\"divide\",2\n5,\"multiply\",3\n```\n\nThis can be helpful when browsing flagged data. Simply point to the flagged directory and the `Interface` will load the examples from the flagged data.\n\nProviding Partial Examples\n\nSometimes your app has many input components, but you would only like to provide examples for a subset of them. In order to exclude some inputs from the examples, pass `None` for all data samples corresponding to those particular components.\n\n", "heading1": "Providing Examples", "source_page_url": "https://gradio.app/guides/more-on-examples", "source_page_title": "Building Interfaces - More On Examples Guide"}, {"text": "You may wish to provide some cached examples of your model for users to quickly try out, in case your model takes a while to run normally.\nIf `cache_examples=True`, your Gradio app will run all of the examples and save the outputs when you call the `launch()` method. This data will be saved in a directory called `gradio_cached_examples` in your working directory by default. You can also set this directory with the `GRADIO_EXAMPLES_CACHE` environment variable, which can be either an absolute path or a relative path to your working directory.\n\nWhenever a user clicks on an example, the output will automatically be populated in the app now, using data from this cached directory instead of actually running the function. This is useful so users can quickly try out your model without adding any load!\n\nAlternatively, you can set `cache_examples=\"lazy\"`. This means that each particular example will only get cached after it is first used (by any user) in the Gradio app. This is helpful if your prediction function is long-running and you do not want to wait a long time for your Gradio app to start.\n\nKeep in mind once the cache is generated, it will not be updated automatically in future launches. If the examples or function logic change, delete the cache folder to clear the cache and rebuild it with another `launch()`.\n", "heading1": "Caching examples", "source_page_url": "https://gradio.app/guides/more-on-examples", "source_page_title": "Building Interfaces - More On Examples Guide"}, {"text": "If the state is something that should be accessible to all function calls and all users, you can create a variable outside the function call and access it inside the function. For example, you may load a large model outside the function and use it inside the function so that every function call does not need to reload the model.\n\n$code_score_tracker\n\nIn the code above, the `scores` array is shared between all users. If multiple users are accessing this demo, their scores will all be added to the same list, and the returned top 3 scores will be collected from this shared reference.\n\n", "heading1": "Global State", "source_page_url": "https://gradio.app/guides/interface-state", "source_page_title": "Building Interfaces - Interface State Guide"}, {"text": "Another type of data persistence Gradio supports is session state, where data persists across multiple submits within a page session. However, data is _not_ shared between different users of your model. To store data in a session state, you need to do three things:\n\n1. Pass in an extra parameter into your function, which represents the state of the interface.\n2. At the end of the function, return the updated value of the state as an extra return value.\n3. Add the `'state'` input and `'state'` output components when creating your `Interface`\n\nHere's a simple app to illustrate session state - this app simply stores users previous submissions and displays them back to the user:\n\n\n$code_interface_state\n$demo_interface_state\n\n\nNotice how the state persists across submits within each page, but if you load this demo in another tab (or refresh the page), the demos will not share chat history. Here, we could not store the submission history in a global variable, otherwise the submission history would then get jumbled between different users.\n\nThe initial value of the `State` is `None` by default. If you pass a parameter to the `value` argument of `gr.State()`, it is used as the default value of the state instead. \n\nNote: the `Interface` class only supports a single session state variable (though it can be a list with multiple elements). For more complex use cases, you can use Blocks, [which supports multiple `State` variables](/guides/state-in-blocks/). Alternatively, if you are building a chatbot that maintains user state, consider using the `ChatInterface` abstraction, [which manages state automatically](/guides/creating-a-chatbot-fast).\n", "heading1": "Session State", "source_page_url": "https://gradio.app/guides/interface-state", "source_page_title": "Building Interfaces - Interface State Guide"}]