freddyaboulton HF Staff commited on
Commit
9dd1dec
·
1 Parent(s): 0b620a0

Upload folder using huggingface_hub

Browse files
README.md CHANGED
@@ -1,15 +1,10 @@
1
 
2
  ---
3
- tags: [gradio-custom-component,gradio-template-Dropdown,test,cool,dropdown]
4
- title: gradio_test3 V0.0.1
5
- colorFrom: pink
6
- colorTo: yellow
7
  sdk: docker
8
  pinned: false
9
  license: apache-2.0
10
  ---
11
-
12
-
13
- # gradio_test3
14
-
15
- This is a test component
 
1
 
2
  ---
3
+ tags: [gradio-custom-component,gradio-template-Fallback,test,no-template]
4
+ title: gradio_test3 V0.0.2
5
+ colorFrom: gray
6
+ colorTo: purple
7
  sdk: docker
8
  pinned: false
9
  license: apache-2.0
10
  ---
 
 
 
 
 
app.py CHANGED
@@ -3,14 +3,9 @@ import gradio as gr
3
  from gradio_test3 import Test3
4
 
5
 
6
- example = Test3().example_inputs()
7
-
8
- demo = gr.Interface(
9
- lambda x:x,
10
- Test3(), # interactive version of your component
11
- Test3(), # static version of your component
12
- # examples=[[example]], # uncomment this line to view the "example version" of your component
13
- )
14
 
15
 
16
  demo.launch()
 
3
  from gradio_test3 import Test3
4
 
5
 
6
+ with gr.Blocks() as demo:
7
+ gr.Markdown("# Change the value (keep it JSON) and the front-end will update automatically.")
8
+ Test3(value={"message": "Hello from Gradio!"}, label="Static")
 
 
 
 
 
9
 
10
 
11
  demo.launch()
requirements.txt CHANGED
@@ -1 +1 @@
1
- gradio_test3-0.0.1-py3-none-any.whl
 
1
+ gradio_test3-0.0.2-py3-none-any.whl
src/backend/gradio_test3/test3.py CHANGED
@@ -1,186 +1,15 @@
1
- """gr.Dropdown() component."""
2
 
3
- from __future__ import annotations
4
 
5
- import warnings
6
- from typing import Any, Callable, Literal
 
7
 
8
- from gradio_client.documentation import document, set_documentation_group
9
-
10
- from gradio.components.base import FormComponent
11
- from gradio.events import Events
12
-
13
- set_documentation_group("component")
14
-
15
-
16
- @document()
17
- class Test3(FormComponent):
18
- """
19
- Creates a dropdown of choices from which entries can be selected.
20
- Preprocessing: passes the value of the selected dropdown entry as a {str} or its index as an {int} into the function, depending on `type`.
21
- Postprocessing: expects a {str} corresponding to the value of the dropdown entry to be selected.
22
- Examples-format: a {str} representing the drop down value to select.
23
- Demos: sentence_builder, titanic_survival
24
- """
25
-
26
- EVENTS = [Events.change, Events.input, Events.select, Events.focus, Events.blur]
27
-
28
- def __init__(
29
- self,
30
- choices: list[str | int | float | tuple[str, str | int | float]] | None = None,
31
- *,
32
- value: str | int | float | list[str | int | float] | Callable | None = None,
33
- type: Literal["value", "index"] = "value",
34
- multiselect: bool | None = None,
35
- allow_custom_value: bool = False,
36
- max_choices: int | None = None,
37
- filterable: bool = True,
38
- label: str | None = None,
39
- info: str | None = None,
40
- every: float | None = None,
41
- show_label: bool | None = None,
42
- container: bool = True,
43
- scale: int | None = None,
44
- min_width: int = 160,
45
- interactive: bool | None = None,
46
- visible: bool = True,
47
- elem_id: str | None = None,
48
- elem_classes: list[str] | str | None = None,
49
- render: bool = True,
50
- ):
51
- """
52
- Parameters:
53
- choices: A list of string options to choose from. An option can also be a tuple of the form (name, value), where name is the displayed name of the dropdown choice and value is the value to be passed to the function, or returned by the function.
54
- value: default value(s) selected in dropdown. If None, no value is selected by default. If callable, the function will be called whenever the app loads to set the initial value of the component.
55
- type: Type of value to be returned by component. "value" returns the string of the choice selected, "index" returns the index of the choice selected.
56
- multiselect: if True, multiple choices can be selected.
57
- allow_custom_value: If True, allows user to enter a custom value that is not in the list of choices.
58
- max_choices: maximum number of choices that can be selected. If None, no limit is enforced.
59
- filterable: If True, user will be able to type into the dropdown and filter the choices by typing. Can only be set to False if `allow_custom_value` is False.
60
- label: The label for this component. Appears above the component and is also used as the header if there are a table of examples for this component. If None and used in a `gr.Interface`, the label will be the name of the parameter this component is assigned to.
61
- info: additional component description.
62
- every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
63
- show_label: if True, will display label.
64
- container: If True, will place the component in a container - providing some extra padding around the border.
65
- scale: relative width compared to adjacent Components in a Row. For example, if Component A has scale=2, and Component B has scale=1, A will be twice as wide as B. Should be an integer.
66
- min_width: minimum pixel width, will wrap if not sufficient screen space to satisfy this value. If a certain scale value results in this Component being narrower than min_width, the min_width parameter will be respected first.
67
- interactive: if True, choices in this dropdown will be selectable; if False, selection will be disabled. If not provided, this is inferred based on whether the component is used as an input or output.
68
- visible: If False, component will be hidden.
69
- elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.
70
- elem_classes: An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles.
71
- render: If False, component will not render be rendered in the Blocks context. Should be used if the intention is to assign event listeners now but render the component later.
72
- """
73
- self.choices = (
74
- # Although we expect choices to be a list of tuples, it can be a list of tuples if the Gradio app
75
- # is loaded with gr.load() since Python tuples are converted to lists in JSON.
76
- [tuple(c) if isinstance(c, (tuple, list)) else (str(c), c) for c in choices]
77
- if choices
78
- else []
79
- )
80
- valid_types = ["value", "index"]
81
- if type not in valid_types:
82
- raise ValueError(
83
- f"Invalid value for parameter `type`: {type}. Please choose from one of: {valid_types}"
84
- )
85
- self.type = type
86
- self.multiselect = multiselect
87
- if multiselect and isinstance(value, str):
88
- value = [value]
89
- if not multiselect and max_choices is not None:
90
- warnings.warn(
91
- "The `max_choices` parameter is ignored when `multiselect` is False."
92
- )
93
- if not filterable and allow_custom_value:
94
- filterable = True
95
- warnings.warn(
96
- "The `filterable` parameter cannot be set to False when `allow_custom_value` is True. Setting `filterable` to True."
97
- )
98
- self.max_choices = max_choices
99
- self.allow_custom_value = allow_custom_value
100
- self.filterable = filterable
101
- super().__init__(
102
- label=label,
103
- info=info,
104
- every=every,
105
- show_label=show_label,
106
- container=container,
107
- scale=scale,
108
- min_width=min_width,
109
- interactive=interactive,
110
- visible=visible,
111
- elem_id=elem_id,
112
- elem_classes=elem_classes,
113
- render=render,
114
- value=value,
115
- )
116
-
117
- def api_info(self) -> dict[str, Any]:
118
- if self.multiselect:
119
- json_type = {
120
- "type": "array",
121
- "items": {"type": "string", "enum": [c[1] for c in self.choices]},
122
- }
123
- else:
124
- json_type = {
125
- "type": "string",
126
- "enum": [c[1] for c in self.choices],
127
- }
128
- return json_type
129
-
130
- def example_inputs(self) -> Any:
131
- if self.multiselect:
132
- return [self.choices[0][1]] if self.choices else []
133
- else:
134
- return self.choices[0][1] if self.choices else None
135
-
136
- def preprocess(
137
- self, payload: str | int | float | list[str | int | float] | None
138
- ) -> str | int | float | list[str | int | float] | list[int | None] | None:
139
- if self.type == "value":
140
- return payload
141
- elif self.type == "index":
142
- choice_values = [value for _, value in self.choices]
143
- if payload is None:
144
- return None
145
- elif self.multiselect:
146
- assert isinstance(payload, list)
147
- return [
148
- choice_values.index(choice) if choice in choice_values else None
149
- for choice in payload
150
- ]
151
- else:
152
- return (
153
- choice_values.index(payload) if payload in choice_values else None
154
- )
155
- else:
156
- raise ValueError(
157
- f"Unknown type: {self.type}. Please choose from: 'value', 'index'."
158
- )
159
-
160
- def _warn_if_invalid_choice(self, value):
161
- if self.allow_custom_value or value in [value for _, value in self.choices]:
162
- return
163
- warnings.warn(
164
- f"The value passed into gr.Dropdown() is not in the list of choices. Please update the list of choices to include: {value} or set allow_custom_value=True."
165
- )
166
-
167
- def postprocess(
168
- self, value: str | int | float | list[str | int | float] | None
169
- ) -> str | int | float | list[str | int | float] | None:
170
- if value is None:
171
- return None
172
- if self.multiselect:
173
- if not isinstance(value, list):
174
- value = [value]
175
- [self._warn_if_invalid_choice(_y) for _y in value]
176
- else:
177
- self._warn_if_invalid_choice(value)
178
  return value
179
 
180
- def as_example(self, input_data):
181
- if self.multiselect:
182
- return [
183
- next((c[0] for c in self.choices if c[1] == data), None)
184
- for data in input_data
185
- ]
186
- return next((c[0] for c in self.choices if c[1] == input_data), None)
 
1
+ from gradio.components.base import Component
2
 
 
3
 
4
+ class Test3(Component):
5
+ def preprocess(self, payload):
6
+ return payload
7
 
8
+ def postprocess(self, value):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  return value
10
 
11
+ def example_inputs(self):
12
+ return {"foo": "bar"}
13
+
14
+ def api_info(self):
15
+ return {"type": {}, "description": "any valid json"}
 
 
src/backend/gradio_test3/test3.pyi CHANGED
@@ -1,373 +1,16 @@
1
- """gr.Dropdown() component."""
2
-
3
- from __future__ import annotations
4
-
5
- import warnings
6
- from typing import Any, Callable, Literal
7
-
8
- from gradio_client.documentation import document, set_documentation_group
9
-
10
- from gradio.components.base import FormComponent
11
- from gradio.events import Events
12
-
13
- set_documentation_group("component")
14
 
15
  from gradio.events import Dependency
16
 
17
- @document()
18
- class Test3(FormComponent):
19
- """
20
- Creates a dropdown of choices from which entries can be selected.
21
- Preprocessing: passes the value of the selected dropdown entry as a {str} or its index as an {int} into the function, depending on `type`.
22
- Postprocessing: expects a {str} corresponding to the value of the dropdown entry to be selected.
23
- Examples-format: a {str} representing the drop down value to select.
24
- Demos: sentence_builder, titanic_survival
25
- """
26
-
27
- EVENTS = [Events.change, Events.input, Events.select, Events.focus, Events.blur]
28
-
29
- def __init__(
30
- self,
31
- choices: list[str | int | float | tuple[str, str | int | float]] | None = None,
32
- *,
33
- value: str | int | float | list[str | int | float] | Callable | None = None,
34
- type: Literal["value", "index"] = "value",
35
- multiselect: bool | None = None,
36
- allow_custom_value: bool = False,
37
- max_choices: int | None = None,
38
- filterable: bool = True,
39
- label: str | None = None,
40
- info: str | None = None,
41
- every: float | None = None,
42
- show_label: bool | None = None,
43
- container: bool = True,
44
- scale: int | None = None,
45
- min_width: int = 160,
46
- interactive: bool | None = None,
47
- visible: bool = True,
48
- elem_id: str | None = None,
49
- elem_classes: list[str] | str | None = None,
50
- render: bool = True,
51
- ):
52
- """
53
- Parameters:
54
- choices: A list of string options to choose from. An option can also be a tuple of the form (name, value), where name is the displayed name of the dropdown choice and value is the value to be passed to the function, or returned by the function.
55
- value: default value(s) selected in dropdown. If None, no value is selected by default. If callable, the function will be called whenever the app loads to set the initial value of the component.
56
- type: Type of value to be returned by component. "value" returns the string of the choice selected, "index" returns the index of the choice selected.
57
- multiselect: if True, multiple choices can be selected.
58
- allow_custom_value: If True, allows user to enter a custom value that is not in the list of choices.
59
- max_choices: maximum number of choices that can be selected. If None, no limit is enforced.
60
- filterable: If True, user will be able to type into the dropdown and filter the choices by typing. Can only be set to False if `allow_custom_value` is False.
61
- label: The label for this component. Appears above the component and is also used as the header if there are a table of examples for this component. If None and used in a `gr.Interface`, the label will be the name of the parameter this component is assigned to.
62
- info: additional component description.
63
- every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
64
- show_label: if True, will display label.
65
- container: If True, will place the component in a container - providing some extra padding around the border.
66
- scale: relative width compared to adjacent Components in a Row. For example, if Component A has scale=2, and Component B has scale=1, A will be twice as wide as B. Should be an integer.
67
- min_width: minimum pixel width, will wrap if not sufficient screen space to satisfy this value. If a certain scale value results in this Component being narrower than min_width, the min_width parameter will be respected first.
68
- interactive: if True, choices in this dropdown will be selectable; if False, selection will be disabled. If not provided, this is inferred based on whether the component is used as an input or output.
69
- visible: If False, component will be hidden.
70
- elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.
71
- elem_classes: An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles.
72
- render: If False, component will not render be rendered in the Blocks context. Should be used if the intention is to assign event listeners now but render the component later.
73
- """
74
- self.choices = (
75
- # Although we expect choices to be a list of tuples, it can be a list of tuples if the Gradio app
76
- # is loaded with gr.load() since Python tuples are converted to lists in JSON.
77
- [tuple(c) if isinstance(c, (tuple, list)) else (str(c), c) for c in choices]
78
- if choices
79
- else []
80
- )
81
- valid_types = ["value", "index"]
82
- if type not in valid_types:
83
- raise ValueError(
84
- f"Invalid value for parameter `type`: {type}. Please choose from one of: {valid_types}"
85
- )
86
- self.type = type
87
- self.multiselect = multiselect
88
- if multiselect and isinstance(value, str):
89
- value = [value]
90
- if not multiselect and max_choices is not None:
91
- warnings.warn(
92
- "The `max_choices` parameter is ignored when `multiselect` is False."
93
- )
94
- if not filterable and allow_custom_value:
95
- filterable = True
96
- warnings.warn(
97
- "The `filterable` parameter cannot be set to False when `allow_custom_value` is True. Setting `filterable` to True."
98
- )
99
- self.max_choices = max_choices
100
- self.allow_custom_value = allow_custom_value
101
- self.filterable = filterable
102
- super().__init__(
103
- label=label,
104
- info=info,
105
- every=every,
106
- show_label=show_label,
107
- container=container,
108
- scale=scale,
109
- min_width=min_width,
110
- interactive=interactive,
111
- visible=visible,
112
- elem_id=elem_id,
113
- elem_classes=elem_classes,
114
- render=render,
115
- value=value,
116
- )
117
-
118
- def api_info(self) -> dict[str, Any]:
119
- if self.multiselect:
120
- json_type = {
121
- "type": "array",
122
- "items": {"type": "string", "enum": [c[1] for c in self.choices]},
123
- }
124
- else:
125
- json_type = {
126
- "type": "string",
127
- "enum": [c[1] for c in self.choices],
128
- }
129
- return json_type
130
-
131
- def example_inputs(self) -> Any:
132
- if self.multiselect:
133
- return [self.choices[0][1]] if self.choices else []
134
- else:
135
- return self.choices[0][1] if self.choices else None
136
-
137
- def preprocess(
138
- self, payload: str | int | float | list[str | int | float] | None
139
- ) -> str | int | float | list[str | int | float] | list[int | None] | None:
140
- if self.type == "value":
141
- return payload
142
- elif self.type == "index":
143
- choice_values = [value for _, value in self.choices]
144
- if payload is None:
145
- return None
146
- elif self.multiselect:
147
- assert isinstance(payload, list)
148
- return [
149
- choice_values.index(choice) if choice in choice_values else None
150
- for choice in payload
151
- ]
152
- else:
153
- return (
154
- choice_values.index(payload) if payload in choice_values else None
155
- )
156
- else:
157
- raise ValueError(
158
- f"Unknown type: {self.type}. Please choose from: 'value', 'index'."
159
- )
160
-
161
- def _warn_if_invalid_choice(self, value):
162
- if self.allow_custom_value or value in [value for _, value in self.choices]:
163
- return
164
- warnings.warn(
165
- f"The value passed into gr.Dropdown() is not in the list of choices. Please update the list of choices to include: {value} or set allow_custom_value=True."
166
- )
167
 
168
- def postprocess(
169
- self, value: str | int | float | list[str | int | float] | None
170
- ) -> str | int | float | list[str | int | float] | None:
171
- if value is None:
172
- return None
173
- if self.multiselect:
174
- if not isinstance(value, list):
175
- value = [value]
176
- [self._warn_if_invalid_choice(_y) for _y in value]
177
- else:
178
- self._warn_if_invalid_choice(value)
179
  return value
180
 
181
- def as_example(self, input_data):
182
- if self.multiselect:
183
- return [
184
- next((c[0] for c in self.choices if c[1] == data), None)
185
- for data in input_data
186
- ]
187
- return next((c[0] for c in self.choices if c[1] == input_data), None)
188
 
189
-
190
- def change(self,
191
- fn: Callable | None,
192
- inputs: Component | Sequence[Component] | set[Component] | None = None,
193
- outputs: Component | Sequence[Component] | None = None,
194
- api_name: str | None | Literal[False] = None,
195
- status_tracker: None = None,
196
- scroll_to_output: bool = False,
197
- show_progress: Literal["full", "minimal", "hidden"] = "full",
198
- queue: bool | None = None,
199
- batch: bool = False,
200
- max_batch_size: int = 4,
201
- preprocess: bool = True,
202
- postprocess: bool = True,
203
- cancels: dict[str, Any] | list[dict[str, Any]] | None = None,
204
- every: float | None = None,
205
- trigger_mode: Literal["once", "multiple", "always_last"] | None = None,
206
- js: str | None = None,) -> Dependency:
207
- """
208
- Parameters:
209
- fn: the function to call when this event is triggered. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
210
- inputs: List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
211
- outputs: List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.
212
- api_name: Defines how the endpoint appears in the API docs. Can be a string, None, or False. If False, the endpoint will not be exposed in the api docs. If set to None, the endpoint will be exposed in the api docs as an unnamed endpoint, although this behavior will be changed in Gradio 4.0. If set to a string, the endpoint will be exposed in the api docs with the given name.
213
- scroll_to_output: If True, will scroll to output component on completion
214
- show_progress: If True, will show progress animation while pending
215
- queue: If True, will place the request on the queue, if the queue has been enabled. If False, will not put this event on the queue, even if the queue has been enabled. If None, will use the queue setting of the gradio app.
216
- batch: If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
217
- max_batch_size: Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
218
- preprocess: If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
219
- postprocess: If False, will not run postprocessing of component data before returning 'fn' output to the browser.
220
- cancels: A list of other events to cancel when this listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.
221
- every: Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
222
- trigger_mode: If "once" (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to "multiple", unlimited submissions are allowed while pending, and "always_last" (default for `.change()` event) would allow a second submission after the pending event is complete.
223
- js: Optional frontend js method to run before running 'fn'. Input arguments for js method are values of 'inputs' and 'outputs', return should be a list of values for output components.
224
- """
225
- ...
226
-
227
- def input(self,
228
- fn: Callable | None,
229
- inputs: Component | Sequence[Component] | set[Component] | None = None,
230
- outputs: Component | Sequence[Component] | None = None,
231
- api_name: str | None | Literal[False] = None,
232
- status_tracker: None = None,
233
- scroll_to_output: bool = False,
234
- show_progress: Literal["full", "minimal", "hidden"] = "full",
235
- queue: bool | None = None,
236
- batch: bool = False,
237
- max_batch_size: int = 4,
238
- preprocess: bool = True,
239
- postprocess: bool = True,
240
- cancels: dict[str, Any] | list[dict[str, Any]] | None = None,
241
- every: float | None = None,
242
- trigger_mode: Literal["once", "multiple", "always_last"] | None = None,
243
- js: str | None = None,) -> Dependency:
244
- """
245
- Parameters:
246
- fn: the function to call when this event is triggered. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
247
- inputs: List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
248
- outputs: List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.
249
- api_name: Defines how the endpoint appears in the API docs. Can be a string, None, or False. If False, the endpoint will not be exposed in the api docs. If set to None, the endpoint will be exposed in the api docs as an unnamed endpoint, although this behavior will be changed in Gradio 4.0. If set to a string, the endpoint will be exposed in the api docs with the given name.
250
- scroll_to_output: If True, will scroll to output component on completion
251
- show_progress: If True, will show progress animation while pending
252
- queue: If True, will place the request on the queue, if the queue has been enabled. If False, will not put this event on the queue, even if the queue has been enabled. If None, will use the queue setting of the gradio app.
253
- batch: If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
254
- max_batch_size: Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
255
- preprocess: If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
256
- postprocess: If False, will not run postprocessing of component data before returning 'fn' output to the browser.
257
- cancels: A list of other events to cancel when this listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.
258
- every: Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
259
- trigger_mode: If "once" (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to "multiple", unlimited submissions are allowed while pending, and "always_last" (default for `.change()` event) would allow a second submission after the pending event is complete.
260
- js: Optional frontend js method to run before running 'fn'. Input arguments for js method are values of 'inputs' and 'outputs', return should be a list of values for output components.
261
- """
262
- ...
263
-
264
- def select(self,
265
- fn: Callable | None,
266
- inputs: Component | Sequence[Component] | set[Component] | None = None,
267
- outputs: Component | Sequence[Component] | None = None,
268
- api_name: str | None | Literal[False] = None,
269
- status_tracker: None = None,
270
- scroll_to_output: bool = False,
271
- show_progress: Literal["full", "minimal", "hidden"] = "full",
272
- queue: bool | None = None,
273
- batch: bool = False,
274
- max_batch_size: int = 4,
275
- preprocess: bool = True,
276
- postprocess: bool = True,
277
- cancels: dict[str, Any] | list[dict[str, Any]] | None = None,
278
- every: float | None = None,
279
- trigger_mode: Literal["once", "multiple", "always_last"] | None = None,
280
- js: str | None = None,) -> Dependency:
281
- """
282
- Parameters:
283
- fn: the function to call when this event is triggered. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
284
- inputs: List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
285
- outputs: List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.
286
- api_name: Defines how the endpoint appears in the API docs. Can be a string, None, or False. If False, the endpoint will not be exposed in the api docs. If set to None, the endpoint will be exposed in the api docs as an unnamed endpoint, although this behavior will be changed in Gradio 4.0. If set to a string, the endpoint will be exposed in the api docs with the given name.
287
- scroll_to_output: If True, will scroll to output component on completion
288
- show_progress: If True, will show progress animation while pending
289
- queue: If True, will place the request on the queue, if the queue has been enabled. If False, will not put this event on the queue, even if the queue has been enabled. If None, will use the queue setting of the gradio app.
290
- batch: If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
291
- max_batch_size: Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
292
- preprocess: If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
293
- postprocess: If False, will not run postprocessing of component data before returning 'fn' output to the browser.
294
- cancels: A list of other events to cancel when this listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.
295
- every: Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
296
- trigger_mode: If "once" (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to "multiple", unlimited submissions are allowed while pending, and "always_last" (default for `.change()` event) would allow a second submission after the pending event is complete.
297
- js: Optional frontend js method to run before running 'fn'. Input arguments for js method are values of 'inputs' and 'outputs', return should be a list of values for output components.
298
- """
299
- ...
300
-
301
- def focus(self,
302
- fn: Callable | None,
303
- inputs: Component | Sequence[Component] | set[Component] | None = None,
304
- outputs: Component | Sequence[Component] | None = None,
305
- api_name: str | None | Literal[False] = None,
306
- status_tracker: None = None,
307
- scroll_to_output: bool = False,
308
- show_progress: Literal["full", "minimal", "hidden"] = "full",
309
- queue: bool | None = None,
310
- batch: bool = False,
311
- max_batch_size: int = 4,
312
- preprocess: bool = True,
313
- postprocess: bool = True,
314
- cancels: dict[str, Any] | list[dict[str, Any]] | None = None,
315
- every: float | None = None,
316
- trigger_mode: Literal["once", "multiple", "always_last"] | None = None,
317
- js: str | None = None,) -> Dependency:
318
- """
319
- Parameters:
320
- fn: the function to call when this event is triggered. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
321
- inputs: List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
322
- outputs: List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.
323
- api_name: Defines how the endpoint appears in the API docs. Can be a string, None, or False. If False, the endpoint will not be exposed in the api docs. If set to None, the endpoint will be exposed in the api docs as an unnamed endpoint, although this behavior will be changed in Gradio 4.0. If set to a string, the endpoint will be exposed in the api docs with the given name.
324
- scroll_to_output: If True, will scroll to output component on completion
325
- show_progress: If True, will show progress animation while pending
326
- queue: If True, will place the request on the queue, if the queue has been enabled. If False, will not put this event on the queue, even if the queue has been enabled. If None, will use the queue setting of the gradio app.
327
- batch: If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
328
- max_batch_size: Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
329
- preprocess: If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
330
- postprocess: If False, will not run postprocessing of component data before returning 'fn' output to the browser.
331
- cancels: A list of other events to cancel when this listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.
332
- every: Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
333
- trigger_mode: If "once" (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to "multiple", unlimited submissions are allowed while pending, and "always_last" (default for `.change()` event) would allow a second submission after the pending event is complete.
334
- js: Optional frontend js method to run before running 'fn'. Input arguments for js method are values of 'inputs' and 'outputs', return should be a list of values for output components.
335
- """
336
- ...
337
-
338
- def blur(self,
339
- fn: Callable | None,
340
- inputs: Component | Sequence[Component] | set[Component] | None = None,
341
- outputs: Component | Sequence[Component] | None = None,
342
- api_name: str | None | Literal[False] = None,
343
- status_tracker: None = None,
344
- scroll_to_output: bool = False,
345
- show_progress: Literal["full", "minimal", "hidden"] = "full",
346
- queue: bool | None = None,
347
- batch: bool = False,
348
- max_batch_size: int = 4,
349
- preprocess: bool = True,
350
- postprocess: bool = True,
351
- cancels: dict[str, Any] | list[dict[str, Any]] | None = None,
352
- every: float | None = None,
353
- trigger_mode: Literal["once", "multiple", "always_last"] | None = None,
354
- js: str | None = None,) -> Dependency:
355
- """
356
- Parameters:
357
- fn: the function to call when this event is triggered. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
358
- inputs: List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
359
- outputs: List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.
360
- api_name: Defines how the endpoint appears in the API docs. Can be a string, None, or False. If False, the endpoint will not be exposed in the api docs. If set to None, the endpoint will be exposed in the api docs as an unnamed endpoint, although this behavior will be changed in Gradio 4.0. If set to a string, the endpoint will be exposed in the api docs with the given name.
361
- scroll_to_output: If True, will scroll to output component on completion
362
- show_progress: If True, will show progress animation while pending
363
- queue: If True, will place the request on the queue, if the queue has been enabled. If False, will not put this event on the queue, even if the queue has been enabled. If None, will use the queue setting of the gradio app.
364
- batch: If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
365
- max_batch_size: Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
366
- preprocess: If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
367
- postprocess: If False, will not run postprocessing of component data before returning 'fn' output to the browser.
368
- cancels: A list of other events to cancel when this listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.
369
- every: Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
370
- trigger_mode: If "once" (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to "multiple", unlimited submissions are allowed while pending, and "always_last" (default for `.change()` event) would allow a second submission after the pending event is complete.
371
- js: Optional frontend js method to run before running 'fn'. Input arguments for js method are values of 'inputs' and 'outputs', return should be a list of values for output components.
372
- """
373
- ...
 
1
+ from gradio.components.base import Component
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
  from gradio.events import Dependency
4
 
5
+ class Test3(Component):
6
+ def preprocess(self, payload):
7
+ return payload
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
+ def postprocess(self, value):
 
 
 
 
 
 
 
 
 
 
10
  return value
11
 
12
+ def example_inputs(self):
13
+ return {"foo": "bar"}
 
 
 
 
 
14
 
15
+ def api_info(self):
16
+ return {"type": {}, "description": "any valid json"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/demo/app.py CHANGED
@@ -3,14 +3,9 @@ import gradio as gr
3
  from gradio_test3 import Test3
4
 
5
 
6
- example = Test3().example_inputs()
7
-
8
- demo = gr.Interface(
9
- lambda x:x,
10
- Test3(), # interactive version of your component
11
- Test3(), # static version of your component
12
- # examples=[[example]], # uncomment this line to view the "example version" of your component
13
- )
14
 
15
 
16
  demo.launch()
 
3
  from gradio_test3 import Test3
4
 
5
 
6
+ with gr.Blocks() as demo:
7
+ gr.Markdown("# Change the value (keep it JSON) and the front-end will update automatically.")
8
+ Test3(value={"message": "Hello from Gradio!"}, label="Static")
 
 
 
 
 
9
 
10
 
11
  demo.launch()
src/frontend/Index.svelte CHANGED
@@ -1,96 +1,35 @@
1
- <script context="module" lang="ts">
2
- export { default as BaseDropdown } from "./shared/Dropdown.svelte";
3
- export { default as BaseMultiselect } from "./shared/Multiselect.svelte";
4
- export { default as BaseExample } from "./Example.svelte";
5
- </script>
6
-
7
  <script lang="ts">
8
- import type { Gradio, SelectData } from "@gradio/utils";
9
- import Multiselect from "./shared/Multiselect.svelte";
10
- import Dropdown from "./shared/Dropdown.svelte";
11
- import { Block } from "@gradio/atoms";
12
  import { StatusTracker } from "@gradio/statustracker";
13
  import type { LoadingStatus } from "@gradio/statustracker";
 
14
 
15
- export let label = "Dropdown";
16
- export let info: string | undefined = undefined;
17
  export let elem_id = "";
18
  export let elem_classes: string[] = [];
19
  export let visible = true;
20
- export let value: string | string[];
21
- export let value_is_output = false;
22
- export let multiselect = false;
23
- export let max_choices: number | null = null;
24
- export let choices: [string, string | number][];
25
- export let show_label: boolean;
26
- export let filterable: boolean;
27
  export let container = true;
28
  export let scale: number | null = null;
29
  export let min_width: number | undefined = undefined;
30
  export let loading_status: LoadingStatus;
31
- export let allow_custom_value = false;
32
  export let gradio: Gradio<{
33
  change: never;
34
- input: never;
35
  select: SelectData;
36
- blur: never;
37
- focus: never;
38
  }>;
39
- export let interactive: boolean;
40
  </script>
41
 
42
- <Block
43
- {visible}
44
- {elem_id}
45
- {elem_classes}
46
- padding={container}
47
- allow_overflow={false}
48
- {scale}
49
- {min_width}
50
- >
51
- <StatusTracker
52
- autoscroll={gradio.autoscroll}
53
- i18n={gradio.i18n}
54
- {...loading_status}
55
- />
56
-
57
- {#if multiselect}
58
- <Multiselect
59
- bind:value
60
- bind:value_is_output
61
- {choices}
62
- {max_choices}
63
- {label}
64
- {info}
65
- {show_label}
66
- {allow_custom_value}
67
- {filterable}
68
- {container}
69
  i18n={gradio.i18n}
70
- on:change={() => gradio.dispatch("change")}
71
- on:input={() => gradio.dispatch("input")}
72
- on:select={(e) => gradio.dispatch("select", e.detail)}
73
- on:blur={() => gradio.dispatch("blur")}
74
- on:focus={() => gradio.dispatch("focus")}
75
- disabled={!interactive}
76
- />
77
- {:else}
78
- <Dropdown
79
- bind:value
80
- bind:value_is_output
81
- {choices}
82
- {label}
83
- {info}
84
- {show_label}
85
- {filterable}
86
- {allow_custom_value}
87
- {container}
88
- on:change={() => gradio.dispatch("change")}
89
- on:input={() => gradio.dispatch("input")}
90
- on:select={(e) => gradio.dispatch("select", e.detail)}
91
- on:blur={() => gradio.dispatch("blur")}
92
- on:focus={() => gradio.dispatch("focus")}
93
- disabled={!interactive}
94
  />
95
  {/if}
 
 
96
  </Block>
 
 
 
 
 
 
 
1
  <script lang="ts">
2
+ import { JsonView } from "@zerodevx/svelte-json-view";
3
+
4
+ import type { Gradio } from "@gradio/utils";
5
+ import { Block, Info } from "@gradio/atoms";
6
  import { StatusTracker } from "@gradio/statustracker";
7
  import type { LoadingStatus } from "@gradio/statustracker";
8
+ import type { SelectData } from "@gradio/utils";
9
 
 
 
10
  export let elem_id = "";
11
  export let elem_classes: string[] = [];
12
  export let visible = true;
13
+ export let value = false;
 
 
 
 
 
 
14
  export let container = true;
15
  export let scale: number | null = null;
16
  export let min_width: number | undefined = undefined;
17
  export let loading_status: LoadingStatus;
 
18
  export let gradio: Gradio<{
19
  change: never;
 
20
  select: SelectData;
21
+ input: never;
 
22
  }>;
 
23
  </script>
24
 
25
+ <Block {visible} {elem_id} {elem_classes} {container} {scale} {min_width}>
26
+ {#if loading_status}
27
+ <StatusTracker
28
+ autoscroll={gradio.autoscroll}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  i18n={gradio.i18n}
30
+ {...loading_status}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  />
32
  {/if}
33
+
34
+ <JsonView json={value} />
35
  </Block>
src/frontend/package-lock.json CHANGED
@@ -1,18 +1,18 @@
1
  {
2
  "name": "gradio_test3",
3
- "version": "0.3.1",
4
  "lockfileVersion": 3,
5
  "requires": true,
6
  "packages": {
7
  "": {
8
  "name": "gradio_test3",
9
- "version": "0.3.1",
10
  "license": "ISC",
11
  "dependencies": {
12
  "@gradio/atoms": "0.2.1",
13
- "@gradio/icons": "0.2.0",
14
  "@gradio/statustracker": "0.3.1",
15
- "@gradio/utils": "0.2.0"
 
16
  }
17
  },
18
  "node_modules/@ampproject/remapping": {
@@ -500,6 +500,14 @@
500
  "integrity": "sha512-/kYRxGDLWzHOB7q+wtSUQlFrtcdUccpfy+X+9iMBpHK8QLLhx2wIPYuS5DYtR9Wa/YlZAbIovy7qVdB1Aq6Lyw==",
501
  "peer": true
502
  },
 
 
 
 
 
 
 
 
503
  "node_modules/acorn": {
504
  "version": "8.11.2",
505
  "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.11.2.tgz",
 
1
  {
2
  "name": "gradio_test3",
3
+ "version": "0.2.1",
4
  "lockfileVersion": 3,
5
  "requires": true,
6
  "packages": {
7
  "": {
8
  "name": "gradio_test3",
9
+ "version": "0.2.1",
10
  "license": "ISC",
11
  "dependencies": {
12
  "@gradio/atoms": "0.2.1",
 
13
  "@gradio/statustracker": "0.3.1",
14
+ "@gradio/utils": "0.2.0",
15
+ "@zerodevx/svelte-json-view": "^1.0.7"
16
  }
17
  },
18
  "node_modules/@ampproject/remapping": {
 
500
  "integrity": "sha512-/kYRxGDLWzHOB7q+wtSUQlFrtcdUccpfy+X+9iMBpHK8QLLhx2wIPYuS5DYtR9Wa/YlZAbIovy7qVdB1Aq6Lyw==",
501
  "peer": true
502
  },
503
+ "node_modules/@zerodevx/svelte-json-view": {
504
+ "version": "1.0.7",
505
+ "resolved": "https://registry.npmjs.org/@zerodevx/svelte-json-view/-/svelte-json-view-1.0.7.tgz",
506
+ "integrity": "sha512-yW0MV+9BCKOwzt3h86y3xDqYdI5st+Rxk+L5pa0Utq7nlPD+VvxyhL7R1gJoLxQvWwjyAvY/fyUCFTdwDyI14w==",
507
+ "peerDependencies": {
508
+ "svelte": "^3.57.0 || ^4.0.0"
509
+ }
510
+ },
511
  "node_modules/acorn": {
512
  "version": "8.11.2",
513
  "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.11.2.tgz",
src/frontend/package.json CHANGED
@@ -1,6 +1,6 @@
1
  {
2
  "name": "gradio_test3",
3
- "version": "0.3.1",
4
  "description": "Gradio UI packages",
5
  "type": "module",
6
  "author": "",
@@ -14,8 +14,8 @@
14
  },
15
  "dependencies": {
16
  "@gradio/atoms": "0.2.1",
17
- "@gradio/icons": "0.2.0",
18
  "@gradio/statustracker": "0.3.1",
19
- "@gradio/utils": "0.2.0"
 
20
  }
21
  }
 
1
  {
2
  "name": "gradio_test3",
3
+ "version": "0.2.1",
4
  "description": "Gradio UI packages",
5
  "type": "module",
6
  "author": "",
 
14
  },
15
  "dependencies": {
16
  "@gradio/atoms": "0.2.1",
 
17
  "@gradio/statustracker": "0.3.1",
18
+ "@gradio/utils": "0.2.0",
19
+ "@zerodevx/svelte-json-view": "^1.0.7"
20
  }
21
  }
src/pyproject.toml CHANGED
@@ -8,13 +8,13 @@ build-backend = "hatchling.build"
8
 
9
  [project]
10
  name = "gradio_test3"
11
- version = "0.0.1"
12
- description = "This is a test component"
13
  readme = "README.md"
14
  license = "MIT"
15
  requires-python = ">=3.8"
16
  authors = [{ name = "YOUR NAME", email = "[email protected]" }]
17
- keywords = ["gradio-custom-component", "gradio-template-Dropdown", "test", "cool", "dropdown"]
18
  # Add dependencies here
19
  dependencies = ["gradio>=4.0,<5.0"]
20
  classifiers = [
 
8
 
9
  [project]
10
  name = "gradio_test3"
11
+ version = "0.0.2"
12
+ description = "This is a test component."
13
  readme = "README.md"
14
  license = "MIT"
15
  requires-python = ">=3.8"
16
  authors = [{ name = "YOUR NAME", email = "[email protected]" }]
17
+ keywords = ["gradio-custom-component", "gradio-template-Fallback", "test", "no-template"]
18
  # Add dependencies here
19
  dependencies = ["gradio>=4.0,<5.0"]
20
  classifiers = [