""" This file defines two useful high-level abstractions to build Gradio apps: Interface and TabbedInterface. """ from __future__ import annotations import inspect import json import os import warnings import weakref from typing import TYPE_CHECKING, Any, Callable, Literal from gradio_client.documentation import document from gradio import Examples, utils, wasm_utils from gradio.blocks import Blocks from gradio.components import ( Button, ClearButton, Component, DuplicateButton, Markdown, State, get_component_instance, ) from gradio.data_classes import InterfaceTypes from gradio.events import Dependency, Events, on from gradio.exceptions import RenderError from gradio.flagging import CSVLogger, FlaggingCallback, FlagMethod from gradio.layouts import Accordion, Column, Row, Tab, Tabs from gradio.pipelines import load_from_js_pipeline, load_from_pipeline from gradio.themes import ThemeClass as Theme if TYPE_CHECKING: # Only import for type checking (is False at runtime). from diffusers import DiffusionPipeline # type: ignore from transformers.pipelines.base import Pipeline @document("launch", "load", "from_pipeline", "integrate", "queue") class Interface(Blocks): """ 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: 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() Demos: hello_world, hello_world_2, hello_world_3 Guides: quickstart, key-features, sharing-your-app, interface-state, reactive-interfaces, advanced-interface-features, setting-up-a-gradio-demo-for-maximum-performance """ # stores references to all currently existing Interface instances instances: weakref.WeakSet = weakref.WeakSet() @classmethod def get_instances(cls) -> list[Interface]: """ :return: list of all current instances. """ return list(Interface.instances) @classmethod def from_pipeline( cls, pipeline: Pipeline | DiffusionPipeline, **kwargs ) -> Interface: """ 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. Parameters: pipeline: the pipeline object to use. Returns: a Gradio Interface object from the given Pipeline Example: import gradio as gr from transformers import pipeline pipe = pipeline("image-classification") gr.Interface.from_pipeline(pipe).launch() """ if wasm_utils.IS_WASM: interface_info = load_from_js_pipeline(pipeline) else: interface_info = load_from_pipeline(pipeline) kwargs = dict(interface_info, **kwargs) interface = cls(**kwargs) return interface def __init__( self, fn: Callable, inputs: str | Component | list[str | Component] | None, outputs: str | Component | list[str | Component] | None, examples: list[Any] | list[list[Any]] | str | None = None, cache_examples: bool | Literal["lazy"] | None = None, examples_per_page: int = 10, live: bool = False, title: str | None = None, description: str | None = None, article: str | None = None, thumbnail: str | None = None, theme: Theme | str | None = None, css: str | None = None, allow_flagging: Literal["never"] | Literal["auto"] | Literal["manual"] | None = None, flagging_options: list[str] | list[tuple[str, str]] | None = None, flagging_dir: str = "flagged", flagging_callback: FlaggingCallback | None = None, analytics_enabled: bool | None = None, batch: bool = False, max_batch_size: int = 4, api_name: str | Literal[False] | None = "predict", _api_mode: bool = False, allow_duplication: bool = False, concurrency_limit: int | None | Literal["default"] = "default", js: str | None = None, head: str | None = None, additional_inputs: str | Component | list[str | Component] | None = None, additional_inputs_accordion: str | Accordion | None = None, *, submit_btn: str | Button = "Submit", stop_btn: str | Button = "Stop", clear_btn: str | Button | None = "Clear", delete_cache: tuple[int, int] | None = None, **kwargs, ): """ Parameters: fn: 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: 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: 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: 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: If True, caches examples in the server for fast runtime in examples. If "lazy", then examples are cached after their first use. If `fn` is a generator function, then the last yielded value will be used as the output. Can also be set by the GRADIO_CACHE_EXAMPLES environment variable, which takes a case-insensitive value, one of: {"true", "false", "lazy"}. The default option in HuggingFace Spaces is True. The default option elsewhere is False. examples_per_page: If examples are provided, how many to display per page. live: Whether the interface should automatically rerun if any of the inputs change. title: 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: 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: 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. thumbnail: This parameter has been deprecated and has no effect. theme: 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: Custom css as a string or path to a css file. This css will be included in the demo webpage. allow_flagging: 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_ALLOW_FLAGGING; otherwise defaults to "manual". flagging_options: If provided, allows user to select from the list of options when flagging. Only applies if allow_flagging 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: What to name the directory where flagged data is stored. flagging_callback: 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: Whether to allow basic telemetry. If None, will use GRADIO_ANALYTICS_ENABLED environment variable if defined, or default to True. batch: 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: Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True) api_name: Defines how the endpoint appears in the API docs. Can be a string, None, or False. If set to a string, the endpoint will be exposed in the API docs with the given name. If None, the name of the prediction function will be used as the API endpoint. If False, the endpoint will not be exposed in the API docs and downstream apps (including those that `gr.load` this app) will not be able to use this event. allow_duplication: If True, then will show a 'Duplicate Spaces' button on Hugging Face Spaces. concurrency_limit: 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). js: Custom js as a string or path to a js file. The custom js should be in the form of a single js function. This function will automatically be executed when the page loads. For more flexibility, use the head parameter to insert js inside