text
stringlengths
0
2k
heading1
stringlengths
4
79
source_page_url
stringclasses
183 values
source_page_title
stringclasses
183 values
Let's update the previous example to include a log out button: ```python import gradio as gr def update_message(request: gr.Request): return f"Welcome, {request.username}" with gr.Blocks() as demo: m = gr.Markdown() logout_button = gr.Button("Logout", link="/logout") demo.load(update_message, None, m) demo.launch(auth=[("Pete", "Pete"), ("Dawood", "Dawood")]) ``` By 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`). Note: 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). OAuth (Login via Hugging Face) Gradio 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. To enable OAuth, you must set `hf_oauth: true` as a Space metadata in your README.md file. This will register your Space as an OAuth application on Hugging Face. Next, you can use `gr.LoginButton` to add a login button to your Gradio app. Once a user is logged in with their HF account, you can retrieve their profile by adding a parameter of type `gr.OAuthProfile` to any Gradio function. The user profile will be automatically injected as a parameter value. If you want to perform actions on behalf of the user (e.g. list user's private repos, create repo, etc.), you can retrieve the user token by adding a parameter of type `gr.OAuthToken`. You must def
Authentication
https://gradio.app/guides/sharing-your-app
Additional Features - Sharing Your App Guide
e. If you want to perform actions on behalf of the user (e.g. list user's private repos, create repo, etc.), you can retrieve the user token by adding a parameter of type `gr.OAuthToken`. You must define which scopes you will use in your Space metadata (see [documentation](https://huggingface.co/docs/hub/spaces-oauthscopes) for more details). Here is a short example: $code_login_with_huggingface When the user clicks on the login button, they get redirected in a new page to authorize your Space. <center> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio-guides/oauth_sign_in.png" style="width:300px; max-width:80%"> </center> Users can revoke access to their profile at any time in their [settings](https://huggingface.co/settings/connected-applications). As seen above, OAuth features are available only when your app runs in a Space. However, you often need to test your app locally 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. **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. OAuth (with external providers) It is also possible to authenticate with external OAuth pr
Authentication
https://gradio.app/guides/sharing-your-app
Additional Features - Sharing Your App Guide
erence is that the `gr.OAuthProfile` or `gr.OAuthToken` will be `None` in the corresponding functions. OAuth (with external providers) It 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`. Similar 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. First, let's show a simplistic example to illustrate the `auth_dependency` parameter: ```python from fastapi import FastAPI, Request import gradio as gr app = FastAPI() def get_user(request: Request): return request.headers.get("user") demo = gr.Interface(lambda s: f"Hello {s}!", "textbox", "textbox") app = gr.mount_gradio_app(app, demo, path="/demo", auth_dependency=get_user) if __name__ == '__main__': uvicorn.run(app) ``` In 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. Here'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)): ```python import os from authlib.integrations.starlette_client import OAuth, OAuthError from fastapi import FastA
Authentication
https://gradio.app/guides/sharing-your-app
Additional Features - Sharing Your App Guide
entials on the [Google Developer Console](https://console.cloud.google.com/project)): ```python import os from authlib.integrations.starlette_client import OAuth, OAuthError from fastapi import FastAPI, Depends, Request from starlette.config import Config from starlette.responses import RedirectResponse from starlette.middleware.sessions import SessionMiddleware import uvicorn import gradio as gr app = FastAPI() Replace these with your own OAuth settings GOOGLE_CLIENT_ID = "..." GOOGLE_CLIENT_SECRET = "..." SECRET_KEY = "..." config_data = {'GOOGLE_CLIENT_ID': GOOGLE_CLIENT_ID, 'GOOGLE_CLIENT_SECRET': GOOGLE_CLIENT_SECRET} starlette_config = Config(environ=config_data) oauth = OAuth(starlette_config) oauth.register( name='google', server_metadata_url='https://accounts.google.com/.well-known/openid-configuration', client_kwargs={'scope': 'openid email profile'}, ) SECRET_KEY = os.environ.get('SECRET_KEY') or "a_very_secret_key" app.add_middleware(SessionMiddleware, secret_key=SECRET_KEY) Dependency to get the current user def get_user(request: Request): user = request.session.get('user') if user: return user['name'] return None @app.get('/') def public(user: dict = Depends(get_user)): if user: return RedirectResponse(url='/gradio') else: return RedirectResponse(url='/login-demo') @app.route('/logout') async def logout(request: Request): request.session.pop('user', None) return RedirectResponse(url='/') @app.route('/login') async def login(request: Request): redirect_uri = request.url_for('auth') If your app is running on https, you should ensure that the `redirect_uri` is https, e.g. uncomment the following lines: from urllib.parse import urlparse, urlunparse redirect_uri = urlunparse(urlparse(str(redirect_uri))._replace(scheme='https')) return await oauth.google.authorize_redirect(request, redirect_uri) @app.route('/auth') async def auth(request: Reque
Authentication
https://gradio.app/guides/sharing-your-app
Additional Features - Sharing Your App Guide
direct_uri = urlunparse(urlparse(str(redirect_uri))._replace(scheme='https')) return await oauth.google.authorize_redirect(request, redirect_uri) @app.route('/auth') async def auth(request: Request): try: access_token = await oauth.google.authorize_access_token(request) except OAuthError: return RedirectResponse(url='/') request.session['user'] = dict(access_token)["userinfo"] return RedirectResponse(url='/') with gr.Blocks() as login_demo: gr.Button("Login", link="/login") app = gr.mount_gradio_app(app, login_demo, path="/login-demo") def greet(request: gr.Request): return f"Welcome to Gradio, {request.username}" with gr.Blocks() as main_demo: m = gr.Markdown("Welcome to Gradio!") gr.Button("Logout", link="/logout") main_demo.load(greet, None, m) app = gr.mount_gradio_app(app, main_demo, path="/gradio", auth_dependency=get_user) if __name__ == '__main__': uvicorn.run(app) ``` There 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).
Authentication
https://gradio.app/guides/sharing-your-app
Additional Features - Sharing Your App Guide
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).
MCP Servers
https://gradio.app/guides/sharing-your-app
Additional Features - Sharing Your App Guide
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).
Rate Limits
https://gradio.app/guides/sharing-your-app
Additional Features - Sharing Your App Guide
By default, Gradio collects certain analytics to help us better understand the usage of the `gradio` library. This includes the following information: * What environment the Gradio app is running on (e.g. Colab Notebook, Hugging Face Spaces) * What input/output components are being used in the Gradio app * Whether the Gradio app is utilizing certain advanced features, such as `auth` or `show_error` * The IP address which is used solely to measure the number of unique developers using Gradio * The version of Gradio that is running No 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. *Note*: this reflects the analytics policy as of `gradio>=4.32.0`.
Analytics
https://gradio.app/guides/sharing-your-app
Additional Features - Sharing Your App Guide
[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. Gradio apps can be easily served as PWAs by setting the `pwa=True` parameter in the `launch()` method. Here's an example: ```python import gradio as gr def greet(name): return "Hello " + name + "!" demo = gr.Interface(fn=greet, inputs="textbox", outputs="textbox") demo.launch(pwa=True) Launch your app as a PWA ``` This will generate a PWA that can be installed on your device. Here's how it looks: ![Installing PWA](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio-guides/install-pwa.gif) When you specify `favicon_path` in the `launch()` method, the icon will be used as the app's icon. Here's an example: ```python demo.launch(pwa=True, favicon_path="./hf-logo.svg") Use a custom icon for your PWA ``` ![Custom PWA Icon](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio-guides/pwa-favicon.png)
Progressive Web App (PWA)
https://gradio.app/guides/sharing-your-app
Additional Features - Sharing Your App Guide
You can initialize the `I18n` class with multiple language dictionaries to add custom translations: ```python import gradio as gr Create an I18n instance with translations for multiple languages i18n = gr.I18n( en={"greeting": "Hello, welcome to my app!", "submit": "Submit"}, es={"greeting": "¡Hola, bienvenido a mi aplicación!", "submit": "Enviar"}, fr={"greeting": "Bonjour, bienvenue dans mon application!", "submit": "Soumettre"} ) with gr.Blocks() as demo: Use the i18n method to translate the greeting gr.Markdown(i18n("greeting")) with gr.Row(): input_text = gr.Textbox(label="Input") output_text = gr.Textbox(label="Output") submit_btn = gr.Button(i18n("submit")) Pass the i18n instance to the launch method demo.launch(i18n=i18n) ```
Setting Up Translations
https://gradio.app/guides/internationalization
Additional Features - Internationalization Guide
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. If a translation isn't available for the user's locale, the system will fall back to English (if available) or display the key itself.
How It Works
https://gradio.app/guides/internationalization
Additional Features - Internationalization Guide
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.
Valid Locale Codes
https://gradio.app/guides/internationalization
Additional Features - Internationalization Guide
The following component properties typically support internationalization: - `description` - `info` - `title` - `placeholder` - `value` - `label` Note 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.
Supported Component Properties
https://gradio.app/guides/internationalization
Additional Features - Internationalization Guide
Client side functions are ideal for updating component properties (like visibility, placeholders, interactive state, or styling). Here's a basic example: ```py import gradio as gr with gr.Blocks() as demo: with gr.Row() as row: btn = gr.Button("Hide this row") This function runs in the browser without a server roundtrip btn.click( lambda: gr.Row(visible=False), None, row, js=True ) demo.launch() ```
When to Use Client Side Functions
https://gradio.app/guides/client-side-functions
Additional Features - Client Side Functions Guide
Client side functions have some important restrictions: * They can only update component properties (not values) * They cannot take any inputs Here are some functions that will work with `js=True`: ```py Simple property updates lambda: gr.Textbox(lines=4) Multiple component updates lambda: [gr.Textbox(lines=4), gr.Button(interactive=False)] Using gr.update() for property changes lambda: gr.update(visible=True, interactive=False) ``` We 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).
Limitations
https://gradio.app/guides/client-side-functions
Additional Features - Client Side Functions Guide
Here's a more complete example showing how client side functions can improve the user experience: $code_todo_list_js
Complete Example
https://gradio.app/guides/client-side-functions
Additional Features - Client Side Functions Guide
When you set `js=True`, Gradio: 1. Transpiles your Python function to JavaScript 2. Runs the function directly in the browser 3. Still sends the request to the server (for consistency and to handle any side effects) This provides immediate visual feedback while ensuring your application state remains consistent.
Behind the Scenes
https://gradio.app/guides/client-side-functions
Additional Features - Client Side Functions Guide