From 727a764f70bd7a03346150a802c23e67f9568385 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=96mer=20Faruk=20=C3=96zdemir?= Date: Tue, 15 Mar 2022 23:43:09 +0300 Subject: [PATCH] Blocks-Components - move State component - move Create get_component_instance --- gradio/components.py | 55 +++++++++++++++++++- gradio/inputs.py | 117 +++---------------------------------------- gradio/outputs.py | 41 ++++++++------- 3 files changed, 81 insertions(+), 132 deletions(-) diff --git a/gradio/components.py b/gradio/components.py index 9d9ee8c6c7..7b025fe421 100644 --- a/gradio/components.py +++ b/gradio/components.py @@ -14,7 +14,7 @@ import pandas as pd import PIL from ffmpy import FFmpeg -from gradio import processing_utils, test_data +from gradio import Interface, processing_utils, test_data from gradio.blocks import Block @@ -1946,3 +1946,56 @@ class Timeseries(Component): (Dict[headers: List[str], data: List[List[Union[str, number]]]]): JSON object with key 'headers' for list of header names, 'data' for 2D array of string or numeric data """ return {"headers": y.columns.values.tolist(), "data": y.values.tolist()} + + +class State(Component): + """ + Special hidden component that stores state across runs of the interface. + + Input type: Any + Output type: Any + Demos: chatbot + """ + + def __init__(self, default: Any = None, *, label: str = None, **kwargs): + """ + Parameters: + default (Any): the initial value of the state. + label (str): component name in interface (not used). + """ + self.default = default + super().__init__(label=label, **kwargs) + + def get_template_context(self): + return {"default": self.default, **super().get_template_context()} + + @classmethod + def get_shortcut_implementations(cls): + return { + "state": {}, + } + + +def get_component_instance(iface: Interface): + # TODO: function may not work properly, and it needs updates regarding its design. See: + # https://github.com/gradio-app/gradio/issues/731 + if isinstance(iface, str): + shortcut = Component.get_all_shortcut_implementations()[iface] + return shortcut[0](**shortcut[1]) + elif isinstance( + iface, dict + ): # a dict with `name` as the input component type and other keys as parameters + name = iface.pop("name") + for component in Component.__subclasses__(): + if component.__name__.lower() == name: + break + else: + raise ValueError("No such InputComponent: {}".format(name)) + return component(**iface) + elif isinstance(iface, Component): + return iface + else: + raise ValueError( + "Input interface must be of type `str` or `dict` or " + "`InputComponent` but is {}".format(iface) + ) diff --git a/gradio/inputs.py b/gradio/inputs.py index 7a5c73bfcd..cf9e700132 100644 --- a/gradio/inputs.py +++ b/gradio/inputs.py @@ -30,6 +30,7 @@ from gradio.components import ( Number, Radio, Slider, + State, Textbox, Timeseries, ) @@ -467,90 +468,7 @@ class Timeseries(Timeseries): super().__init__(x=x, y=y, label=label, optional=optional) -class InputComponent(Component): - """ - Input Component. All input components subclass this. - """ - - def __init__( - self, label: str, requires_permissions: bool = False, optional: bool = False - ): - """ - Constructs an input component. - """ - self.component_type = "input" - self.set_interpret_parameters() - self.optional = optional - super().__init__(label=label, requires_permissions=requires_permissions) - - def preprocess(self, x: Any) -> Any: - """ - Any preprocessing needed to be performed on function input. - """ - return x - - def serialize(self, x: Any, called_directly: bool) -> Any: - """ - Convert from a human-readable version of the input (path of an image, URL of a video, etc.) into the interface to a serialized version (e.g. base64) to pass into an API. May do different things if the interface is called() vs. used via GUI. - Parameters: - x (Any): Input to interface - called_directly (bool): if true, the interface was called(), otherwise, it is being used via the GUI - """ - return x - - def preprocess_example(self, x: Any) -> Any: - """ - Any preprocessing needed to be performed on an example before being passed to the main function. - """ - return x - - def set_interpret_parameters(self): - """ - Set any parameters for interpretation. - """ - return self - - def get_interpretation_neighbors(self, x: Any) -> Tuple[List[Any], Dict[Any], bool]: - """ - Generates values similar to input to be used to interpret the significance of the input in the final output. - Parameters: - x (Any): Input to interface - Returns: (neighbor_values, interpret_kwargs, interpret_by_removal) - neighbor_values (List[Any]): Neighboring values to input x to compute for interpretation - interpret_kwargs (Dict[Any]): Keyword arguments to be passed to get_interpretation_scores - interpret_by_removal (bool): If True, returned neighbors are values where the interpreted subsection was removed. If False, returned neighbors are values where the interpreted subsection was modified to a different value. - """ - pass - - def get_interpretation_scores( - self, x: Any, neighbors: List[Any], scores: List[float], **kwargs - ) -> List[Any]: - """ - Arrange the output values from the neighbors into interpretation scores for the interface to render. - Parameters: - x (Any): Input to interface - neighbors (List[Any]): Neighboring values to input x used for interpretation. - scores (List[float]): Output value corresponding to each neighbor in neighbors - kwargs (Dict[str, Any]): Any additional arguments passed from get_interpretation_neighbors. - Returns: - (List[Any]): Arrangement of interpretation scores for interfaces to render. - """ - pass - - def generate_sample(self) -> Any: - """ - Returns a sample value of the input that would be accepted by the api. Used for api documentation. - """ - pass - - def get_template_context(self): - return { - "optional": self.optional, - **super().get_template_context(), - } - - -class State(InputComponent): +class State(State): """ Special hidden component that stores state across runs of the interface. Input type: Any @@ -569,9 +487,11 @@ class State(InputComponent): default (Any): the initial value of the state. optional (bool): this parameter is ignored. """ - - self.default = default - super().__init__(label) + warnings.warn( + "Usage of gradio.inputs is deprecated, and will not be supported in the future, please import your components from gradio.components", + DeprecationWarning, + ) + super().__init__(label=label, default=default, optional=optional) def get_template_context(self): return {"default": self.default, **super().get_template_context()} @@ -581,26 +501,3 @@ class State(InputComponent): return { "state": {}, } - - -def get_input_instance(iface: Interface): - if isinstance(iface, str): - shortcut = InputComponent.get_all_shortcut_implementations()[iface] - return shortcut[0](**shortcut[1]) - elif isinstance( - iface, dict - ): # a dict with `name` as the input component type and other keys as parameters - name = iface.pop("name") - for component in InputComponent.__subclasses__(): - if component.__name__.lower() == name: - break - else: - raise ValueError("No such InputComponent: {}".format(name)) - return component(**iface) - elif isinstance(iface, InputComponent): - return iface - else: - raise ValueError( - "Input interface must be of type `str` or `dict` or " - "`InputComponent` but is {}".format(iface) - ) diff --git a/gradio/outputs.py b/gradio/outputs.py index 91e5b2ee8e..26f7f418f7 100644 --- a/gradio/outputs.py +++ b/gradio/outputs.py @@ -27,6 +27,7 @@ from gradio.components import ( Dataframe, File, Image, + State, Textbox, Timeseries, Video, @@ -195,6 +196,25 @@ class Timeseries(Timeseries): super().__init__(x=x, y=y, label=label) +class State(State): + """ + Special hidden component that stores state across runs of the interface. + Output type: Any + Demos: chatbot + """ + + def __init__(self, label: Optional[str] = None): + """ + Parameters: + label (str): component name in interface (not used). + """ + warnings.warn( + "Usage of gradio.outputs is deprecated, and will not be supported in the future, please import your components from gradio.components", + DeprecationWarning, + ) + super().__init__(label=label) + + class OutputComponent(Component): """ Output Component. All output components subclass this. @@ -595,27 +615,6 @@ class Chatbot(OutputComponent): return y -class State(OutputComponent): - """ - Special hidden component that stores state across runs of the interface. - Output type: Any - Demos: chatbot - """ - - def __init__(self, label: Optional[str] = None): - """ - Parameters: - label (str): component name in interface (not used). - """ - super().__init__(label) - - @classmethod - def get_shortcut_implementations(cls): - return { - "state": {}, - } - - def get_output_instance(iface: Interface): if isinstance(iface, str): shortcut = OutputComponent.get_all_shortcut_implementations()[iface]