# Interface

```python
gradio.Interface(···)
```

### Description

Interface is Gradio's main high-level class, and allows you to create a web-based GUI / demo around a machine learning model (or any Python function) in a few lines of code. You must specify three parameters: (1) the function to create a GUI for (2) the desired input components and (3) the desired output components. Additional parameters can be used to control the appearance and behavior of the demo.

### Example Usage

```python
import gradio as gr

def image_classifier(inp):
    return {'cat': 0.3, 'dog': 0.7}

demo = gr.Interface(fn=image_classifier, inputs="image", outputs="label")
demo.launch()
```

### Initialization

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `fn` | `Callable` | `` | the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component. |
| `inputs` | `str \| Component \| list[str \| Component] \| None` | `` | a single Gradio component, or list of Gradio components. Components can either be passed as instantiated objects, or referred to by their string shortcuts. The number of input components should match the number of parameters in fn. If set to None, then only the output components will be displayed. |
| `outputs` | `str \| Component \| list[str \| Component] \| None` | `` | a single Gradio component, or list of Gradio components. Components can either be passed as instantiated objects, or referred to by their string shortcuts. The number of output components should match the number of values returned by fn. If set to None, then only the input components will be displayed. |
| `examples` | `list[Any] \| list[list[Any]] \| str \| None` | `None` | sample inputs for the function; if provided, appear below the UI components and can be clicked to populate the interface. Should be nested list, in which the outer list consists of samples and each inner list consists of an input corresponding to each input component. A string path to a directory of examples can also be provided, but it should be within the directory with the python file running the gradio app. If there are multiple input components and a directory is provided, a log.csv file must be present in the directory to link corresponding inputs. |
| `cache_examples` | `bool \| None` | `None` | If True, caches examples in the server for fast runtime in examples. If "lazy", then examples are cached (for all users of the app) after their first use (by any user of the app). If None, will use the GRADIO_CACHE_EXAMPLES environment variable, which should be either "true" or "false". In HuggingFace Spaces, this parameter defaults to True (as long as `fn` and `outputs` are also provided).  Note that examples are cached separately from Gradio's queue() so certain features, such as gr.Progress(), gr.Info(), gr.Warning(), etc. will not be displayed in Gradio's UI for cached examples. |
| `cache_mode` | `Literal['eager', 'lazy'] \| None` | `None` | if "lazy", examples are cached after their first use. If "eager", all examples are cached at app launch. If None, will use the GRADIO_CACHE_MODE environment variable if defined, or default to "eager". In HuggingFace Spaces, this parameter defaults to "eager" except for ZeroGPU Spaces, in which case it defaults to "lazy". |
| `examples_per_page` | `int` | `10` | if examples are provided, how many to display per page. |
| `example_labels` | `list[str] \| None` | `None` | a list of labels for each example. If provided, the length of this list should be the same as the number of examples, and these labels will be used in the UI instead of rendering the example values. |
| `preload_example` | `int \| Literal[False]` | `0` | If an integer is provided (and examples are being cached eagerly and none of the input components have a developer-provided `value`), the example at that index in the examples list will be preloaded when the Gradio app is first loaded. If False, no example will be preloaded. |
| `live` | `bool` | `False` | whether the interface should automatically rerun if any of the inputs change. |
| `title` | `str \| I18nData \| None` | `None` | a title for the interface; if provided, appears above the input and output components in large font. Also used as the tab title when opened in a browser window. |
| `description` | `str \| None` | `None` | a description for the interface; if provided, appears above the input and output components and beneath the title in regular font. Accepts Markdown and HTML content. |
| `article` | `str \| None` | `None` | an expanded article explaining the interface; if provided, appears below the input and output components in regular font. Accepts Markdown and HTML content. If it is an HTTP(S) link to a downloadable remote file, the content of this file is displayed. |
| `flagging_mode` | `Literal['never'] \| Literal['auto'] \| Literal['manual'] \| None` | `None` | one of "never", "auto", or "manual". If "never" or "auto", users will not see a button to flag an input and output. If "manual", users will see a button to flag. If "auto", every input the user submits will be automatically flagged, along with the generated output. If "manual", both the input and outputs are flagged when the user clicks flag button. This parameter can be set with environmental variable GRADIO_FLAGGING_MODE; otherwise defaults to "manual". |
| `flagging_options` | `list[str] \| list[tuple[str, str]] \| None` | `None` | if provided, allows user to select from the list of options when flagging. Only applies if flagging_mode is "manual". Can either be a list of tuples of the form (label, value), where label is the string that will be displayed on the button and value is the string that will be stored in the flagging CSV; or it can be a list of strings ["X", "Y"], in which case the values will be the list of strings and the labels will ["Flag as X", "Flag as Y"], etc. |
| `flagging_dir` | `str` | `".gradio/flagged"` | path to the directory where flagged data is stored. If the directory does not exist, it will be created. |
| `flagging_callback` | `FlaggingCallback \| None` | `None` | either None or an instance of a subclass of FlaggingCallback which will be called when a sample is flagged. If set to None, an instance of gradio.flagging.CSVLogger will be created and logs will be saved to a local CSV file in flagging_dir. Default to None. |
| `analytics_enabled` | `bool \| None` | `None` | whether to allow basic telemetry. If None, will use GRADIO_ANALYTICS_ENABLED environment variable if defined, or default to True. |
| `batch` | `bool` | `False` | if True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component. |
| `max_batch_size` | `int` | `4` | the maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True) |
| `api_visibility` | `Literal['public', 'private', 'undocumented']` | `"public"` | Controls the visibility of the prediction endpoint. Can be "public" (shown in API docs and callable), "private" (hidden from API docs and not callable), or "undocumented" (hidden from API docs but callable). |
| `api_name` | `str \| None` | `None` | defines how the prediction endpoint appears in the API docs. Can be a string or None. If set to a string, the endpoint will be exposed in the API docs with the given name. If None, the name of the function will be used. |
| `api_description` | `str \| None \| Literal[False]` | `None` | Description of the API endpoint. Can be a string, None, or False. If set to a string, the endpoint will be exposed in the API docs with the given description. If None, the function's docstring will be used as the API endpoint description. If False, then no description will be displayed in the API docs. |
| `allow_duplication` | `bool` | `False` | if True, then will show a 'Duplicate Spaces' button on Hugging Face Spaces. |
| `concurrency_limit` | `int \| None \| Literal['default']` | `"default"` | if set, this is the maximum number of this event that can be running simultaneously. Can be set to None to mean no concurrency_limit (any number of this event can be running simultaneously). Set to "default" to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `.queue()`, which itself is 1 by default). |
| `additional_inputs` | `str \| Component \| list[str \| Component] \| None` | `None` | a single Gradio component, or list of Gradio components. Components can either be passed as instantiated objects, or referred to by their string shortcuts. These components will be rendered in an accordion below the main input components. By default, no additional input components will be displayed. |
| `additional_inputs_accordion` | `str \| Accordion \| None` | `None` | if a string is provided, this is the label of the `gr.Accordion` to use to contain additional inputs. A `gr.Accordion` object can be provided as well to configure other properties of the container holding the additional inputs. Defaults to a `gr.Accordion(label="Additional Inputs", open=False)`. This parameter is only used if `additional_inputs` is provided. |
| `submit_btn` | `str \| Button` | `"Submit"` | the button to use for submitting inputs. Defaults to a `gr.Button("Submit", variant="primary")`. This parameter does not apply if the Interface is output-only, in which case the submit button always displays "Generate". Can be set to a string (which becomes the button label) or a `gr.Button` object (which allows for more customization). |
| `stop_btn` | `str \| Button` | `"Stop"` | the button to use for stopping the interface. Defaults to a `gr.Button("Stop", variant="stop", visible=False)`. Can be set to a string (which becomes the button label) or a `gr.Button` object (which allows for more customization). |
| `clear_btn` | `str \| Button \| None` | `"Clear"` | the button to use for clearing the inputs. Defaults to a `gr.Button("Clear", variant="secondary")`. Can be set to a string (which becomes the button label) or a `gr.Button` object (which allows for more customization). Can be set to None, which hides the button. |
| `delete_cache` | `tuple[int, int] \| None` | `None` | a tuple corresponding [frequency, age] both expressed in number of seconds. Every `frequency` seconds, the temporary files created by this Blocks instance will be deleted if more than `age` seconds have passed since the file was created. For example, setting this to (86400, 86400) will delete temporary files every day. The cache will be deleted entirely when the server restarts. If None, no cache deletion will occur. |
| `show_progress` | `Literal['full', 'minimal', 'hidden']` | `"full"` | how to show the progress animation while event is running: "full" shows a spinner which covers the output component area as well as a runtime display in the upper right corner, "minimal" only shows the runtime display, "hidden" shows no progress animation at all |
| `fill_width` | `bool` | `False` | whether to horizontally expand to fill container fully. If False, centers and constrains app to a maximum width. |
| `time_limit` | `int \| None` | `30` | The time limit for the stream to run. Default is 30 seconds. Parameter only used for streaming images or audio if the interface is live and the input components are set to "streaming=True". |
| `stream_every` | `float` | `0.5` | The latency (in seconds) at which stream chunks are sent to the backend. Defaults to 0.5 seconds. Parameter only used for streaming images or audio if the interface is live and the input components are set to "streaming=True". |
| `deep_link` | `str \| DeepLinkButton \| bool \| None` | `None` | a string or `gr.DeepLinkButton` object that creates a unique URL you can use to share your app and all components **as they currently are** with others. Automatically enabled on Hugging Face Spaces unless explicitly set to False. |
| `validator` | `Callable \| None` | `None` | a function that takes in the inputs and can optionally return a gr.validate() object for each input. |
### Demos

**hello_world**

[See demo on Hugging Face Spaces](https://huggingface.co/spaces/gradio/hello_world)

```python
import gradio as gr


def greet(name):
    return "Hello " + name + "!"


demo = gr.Interface(fn=greet, inputs="textbox", outputs="textbox", api_name="predict")

if __name__ == "__main__":
    demo.launch()
```

**hello_world_2**

[See demo on Hugging Face Spaces](https://huggingface.co/spaces/gradio/hello_world_2)

```python
import gradio as gr

def greet(name, intensity):
    return "Hello, " + name + "!" * intensity

demo = gr.Interface(
    fn=greet,
    inputs=["text", gr.Slider(value=2, minimum=1, maximum=10, step=1)],
    outputs=[gr.Textbox(label="greeting", lines=3)],
    api_name="predict"
)

if __name__ == "__main__":
    demo.launch()
```

**hello_world_3**

[See demo on Hugging Face Spaces](https://huggingface.co/spaces/gradio/hello_world_3)

```python
import gradio as gr

def greet(name, is_morning, temperature):
    salutation = "Good morning" if is_morning else "Good evening"
    greeting = f"{salutation} {name}. It is {temperature} degrees today"
    celsius = (temperature - 32) * 5 / 9
    return greeting, round(celsius, 2)

demo = gr.Interface(
    fn=greet,
    inputs=["text", "checkbox", gr.Slider(0, 100)],
    outputs=["text", "number"],
    api_name="predict"
)
if __name__ == "__main__":
    demo.launch()
```

### Methods

#### Description

Event listeners allow you to respond to user interactions with the UI components you've defined in a Gradio Blocks app. When a user interacts with an element, such as changing a slider value or uploading an image, a function is called.

#### Supported Event Listeners

The `Interface` component supports the following event listeners:

- `Interface.launch(fn, ...)`: Launches a simple web server that serves the demo. Can also be used to create a public link used by anyone to access the demo from their browser by setting share=True.
- `Interface.load(fn, ...)`: This listener is triggered when the Interface initially loads in the browser.
- `Interface.from_pipeline(fn, ...)`: Class method that constructs an Interface from a Hugging Face transformers.Pipeline or diffusers.DiffusionPipeline object. The input and output components are automatically determined from the pipeline.
- `Interface.integrate(fn, ...)`: A catch-all method for integrating with other libraries. This method should be run after launch()
- `Interface.queue(fn, ...)`: By enabling the queue you can control when users know their position in the queue, and set a limit on maximum number of events allowed.

#### Event Parameters

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `inline` | `bool \| None` | `None` | whether to display in the gradio app inline in an iframe. Defaults to True in python notebooks; False otherwise. |
| `inbrowser` | `bool` | `False` | whether to automatically launch the gradio app in a new tab on the default browser. |
| `share` | `bool \| None` | `None` | whether to create a publicly shareable link for the gradio app. Creates an SSH tunnel to make your UI accessible from anywhere. If not provided, it is set to False by default every time, except when running in Google Colab. When localhost is not accessible (e.g. Google Colab), setting share=False is not supported. Can be set by environment variable GRADIO_SHARE=True. |
| `debug` | `bool` | `False` | if True, blocks the main thread from running. If running in Google Colab, this is needed to print the errors in the cell output. |
| `max_threads` | `int` | `40` | the maximum number of total threads that the Gradio app can generate in parallel. The default is inherited from the starlette library (currently 40). |
| `auth` | `Callable[[str, str], bool] \| tuple[str, str] \| list[tuple[str, str]] \| None` | `None` | If provided, username and password (or list of username-password tuples) required to access app. Can also provide function that takes username and password and returns True if valid login. |
| `auth_message` | `str \| None` | `None` | If provided, HTML message provided on login page. |
| `prevent_thread_lock` | `bool` | `False` | By default, the gradio app blocks the main thread while the server is running. If set to True, the gradio app will not block and the gradio server will terminate as soon as the script finishes. |
| `show_error` | `bool` | `False` | If True, any errors in the gradio app will be displayed in an alert modal and printed in the browser console log. They will also be displayed in the alert modal of downstream apps that gr.load() this app. |
| `server_name` | `str \| None` | `None` | to make app accessible on local network, set this to "0.0.0.0". Can be set by environment variable GRADIO_SERVER_NAME. If None, will use "127.0.0.1". |
| `server_port` | `int \| None` | `None` | will start gradio app on this port (if available). Can be set by environment variable GRADIO_SERVER_PORT. If None, will search for an available port starting at 7860. |
| `height` | `int` | `500` | The height in pixels of the iframe element containing the gradio app (used if inline=True) |
| `width` | `int \| str` | `"100%"` | The width in pixels of the iframe element containing the gradio app (used if inline=True) |
| `favicon_path` | `str \| Path \| None` | `None` | If a path to a file (.png, .gif, or .ico) is provided, it will be used as the favicon for the web page. |
| `ssl_keyfile` | `str \| None` | `None` | If a path to a file is provided, will use this as the private key file to create a local server running on https. |
| `ssl_certfile` | `str \| None` | `None` | If a path to a file is provided, will use this as the signed certificate for https. Needs to be provided if ssl_keyfile is provided. |
| `ssl_keyfile_password` | `str \| None` | `None` | If a password is provided, will use this with the ssl certificate for https. |
| `ssl_verify` | `bool` | `True` | If False, skips certificate validation which allows self-signed certificates to be used. |
| `quiet` | `bool` | `False` | If True, suppresses most print statements. |
| `footer_links` | `list[Literal['api', 'gradio', 'settings'] \| dict[str, str]] \| None` | `None` | The links to display in the footer of the app. Accepts a list, where each element of the list must be one of "api", "gradio", or "settings" corresponding to the API docs, "built with Gradio", and settings pages respectively. If None, all three links will be shown in the footer. An empty list means that no footer is shown. |
| `allowed_paths` | `list[str] \| None` | `None` | List of complete filepaths or parent directories that gradio is allowed to serve. Must be absolute paths. Warning: if you provide directories, any files in these directories or their subdirectories are accessible to all users of your app. Can be set by comma separated environment variable GRADIO_ALLOWED_PATHS. These files are generally assumed to be secure and will be displayed in the browser when possible. |
| `blocked_paths` | `list[str] \| None` | `None` | List of complete filepaths or parent directories that gradio is not allowed to serve (i.e. users of your app are not allowed to access). Must be absolute paths. Warning: takes precedence over `allowed_paths` and all other directories exposed by Gradio by default. Can be set by comma separated environment variable GRADIO_BLOCKED_PATHS. |
| `root_path` | `str \| None` | `None` | The root path (or "mount point") of the application, if it's not served from the root ("/") of the domain. Often used when the application is behind a reverse proxy that forwards requests to the application. For example, if the application is served at "https://example.com/myapp", the `root_path` should be set to "/myapp". A full URL beginning with http:// or https:// can be provided, which will be used as the root path in its entirety. Can be set by environment variable GRADIO_ROOT_PATH. Defaults to "". |
| `app_kwargs` | `dict[str, Any] \| None` | `None` | Additional keyword arguments to pass to the underlying FastAPI app as a dictionary of parameter keys and argument values. For example, `{"docs_url": "/docs"}` |
| `state_session_capacity` | `int` | `10000` | The maximum number of sessions whose information to store in memory. If the number of sessions exceeds this number, the oldest sessions will be removed. Reduce capacity to reduce memory usage when using gradio.State or returning updated components from functions. Defaults to 10000. |
| `share_server_address` | `str \| None` | `None` | Use this to specify a custom FRP server and port for sharing Gradio apps (only applies if share=True). If not provided, will use the default FRP server at https://gradio.live. See https://github.com/huggingface/frp for more information. |
| `share_server_protocol` | `Literal['http', 'https'] \| None` | `None` | Use this to specify the protocol to use for the share links. Defaults to "https", unless a custom share_server_address is provided, in which case it defaults to "http". If you are using a custom share_server_address and want to use https, you must set this to "https". |
| `share_server_tls_certificate` | `str \| None` | `None` | The path to a TLS certificate file to use when connecting to a custom share server. This parameter is not used with the default FRP server at https://gradio.live. Otherwise, you must provide a valid TLS certificate file (e.g. a "cert.pem") relative to the current working directory, or the connection will not use TLS encryption, which is insecure. |
| `auth_dependency` | `Callable[[fastapi.Request], str \| None] \| None` | `None` | A function that takes a FastAPI request and returns a string user ID or None. If the function returns None for a specific request, that user is not authorized to access the app (they will see a 401 Unauthorized response). To be used with external authentication systems like OAuth. Cannot be used with `auth`. |
| `max_file_size` | `str \| int \| None` | `None` | The maximum file size in bytes that can be uploaded. Can be a string of the form "<value><unit>", where value is any positive integer and unit is one of "b", "kb", "mb", "gb", "tb". If None, no limit is set. |
| `enable_monitoring` | `bool \| None` | `None` | Enables traffic monitoring of the app through the /monitoring endpoint. By default is None, which enables this endpoint. If explicitly True, will also print the monitoring URL to the console. If False, will disable monitoring altogether. |
| `strict_cors` | `bool` | `True` | If True, prevents external domains from making requests to a Gradio server running on localhost. If False, allows requests to localhost that originate from localhost but also, crucially, from "null". This parameter should normally be True to prevent CSRF attacks but may need to be False when embedding a *locally-running Gradio app* using web components. |
| `node_server_name` | `str \| None` | `None` |  |
| `node_port` | `int \| None` | `None` |  |
| `ssr_mode` | `bool \| None` | `None` | If True, the Gradio app will be rendered using server-side rendering mode, which is typically more performant and provides better SEO, but this requires Node 20+ to be installed on the system. If False, the app will be rendered using client-side rendering mode. If None, will use GRADIO_SSR_MODE environment variable or default to False. |
| `pwa` | `bool \| None` | `None` | If True, the Gradio app will be set up as an installable PWA (Progressive Web App). If set to None (default behavior), then the PWA feature will be enabled if this Gradio app is launched on Spaces, but not otherwise. |
| `mcp_server` | `bool \| None` | `None` | If True, the Gradio app will be set up as an MCP server and documented functions will be added as MCP tools. If None (default behavior), then the GRADIO_MCP_SERVER environment variable will be used to determine if the MCP server should be enabled. |
| `i18n` | `I18n \| None` | `None` | An I18n instance containing custom translations, which are used to translate strings in our components (e.g. the labels of components or Markdown strings). This feature can only be used to translate static text in the frontend, not values in the backend. |
| `theme` | `Theme \| str \| None` | `None` | A Theme object or a string representing a theme. If a string, will look for a built-in theme with that name (e.g. "soft" or "default"), or will attempt to load a theme from the Hugging Face Hub (e.g. "gradio/monochrome"). If None, will use the Default theme. |
| `css` | `str \| None` | `None` | Custom css as a code string. This css will be included in the demo webpage. |
| `css_paths` | `str \| Path \| list[str \| Path] \| None` | `None` | Custom css as a pathlib.Path to a css file or a list of such paths. This css files will be read, concatenated, and included in the demo webpage. If the `css` parameter is also set, the css from `css` will be included first. |
| `js` | `str \| Literal[True] \| None` | `None` | Custom js as a code string. The js code will automatically be executed when the page loads. For more flexibility, use the head parameter to insert js inside <script> tags. |
| `head` | `str \| None` | `None` | Custom html code to insert into the head of the demo webpage. This can be used to add custom meta tags, multiple scripts, stylesheets, etc. to the page. |
| `head_paths` | `str \| Path \| list[str \| Path] \| None` | `None` | Custom html code as a pathlib.Path to a html file or a list of such paths. This html files will be read, concatenated, and included in the head of the demo webpage. If the `head` parameter is also set, the html from `head` will be included first. |
- [The Interface Class](https://www.gradio.app/guides/the-interface-class/)
- [Interface State](https://www.gradio.app/guides/interface-state/)
- [Reactive Interfaces](https://www.gradio.app/guides/reactive-interfaces/)
- [Four Kinds Of Interfaces](https://www.gradio.app/guides/four-kinds-of-interfaces/)
- [Sharing Your App](https://www.gradio.app/guides/sharing-your-app/)
