コード例 #1
0
ファイル: external.py プロジェクト: charithmadhuranga/gradio
def interface_params_from_config(config_dict):
    ## instantiate input component and output component
    config_dict["inputs"] = [inputs.get_input_instance(component) for component in config_dict["input_components"]]
    config_dict["outputs"] = [outputs.get_output_instance(component) for component in config_dict["output_components"]]
    parameters = {
        "allow_flagging", "allow_screenshot", "article", "description", "flagging_options", "inputs", "outputs",
        "show_input", "show_output", "theme", "title"
    }
    config_dict = {k: config_dict[k] for k in parameters}
    return config_dict
コード例 #2
0
    def __init__(self,
                 fn,
                 inputs=None,
                 outputs=None,
                 verbose=False,
                 examples=None,
                 examples_per_page=10,
                 live=False,
                 layout="horizontal",
                 show_input=True,
                 show_output=True,
                 capture_session=False,
                 interpretation=None,
                 num_shap=2.0,
                 theme=None,
                 repeat_outputs_per_model=True,
                 title=None,
                 description=None,
                 article=None,
                 thumbnail=None,
                 css=None,
                 server_port=None,
                 server_name=networking.LOCALHOST_NAME,
                 height=500,
                 width=900,
                 allow_screenshot=True,
                 allow_flagging=True,
                 flagging_options=None,
                 encrypt=False,
                 show_tips=False,
                 embedding=None,
                 flagging_dir="flagged",
                 analytics_enabled=True):
        """
        Parameters:
        fn (Callable): the function to wrap an interface around.
        inputs (Union[str, 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, 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): 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, 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): 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 built-in interpreter. 
        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.
        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", "compact" or "huggingface".
        css (str): custom css or path to custom css file to use with interface.
        server_port (int): will start gradio app on this port (if available) 
        server_name (str): to make app accessible on local network set to "0.0.0.0".
        allow_screenshot (bool): if False, users will not see a button to take a screenshot of the interface.
        allow_flagging (bool): if False, users will not see a button to flag an input and output.
        flagging_options (List[str]): if not None, provides options a user must select when flagging.
        encrypt (bool): 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): if True, will occasionally show tips about new Gradio features
        """
        if not isinstance(fn, list):
            fn = [fn]
        if isinstance(inputs, list):
            self.input_components = [get_input_instance(i) for i in inputs]
        else:
            self.input_components = [get_input_instance(inputs)]
        if isinstance(outputs, list):
            self.output_components = [get_output_instance(i) for i in outputs]
        else:
            self.output_components = [get_output_instance(outputs)]

        if repeat_outputs_per_model:
            self.output_components *= len(fn)
        self.predict = fn
        self.function_names = [func.__name__ for func in fn]
        self.__name__ = ", ".join(self.function_names)
        self.verbose = verbose
        self.status = "OFF"
        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
        self.interpretation = interpretation
        self.session = None
        self.server_name = server_name
        self.title = title
        self.description = description
        if article is not None:
            article = utils.readme_to_html(article)
            article = markdown2.markdown(article)
        self.article = article
        self.thumbnail = thumbnail
        self.theme = theme if theme is not None else os.getenv(
            "GRADIO_THEME", "default")
        self.height = height
        self.width = width
        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, str) or (
                isinstance(examples, list) and
            (len(examples) == 0 or isinstance(examples[0], list))):
            self.examples = examples
        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.server_port = server_port
        self.simple_server = None
        self.allow_screenshot = allow_screenshot
        self.allow_flagging = os.getenv("GRADIO_FLAGGING") or allow_flagging
        self.flagging_options = flagging_options
        self.flagging_dir = flagging_dir
        self.encrypt = encrypt
        Interface.instances.add(self)
        self.analytics_enabled = analytics_enabled
        self.save_to = None
        self.share = None
        self.share_url = None
        self.local_url = None
        self.embedding = embedding
        self.show_tips = show_tips
        self.requires_permissions = any([
            component.requires_permissions
            for component in self.input_components
        ])

        data = {
            'fn': fn,
            'inputs': inputs,
            'outputs': outputs,
            'live': live,
            'capture_session': capture_session,
            'ip_address': ip_address,
            'interpretation': interpretation,
            'embedding': embedding,
            'allow_flagging': allow_flagging,
            'allow_screenshot': allow_screenshot,
        }

        if self.capture_session:
            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.
                pass

        if self.allow_flagging:
            os.makedirs(self.flagging_dir, exist_ok=True)

        if self.analytics_enabled:
            try:
                requests.post(analytics_url + 'gradio-initiated-analytics/',
                              data=data,
                              timeout=3)
            except (requests.ConnectionError, requests.exceptions.ReadTimeout):
                pass  # do not push analytics if no network