Beispiel #1
0
    def test_should_warn_url_not_having_version(self, mock_json):

        mock_json.return_value = {"foo": "bar"}

        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("always")
            version_check()
            self.assertEqual(str(w[-1].message),
                             "package URL does not contain version info.")
Beispiel #2
0
    def test_should_warn_with_unable_to_parse(self, mock_get):

        mock_get.side_effect = json.decoder.JSONDecodeError(
            "Expecting value", "", 0)

        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("always")
            version_check()
            self.assertEqual(
                str(w[-1].message),
                "unable to parse version details from package URL.")
Beispiel #3
0
    def test_should_fail_with_distribution_not_found(self, mock_require):

        mock_require.side_effect = pkg_resources.DistributionNotFound()

        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("always")
            version_check()
            self.assertEqual(
                str(w[-1].message),
                "gradio is not setup or installed properly. Unable to get version info.",
            )
Beispiel #4
0
    def launch(self,
               inline=None,
               inbrowser=None,
               share=False,
               debug=False,
               auth=None):
        """
        Parameters:
        inline (bool): whether to display in the interface inline on python notebooks.
        inbrowser (bool): whether to automatically launch the interface in a new tab on the default browser.
        share (bool): whether to create a publicly shareable link from your computer for the interface.
        debug (bool): if True, and the interface was launched from Google Colab, prints the errors in the cell output.
        auth (Tuple[str, str]): If provided, username and password required to access interface.
        Returns:
        app (flask.Flask): Flask app object
        path_to_local_server (str): Locally accessible link
        share_url (str): Publicly accessible link (if share=True)
        """
        # Alert user if a more recent version of the library exists
        utils.version_check()

        # Set up local flask server
        config = self.get_config_file()
        self.config = config
        self.auth = auth

        # Launch local flask server
        server_port, app, thread = networking.start_server(
            self, self.server_name, self.server_port, self.auth)
        path_to_local_server = "http://{}:{}/".format(self.server_name,
                                                      server_port)
        self.server_port = server_port
        self.status = "RUNNING"
        self.server = app

        # Count number of launches
        launch_counter()

        # If running in a colab or not able to access localhost, automatically create a shareable link
        is_colab = utils.colab_check()
        if is_colab or not (networking.url_ok(path_to_local_server)):
            share = True
            if debug:
                print(strings.en["COLAB_DEBUG_TRUE"])
            else:
                print(strings.en["COLAB_DEBUG_FALSE"])
        else:
            print(strings.en["RUNNING_LOCALLY"].format(path_to_local_server))

        # Set up shareable link
        self.share = share
        if share:
            print(strings.en["SHARE_LINK_MESSAGE"])
            try:
                share_url = networking.setup_tunnel(server_port)
                print(strings.en["SHARE_LINK_DISPLAY"].format(share_url))
            except RuntimeError:
                send_error_analytics(self.analytics_enabled)
                share_url = None
        else:
            print(strings.en["PUBLIC_SHARE_TRUE"])
            share_url = None

        # Open a browser tab with the interface.
        if inbrowser:
            if share:
                webbrowser.open(share_url)
            else:
                webbrowser.open(path_to_local_server)

        # Check if running in a Python notebook in which case, display inline
        if inline is None:
            inline = utils.ipython_check()
        if inline:
            from IPython.display import IFrame, display
            # Embed the remote interface page if on google colab; otherwise, embed the local page.
            print(strings.en["INLINE_DISPLAY_BELOW"])
            if share:
                while not networking.url_ok(share_url):
                    time.sleep(1)
                display(IFrame(share_url, width=1000, height=500))
            else:
                display(IFrame(path_to_local_server, width=1000, height=500))

        send_launch_analytics(analytics_enabled=self.analytics_enabled,
                              inbrowser=inbrowser,
                              is_colab=is_colab,
                              share=share,
                              share_url=share_url)

        show_tip(self)

        # Run server perpetually under certain circumstances
        if debug or int(os.getenv('GRADIO_DEBUG', 0)) == 1:
            while True:
                sys.stdout.flush()
                time.sleep(0.1)
        is_in_interactive_mode = bool(
            getattr(sys, 'ps1', sys.flags.interactive))
        if not is_in_interactive_mode:
            self.run_until_interrupted(thread, path_to_local_server)

        return app, path_to_local_server, share_url
Beispiel #5
0
    def launch(self, inline=None, inbrowser=None, share=False, debug=False):
        """
        Parameters:
        inline (bool): whether to display in the interface inline on python notebooks.
        inbrowser (bool): whether to automatically launch the interface in a new tab on the default browser.
        share (bool): whether to create a publicly shareable link from your computer for the interface.
        debug (bool): if True, and the interface was launched from Google Colab, prints the errors in the cell output.
        Returns:
        app (flask.Flask): Flask app object
        path_to_local_server (str): Locally accessible link
        share_url (str): Publicly accessible link (if share=True)
        """
        config = self.get_config_file()
        networking.set_config(config)
        networking.set_meta_tags(self.title, self.description, self.thumbnail)

        server_port, app, thread = networking.start_server(
            self, self.server_name, self.server_port)
        path_to_local_server = "http://{}:{}/".format(self.server_name, server_port)
        self.status = "RUNNING"
        self.server = app

        utils.version_check()
        is_colab = utils.colab_check()
        if is_colab:
            share = True
        if not is_colab:
            if not networking.url_ok(path_to_local_server):
                share = True
            else:
                print(strings.en["RUNNING_LOCALLY"].format(path_to_local_server))
        else:
            if debug:
                print("Colab notebook detected. This cell will run indefinitely so that you can see errors and logs. "
                      "To turn off, set debug=False in launch().")
            else:
                print("Colab notebook detected. To show errors in colab notebook, set debug=True in launch()")

        if share:
            print("This share link will expire in 6 hours. If you need a "
                  "permanent link, email [email protected]")
            try:
                share_url = networking.setup_tunnel(self.launch_port)
                print("Running on External URL:", share_url)
            except RuntimeError:
                data = {'error': 'RuntimeError in launch method'}
                if self.analytics_enabled:
                    try:
                        requests.post(analytics_url + 'gradio-error-analytics/',
                                      data=data)
                    except requests.ConnectionError:
                        pass  # do not push analytics if no network
                share_url = None
                if self.verbose:
                    print(strings.en["NGROK_NO_INTERNET"])
        else:
            print("To get a public link for a hosted model, "
                    "set Share=True")
            if self.verbose:
                print(strings.en["PUBLIC_SHARE_TRUE"])
            share_url = None

        if inline is None:
            inline = utils.ipython_check()
            if inbrowser is None:
                # if interface won't appear inline, open it in new tab,
                # otherwise keep it inline
                inbrowser = not inline
        else:
            if inbrowser is None:
                inbrowser = False

        if inbrowser and not is_colab:
            webbrowser.open(path_to_local_server)  # Open a browser tab
            # with the interface.
        if inline:
            from IPython.display import IFrame, display
            # Embed the remote interface page if on google colab;
            # otherwise, embed the local page.
            print("Interface loading below...")
            if share:
                while not networking.url_ok(share_url):
                    time.sleep(1)
                display(IFrame(share_url, width=1000, height=500))
            else:
                display(IFrame(path_to_local_server, width=1000, height=500))

        r = requests.get(path_to_local_server + "enable_sharing/" + (share_url or "None"))

        if debug:
            while True:
                sys.stdout.flush()
                time.sleep(0.1)

        launch_method = 'browser' if inbrowser else 'inline'

        if self.analytics_enabled:
            data = {
                'launch_method': launch_method,
                'is_google_colab': is_colab,
                'is_sharing_on': share,
                'share_url': share_url,
                'ip_address': ip_address
            }
            try:
                requests.post(analytics_url + 'gradio-launched-analytics/',
                              data=data)
            except requests.ConnectionError:
                pass  # do not push analytics if no network

        is_in_interactive_mode = bool(getattr(sys, 'ps1', sys.flags.interactive))
        if not is_in_interactive_mode:
            self.run_until_interrupted(thread, path_to_local_server)

        return app, path_to_local_server, share_url
Beispiel #6
0
    def launch(self,
               inline=None,
               inbrowser=None,
               share=False,
               debug=False,
               auth=None,
               auth_message=None,
               private_endpoint=None,
               prevent_thread_lock=False):
        """
        Parameters:
        inline (bool): whether to display in the interface inline on python notebooks.
        inbrowser (bool): whether to automatically launch the interface in a new tab on the default browser.
        share (bool): whether to create a publicly shareable link from your computer for the interface.
        debug (bool): if True, and the interface was launched from Google Colab, prints the errors in the cell output.
        auth (Callable, Union[Tuple[str, str], List[Tuple[str, str]]]): If provided, username and password (or list of username-password tuples) required to access interface. Can also provide function that takes username and password and return True if valid login.
        auth_message (str): If provided, HTML message provided on login page.
        Returns:
        app (flask.Flask): Flask app object
        path_to_local_server (str): Locally accessible link
        share_url (str): Publicly accessible link (if share=True)
        """
        # Alert user if a more recent version of the library exists
        utils.version_check()

        # Set up local flask server
        config = self.get_config_file()
        self.config = config
        if auth and not callable(auth) and not isinstance(
                auth[0], tuple) and not isinstance(auth[0], list):
            auth = [auth]
        self.auth = auth
        self.auth_message = auth_message

        # Request key for encryption
        if self.encrypt:
            self.encryption_key = encryptor.get_key(
                getpass("Enter key for encryption: "))

        # Launch local flask server
        server_port, app, thread = networking.start_server(
            self, self.server_name, self.server_port, self.auth)
        path_to_local_server = "http://{}:{}/".format(self.server_name,
                                                      server_port)
        self.local_url = path_to_local_server
        self.server_port = server_port
        self.status = "RUNNING"
        self.server = app

        # Count number of launches
        launch_counter()

        # If running in a colab or not able to access localhost, automatically create a shareable link
        is_colab = utils.colab_check()
        if is_colab or not (networking.url_ok(path_to_local_server)):
            share = True
            if is_colab:
                if debug:
                    print(strings.en["COLAB_DEBUG_TRUE"])
                else:
                    print(strings.en["COLAB_DEBUG_FALSE"])
        else:
            print(strings.en["RUNNING_LOCALLY"].format(path_to_local_server))
        if is_colab and self.requires_permissions:
            print(strings.en["MEDIA_PERMISSIONS_IN_COLAB"])

        if private_endpoint is not None:
            share = True
        # Set up shareable link
        self.share = share

        if share:
            if not private_endpoint:
                print(strings.en["SHARE_LINK_MESSAGE"])
            try:
                share_url = networking.setup_tunnel(server_port,
                                                    private_endpoint)
                self.share_url = share_url
                print(strings.en["SHARE_LINK_DISPLAY"].format(share_url))
            except RuntimeError:
                send_error_analytics(self.analytics_enabled)
                share_url = None
        else:
            print(strings.en["PUBLIC_SHARE_TRUE"])
            share_url = None

        # Open a browser tab with the interface.
        if inbrowser:
            if share:
                webbrowser.open(share_url)
            else:
                webbrowser.open(path_to_local_server)

        # Check if running in a Python notebook in which case, display inline
        if inline is None:
            inline = utils.ipython_check()
        if inline:
            try:
                from IPython.display import IFrame, display
                # Embed the remote interface page if on google colab; otherwise, embed the local page.
                print(strings.en["INLINE_DISPLAY_BELOW"])
                if share:
                    while not networking.url_ok(share_url):
                        time.sleep(1)
                    display(
                        IFrame(share_url, width=self.width,
                               height=self.height))
                else:
                    display(
                        IFrame(path_to_local_server,
                               width=self.width,
                               height=self.height))
            except ImportError:
                pass  # IPython is not available so does not print inline.

        send_launch_analytics(analytics_enabled=self.analytics_enabled,
                              inbrowser=inbrowser,
                              is_colab=is_colab,
                              share=share,
                              share_url=share_url)

        show_tip(self)

        # Run server perpetually under certain circumstances
        if debug or int(os.getenv('GRADIO_DEBUG', 0)) == 1:
            while True:
                sys.stdout.flush()
                time.sleep(0.1)
        is_in_interactive_mode = bool(
            getattr(sys, 'ps1', sys.flags.interactive))
        if not prevent_thread_lock and not is_in_interactive_mode:
            self.run_until_interrupted(thread, path_to_local_server)

        return app, path_to_local_server, share_url
Beispiel #7
0
    def __init__(
        self,
        fn: Callable | List[Callable],
        inputs: str | Component | List[str | Component] = None,
        outputs: str | Component | List[str | Component] = None,
        verbose: bool = False,
        examples: Optional[List[Any] | List[List[Any]] | str] = None,
        cache_examples: bool = False,
        examples_per_page: int = 10,
        live: bool = False,
        layout: str = "unaligned",
        show_input: bool = True,
        show_output: bool = True,
        capture_session: Optional[bool] = None,
        interpretation: Optional[Callable | str] = None,
        num_shap: float = 2.0,
        theme: Optional[str] = None,
        repeat_outputs_per_model: bool = True,
        title: Optional[str] = None,
        description: Optional[str] = None,
        article: Optional[str] = None,
        thumbnail: Optional[str] = None,
        css: Optional[str] = None,
        height=None,
        width=None,
        allow_screenshot: bool = False,
        allow_flagging: Optional[str] = None,
        flagging_options: List[str] = None,
        encrypt=None,
        show_tips=None,
        flagging_dir: str = "flagged",
        analytics_enabled: Optional[bool] = None,
        server_name=None,
        server_port=None,
        enable_queue=None,
        api_mode=None,
        flagging_callback: FlaggingCallback = CSVLogger(),
    ):  # TODO: (faruk) Let's remove depreceated parameters in the version 3.0.0
        """
        Parameters:
        fn (Union[Callable, List[Callable]]): the function to wrap an interface around.
        inputs (Union[str, InputComponent, List[Union[str, InputComponent]]]): a single Gradio input component, or list of Gradio input 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.
        outputs (Union[str, OutputComponent, List[Union[str, OutputComponent]]]): a single Gradio output component, or list of Gradio output 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.
        verbose (bool): DEPRECATED. Whether to print detailed information during launch.
        examples (Union[List[List[Any]], str]): sample inputs for the function; if provided, appears below the UI components and can be used 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. 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.
        examples_per_page (int): If examples are provided, how many to display per page.
        live (bool): whether the interface should automatically reload on change.
        layout (str): Layout of input and output panels. "horizontal" arranges them as two columns of equal height, "unaligned" arranges them as two columns of unequal height, and "vertical" arranges them vertically.
        capture_session (bool): DEPRECATED. If True, captures the default graph and session (needed for Tensorflow 1.x)
        interpretation (Union[Callable, str]): function that provides interpretation explaining prediction output. Pass "default" to use simple built-in interpreter, "shap" to use a built-in shapley-based interpreter, or your own custom interpretation function.
        num_shap (float): a multiplier that determines how many examples are computed for shap-based interpretation. Increasing this value will increase shap runtime, but improve results. Only applies if interpretation is "shap".
        title (str): a title for the interface; if provided, appears above the input and output components.
        description (str): a description for the interface; if provided, appears above the input and output components.
        article (str): an expanded article explaining the interface; if provided, appears below the input and output components. Accepts Markdown and HTML content.
        thumbnail (str): path to image or src to use as display picture for models listed in gradio.app/hub
        theme (str): Theme to use - one of "default", "huggingface", "seafoam", "grass", "peach". Add "dark-" prefix, e.g. "dark-peach" for dark theme (or just "dark" for the default dark theme).
        css (str): custom css or path to custom css file to use with interface.
        allow_screenshot (bool): DEPRECATED if False, users will not see a button to take a screenshot of the interface.
        allow_flagging (str): 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 prediction will be automatically flagged. If "manual", samples are flagged when the user clicks flag button. Can be set with environmental variable GRADIO_ALLOW_FLAGGING.
        flagging_options (List[str]): if provided, allows user to select from the list of options when flagging. Only applies if allow_flagging is "manual".
        encrypt (bool): DEPRECATED. If True, flagged data will be encrypted by key provided by creator at launch
        flagging_dir (str): what to name the dir where flagged data is stored.
        show_tips (bool): DEPRECATED. if True, will occasionally show tips about new Gradio features
        enable_queue (bool): DEPRECATED. if True, inference requests will be served through a queue instead of with parallel threads. Required for longer inference times (> 1min) to prevent timeout.
        api_mode (bool): DEPRECATED. If True, will skip preprocessing steps when the Interface is called() as a function (should remain False unless the Interface is loaded from an external repo)
        server_name (str): DEPRECATED. Name of the server to use for serving the interface - pass in launch() instead.
        server_port (int): DEPRECATED. Port of the server to use for serving the interface - pass in launch() instead.
        """
        super().__init__(analytics_enabled=analytics_enabled, mode="interface")

        if inputs is None:
            inputs = []
        if outputs is None:
            outputs = []

        if not isinstance(fn, list):
            fn = [fn]
        if not isinstance(inputs, list):
            inputs = [inputs]
        if not isinstance(outputs, list):
            outputs = [outputs]

        if "state" in inputs or "state" in outputs:
            state_input_count = len([i for i in inputs if i == "state"])
            state_output_count = len([o for o in outputs if o == "state"])
            if state_input_count != 1 or state_output_count != 1:
                raise ValueError(
                    "If using 'state', there must be exactly one state input and one state output."
                )
            default = utils.get_default_args(fn[0])[inputs.index("state")]
            state_variable = Variable(default_value=default)
            inputs[inputs.index("state")] = state_variable
            outputs[outputs.index("state")] = state_variable

        self.input_components = [get_component_instance(i) for i in inputs]
        self.output_components = [get_component_instance(o) for o in outputs]
        for o in self.output_components:
            o.interactive = (
                False  # Force output components to be treated as non-interactive
            )

        if repeat_outputs_per_model:
            self.output_components *= len(fn)

        if (
            interpretation is None
            or isinstance(interpretation, list)
            or callable(interpretation)
        ):
            self.interpretation = interpretation
        elif isinstance(interpretation, str):
            self.interpretation = [
                interpretation.lower() for _ in self.input_components
            ]
        else:
            raise ValueError("Invalid value for parameter: interpretation")

        self.predict = fn
        self.predict_durations = [[0, 0]] * len(fn)
        self.function_names = [func.__name__ for func in fn]
        self.__name__ = ", ".join(self.function_names)

        if verbose:
            warnings.warn(
                "The `verbose` parameter in the `Interface`"
                "is deprecated and has no effect."
            )
        if allow_screenshot:
            warnings.warn(
                "The `allow_screenshot` parameter in the `Interface`"
                "is deprecated and has no effect."
            )

        self.live = live
        self.layout = layout
        self.show_input = show_input
        self.show_output = show_output
        self.flag_hash = random.getrandbits(32)
        self.capture_session = capture_session

        if capture_session is not None:
            warnings.warn(
                "The `capture_session` parameter in the `Interface`"
                " is deprecated and may be removed in the future."
            )
            try:
                import tensorflow as tf

                self.session = tf.get_default_graph(), tf.keras.backend.get_session()
            except (ImportError, AttributeError):
                # If they are using TF >= 2.0 or don't have TF,
                # just ignore this parameter.
                pass

        if server_name is not None or server_port is not None:
            raise DeprecationWarning(
                "The `server_name` and `server_port` parameters in `Interface`"
                "are deprecated. Please pass into launch() instead."
            )

        self.session = None
        self.title = title

        CLEANER = re.compile("<.*?>")

        def clean_html(raw_html):
            cleantext = re.sub(CLEANER, "", raw_html)
            return cleantext

        md = MarkdownIt(
            "js-default",
            {
                "linkify": True,
                "typographer": True,
                "html": True,
            },
        ).use(footnote_plugin)

        simple_description = None
        if description is not None:
            description = md.render(description)
            simple_description = clean_html(description)
        self.simple_description = simple_description
        self.description = description
        if article is not None:
            article = utils.readme_to_html(article)
            article = md.render(article)
        self.article = article

        self.thumbnail = thumbnail
        theme = theme if theme is not None else os.getenv("GRADIO_THEME", "default")
        self.is_space = True if os.getenv("SYSTEM") == "spaces" else False
        DEPRECATED_THEME_MAP = {
            "darkdefault": "default",
            "darkhuggingface": "dark-huggingface",
            "darkpeach": "dark-peach",
            "darkgrass": "dark-grass",
        }
        VALID_THEME_SET = (
            "default",
            "huggingface",
            "seafoam",
            "grass",
            "peach",
            "dark",
            "dark-huggingface",
            "dark-seafoam",
            "dark-grass",
            "dark-peach",
        )
        if theme in DEPRECATED_THEME_MAP:
            warnings.warn(
                f"'{theme}' theme name is deprecated, using {DEPRECATED_THEME_MAP[theme]} instead."
            )
            theme = DEPRECATED_THEME_MAP[theme]
        elif theme not in VALID_THEME_SET:
            raise ValueError(
                f"Invalid theme name, theme must be one of: {', '.join(VALID_THEME_SET)}"
            )
        self.theme = theme

        self.height = height
        self.width = width
        if self.height is not None or self.width is not None:
            warnings.warn(
                "The `height` and `width` parameters in `Interface` "
                "are deprecated and should be passed into launch()."
            )

        if css is not None and os.path.exists(css):
            with open(css) as css_file:
                self.css = css_file.read()
        else:
            self.css = css
        if examples is None or (
            isinstance(examples, list)
            and (len(examples) == 0 or isinstance(examples[0], list))
        ):
            self.examples = examples
        elif (
            isinstance(examples, list) and len(self.input_components) == 1
        ):  # If there is only one input component, examples can be provided as a regular list instead of a list of lists
            self.examples = [[e] for e in examples]
        elif isinstance(examples, str):
            if not os.path.exists(examples):
                raise FileNotFoundError(
                    "Could not find examples directory: " + examples
                )
            log_file = os.path.join(examples, "log.csv")
            if not os.path.exists(log_file):
                if len(self.input_components) == 1:
                    exampleset = [
                        [os.path.join(examples, item)] for item in os.listdir(examples)
                    ]
                else:
                    raise FileNotFoundError(
                        "Could not find log file (required for multiple inputs): "
                        + log_file
                    )
            else:
                with open(log_file) as logs:
                    exampleset = list(csv.reader(logs))
                    exampleset = exampleset[1:]  # remove header
            for i, example in enumerate(exampleset):
                for j, (component, cell) in enumerate(
                    zip(
                        self.input_components + self.output_components,
                        example,
                    )
                ):
                    exampleset[i][j] = component.restore_flagged(
                        examples,
                        cell,
                        None,
                    )
            self.examples = exampleset
        else:
            raise ValueError(
                "Examples argument must either be a directory or a nested "
                "list, where each sublist represents a set of inputs."
            )
        self.num_shap = num_shap
        self.examples_per_page = examples_per_page

        self.simple_server = None
        self.allow_screenshot = allow_screenshot

        # For analytics_enabled and allow_flagging: (1) first check for
        # parameter, (2) check for env variable, (3) default to True/"manual"
        self.analytics_enabled = (
            analytics_enabled
            if analytics_enabled is not None
            else os.getenv("GRADIO_ANALYTICS_ENABLED", "True") == "True"
        )
        if allow_flagging is None:
            allow_flagging = os.getenv("GRADIO_ALLOW_FLAGGING", "manual")
        if allow_flagging is True:
            warnings.warn(
                "The `allow_flagging` parameter in `Interface` now"
                "takes a string value ('auto', 'manual', or 'never')"
                ", not a boolean. Setting parameter to: 'manual'."
            )
            self.allow_flagging = "manual"
        elif allow_flagging == "manual":
            self.allow_flagging = "manual"
        elif allow_flagging is False:
            warnings.warn(
                "The `allow_flagging` parameter in `Interface` now"
                "takes a string value ('auto', 'manual', or 'never')"
                ", not a boolean. Setting parameter to: 'never'."
            )
            self.allow_flagging = "never"
        elif allow_flagging == "never":
            self.allow_flagging = "never"
        elif allow_flagging == "auto":
            self.allow_flagging = "auto"
        else:
            raise ValueError(
                "Invalid value for `allow_flagging` parameter."
                "Must be: 'auto', 'manual', or 'never'."
            )

        self.flagging_options = flagging_options
        self.flagging_callback = flagging_callback
        self.flagging_dir = flagging_dir

        self.save_to = None  # Used for selenium tests
        self.share = None
        self.share_url = None
        self.local_url = None

        if show_tips is not None:
            warnings.warn(
                "The `show_tips` parameter in the `Interface` is deprecated. Please use the `show_tips` parameter in `launch()` instead"
            )

        self.requires_permissions = any(
            [component.requires_permissions for component in self.input_components]
        )

        self.enable_queue = enable_queue

        self.favicon_path = None
        self.height = height
        self.width = width
        if self.height is not None or self.width is not None:
            warnings.warn(
                "The `width` and `height` parameters in the `Interface` class"
                "will be deprecated. Please provide these parameters"
                "in `launch()` instead"
            )

        self.encrypt = encrypt
        if self.encrypt is not None:
            warnings.warn(
                "The `encrypt` parameter in the `Interface` class"
                "will be deprecated. Please provide this parameter"
                "in `launch()` instead"
            )

        if api_mode is not None:
            warnings.warn("The `api_mode` parameter in the `Interface` is deprecated.")
        self.api_mode = False

        data = {
            "fn": fn,
            "inputs": inputs,
            "outputs": outputs,
            "live": live,
            "capture_session": capture_session,
            "ip_address": self.ip_address,
            "interpretation": interpretation,
            "allow_flagging": allow_flagging,
            "allow_screenshot": allow_screenshot,
            "custom_css": self.css is not None,
            "theme": self.theme,
        }

        if self.analytics_enabled:
            utils.initiated_analytics(data)

        utils.version_check()
        Interface.instances.add(self)

        param_names = inspect.getfullargspec(self.predict[0])[0]
        for component, param_name in zip(self.input_components, param_names):
            if component.label is None:
                component.label = param_name
        for i, component in enumerate(self.output_components):
            if component.label is None:
                if len(self.output_components) == 1:
                    component.label = "output"
                else:
                    component.label = "output " + str(i)

        self.cache_examples = cache_examples
        if cache_examples:
            cache_interface_examples(self)

        if self.allow_flagging != "never":
            self.flagging_callback.setup(
                self.input_components + self.output_components, self.flagging_dir
            )

        with self:
            if self.title:
                Markdown(
                    "<h1 style='text-align: center; margin-bottom: 1rem'>"
                    + self.title
                    + "</h1>"
                )
            if self.description:
                Markdown(self.description)
            with Row():
                with Column(
                    css={
                        "background-color": "rgb(249,250,251)",
                        "padding": "0.5rem",
                        "border-radius": "0.5rem",
                    }
                ):
                    input_component_column = Column()
                    with input_component_column:
                        for component in self.input_components:
                            component.render()
                    if self.interpretation:
                        interpret_component_column = Column(visible=False)
                        interpretation_set = []
                        with interpret_component_column:
                            for component in self.input_components:
                                interpretation_set.append(Interpretation(component))
                    with Row():
                        clear_btn = Button("Clear")
                        if not self.live:
                            submit_btn = Button("Submit")
                with Column(
                    css={
                        "background-color": "rgb(249,250,251)",
                        "padding": "0.5rem",
                        "border-radius": "0.5rem",
                    }
                ):
                    status_tracker = StatusTracker(cover_container=True)
                    for component in self.output_components:
                        component.render()
                    with Row():
                        flag_btn = Button("Flag")
                        if self.interpretation:
                            interpretation_btn = Button("Interpret")
            submit_fn = (
                lambda *args: self.run_prediction(args)[0]
                if len(self.output_components) == 1
                else self.run_prediction(args)
            )
            if self.live:
                for component in self.input_components:
                    component.change(
                        submit_fn, self.input_components, self.output_components
                    )
            else:
                submit_btn.click(
                    submit_fn,
                    self.input_components,
                    self.output_components,
                    queue=self.enable_queue,
                    status_tracker=status_tracker,
                )
            clear_btn.click(
                lambda: [
                    component.default_value
                    if hasattr(component, "default_value")
                    else None
                    for component in self.input_components + self.output_components
                ]
                + [True]
                + ([False] if self.interpretation else []),
                [],
                self.input_components
                + self.output_components
                + [input_component_column]
                + ([interpret_component_column] if self.interpretation else []),
            )
            if self.examples:
                examples = Dataset(
                    components=self.input_components,
                    samples=self.examples,
                    type="index",
                )

                def load_example(example_id):
                    processed_examples = [
                        component.preprocess_example(sample)
                        for component, sample in zip(
                            self.input_components, self.examples[example_id]
                        )
                    ]
                    if self.cache_examples:
                        processed_examples += load_from_cache(self, example_id)
                    if len(processed_examples) == 1:
                        return processed_examples[0]
                    else:
                        return processed_examples

                examples._click_no_postprocess(
                    load_example,
                    inputs=[examples],
                    outputs=self.input_components
                    + (self.output_components if self.cache_examples else []),
                )

            flag_btn._click_no_preprocess(
                lambda *flag_data: self.flagging_callback.flag(flag_data),
                inputs=self.input_components + self.output_components,
                outputs=[],
            )
            if self.interpretation:
                interpretation_btn._click_no_preprocess(
                    lambda *data: self.interpret(data) + [False, True],
                    inputs=self.input_components + self.output_components,
                    outputs=interpretation_set
                    + [input_component_column, interpret_component_column],
                    status_tracker=status_tracker,
                )