Skip to content

Commit 5c34d91

Browse files
authored
added better default labels to form components (#1040)
* added better default labels to form components * updated default labels * formatting * fixed tests
1 parent 20847c5 commit 5c34d91

15 files changed

Lines changed: 150 additions & 173 deletions

File tree

gradio/blocks.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -307,7 +307,7 @@ def get_config_file(self):
307307
{
308308
"id": _id,
309309
"type": (block.get_block_name()),
310-
"props": block.get_template_context()
310+
"props": utils.delete_none(block.get_template_context())
311311
if hasattr(block, "get_template_context")
312312
else None,
313313
}

gradio/components.py

Lines changed: 97 additions & 93 deletions
Original file line numberDiff line numberDiff line change
@@ -132,9 +132,7 @@ def get_component_shortcut(cls, str_shortcut: str) -> Optional[Component]:
132132
Creates a component, where class name equals to str_shortcut.
133133
134134
@param str_shortcut: string shortcut of a component
135-
@return:
136-
True, found_class or
137-
False, None
135+
@return: the insantiated component object, or None if no such component exists
138136
"""
139137
# If we do not import templates Python cannot recognize grandchild classes names.
140138
import gradio.templates
@@ -2371,7 +2369,11 @@ def get_template_context(self):
23712369
return {"default_value": self.default_value, **super().get_template_context()}
23722370

23732371

2372+
############################
23742373
# Only Output Components
2374+
############################
2375+
2376+
23752377
class Label(Component):
23762378
"""
23772379
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.
@@ -2998,7 +3000,97 @@ def clear(self, fn: Callable, inputs: List[Component], outputs: List[Component])
29983000
self.set_event_trigger("clear", fn, inputs, outputs)
29993001

30003002

3003+
class Plot(Component):
3004+
"""
3005+
Used for plot output.
3006+
Output type: matplotlib plt, plotly figure, or Bokeh fig (json_item format)
3007+
Demos: outbreak_forecast
3008+
"""
3009+
3010+
def __init__(
3011+
self,
3012+
type: str = None,
3013+
label: str = None,
3014+
css: Optional[Dict] = None,
3015+
**kwargs,
3016+
):
3017+
"""
3018+
Parameters:
3019+
type (str): type of plot (matplotlib, plotly)
3020+
label (str): component name in interface.
3021+
"""
3022+
self.type = type
3023+
super().__init__(label=label, css=css, **kwargs)
3024+
3025+
def get_template_context(self):
3026+
return {**super().get_template_context()}
3027+
3028+
def postprocess(self, y):
3029+
"""
3030+
Parameters:
3031+
y (str): plot data
3032+
Returns:
3033+
(str): plot type
3034+
(str): plot base64 or json
3035+
"""
3036+
dtype = self.type
3037+
if self.type == "plotly":
3038+
out_y = y.to_json()
3039+
elif self.type == "matplotlib":
3040+
out_y = processing_utils.encode_plot_to_base64(y)
3041+
elif self.type == "bokeh":
3042+
out_y = json.dumps(y)
3043+
elif self.type == "auto":
3044+
if isinstance(y, (ModuleType, matplotlib.pyplot.Figure)):
3045+
dtype = "matplotlib"
3046+
out_y = processing_utils.encode_plot_to_base64(y)
3047+
elif isinstance(y, dict):
3048+
dtype = "bokeh"
3049+
out_y = json.dumps(y)
3050+
else:
3051+
dtype = "plotly"
3052+
out_y = y.to_json()
3053+
else:
3054+
raise ValueError(
3055+
"Unknown type. Please choose from: 'plotly', 'matplotlib', 'bokeh'."
3056+
)
3057+
return {"type": dtype, "plot": out_y}
3058+
3059+
def change(
3060+
self,
3061+
fn: Callable,
3062+
inputs: List[Component],
3063+
outputs: List[Component],
3064+
status_tracker: Optional[StatusTracker] = None,
3065+
):
3066+
"""
3067+
Parameters:
3068+
fn: Callable function
3069+
inputs: List of inputs
3070+
outputs: List of outputs
3071+
status: StatusTracker to visualize function progress
3072+
Returns: None
3073+
"""
3074+
self.set_event_trigger(
3075+
"change", fn, inputs, outputs, status_tracker=status_tracker
3076+
)
3077+
3078+
def clear(self, fn: Callable, inputs: List[Component], outputs: List[Component]):
3079+
"""
3080+
Parameters:
3081+
fn: Callable function
3082+
inputs: List of inputs
3083+
outputs: List of outputs
3084+
Returns: None
3085+
"""
3086+
self.set_event_trigger("clear", fn, inputs, outputs)
3087+
3088+
3089+
############################
30013090
# Static Components
3091+
############################
3092+
3093+
30023094
class Markdown(Component):
30033095
"""
30043096
Used for Markdown output. Expects a valid string that is rendered into Markdown.
@@ -3186,92 +3278,6 @@ def _click_no_postprocess(
31863278
)
31873279

31883280

3189-
class Plot(Component):
3190-
"""
3191-
Used for plot output.
3192-
Output type: matplotlib plt, plotly figure, or Bokeh fig (json_item format)
3193-
Demos: outbreak_forecast
3194-
"""
3195-
3196-
def __init__(
3197-
self,
3198-
type: str = None,
3199-
label: str = None,
3200-
css: Optional[Dict] = None,
3201-
**kwargs,
3202-
):
3203-
"""
3204-
Parameters:
3205-
type (str): type of plot (matplotlib, plotly)
3206-
label (str): component name in interface.
3207-
"""
3208-
self.type = type
3209-
super().__init__(label=label, css=css, **kwargs)
3210-
3211-
def get_template_context(self):
3212-
return {**super().get_template_context()}
3213-
3214-
def postprocess(self, y):
3215-
"""
3216-
Parameters:
3217-
y (str): plot data
3218-
Returns:
3219-
(str): plot type
3220-
(str): plot base64 or json
3221-
"""
3222-
dtype = self.type
3223-
if self.type == "plotly":
3224-
out_y = y.to_json()
3225-
elif self.type == "matplotlib":
3226-
out_y = processing_utils.encode_plot_to_base64(y)
3227-
elif self.type == "bokeh":
3228-
out_y = json.dumps(y)
3229-
elif self.type == "auto":
3230-
if isinstance(y, (ModuleType, matplotlib.pyplot.Figure)):
3231-
dtype = "matplotlib"
3232-
out_y = processing_utils.encode_plot_to_base64(y)
3233-
elif isinstance(y, dict):
3234-
dtype = "bokeh"
3235-
out_y = json.dumps(y)
3236-
else:
3237-
dtype = "plotly"
3238-
out_y = y.to_json()
3239-
else:
3240-
raise ValueError(
3241-
"Unknown type. Please choose from: 'plotly', 'matplotlib', 'bokeh'."
3242-
)
3243-
return {"type": dtype, "plot": out_y}
3244-
3245-
def change(
3246-
self,
3247-
fn: Callable,
3248-
inputs: List[Component],
3249-
outputs: List[Component],
3250-
status_tracker: Optional[StatusTracker] = None,
3251-
):
3252-
"""
3253-
Parameters:
3254-
fn: Callable function
3255-
inputs: List of inputs
3256-
outputs: List of outputs
3257-
status: StatusTracker to visualize function progress
3258-
Returns: None
3259-
"""
3260-
self.set_event_trigger(
3261-
"change", fn, inputs, outputs, status_tracker=status_tracker
3262-
)
3263-
3264-
def clear(self, fn: Callable, inputs: List[Component], outputs: List[Component]):
3265-
"""
3266-
Parameters:
3267-
fn: Callable function
3268-
inputs: List of inputs
3269-
outputs: List of outputs
3270-
Returns: None
3271-
"""
3272-
self.set_event_trigger("clear", fn, inputs, outputs)
3273-
3274-
32753281
class Interpretation(Component):
32763282
"""
32773283
Used to create an interpretation widget for a component.
@@ -3295,14 +3301,12 @@ def get_template_context(self):
32953301
}
32963302

32973303

3298-
def component(str_shortcut: str) -> (bool, Optional[Component]):
3304+
def component(str_shortcut: str) -> Optional[Component]:
32993305
"""
33003306
Creates a component, where class name equals to str_shortcut.
33013307
33023308
@param str_shortcut: string shortcut of a component
3303-
@return:
3304-
True, found_class or
3305-
False, None
3309+
@return component: the component object
33063310
"""
33073311
component = Component.get_component_shortcut(str_shortcut)
33083312
if component is None:

gradio/interface.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
from markdown_it import MarkdownIt
1919
from mdit_py_plugins.footnote import footnote_plugin
2020

21-
from gradio import context, interpretation, utils
21+
from gradio import interpretation, utils
2222
from gradio.blocks import Blocks, Column, Row, TabItem, Tabs
2323
from gradio.components import (
2424
Button,
@@ -32,8 +32,6 @@
3232
)
3333
from gradio.external import load_from_pipeline, load_interface # type: ignore
3434
from gradio.flagging import CSVLogger, FlaggingCallback # type: ignore
35-
from gradio.inputs import State as i_State # type: ignore
36-
from gradio.outputs import State as o_State # type: ignore
3735
from gradio.process_examples import cache_interface_examples, load_from_cache
3836

3937
if TYPE_CHECKING: # Only import for type checking (is False at runtime).
@@ -487,7 +485,10 @@ def clean_html(raw_html):
487485
component.label = param_name
488486
for i, component in enumerate(self.output_components):
489487
if component.label is None:
490-
component.label = "output_" + str(i)
488+
if len(self.output_components) == 1:
489+
component.label = "output"
490+
else:
491+
component.label = "output " + str(i)
491492

492493
self.cache_examples = cache_examples
493494
if cache_examples:

gradio/templates/frontend/index.html

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@
5555
</script>
5656
<script src="https://cdnjs.cloudflare.com/ajax/libs/iframe-resizer/4.3.1/iframeResizer.contentWindow.min.js"></script>
5757
<title>Gradio</title>
58-
<script type="module" crossorigin src="./assets/index.49d6d26d.js"></script>
58+
<script type="module" crossorigin src="./assets/index.2f71b643.js"></script>
5959
<link rel="stylesheet" href="./assets/index.39bf42f9.css">
6060
</head>
6161

0 commit comments

Comments
 (0)