Ejemplo n.º 1
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()
        networking.set_config(config)
        networking.set_meta_tags(self.title, self.description, self.thumbnail)
        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
Ejemplo n.º 2
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
        httpd (str): HTTPServer object
        path_to_local_server (str): Locally accessible link
        share_url (str): Publicly accessible link (if share=True)
        """

        output_directory = tempfile.mkdtemp()
        # Set up a port to serve the directory containing the static files with interface.
        server_port, httpd = networking.start_simple_server(
            self,
            output_directory,
            self.server_name,
            server_port=self.server_port)
        path_to_local_server = "http://{}:{}/".format(self.server_name,
                                                      server_port)
        networking.build_template(output_directory)

        self.server_port = server_port
        self.status = "RUNNING"
        self.simple_server = httpd

        try:
            current_pkg_version = pkg_resources.require("gradio")[0].version
            latest_pkg_version = requests.get(
                url=PKG_VERSION_URL).json()["version"]
            if StrictVersion(latest_pkg_version) > StrictVersion(
                    current_pkg_version):
                print("IMPORTANT: You are using gradio version {}, "
                      "however version {} "
                      "is available, please upgrade.".format(
                          current_pkg_version, latest_pkg_version))
                print('--------')
        except:  # TODO(abidlabs): don't catch all exceptions
            pass

        is_colab = utils.colab_check()
        if not is_colab:
            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:
            try:
                share_url = networking.setup_tunnel(server_port)
                print("Running on External URL:", share_url)
            except RuntimeError:
                utils.error_analytics("RuntimeError")
                share_url = None
                if self.verbose:
                    print(strings.en["NGROK_NO_INTERNET"])
        else:
            if is_colab:  # For a colab notebook, create a public link even if
                # share is False.
                share_url = networking.setup_tunnel(server_port)
                print("Running on External URL:", share_url)
                if self.verbose:
                    print(strings.en["COLAB_NO_LOCAL"])
            else:  # If it's not a colab notebook and share=False, print a message telling them about the share option.
                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
            if (is_colab):
                # Embed the remote interface page if on google colab;
                # otherwise, embed the local page.
                print("Interface loading below...")
                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))

        config = self.get_config_file()
        config["share_url"] = share_url

        processed_examples = []
        if self.examples is not None:
            for example_set in self.examples:
                processed_set = []
                for iface, example in zip(self.input_interfaces, example_set):
                    processed_set.append(iface.process_example(example))
                processed_examples.append(processed_set)
            config["examples"] = processed_examples

        networking.set_config(config, output_directory)
        networking.set_meta_tags(output_directory, self.title,
                                 self.description, self.thumbnail)

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

        launch_method = 'browser' if inbrowser else 'inline'
        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
        return httpd, path_to_local_server, share_url
Ejemplo n.º 3
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