Exemplo n.º 1
0
 def test_set_sample_data(self):
     test_array = ["test1", "test2", "test3"]
     temp_dir = tempfile.mkdtemp()
     inp = inputs.Sketchpad()
     out = outputs.Label()
     networking.build_template(temp_dir, inp, out)
     networking.set_sample_data_in_config_file(temp_dir, test_array)
     # We need to come up with a better way so that the config file isn't invalid json unless
     # the following parameters are set... (TODO: abidlabs)
     networking.set_always_flagged_in_config_file(temp_dir, False)
     networking.set_disabled_in_config_file(temp_dir, False)
     config_file = os.path.join(temp_dir, 'static/config.json')
     with open(config_file) as json_file:
         data = json.load(json_file)
         self.assertTrue(test_array == data["sample_inputs"])
Exemplo n.º 2
0
    def launch(self, inline=None, inbrowser=None, share=True, validate=True):
        """
        Standard method shared by interfaces that creates the interface and sets up a websocket to communicate with it.
        :param inline: boolean. If True, then a gradio interface is created inline (e.g. in jupyter or colab notebook)
        :param inbrowser: boolean. If True, then a new browser window opens with the gradio interface.
        :param share: boolean. If True, then a share link is generated using ngrok is displayed to the user.
        :param validate: boolean. If True, then the validation is run if the interface has not already been validated.
        """
        if validate and not self.validate_flag:
            self.validate()

        # If an existing interface is running with this instance, close it.
        if self.status == self.STATUS_TYPES["RUNNING"]:
            if self.verbose:
                print("Closing existing server...")
            if self.simple_server is not None:
                try:
                    networking.close_server(self.simple_server)
                except OSError:
                    pass

        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)
        path_to_local_server = "http://localhost:{}/".format(server_port)
        networking.build_template(
            output_directory, self.input_interface, self.output_interface
        )

        self.update_config_file(output_directory)

        self.status = self.STATUS_TYPES["RUNNING"]
        self.simple_server = httpd

        is_colab = False
        try:  # Check if running interactively using ipython.
            from_ipynb = get_ipython()
            if "google.colab" in str(from_ipynb):
                is_colab = True
        except NameError:
            pass

        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(f"IMPORTANT: You are using gradio version {current_pkg_version}, "
                      f"however version {latest_pkg_version} "
                      f"is available, please upgrade.")
                print('--------')
        except:  # TODO(abidlabs): don't catch all exceptions
            pass

        if self.verbose:
            print(strings.en["BETA_MESSAGE"])
            if not is_colab:
                print(strings.en["RUNNING_LOCALLY"].format(path_to_local_server))
        if share:
            try:
                share_url = networking.setup_tunnel(server_port)
            except 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)
                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 share_url is not None:
            networking.set_share_url_in_config_file(output_directory, share_url)
            if self.verbose:
                print(strings.en["GENERATING_PUBLIC_LINK"], end='\r')
                time.sleep(5)
                print(strings.en["MODEL_PUBLICLY_AVAILABLE_URL"].format(share_url))

        if inline is None:
            try:  # Check if running interactively using ipython.
                get_ipython()
                inline = True
                if inbrowser is None:
                    inbrowser = False
            except NameError:
                inline = False
                if inbrowser is None:
                    inbrowser = True
        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.
                display(IFrame(share_url, width=1000, height=500))
            else:
                display(IFrame(path_to_local_server, width=1000, height=500))

        return httpd, path_to_local_server, share_url
Exemplo 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
        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