Blocks-Components

- move Timeseries component
This commit is contained in:
Ömer Faruk Özdemir 2022-03-15 23:28:32 +03:00
parent fbca310ccb
commit 7c50d2600d
3 changed files with 155 additions and 126 deletions

View File

@ -1857,3 +1857,92 @@ class Dataframe(Component):
+ self.type
+ ". Please choose from: 'pandas', 'numpy', 'array'."
)
class Timeseries(Component):
"""
Component accepts pandas.DataFrame uploaded as a timeseries csv file or as an output.
Input type: pandas.DataFrame
Output type: pandas.DataFrame
Demos: fraud_detector
"""
def __init__(
self,
default=None,
*,
x: Optional[str] = None,
y: str | List[str] = None,
label: Optional[str] = None,
**kwargs,
):
"""
Parameters:
default: IGNORED
x (str): Column name of x (time) series. None if csv has no headers, in which case first column is x series.
y (Union[str, List[str]]): Column name of y series, or list of column names if multiple series. None if csv has no headers, in which case every column after first is a y series.
label (str): component name in interface.
"""
self.x = x
if isinstance(y, str):
y = [y]
self.y = y
super().__init__(label=label, **kwargs)
def get_template_context(self):
return {
"x": self.x,
"y": self.y,
**super().get_template_context(),
}
@classmethod
def get_shortcut_implementations(cls):
return {
"timeseries": {},
}
def preprocess_example(self, x):
return {"name": x, "is_example": True}
def preprocess(self, x: Dict | None) -> pd.DataFrame | None:
"""
Parameters:
x (Dict[data: List[List[Union[str, number, bool]]], headers: List[str], range: List[number]]): Dict with keys 'data': 2D array of str, numeric, or bool data, 'headers': list of strings for header names, 'range': optional two element list designating start of end of subrange.
Returns:
(pandas.DataFrame): Dataframe of timeseries data
"""
if x is None:
return x
elif x.get("is_example"):
dataframe = pd.read_csv(x["name"])
else:
dataframe = pd.DataFrame(data=x["data"], columns=x["headers"])
if x.get("range") is not None:
dataframe = dataframe.loc[dataframe[self.x or 0] >= x["range"][0]]
dataframe = dataframe.loc[dataframe[self.x or 0] <= x["range"][1]]
return dataframe
def save_flagged(self, dir, label, data, encryption_key):
"""
Returns: (List[List[Union[str, float]]]) 2D array
"""
return json.dumps(data)
def restore_flagged(self, dir, data, encryption_key):
return json.loads(data)
def generate_sample(self):
return {"data": [[1] + [2] * len(self.y)] * 4, "headers": [self.x] + self.y}
# Output Functionalities
def postprocess(self, y):
"""
Parameters:
y (pandas.DataFrame): timeseries data
Returns:
(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()}

View File

@ -31,6 +31,7 @@ from gradio.components import (
Radio,
Slider,
Textbox,
Timeseries,
)
if TYPE_CHECKING: # Only import for type checking (is False at runtime).
@ -421,6 +422,10 @@ class Dataframe(Dataframe):
label (str): component name in interface.
optional (bool): this parameter is ignored.
"""
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__(
headers=headers,
row_count=row_count,
@ -434,6 +439,34 @@ class Dataframe(Dataframe):
)
class Timeseries(Timeseries):
"""
Component accepts pandas.DataFrame uploaded as a timeseries csv file.
Input type: pandas.DataFrame
Demos: fraud_detector
"""
def __init__(
self,
x: Optional[str] = None,
y: str | List[str] = None,
label: Optional[str] = None,
optional: bool = False,
):
"""
Parameters:
x (str): Column name of x (time) series. None if csv has no headers, in which case first column is x series.
y (Union[str, List[str]]): Column name of y series, or list of column names if multiple series. None if csv has no headers, in which case every column after first is a y series.
label (str): component name in interface.
optional (bool): If True, the interface can be submitted with no uploaded csv file, in which case the input value is None.
"""
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__(x=x, y=y, label=label, optional=optional)
class InputComponent(Component):
"""
Input Component. All input components subclass this.
@ -517,81 +550,6 @@ class InputComponent(Component):
}
class Timeseries(InputComponent):
"""
Component accepts pandas.DataFrame uploaded as a timeseries csv file.
Input type: pandas.DataFrame
Demos: fraud_detector
"""
def __init__(
self,
x: Optional[str] = None,
y: str | List[str] = None,
label: Optional[str] = None,
optional: bool = False,
):
"""
Parameters:
x (str): Column name of x (time) series. None if csv has no headers, in which case first column is x series.
y (Union[str, List[str]]): Column name of y series, or list of column names if multiple series. None if csv has no headers, in which case every column after first is a y series.
label (str): component name in interface.
optional (bool): If True, the interface can be submitted with no uploaded csv file, in which case the input value is None.
"""
self.x = x
if isinstance(y, str):
y = [y]
self.y = y
super().__init__(label, optional=optional)
def get_template_context(self):
return {
"x": self.x,
"y": self.y,
"optional": self.optional,
**super().get_template_context(),
}
@classmethod
def get_shortcut_implementations(cls):
return {
"timeseries": {},
}
def preprocess_example(self, x):
return {"name": x, "is_example": True}
def preprocess(self, x: Dict | None) -> pd.DataFrame | None:
"""
Parameters:
x (Dict[data: List[List[Union[str, number, bool]]], headers: List[str], range: List[number]]): Dict with keys 'data': 2D array of str, numeric, or bool data, 'headers': list of strings for header names, 'range': optional two element list designating start of end of subrange.
Returns:
(pandas.DataFrame): Dataframe of timeseries data
"""
if x is None:
return x
elif x.get("is_example"):
dataframe = pd.read_csv(x["name"])
else:
dataframe = pd.DataFrame(data=x["data"], columns=x["headers"])
if x.get("range") is not None:
dataframe = dataframe.loc[dataframe[self.x or 0] >= x["range"][0]]
dataframe = dataframe.loc[dataframe[self.x or 0] <= x["range"][1]]
return dataframe
def save_flagged(self, dir, label, data, encryption_key):
"""
Returns: (List[List[Union[str, float]]]) 2D array
"""
return json.dumps(data)
def restore_flagged(self, dir, data, encryption_key):
return json.loads(data)
def generate_sample(self):
return {"data": [[1] + [2] * len(self.y)] * 4, "headers": [self.x] + self.y}
class State(InputComponent):
"""
Special hidden component that stores state across runs of the interface.

View File

@ -21,7 +21,16 @@ import PIL
from ffmpy import FFmpeg
from gradio import processing_utils
from gradio.components import Audio, Component, Dataframe, File, Image, Textbox, Video
from gradio.components import (
Audio,
Component,
Dataframe,
File,
Image,
Textbox,
Timeseries,
Video,
)
if TYPE_CHECKING: # Only import for type checking (is False at runtime).
from gradio import Interface
@ -163,6 +172,29 @@ class Dataframe(Dataframe):
)
class Timeseries(Timeseries):
"""
Component accepts pandas.DataFrame.
Output type: pandas.DataFrame
Demos: fraud_detector
"""
def __init__(
self, x: str = None, y: str | List[str] = None, label: Optional[str] = None
):
"""
Parameters:
x (str): Column name of x (time) series. None if csv has no headers, in which case first column is x series.
y (Union[str, List[str]]): Column name of y series, or list of column names if multiple series. None if csv has no headers, in which case every column after first is a y series.
label (str): component name in interface.
"""
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__(x=x, y=y, label=label)
class OutputComponent(Component):
"""
Output Component. All output components subclass this.
@ -529,56 +561,6 @@ class Carousel(OutputComponent):
]
class Timeseries(OutputComponent):
"""
Component accepts pandas.DataFrame.
Output type: pandas.DataFrame
Demos: fraud_detector
"""
def __init__(
self, x: str = None, y: str | List[str] = None, label: Optional[str] = None
):
"""
Parameters:
x (str): Column name of x (time) series. None if csv has no headers, in which case first column is x series.
y (Union[str, List[str]]): Column name of y series, or list of column names if multiple series. None if csv has no headers, in which case every column after first is a y series.
label (str): component name in interface.
"""
self.x = x
if isinstance(y, str):
y = [y]
self.y = y
super().__init__(label)
def get_template_context(self):
return {"x": self.x, "y": self.y, **super().get_template_context()}
@classmethod
def get_shortcut_implementations(cls):
return {
"timeseries": {},
}
def postprocess(self, y):
"""
Parameters:
y (pandas.DataFrame): timeseries data
Returns:
(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()}
def save_flagged(self, dir, label, data, encryption_key):
"""
Returns: (List[List[Union[str, float]]]) 2D array
"""
return json.dumps(data)
def restore_flagged(self, dir, data, encryption_key):
return json.loads(data)
class Chatbot(OutputComponent):
"""
Component displays a chatbot output showing both user submitted messages and responses