Merge pull request #843 from gradio-app/Blocks-Components-v2

Blocks components V2
This commit is contained in:
Abubakar Abid 2022-03-22 10:31:34 -07:00 committed by GitHub
commit e8e8439cb1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 215 additions and 215 deletions

View File

@ -209,7 +209,7 @@ class Textbox(Component):
def __init__(
self,
default: str = "",
default_value: str = "",
*,
lines: int = 1,
placeholder: Optional[str] = None,
@ -218,12 +218,10 @@ class Textbox(Component):
):
"""
Parameters:
default (str): default text to provide in textarea.
default_value (str): default text to provide in textarea.
lines (int): number of line rows to provide in textarea.
placeholder (str): placeholder hint to provide behind textarea.
label (str): component name in interface.
numeric (bool): DEPRECATED.
type (str): DEPRECATED.
"""
if "numeric" in kwargs:
warnings.warn(
@ -235,11 +233,11 @@ class Textbox(Component):
"The 'type' parameter has been deprecated. Use the Number component instead if you need it.",
DeprecationWarning,
)
default = str(default)
default_value = str(default_value)
self.lines = lines
self.placeholder = placeholder
self.default = default
self.test_input = default
self.default = default_value
self.test_input = default_value
self.interpret_by_tokens = True
super().__init__(label=label, **kwargs)
@ -373,17 +371,17 @@ class Number(Component):
def __init__(
self,
default: Optional[float] = None,
default_value: Optional[float] = None,
*,
label: Optional[str] = None,
**kwargs,
):
"""
Parameters:
default (float): default value.
default_value (float): default value.
label (str): component name in interface.
"""
self.default = float(default) if default is not None else None
self.default = float(default_value) if default_value is not None else None
self.test_input = self.default if self.default is not None else 1
self.interpret_by_tokens = False
super().__init__(label=label, **kwargs)
@ -486,7 +484,7 @@ class Slider(Component):
def __init__(
self,
default: Optional[float] = None,
default_value: Optional[float] = None,
*,
minimum: float = 0,
maximum: float = 100,
@ -496,7 +494,7 @@ class Slider(Component):
):
"""
Parameters:
default (float): default value.
default_value (float): default value.
minimum (float): minimum value for slider.
maximum (float): maximum value for slider.
step (float): increment between slider values.
@ -509,7 +507,7 @@ class Slider(Component):
power = math.floor(math.log10(difference) - 2)
step = 10**power
self.step = step
self.default = minimum if default is None else default
self.default = minimum if default_value is None else default_value
self.test_input = self.default
self.interpret_by_tokens = False
super().__init__(label=label, **kwargs)
@ -596,14 +594,16 @@ class Checkbox(Component):
Demos: sentence_builder, titanic_survival
"""
def __init__(self, default: bool = False, *, label: Optional[str] = None, **kwargs):
def __init__(
self, default_value: bool = False, *, label: Optional[str] = None, **kwargs
):
"""
Parameters:
default (bool): if True, checked by default.
default_value (bool): if True, checked by default.
label (str): component name in interface.
"""
self.test_input = True
self.default = default
self.default = default_value
self.interpret_by_tokens = False
super().__init__(label=label, **kwargs)
@ -678,7 +678,7 @@ class CheckboxGroup(Component):
def __init__(
self,
default: List[str] = None,
default_value: List[str] = None,
*,
choices: List[str],
type: str = "value",
@ -687,17 +687,17 @@ class CheckboxGroup(Component):
):
"""
Parameters:
default (List[str]): default selected list of options.
default_value (List[str]): default selected list of options.
choices (List[str]): list of options to select from.
type (str): Type of value to be returned by component. "value" returns the list of strings of the choices selected, "index" returns the list of indicies of the choices selected.
label (str): component name in interface.
"""
if (
default is None
default_value is None
): # Mutable parameters shall not be given as default parameters in the function.
default = []
default_value = []
self.choices = choices
self.default = default
self.default = default_value
self.type = type
self.test_input = self.choices
self.interpret_by_tokens = False
@ -795,7 +795,7 @@ class Radio(Component):
def __init__(
self,
default: Optional[str] = None,
default_value: Optional[str] = None,
*,
choices: List[str],
type: str = "value",
@ -804,7 +804,7 @@ class Radio(Component):
):
"""
Parameters:
default (str): the button selected by default. If None, no button is selected by default.
default_value (str): the button selected by default. If None, no button is selected by default.
choices (List[str]): list of options to select from.
type (str): Type of value to be returned by component. "value" returns the string of the choice selected, "index" returns the index of the choice selected.
label (str): component name in interface.
@ -812,7 +812,7 @@ class Radio(Component):
self.choices = choices
self.type = type
self.test_input = self.choices[0]
self.default = default if default is not None else self.choices[0]
self.default = default_value if default_value is not None else self.choices[0]
self.interpret_by_tokens = False
super().__init__(label=label, **kwargs)
@ -887,7 +887,7 @@ class Dropdown(Radio):
def __init__(
self,
default: Optional[str] = None,
default_value: Optional[str] = None,
*,
choices: List[str],
type: str = "value",
@ -896,14 +896,18 @@ class Dropdown(Radio):
):
"""
Parameters:
default_value (str): default value selected in dropdown. If None, no value is selected by default.
choices (List[str]): list of options to select from.
type (str): Type of value to be returned by component. "value" returns the string of the choice selected, "index" returns the index of the choice selected.
default (str): default value selected in dropdown. If None, no value is selected by default.
label (str): component name in interface.
"""
# Everything is same with Dropdown and Radio, so let's make use of it :)
super().__init__(
default=default, choices=choices, type=type, label=label, **kwargs
default_value=default_value,
choices=choices,
type=type,
label=label,
**kwargs,
)
@ -918,7 +922,7 @@ class Image(Component):
def __init__(
self,
default=None,
default_value=None,
*,
shape: Tuple[int, int] = None,
image_mode: str = "RGB",
@ -931,15 +935,13 @@ class Image(Component):
):
"""
Parameters:
default(str): IGNORED
default_value(str): IGNORED
shape (Tuple[int, int]): (width, height) shape to crop and resize image to; if None, matches input image size.
image_mode (str): "RGB" if color, or "L" if black and white.
invert_colors (bool): whether to invert the image as a preprocessing step.
source (str): Source of image. "upload" creates a box where user can drop an image file, "webcam" allows user to take snapshot from their webcam, "canvas" defaults to a white image that can be edited and drawn upon with tools.
tool (str): Tools used for editing. "editor" allows a full screen editor, "select" provides a cropping and zoom tool.
type (str): #TODO:(Faruk) combine the descriptions below
input: Type of value to be returned by component. "numpy" returns a numpy array with shape (width, height, 3) and values from 0 to 255, "pil" returns a PIL image object, "file" returns a temporary file object whose path can be retrieved by file_obj.name, "filepath" returns the path directly.
output: Type of value to be passed to component. "numpy" expects a numpy array with shape (width, height, 3), "pil" expects a PIL image object, "file" expects a file path to the saved image or a remote URL, "plot" expects a matplotlib.pyplot object, "auto" detects return type.
type (str): The format the image is converted to before being passed into the prediction function. "numpy" converts the image to a numpy array with shape (width, height, 3) and values from 0 to 255, "pil" converts the image to a PIL image object, "file" produces a temporary file object whose path can be retrieved by file_obj.name, "filepath" returns the path directly.
label (str): component name in interface.
"""
if "plot" in kwargs:
@ -952,6 +954,7 @@ class Image(Component):
self.type = type
self.type = type
self.output_type = "auto"
self.shape = shape
self.image_mode = image_mode
self.source = source
@ -1173,7 +1176,7 @@ class Image(Component):
Returns:
(str): base64 url data
"""
if self.type == "auto":
if self.output_type == "auto":
if isinstance(y, np.ndarray):
dtype = "numpy"
elif isinstance(y, PIL.Image.Image):
@ -1187,7 +1190,7 @@ class Image(Component):
"Unknown type. Please choose from: 'numpy', 'pil', 'file', 'plot'."
)
else:
dtype = self.type
dtype = self.output_type
if dtype in ["numpy", "pil"]:
if dtype == "pil":
y = np.array(y)
@ -1220,7 +1223,7 @@ class Video(Component):
def __init__(
self,
default="",
default_value="",
*,
type: Optional[str] = None,
source: str = "upload",
@ -1229,7 +1232,7 @@ class Video(Component):
):
"""
Parameters:
default (str): IGNORED
default_value (str): IGNORED
type (str): Type of video format to be returned by component, such as 'avi' or 'mp4'. Use 'mp4' to ensure browser playability. If set to None, video will keep uploaded format.
source (str): Source of video. "upload" creates a box where user can drop an video file, "webcam" allows user to record a video from their webcam.
label (str): component name in interface.
@ -1333,7 +1336,7 @@ class Audio(Component):
def __init__(
self,
default="",
default_value="",
*,
source: str = "upload",
type: str = "numpy",
@ -1342,13 +1345,15 @@ class Audio(Component):
):
"""
Parameters:
default_value (str): IGNORED
source (str): Source of audio. "upload" creates a box where user can drop an audio file, "microphone" creates a microphone input.
type (str): Type of value to be returned by component. "numpy" returns a 2-set tuple with an integer sample_rate and the data numpy.array of shape (samples, 2), "file" returns a temporary file object whose path can be retrieved by file_obj.name, "filepath" returns the path directly.
type (str): The format the image is converted to before being passed into the prediction function. "numpy" converts the image to a numpy array with shape (width, height, 3) and values from 0 to 255, "pil" converts the image to a PIL image object, "file" produces a temporary file object whose path can be retrieved by file_obj.name, "filepath" returns the path directly.
label (str): component name in interface.
"""
self.source = source
requires_permissions = source == "microphone"
self.type = type
self.output_type = "auto"
self.test_input = test_data.BASE64_AUDIO
self.interpret_by_tokens = True
super().__init__(
@ -1543,7 +1548,7 @@ class Audio(Component):
Returns:
(str): base64 url data
"""
if self.type in ["numpy", "file", "auto"]:
if self.output_type in ["numpy", "file", "auto"]:
if self.type == "numpy" or (self.type == "auto" and isinstance(y, tuple)):
sample_rate, data = y
file = tempfile.NamedTemporaryFile(
@ -1572,7 +1577,7 @@ class File(Component):
def __init__(
self,
default: str = "",
default_value: str = "",
*,
file_count: str = "single",
type: str = "file",
@ -1581,7 +1586,7 @@ class File(Component):
):
"""
Parameters:
default (str): IGNORED
default_value (str): IGNORED
file_count (str): if single, allows user to upload one file. If "multiple", user uploads multiple files. If "directory", user uploads all files in selected directory. Return type will be list for each file in case of "multiple" or "directory".
type (str): Type of value to be returned by component. "file" returns a temporary file object whose path can be retrieved by file_obj.name, "binary" returns an bytes object.
label (str): component name in interface.
@ -1689,7 +1694,7 @@ class Dataframe(Component):
def __init__(
self,
default: Optional[List[List[Any]]] = None,
default_value: Optional[List[List[Any]]] = None,
*,
headers: Optional[List[str]] = None,
row_count: int = 3,
@ -1705,7 +1710,7 @@ class Dataframe(Component):
):
"""
Input Parameters:
default (List[List[Any]]): Default value
default_value (List[List[Any]]): Default value
headers (List[str]): Header names to dataframe. If None, no headers are shown.
row_count (int): Limit number of rows for input.
col_count (int): Limit number of columns for input. If equal to 1, return data will be one-dimensional. Ignored if `headers` is provided.
@ -1713,13 +1718,11 @@ class Dataframe(Component):
col_width (Union[int, List[int]]): Width of columns in pixels. Can be provided as single value or list of values per column.
type (str): Type of value to be returned by component. "pandas" for pandas dataframe, "numpy" for numpy array, or "array" for a Python array.
label (str): component name in interface.
Output Parameters: #TODO:(faruk) might converge these in the future
Output Parameters:
headers (List[str]): Header names to dataframe. Only applicable if type is "numpy" or "array".
max_rows (int): Maximum number of rows to display at once. Set to None for infinite.
max_cols (int): Maximum number of columns to display at once. Set to None for infinite.
overflow_row_behaviour (str): If set to "paginate", will create pages for overflow rows. If set to "show_ends", will show initial and final rows and truncate middle rows.
type (str): Type of value to be passed to component. "pandas" for pandas dataframe, "numpy" for numpy array, or "array" for Python array, "auto" detects return type.
"""
self.headers = headers
self.datatype = datatype
@ -1727,9 +1730,10 @@ class Dataframe(Component):
self.col_count = len(headers) if headers else col_count
self.col_width = col_width
self.type = type
self.output_type = "auto"
self.default = (
default
if default is not None
default_value
if default_value is not None
else [[None for _ in range(self.col_count)] for _ in range(self.row_count)]
)
sample_values = {
@ -1820,7 +1824,7 @@ class Dataframe(Component):
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
"""
if self.type == "auto":
if self.output_type == "auto":
if isinstance(y, pd.core.frame.DataFrame):
dtype = "pandas"
elif isinstance(y, np.ndarray):
@ -1828,7 +1832,7 @@ class Dataframe(Component):
elif isinstance(y, list):
dtype = "array"
else:
dtype = self.type
dtype = self.output_type
if dtype == "pandas":
return {"headers": list(y.columns), "data": y.values.tolist()}
elif dtype in ("numpy", "array"):
@ -1856,7 +1860,7 @@ class Timeseries(Component):
def __init__(
self,
default=None,
default_value=None,
*,
x: Optional[str] = None,
y: str | List[str] = None,
@ -1865,7 +1869,7 @@ class Timeseries(Component):
):
"""
Parameters:
default: IGNORED
default_value: 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.
@ -1943,13 +1947,13 @@ class State(Component):
Demos: chatbot
"""
def __init__(self, default: Any = None, *, label: str = None, **kwargs):
def __init__(self, default_value: Any = None, *, label: str = None, **kwargs):
"""
Parameters:
default (Any): the initial value of the state.
default_value (Any): the initial value of the state.
label (str): component name in interface (not used).
"""
self.default = default
self.default = default_value
super().__init__(label=label, **kwargs)
def get_template_context(self):
@ -1974,22 +1978,20 @@ class Label(Component):
def __init__(
self,
default: str = "",
default_value: str = "",
*,
num_top_classes: Optional[int] = None,
type: str = "auto",
label: Optional[str] = None,
**kwargs,
):
"""
Parameters:
default(str): IGNORED
default_value(str): IGNORED
num_top_classes (int): number of most confident classes to show.
type (str): Type of value to be passed to component. "value" expects a single out label, "confidences" expects a dictionary mapping labels to confidence scores, "auto" detects return type.
label (str): component name in interface.
"""
self.num_top_classes = num_top_classes
self.type = type
self.output_type = "auto"
super().__init__(label=label, **kwargs)
def postprocess(self, y):
@ -1999,12 +2001,12 @@ class Label(Component):
Returns:
(Dict[label: str, confidences: List[Dict[label: str, confidence: number]]]): Object with key 'label' representing primary label, and key 'confidences' representing a list of label-confidence pairs
"""
if self.type == "label" or (
self.type == "auto" and (isinstance(y, (str, numbers.Number)))
if self.output_type == "label" or (
self.output_type == "auto" and (isinstance(y, (str, numbers.Number)))
):
return {"label": str(y)}
elif self.type == "confidences" or (
self.type == "auto" and isinstance(y, dict)
elif self.output_type == "confidences" or (
self.output_type == "auto" and isinstance(y, dict)
):
sorted_pred = sorted(y.items(), key=operator.itemgetter(1), reverse=True)
if self.num_top_classes is not None:
@ -2024,8 +2026,8 @@ class Label(Component):
def deserialize(self, y):
# 5 cases: (1): {'label': 'lion'}, {'label': 'lion', 'confidences':...}, {'lion': 0.46, ...}, 'lion', '0.46'
if self.type == "label" or (
self.type == "auto"
if self.output_type == "label" or (
self.output_type == "auto"
and (
isinstance(y, (str, numbers.Number))
or ("label" in y and not ("confidences" in y.keys()))
@ -2035,7 +2037,7 @@ class Label(Component):
return y
else:
return y["label"]
elif self.type == "confidences" or self.type == "auto":
elif self.output_type == "confidences" or self.output_type == "auto":
if ("confidences" in y.keys()) and isinstance(y["confidences"], list):
return {k["label"]: k["confidence"] for k in y["confidences"]}
else:
@ -2070,24 +2072,6 @@ class Label(Component):
return data
class KeyValues(Component):
"""
Component displays a table representing values for multiple fields.
Output type: Union[Dict, List[Tuple[str, Union[str, int, float]]]]
Demos: text_analysis
"""
def __init__(self, default: str = " ", *, label: Optional[str] = None, **kwargs):
"""
Parameters:
default (str): IGNORED
label (str): component name in interface.
"""
raise DeprecationWarning(
"The KeyValues component is deprecated. Please use the DataFrame or JSON "
"components instead.")
class HighlightedText(Component):
"""
Component creates text that contains spans that are highlighted by category or numerical value.
@ -2098,7 +2082,7 @@ class HighlightedText(Component):
def __init__(
self,
default: str = "",
default_value: str = "",
*,
color_map: Dict[str, str] = None,
label: Optional[str] = None,
@ -2107,7 +2091,7 @@ class HighlightedText(Component):
):
"""
Parameters:
default (str): IGNORED
default_value (str): IGNORED
color_map (Dict[str, str]): Map between category and respective colors
label (str): component name in interface.
show_legend (bool): whether to show span categories in a separate legend or inline.
@ -2153,10 +2137,12 @@ class JSON(Component):
Demos: zip_to_json
"""
def __init__(self, default: str = "", *, label: Optional[str] = None, **kwargs):
def __init__(
self, default_value: str = "", *, label: Optional[str] = None, **kwargs
):
"""
Parameters:
default (str): IGNORED
default_value (str): IGNORED
label (str): component name in interface.
"""
super().__init__(label=label, **kwargs)
@ -2193,10 +2179,10 @@ class HTML(Component):
Demos: text_analysis
"""
def __init__(self, default: str = "", label: Optional[str] = None, **kwargs):
def __init__(self, default_value: str = "", label: Optional[str] = None, **kwargs):
"""
Parameters:
default (str): IGNORED
default_value (str): IGNORED
label (str): component name in interface.
"""
super().__init__(label=label, **kwargs)
@ -2226,7 +2212,7 @@ class Carousel(Component):
def __init__(
self,
default="",
default_value="",
*,
components: Component | List[Component],
label: Optional[str] = None,
@ -2234,7 +2220,7 @@ class Carousel(Component):
):
"""
Parameters:
default (str): IGNORED
default_value (str): IGNORED
components (Union[List[OutputComponent], OutputComponent]): Classes of component(s) that will be scrolled through.
label (str): component name in interface.
"""
@ -2303,10 +2289,10 @@ class Chatbot(Component):
Demos: chatbot
"""
def __init__(self, default="", *, label: Optional[str] = None, **kwargs):
def __init__(self, default_value="", *, label: Optional[str] = None, **kwargs):
"""
Parameters:
default (str): IGNORED
default_value (str): IGNORED
label (str): component name in interface (not used).
"""
super().__init__(label=label, **kwargs)
@ -2333,15 +2319,13 @@ class Chatbot(Component):
# Static Components
class Markdown(Component):
# TODO: might add default parameter to initilization, WDYT Ali Abid?
def __init__(self, label):
super().__init__(label=label)
def __init__(self, default_value: str = "", *, label: str, **kwargs):
super().__init__(label=label, **kwargs)
class Button(Component):
# TODO: might add default parameter to initilization, WDYT Ali Abid?
def __init__(self, label):
super().__init__(label=label)
def __init__(self, default_value: str = "", *, label: str, **kwargs):
super().__init__(label=label, **kwargs)
# TODO: (faruk) does this take component or interface as a input?

View File

@ -49,7 +49,7 @@ def get_huggingface_interface(model_name, api_key, alias):
pipelines = {
"audio-classification": {
# example model: https://hf.co/ehcalabres/wav2vec2-lg-xlsr-en-speech-emotion-recognition
"inputs": components.Audio(label="Input", source="upload", type="filepath"),
"inputs": components.Audio(source="upload", type="filepath", label="Input"),
"outputs": components.Label(label="Class"),
"preprocess": lambda i: base64.b64decode(
i["data"].split(",")[1]
@ -60,7 +60,7 @@ def get_huggingface_interface(model_name, api_key, alias):
},
"audio-to-audio": {
# example model: https://hf.co/speechbrain/mtl-mimic-voicebank
"inputs": components.Audio(label="Input", source="upload", type="filepath"),
"inputs": components.Audio(source="upload", type="filepath", label="Input"),
"outputs": components.Audio(label="Output"),
"preprocess": lambda i: base64.b64decode(
i["data"].split(",")[1]
@ -69,7 +69,7 @@ def get_huggingface_interface(model_name, api_key, alias):
},
"automatic-speech-recognition": {
# example model: https://hf.co/jonatasgrosman/wav2vec2-large-xlsr-53-english
"inputs": components.Audio(label="Input", source="upload", type="filepath"),
"inputs": components.Audio(source="upload", type="filepath", label="Input"),
"outputs": components.Textbox(label="Output"),
"preprocess": lambda i: base64.b64decode(
i["data"].split(",")[1]
@ -91,7 +91,7 @@ def get_huggingface_interface(model_name, api_key, alias):
},
"image-classification": {
# Example: https://huggingface.co/google/vit-base-patch16-224
"inputs": components.Image(label="Input Image", type="filepath"),
"inputs": components.Image(type="filepath", label="Input Image"),
"outputs": components.Label(label="Classification"),
"preprocess": lambda i: base64.b64decode(
i.split(",")[1]
@ -111,10 +111,13 @@ def get_huggingface_interface(model_name, api_key, alias):
# TODO: also: support NER pipeline, object detection, table question answering
"question-answering": {
"inputs": [
components.Textbox(label="Context", lines=7),
components.Textbox(lines=7, label="Context"),
components.Textbox(label="Question"),
],
"outputs": [components.Textbox(label="Answer"), components.Label(label="Score")],
"outputs": [
components.Textbox(label="Answer"),
components.Label(label="Score"),
],
"preprocess": lambda c, q: {"inputs": {"context": c, "question": q}},
"postprocess": lambda r: (r.json()["answer"], r.json()["score"]),
},
@ -126,7 +129,7 @@ def get_huggingface_interface(model_name, api_key, alias):
},
"text-classification": {
"inputs": components.Textbox(label="Input"),
"outputs": components.Label(label="Classification", type="confidences"),
"outputs": components.Label(type="confidences", label="Classification"),
"preprocess": lambda x: {"inputs": x},
"postprocess": lambda r: {
i["label"].split(", ")[0]: i["score"] for i in r.json()[0]
@ -156,7 +159,7 @@ def get_huggingface_interface(model_name, api_key, alias):
components.Textbox(label="Possible class names (" "comma-separated)"),
components.Checkbox(label="Allow multiple true classes"),
],
"outputs": components.Label(label="Classification", type="confidences"),
"outputs": components.Label(type="confidences", label="Classification"),
"preprocess": lambda i, c, m: {
"inputs": i,
"parameters": {"candidate_labels": c, "multi_class": m},
@ -170,12 +173,12 @@ def get_huggingface_interface(model_name, api_key, alias):
# example model: hf.co/sentence-transformers/distilbert-base-nli-stsb-mean-tokens
"inputs": [
components.Textbox(
label="Source Sentence", default="That is a happy person"
default_value="That is a happy person", label="Source Sentence"
),
components.Textbox(
lines=7,
label="Sentences to compare to",
placeholder="Separate each sentence by a newline",
label="Sentences to compare to",
),
],
"outputs": components.Label(label="Classification"),
@ -354,7 +357,9 @@ def load_from_pipeline(pipeline):
pipeline, transformers.AudioClassificationPipeline
):
pipeline_info = {
"inputs": components.Audio(label="Input", source="microphone", type="filepath"),
"inputs": components.Audio(
source="microphone", type="filepath", label="Input"
),
"outputs": components.Label(label="Class"),
"preprocess": lambda i: {"inputs": i},
"postprocess": lambda r: {i["label"].split(", ")[0]: i["score"] for i in r},
@ -363,7 +368,9 @@ def load_from_pipeline(pipeline):
pipeline, transformers.AutomaticSpeechRecognitionPipeline
):
pipeline_info = {
"inputs": components.Audio(label="Input", source="microphone", type="filepath"),
"inputs": components.Audio(
source="microphone", type="filepath", label="Input"
),
"outputs": components.Textbox(label="Output"),
"preprocess": lambda i: {"inputs": i},
"postprocess": lambda r: r["text"],
@ -390,8 +397,8 @@ def load_from_pipeline(pipeline):
pipeline, transformers.ImageClassificationPipeline
):
pipeline_info = {
"inputs": components.Image(label="Input Image", type="filepath"),
"outputs": components.Label(label="Classification", type="confidences"),
"inputs": components.Image(type="filepath", label="Input Image"),
"outputs": components.Label(type="confidences", label="Classification"),
"preprocess": lambda i: {"images": i},
"postprocess": lambda r: {i["label"].split(", ")[0]: i["score"] for i in r},
}
@ -400,11 +407,13 @@ def load_from_pipeline(pipeline):
):
pipeline_info = {
"inputs": [
components.Textbox(label="Context", lines=7),
components.Textbox(lines=7, label="Context"),
components.Textbox(label="Question"),
],
"outputs": [components.Textbox(label="Answer"),
components.Label(label="Score")],
"outputs": [
components.Textbox(label="Answer"),
components.Label(label="Score"),
],
"preprocess": lambda c, q: {"context": c, "question": q},
"postprocess": lambda r: (r["answer"], r["score"]),
}
@ -412,7 +421,7 @@ def load_from_pipeline(pipeline):
pipeline, transformers.SummarizationPipeline
):
pipeline_info = {
"inputs": components.Textbox(label="Input", lines=7),
"inputs": components.Textbox(lines=7, label="Input"),
"outputs": components.Textbox(label="Summary"),
"preprocess": lambda x: {"inputs": x},
"postprocess": lambda r: r[0]["summary_text"],

View File

@ -9,25 +9,23 @@ from __future__ import annotations
import warnings
from typing import Any, List, Optional, Tuple
from gradio.components import (
Audio,
Checkbox,
CheckboxGroup,
Dataframe,
Dropdown,
File,
Image,
Number,
Radio,
Slider,
State,
Textbox,
Timeseries,
Video,
)
from gradio.components import Audio as C_Audio
from gradio.components import Checkbox as C_Checkbox
from gradio.components import CheckboxGroup as C_CheckboxGroup
from gradio.components import Dataframe as C_Dataframe
from gradio.components import Dropdown as C_Dropdown
from gradio.components import File as C_File
from gradio.components import Image as C_Image
from gradio.components import Number as C_Number
from gradio.components import Radio as C_Radio
from gradio.components import Slider as C_Slider
from gradio.components import State as C_State
from gradio.components import Textbox as C_Textbox
from gradio.components import Timeseries as C_Timeseries
from gradio.components import Video as C_Video
class Textbox(Textbox):
class Textbox(C_Textbox):
def __init__(
self,
lines: int = 1,
@ -43,17 +41,17 @@ class Textbox(Textbox):
DeprecationWarning,
)
super().__init__(
default_value=default,
lines=lines,
placeholder=placeholder,
default=default,
label=label,
numeric=numeric,
type=type,
label=label,
optional=optional,
)
class Number(Number):
class Number(C_Number):
"""
Component creates a field for user to enter numeric input. Provides a number as an argument to the wrapped function.
Input type: float
@ -76,10 +74,10 @@ class Number(Number):
"Usage of gradio.inputs is deprecated, and will not be supported in the future, please import your component from gradio.components",
DeprecationWarning,
)
super().__init__(default=default, label=label, optional=optional)
super().__init__(default_value=default, label=label, optional=optional)
class Slider(Slider):
class Slider(C_Slider):
"""
Component creates a slider that ranges from `minimum` to `maximum`. Provides a number as an argument to the wrapped function.
Input type: float
@ -110,16 +108,16 @@ class Slider(Slider):
)
super().__init__(
label=label,
default_value=default,
minimum=minimum,
maximum=maximum,
step=step,
default=default,
label=label,
optional=optional,
)
class Checkbox(Checkbox):
class Checkbox(C_Checkbox):
"""
Component creates a checkbox that can be set to `True` or `False`. Provides a boolean as an argument to the wrapped function.
Input type: bool
@ -142,10 +140,10 @@ class Checkbox(Checkbox):
"Usage of gradio.inputs is deprecated, and will not be supported in the future, please import your component from gradio.components",
DeprecationWarning,
)
super().__init__(label=label, default=default, optional=optional)
super().__init__(default_value=default, label=label, optional=optional)
class CheckboxGroup(CheckboxGroup):
class CheckboxGroup(C_CheckboxGroup):
"""
Component creates a set of checkboxes of which a subset can be selected. Provides a list of strings representing the selected choices as an argument to the wrapped function.
Input type: Union[List[str], List[int]]
@ -173,11 +171,15 @@ class CheckboxGroup(CheckboxGroup):
DeprecationWarning,
)
super().__init__(
choices=choices, default=default, type=type, label=label, optional=optional
default_value=default,
choices=choices,
type=type,
label=label,
optional=optional,
)
class Radio(Radio):
class Radio(C_Radio):
"""
Component creates a set of radio buttons of which only one can be selected. Provides string representing selected choice as an argument to the wrapped function.
Input type: Union[str, int]
@ -205,11 +207,15 @@ class Radio(Radio):
DeprecationWarning,
)
super().__init__(
choices=choices, type=type, default=default, label=label, optional=optional
choices=choices,
type=type,
default_value=default,
label=label,
optional=optional,
)
class Dropdown(Dropdown):
class Dropdown(C_Dropdown):
"""
Component creates a dropdown of which only one can be selected. Provides string representing selected choice as an argument to the wrapped function.
Input type: Union[str, int]
@ -237,11 +243,15 @@ class Dropdown(Dropdown):
DeprecationWarning,
)
super().__init__(
choices=choices, type=type, default=default, label=label, optional=optional
choices=choices,
type=type,
default_value=default,
label=label,
optional=optional,
)
class Image(Image):
class Image(C_Image):
"""
Component creates an image upload box with editing capabilities.
Input type: Union[numpy.array, PIL.Image, file-object]
@ -286,7 +296,7 @@ class Image(Image):
)
class Video(Video):
class Video(C_Video):
"""
Component creates a video file upload that is converted to a file path.
@ -315,7 +325,7 @@ class Video(Video):
super().__init__(type=type, source=source, label=label, optional=optional)
class Audio(Audio):
class Audio(C_Audio):
"""
Component accepts audio input files.
Input type: Union[Tuple[int, numpy.array], file-object, numpy.array]
@ -343,7 +353,7 @@ class Audio(Audio):
super().__init__(source=source, type=type, label=label, optional=optional)
class File(File):
class File(C_File):
"""
Component accepts generic file uploads.
Input type: Union[file-object, bytes, List[Union[file-object, bytes]]]
@ -379,7 +389,7 @@ class File(File):
)
class Dataframe(Dataframe):
class Dataframe(C_Dataframe):
"""
Component accepts 2D input through a spreadsheet interface.
Input type: Union[pandas.DataFrame, numpy.array, List[Union[str, float]], List[List[Union[str, float]]]]
@ -415,19 +425,19 @@ class Dataframe(Dataframe):
DeprecationWarning,
)
super().__init__(
default_value=default,
headers=headers,
row_count=row_count,
col_count=col_count,
datatype=datatype,
col_width=col_width,
default=default,
type=type,
label=label,
optional=optional,
)
class Timeseries(Timeseries):
class Timeseries(C_Timeseries):
"""
Component accepts pandas.DataFrame uploaded as a timeseries csv file.
Input type: pandas.DataFrame
@ -455,7 +465,7 @@ class Timeseries(Timeseries):
super().__init__(x=x, y=y, label=label, optional=optional)
class State(State):
class State(C_State):
"""
Special hidden component that stores state across runs of the interface.
Input type: Any
@ -478,7 +488,7 @@ class State(State):
"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)
super().__init__(default_value=default, label=label, optional=optional)
def get_template_context(self):
return {"default": self.default, **super().get_template_context()}

View File

@ -3,7 +3,7 @@ import math
import numpy as np
from gradio.components import Label, Textbox, Number
from gradio.components import Label, Number, Textbox
def run_interpret(interface, raw_input):

View File

@ -6,29 +6,27 @@ automatically added to a registry, which allows them to be easily referenced in
from __future__ import annotations
from typing import Dict, List, Optional
import warnings
from typing import Dict, List, Optional
from gradio.components import (
HTML,
JSON,
Audio,
Carousel,
Chatbot,
Component,
Dataframe,
File,
HighlightedText,
Image,
KeyValues,
Label,
State,
Textbox,
Timeseries,
Video,
)
from gradio.components import HTML as C_HTML
from gradio.components import JSON as C_JSON
from gradio.components import Audio as C_Audio
from gradio.components import Carousel as C_Carousel
from gradio.components import Chatbot as C_Chatbot
from gradio.components import Component as Component
from gradio.components import Dataframe as C_Dataframe
from gradio.components import File as C_File
from gradio.components import HighlightedText as C_HighlightedText
from gradio.components import Image as C_Image
from gradio.components import Label as C_Label
from gradio.components import State as C_State
from gradio.components import Textbox as C_Textbox
from gradio.components import Timeseries as C_Timeseries
from gradio.components import Video as C_Video
class Textbox(Textbox):
class Textbox(C_Textbox):
def __init__(
self,
type: str = "auto",
@ -38,10 +36,10 @@ class Textbox(Textbox):
"Usage of gradio.outputs is deprecated, and will not be supported in the future, please import your components from gradio.components",
DeprecationWarning,
)
super().__init__(type=type, label=label)
super().__init__(label=label, type=type)
class Image(Image):
class Image(C_Image):
"""
Component displays an output image.
Output type: Union[numpy.array, PIL.Image, str, matplotlib.pyplot, Tuple[Union[numpy.array, PIL.Image, str], List[Tuple[str, float, float, float, float]]]]
@ -61,10 +59,10 @@ class Image(Image):
"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, type=type, plot=plot)
super().__init__(type=type, label=label, plot=plot)
class Video(Video):
class Video(C_Video):
"""
Used for video output.
Output type: filepath
@ -81,10 +79,10 @@ class Video(Video):
"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, type=type)
super().__init__(type=type, label=label)
class Audio(Audio):
class Audio(C_Audio):
"""
Creates an audio player that plays the output audio.
Output type: Union[Tuple[int, numpy.array], str]
@ -104,7 +102,7 @@ class Audio(Audio):
super().__init__(type=type, label=label)
class File(File):
class File(C_File):
"""
Used for file output.
Output type: Union[file-like, str]
@ -123,7 +121,7 @@ class File(File):
super().__init__(label=label)
class Dataframe(Dataframe):
class Dataframe(C_Dataframe):
"""
Component displays 2D output through a spreadsheet interface.
Output type: Union[pandas.DataFrame, numpy.array, List[Union[str, float]], List[List[Union[str, float]]]]
@ -154,15 +152,15 @@ class Dataframe(Dataframe):
)
super().__init__(
headers=headers,
type=type,
label=label,
max_rows=max_rows,
max_cols=max_cols,
overflow_row_behaviour=overflow_row_behaviour,
type=type,
label=label,
)
class Timeseries(Timeseries):
class Timeseries(C_Timeseries):
"""
Component accepts pandas.DataFrame.
Output type: pandas.DataFrame
@ -185,7 +183,7 @@ class Timeseries(Timeseries):
super().__init__(x=x, y=y, label=label)
class State(State):
class State(C_State):
"""
Special hidden component that stores state across runs of the interface.
Output type: Any
@ -204,7 +202,7 @@ class State(State):
super().__init__(label=label)
class Label(Label):
class Label(C_Label):
"""
Component outputs a classification label, along with confidence scores of top categories if provided. Confidence scores are represented as a dictionary mapping labels to scores between 0 and 1.
Output type: Union[Dict[str, float], str, int, float]
@ -230,26 +228,28 @@ class Label(Label):
super().__init__(num_top_classes=num_top_classes, type=type, label=label)
class KeyValues(KeyValues):
class KeyValues:
"""
Component displays a table representing values for multiple fields.
Output type: Union[Dict, List[Tuple[str, Union[str, int, float]]]]
Demos: text_analysis
"""
def __init__(self, label: Optional[str] = None):
def __init__(
self, default_value: str = " ", *, label: Optional[str] = None, **kwargs
):
"""
Parameters:
default_value (str): IGNORED
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,
raise DeprecationWarning(
"The KeyValues component is deprecated. Please use the DataFrame or JSON "
"components instead."
)
super().__init__(label=label)
class HighlightedText(HighlightedText):
class HighlightedText(C_HighlightedText):
"""
Component creates text that contains spans that are highlighted by category or numerical value.
Output is represent as a list of Tuple pairs, where the first element represents the span of text represented by the tuple, and the second element represents the category or value of the text.
@ -276,7 +276,7 @@ class HighlightedText(HighlightedText):
super().__init__(color_map=color_map, label=label, show_legend=show_legend)
class JSON(JSON):
class JSON(C_JSON):
"""
Used for JSON output. Expects a JSON string or a Python object that is JSON serializable.
Output type: Union[str, Any]
@ -295,7 +295,7 @@ class JSON(JSON):
super().__init__(label=label)
class HTML(HTML):
class HTML(C_HTML):
"""
Used for HTML output. Expects an HTML valid string.
Output type: str
@ -310,7 +310,7 @@ class HTML(HTML):
super().__init__(label=label)
class Carousel(Carousel):
class Carousel(C_Carousel):
"""
Component displays a set of output components that can be scrolled through.
Output type: List[List[Any]]
@ -331,10 +331,10 @@ class Carousel(Carousel):
"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, components=components)
super().__init__(components=components, label=label)
class Chatbot(Chatbot):
class Chatbot(C_Chatbot):
"""
Component displays a chatbot output showing both user submitted messages and responses
Output type: List[Tuple[str, str]]
@ -351,4 +351,3 @@ class Chatbot(Chatbot):
DeprecationWarning,
)
super().__init__(label=label)

View File

@ -28,7 +28,7 @@ class TestTextbox(unittest.TestCase):
self.assertEqual(restored, "Hello World!")
with self.assertWarns(DeprecationWarning):
numeric_text_input = gr.inputs.Textbox(type="number")
_ = gr.inputs.Textbox(type="number")
self.assertEqual(
text_input.tokenize("Hello World! Gradio speaking."),
@ -183,7 +183,7 @@ class TestSlider(unittest.TestCase):
self.assertIsInstance(slider_input.generate_sample(), int)
slider_input = gr.inputs.Slider(
minimum=10, maximum=20, step=1, default=15, label="Slide Your Input"
default=15, minimum=10, maximum=20, step=1, label="Slide Your Input"
)
self.assertEqual(
slider_input.get_template_context(),
@ -287,7 +287,7 @@ class TestCheckboxGroup(unittest.TestCase):
self.assertEqual(restored, ["a", "c"])
self.assertIsInstance(checkboxes_input.generate_sample(), list)
checkboxes_input = gr.inputs.CheckboxGroup(
choices=["a", "b", "c"], default=["a", "c"], label="Check Your Inputs"
default=["a", "c"], choices=["a", "b", "c"], label="Check Your Inputs"
)
self.assertEqual(
checkboxes_input.get_template_context(),
@ -401,7 +401,7 @@ class TestImage(unittest.TestCase):
img = gr.test_data.BASE64_IMAGE
image_input = gr.inputs.Image()
self.assertEqual(image_input.preprocess(img).shape, (68, 61, 3))
image_input = gr.inputs.Image(image_mode="L", shape=(25, 25))
image_input = gr.inputs.Image(shape=(25, 25), image_mode="L")
self.assertEqual(image_input.preprocess(img).shape, (25, 25))
image_input = gr.inputs.Image(shape=(30, 10), type="pil")
self.assertEqual(image_input.preprocess(img).size, (30, 10))

View File

@ -77,9 +77,7 @@ class TestHelperMethods(unittest.TestCase):
def test_quantify_difference_with_number(self):
iface = Interface(lambda text: text, ["textbox"], ["number"])
diff = gradio.interpretation.quantify_difference_in_label(
iface, [4], [6]
)
diff = gradio.interpretation.quantify_difference_in_label(iface, [4], [6])
self.assertEquals(diff, -2)
def test_quantify_difference_with_label(self):