gradio-checkboxgroupmarkdown 0.0.2__py3-none-any.whl

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,621 @@
1
+ """gr.CheckboxGroup() component"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable, Sequence
6
+ from typing import TYPE_CHECKING, Any, Literal
7
+
8
+ from gradio_client.documentation import document
9
+
10
+ from gradio.components.base import Component, FormComponent
11
+ from gradio.events import Events
12
+ from gradio.exceptions import Error
13
+
14
+ if TYPE_CHECKING:
15
+ from gradio.components import Timer
16
+
17
+
18
+ class CheckboxGroupMarkdown(FormComponent):
19
+ """
20
+ Creates a set of checkboxes. Can be used as an input to pass a set of values to a function or as an output to display values, a subset of which are selected.
21
+ Demos: sentence_builder
22
+ """
23
+
24
+ EVENTS = [Events.change, Events.input, Events.select]
25
+
26
+ def __init__(
27
+ self,
28
+ choices: list[dict]
29
+ | None = None,
30
+ *,
31
+ value: Sequence[str | float | int] | str | float | int | Callable | None = None,
32
+ type: ChoiceType = "value",
33
+ label: str | None = None,
34
+ info: str | None = None,
35
+ every: Timer | float | None = None,
36
+ inputs: Component | Sequence[Component] | set[Component] | None = None,
37
+ show_label: bool | None = None,
38
+ container: bool = True,
39
+ scale: int | None = None,
40
+ min_width: int = 160,
41
+ interactive: bool | None = None,
42
+ visible: bool = True,
43
+ elem_id: str | None = None,
44
+ elem_classes: list[str] | str | None = None,
45
+ render: bool = True,
46
+ key: int | str | None = None,
47
+ ):
48
+ """
49
+ Parameters:
50
+ choices: A list of string or numeric options to select from. An option can also be a tuple of the form (name, value), where name is the displayed name of the checkbox button and value is the value to be passed to the function, or returned by the function.
51
+ value: Default selected list of options. If a single choice is selected, it can be passed in as a string or numeric type. If callable, the function will be called whenever the app loads to set the initial value of the component.
52
+ type: Type of value to be returned by component. "value" returns the list of strings of the choices selected, "index" returns the list of indices of the choices selected.
53
+ label: the label for this component, displayed above the component if `show_label` is `True` 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 corresponds to.
54
+ info: additional component description, appears below the label in smaller font. Supports markdown / HTML syntax.
55
+ every: Continously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.
56
+ inputs: Components that are used as inputs to calculate `value` if `value` is a function (has no effect otherwise). `value` is recalculated any time the inputs change.
57
+ show_label: If True, will display label.
58
+ container: If True, will place the component in a container - providing some extra padding around the border.
59
+ 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.
60
+ 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.
61
+ interactive: If True, choices in this checkbox group will be checkable; if False, checking will be disabled. If not provided, this is inferred based on whether the component is used as an input or output.
62
+ visible: If False, component will be hidden.
63
+ 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.
64
+ 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.
65
+ 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.
66
+ key: if assigned, will be used to assume identity across a re-render. Components that have the same key across a re-render will have their value preserved.
67
+ """
68
+ self.choices = choices if choices else []
69
+ valid_types = ["value", "index", "title", "content", "all"]
70
+ if type not in valid_types:
71
+ raise ValueError(
72
+ f"Invalid value for parameter `type`: {type}. Please choose from one of: {valid_types}"
73
+ )
74
+ self.type = type
75
+ super().__init__(
76
+ label=label,
77
+ info=info,
78
+ every=every,
79
+ inputs=inputs,
80
+ show_label=show_label,
81
+ container=container,
82
+ scale=scale,
83
+ min_width=min_width,
84
+ interactive=interactive,
85
+ visible=visible,
86
+ elem_id=elem_id,
87
+ elem_classes=elem_classes,
88
+ render=render,
89
+ key=key,
90
+ value=value,
91
+ )
92
+
93
+ def example_payload(self) -> Any:
94
+ """Return example payload using first choice id if choices exist"""
95
+ if not self.choices:
96
+ return None
97
+ return [self.choices[0]["id"]]
98
+
99
+ def example_value(self) -> Any:
100
+ """Return example value using first choice id if choices exist"""
101
+ if not self.choices:
102
+ return None
103
+ return [self.choices[0]["id"]]
104
+
105
+ def api_info(self) -> dict[str, Any]:
106
+ return {
107
+ "choices": {
108
+ "type": "array",
109
+ "items": {
110
+ "type": "object",
111
+ "properties": {
112
+ "id": {"type": "string"},
113
+ "title": {"type": "string"},
114
+ "content": {"type": "string"},
115
+ "selected": {"type": "boolean", "default": False}
116
+ },
117
+ "required": ["id", "title", "content"]
118
+ }
119
+ },
120
+ "value": {"type": "array", "items": {"type": "string"}},
121
+ }
122
+
123
+
124
+ def preprocess(
125
+ self, payload: list[str | int | float]
126
+ ) -> Union[list[str], list[int], list[dict]]:
127
+ """
128
+ Parameters:
129
+ payload: the list of checked checkboxes' values
130
+ Returns:
131
+ Passes the list of checked checkboxes as a `list[str | int | float]` or their indices as a `list[int]` into the function, depending on `type`.
132
+ """
133
+ id_to_choice = {choice["id"]: choice for choice in self.choices}
134
+
135
+ # Update selected state based on payload
136
+ for choice in self.choices:
137
+ choice["selected"] = choice["id"] in payload
138
+
139
+ # Create dict with default selected=False if not present
140
+ id_to_choice = {
141
+ choice["id"]: {**choice, "selected": choice.get("selected", False)}
142
+ for choice in self.choices
143
+ }
144
+
145
+ for value in payload:
146
+ if value not in id_to_choice.keys():
147
+ raise Error(f"Value: {value!r} not in choices: {id_to_choice.keys()}")
148
+ if self.type == "value":
149
+ # Return selected IDs directly
150
+ return payload
151
+ elif self.type == "index":
152
+ # Return the indices of the selected choices
153
+ return [i for i, c in enumerate(self.choices) if c["id"] in payload]
154
+ elif self.type == "title":
155
+ # Return the titles of the selected choices
156
+ return [id_to_choice[i]["title"] for i in payload if i in id_to_choice]
157
+ elif self.type == "content":
158
+ # Return the content of the selected choices
159
+ return [id_to_choice[i]["content"] for i in payload if i in id_to_choice]
160
+ elif self.type == "all":
161
+ # Return full choice objects as dictionaries
162
+ return [id_to_choice[i] for i in payload if i in id_to_choice]
163
+ else:
164
+ raise ValueError(
165
+ f"Unknown type: {self.type}. Please choose from: {['value', 'index', 'title', 'content', 'all']}"
166
+ )
167
+
168
+
169
+ def postprocess(
170
+ self, value: list[str | int | float] | str | int | float | None
171
+ ) -> list[str | int | float]:
172
+ """
173
+ Parameters:
174
+ value: Expects a `list[str | int | float]` of values or a single `str | int | float` value, the checkboxes with these values are checked.
175
+ Returns:
176
+ the list of checked checkboxes' values
177
+ """
178
+ if value is None:
179
+ return []
180
+ if not isinstance(value, list):
181
+ value = [value]
182
+ return value
183
+ from typing import Callable, Literal, Sequence, Any, TYPE_CHECKING
184
+ from gradio.blocks import Block
185
+ if TYPE_CHECKING:
186
+ from gradio.components import Timer
187
+
188
+
189
+ def change(self,
190
+ fn: Callable[..., Any] | None = None,
191
+ inputs: Block | Sequence[Block] | set[Block] | None = None,
192
+ outputs: Block | Sequence[Block] | None = None,
193
+ api_name: str | None | Literal[False] = None,
194
+ scroll_to_output: bool = False,
195
+ show_progress: Literal["full", "minimal", "hidden"] = "full",
196
+ queue: bool | None = None,
197
+ batch: bool = False,
198
+ max_batch_size: int = 4,
199
+ preprocess: bool = True,
200
+ postprocess: bool = True,
201
+ cancels: dict[str, Any] | list[dict[str, Any]] | None = None,
202
+ every: Timer | float | None = None,
203
+ trigger_mode: Literal["once", "multiple", "always_last"] | None = None,
204
+ js: str | None = None,
205
+ concurrency_limit: int | None | Literal["default"] = "default",
206
+ concurrency_id: str | None = None,
207
+ show_api: bool = True,
208
+
209
+ ) -> Dependency:
210
+ """
211
+ Parameters:
212
+ 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.
213
+ inputs: list of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
214
+ outputs: list of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.
215
+ 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.
216
+ scroll_to_output: if True, will scroll to output component on completion
217
+ show_progress: how to show the progress animation while event is running: "full" shows a spinner which covers the output component area as well as a runtime display in the upper right corner, "minimal" only shows the runtime display, "hidden" shows no progress animation at all
218
+ 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.
219
+ 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.
220
+ max_batch_size: maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
221
+ 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).
222
+ postprocess: if False, will not run postprocessing of component data before returning 'fn' output to the browser.
223
+ 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.
224
+ every: continously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.
225
+ 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()` and `.key_up()` events) would allow a second submission after the pending event is complete.
226
+ 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.
227
+ concurrency_limit: if set, this is the maximum number of this event that can be running simultaneously. Can be set to None to mean no concurrency_limit (any number of this event can be running simultaneously). Set to "default" to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).
228
+ concurrency_id: if set, this is the id of the concurrency group. Events with the same concurrency_id will be limited by the lowest set concurrency_limit.
229
+ show_api: whether to show this event in the "view API" page of the Gradio app, or in the ".view_api()" method of the Gradio clients. Unlike setting api_name to False, setting show_api to False will still allow downstream apps as well as the Clients to use this event. If fn is None, show_api will automatically be set to False.
230
+
231
+ """
232
+ ...
233
+
234
+ def input(self,
235
+ fn: Callable[..., Any] | None = None,
236
+ inputs: Block | Sequence[Block] | set[Block] | None = None,
237
+ outputs: Block | Sequence[Block] | None = None,
238
+ api_name: str | None | Literal[False] = None,
239
+ scroll_to_output: bool = False,
240
+ show_progress: Literal["full", "minimal", "hidden"] = "full",
241
+ queue: bool | None = None,
242
+ batch: bool = False,
243
+ max_batch_size: int = 4,
244
+ preprocess: bool = True,
245
+ postprocess: bool = True,
246
+ cancels: dict[str, Any] | list[dict[str, Any]] | None = None,
247
+ every: Timer | float | None = None,
248
+ trigger_mode: Literal["once", "multiple", "always_last"] | None = None,
249
+ js: str | None = None,
250
+ concurrency_limit: int | None | Literal["default"] = "default",
251
+ concurrency_id: str | None = None,
252
+ show_api: bool = True,
253
+
254
+ ) -> Dependency:
255
+ """
256
+ Parameters:
257
+ 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.
258
+ inputs: list of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
259
+ outputs: list of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.
260
+ 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.
261
+ scroll_to_output: if True, will scroll to output component on completion
262
+ show_progress: how to show the progress animation while event is running: "full" shows a spinner which covers the output component area as well as a runtime display in the upper right corner, "minimal" only shows the runtime display, "hidden" shows no progress animation at all
263
+ 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.
264
+ 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.
265
+ max_batch_size: maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
266
+ 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).
267
+ postprocess: if False, will not run postprocessing of component data before returning 'fn' output to the browser.
268
+ 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.
269
+ every: continously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.
270
+ 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()` and `.key_up()` events) would allow a second submission after the pending event is complete.
271
+ 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.
272
+ concurrency_limit: if set, this is the maximum number of this event that can be running simultaneously. Can be set to None to mean no concurrency_limit (any number of this event can be running simultaneously). Set to "default" to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).
273
+ concurrency_id: if set, this is the id of the concurrency group. Events with the same concurrency_id will be limited by the lowest set concurrency_limit.
274
+ show_api: whether to show this event in the "view API" page of the Gradio app, or in the ".view_api()" method of the Gradio clients. Unlike setting api_name to False, setting show_api to False will still allow downstream apps as well as the Clients to use this event. If fn is None, show_api will automatically be set to False.
275
+
276
+ """
277
+ ...
278
+
279
+ def select(self,
280
+ fn: Callable[..., Any] | None = None,
281
+ inputs: Block | Sequence[Block] | set[Block] | None = None,
282
+ outputs: Block | Sequence[Block] | None = None,
283
+ api_name: str | None | Literal[False] = None,
284
+ scroll_to_output: bool = False,
285
+ show_progress: Literal["full", "minimal", "hidden"] = "full",
286
+ queue: bool | None = None,
287
+ batch: bool = False,
288
+ max_batch_size: int = 4,
289
+ preprocess: bool = True,
290
+ postprocess: bool = True,
291
+ cancels: dict[str, Any] | list[dict[str, Any]] | None = None,
292
+ every: Timer | float | None = None,
293
+ trigger_mode: Literal["once", "multiple", "always_last"] | None = None,
294
+ js: str | None = None,
295
+ concurrency_limit: int | None | Literal["default"] = "default",
296
+ concurrency_id: str | None = None,
297
+ show_api: bool = True,
298
+
299
+ ) -> Dependency:
300
+ """
301
+ Parameters:
302
+ 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.
303
+ inputs: list of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
304
+ outputs: list of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.
305
+ 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.
306
+ scroll_to_output: if True, will scroll to output component on completion
307
+ show_progress: how to show the progress animation while event is running: "full" shows a spinner which covers the output component area as well as a runtime display in the upper right corner, "minimal" only shows the runtime display, "hidden" shows no progress animation at all
308
+ 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.
309
+ 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.
310
+ max_batch_size: maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
311
+ 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).
312
+ postprocess: if False, will not run postprocessing of component data before returning 'fn' output to the browser.
313
+ 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.
314
+ every: continously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.
315
+ 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()` and `.key_up()` events) would allow a second submission after the pending event is complete.
316
+ 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.
317
+ concurrency_limit: if set, this is the maximum number of this event that can be running simultaneously. Can be set to None to mean no concurrency_limit (any number of this event can be running simultaneously). Set to "default" to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).
318
+ concurrency_id: if set, this is the id of the concurrency group. Events with the same concurrency_id will be limited by the lowest set concurrency_limit.
319
+ show_api: whether to show this event in the "view API" page of the Gradio app, or in the ".view_api()" method of the Gradio clients. Unlike setting api_name to False, setting show_api to False will still allow downstream apps as well as the Clients to use this event. If fn is None, show_api will automatically be set to False.
320
+
321
+ """
322
+ ...
323
+
324
+ class CheckboxMarkdownGroup(FormComponent):
325
+ """
326
+ Creates a set of checkboxes. Can be used as an input to pass a set of values to a function or as an output to display values, a subset of which are selected.
327
+ Demos: sentence_builder
328
+ """
329
+
330
+ EVENTS = [Events.change, Events.input, Events.select]
331
+
332
+ def __init__(
333
+ self,
334
+ choices: list[Choice]
335
+ | None = None,
336
+ *,
337
+ value: Sequence[str | float | int] | str | float | int | Callable | None = None,
338
+ type: ChoiceType = "value",
339
+ label: str | None = None,
340
+ info: str | None = None,
341
+ every: Timer | float | None = None,
342
+ inputs: Component | Sequence[Component] | set[Component] | None = None,
343
+ show_label: bool | None = None,
344
+ container: bool = True,
345
+ scale: int | None = None,
346
+ min_width: int = 160,
347
+ interactive: bool | None = None,
348
+ visible: bool = True,
349
+ elem_id: str | None = None,
350
+ elem_classes: list[str] | str | None = None,
351
+ render: bool = True,
352
+ key: int | str | None = None,
353
+ ):
354
+ """
355
+ Parameters:
356
+ choices: A list of string or numeric options to select from. An option can also be a tuple of the form (name, value), where name is the displayed name of the checkbox button and value is the value to be passed to the function, or returned by the function.
357
+ value: Default selected list of options. If a single choice is selected, it can be passed in as a string or numeric type. If callable, the function will be called whenever the app loads to set the initial value of the component.
358
+ type: Type of value to be returned by component. "value" returns the list of strings of the choices selected, "index" returns the list of indices of the choices selected.
359
+ label: the label for this component, displayed above the component if `show_label` is `True` 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 corresponds to.
360
+ info: additional component description, appears below the label in smaller font. Supports markdown / HTML syntax.
361
+ every: Continously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.
362
+ inputs: Components that are used as inputs to calculate `value` if `value` is a function (has no effect otherwise). `value` is recalculated any time the inputs change.
363
+ show_label: If True, will display label.
364
+ container: If True, will place the component in a container - providing some extra padding around the border.
365
+ 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.
366
+ 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.
367
+ interactive: If True, choices in this checkbox group will be checkable; if False, checking will be disabled. If not provided, this is inferred based on whether the component is used as an input or output.
368
+ visible: If False, component will be hidden.
369
+ 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.
370
+ 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.
371
+ 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.
372
+ key: if assigned, will be used to assume identity across a re-render. Components that have the same key across a re-render will have their value preserved.
373
+ """
374
+ self.choices = choices if choices else []
375
+ valid_types = ["value", "index", "title", "content", "all"]
376
+ if type not in valid_types:
377
+ raise ValueError(
378
+ f"Invalid value for parameter `type`: {type}. Please choose from one of: {valid_types}"
379
+ )
380
+ self.type = type
381
+ super().__init__(
382
+ label=label,
383
+ info=info,
384
+ every=every,
385
+ inputs=inputs,
386
+ show_label=show_label,
387
+ container=container,
388
+ scale=scale,
389
+ min_width=min_width,
390
+ interactive=interactive,
391
+ visible=visible,
392
+ elem_id=elem_id,
393
+ elem_classes=elem_classes,
394
+ render=render,
395
+ key=key,
396
+ value=value,
397
+ )
398
+
399
+ def example_payload(self) -> Any:
400
+ return [self.choices[0].id] if self.choices else None
401
+
402
+ def example_value(self) -> Any:
403
+ return [self.choices[0].id] if self.choices else None
404
+
405
+ def api_info(self) -> dict[str, Any]:
406
+ return {
407
+ "items": {"enum": [c.id for c in self.choices], "type": "string"},
408
+ "title": "Checkbox Group",
409
+ "type": "array",
410
+ }
411
+
412
+ def preprocess(
413
+ self, payload: list[str | int | float]
414
+ ) -> Union[list[str], list[int], list[dict]]:
415
+ """
416
+ Parameters:
417
+ payload: the list of checked checkboxes' values
418
+ Returns:
419
+ Passes the list of checked checkboxes as a `list[str | int | float]` or their indices as a `list[int]` into the function, depending on `type`.
420
+ """
421
+ id_to_choice = {choice.id: choice for choice in self.choices}
422
+ for value in payload:
423
+ if value not in id_to_choice.keys():
424
+ raise Error(
425
+ f"Value: {value!r} (type: {type(value)}) is not in the list of choices: {id_to_choice.keys()}"
426
+ )
427
+ if self.type == "value":
428
+ # Return selected IDs directly
429
+ return payload
430
+ elif self.type == "index":
431
+ # Return the indices of the selected choices
432
+ return [i for i, c in enumerate(self.choices) if c.id in payload]
433
+ elif self.type == "title":
434
+ # Return the titles of the selected choices
435
+ return [id_to_choice[i].title for i in payload if i in id_to_choice]
436
+ elif self.type == "content":
437
+ # Return the content of the selected choices
438
+ return [id_to_choice[i].content for i in payload if i in id_to_choice]
439
+ elif self.type == "all":
440
+ # Return full choice objects as dictionaries
441
+ return [id_to_choice[i].__dict__ for i in payload if i in id_to_choice]
442
+ else:
443
+ raise ValueError(
444
+ f"Unknown type: {self.type}. Please choose from: 'value', 'index'."
445
+ )
446
+
447
+
448
+ def postprocess(
449
+ self, value: list[str | int | float] | str | int | float | None
450
+ ) -> list[str | int | float]:
451
+ """
452
+ Parameters:
453
+ value: Expects a `list[str | int | float]` of values or a single `str | int | float` value, the checkboxes with these values are checked.
454
+ Returns:
455
+ the list of checked checkboxes' values
456
+ """
457
+ if value is None:
458
+ return []
459
+ if not isinstance(value, list):
460
+ value = [value]
461
+ return value
462
+
463
+ def update(
464
+ self,
465
+ choices: list[Choice] | None = None,
466
+ value: Sequence[str | float | int] | str | float | int | None = None,
467
+ ) -> dict[str, Any]:
468
+ """Updates the choices and value of the checkbox group.
469
+ Parameters:
470
+ choices: New list of choices to set
471
+ value: New selected values to set
472
+ Returns:
473
+ A dict containing the new choices and value
474
+ """
475
+ updated_config = {}
476
+ if choices is not None:
477
+ updated_config["choices"] = choices
478
+ if value is not None:
479
+ updated_config["value"] = value
480
+ return updated_config
481
+ from typing import Callable, Literal, Sequence, Any, TYPE_CHECKING
482
+ from gradio.blocks import Block
483
+ if TYPE_CHECKING:
484
+ from gradio.components import Timer
485
+
486
+
487
+ def change(self,
488
+ fn: Callable[..., Any] | None = None,
489
+ inputs: Block | Sequence[Block] | set[Block] | None = None,
490
+ outputs: Block | Sequence[Block] | None = None,
491
+ api_name: str | None | Literal[False] = None,
492
+ scroll_to_output: bool = False,
493
+ show_progress: Literal["full", "minimal", "hidden"] = "full",
494
+ queue: bool | None = None,
495
+ batch: bool = False,
496
+ max_batch_size: int = 4,
497
+ preprocess: bool = True,
498
+ postprocess: bool = True,
499
+ cancels: dict[str, Any] | list[dict[str, Any]] | None = None,
500
+ every: Timer | float | None = None,
501
+ trigger_mode: Literal["once", "multiple", "always_last"] | None = None,
502
+ js: str | None = None,
503
+ concurrency_limit: int | None | Literal["default"] = "default",
504
+ concurrency_id: str | None = None,
505
+ show_api: bool = True,
506
+
507
+ ) -> Dependency:
508
+ """
509
+ Parameters:
510
+ 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.
511
+ inputs: list of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
512
+ outputs: list of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.
513
+ 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.
514
+ scroll_to_output: if True, will scroll to output component on completion
515
+ show_progress: how to show the progress animation while event is running: "full" shows a spinner which covers the output component area as well as a runtime display in the upper right corner, "minimal" only shows the runtime display, "hidden" shows no progress animation at all
516
+ 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.
517
+ 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.
518
+ max_batch_size: maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
519
+ 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).
520
+ postprocess: if False, will not run postprocessing of component data before returning 'fn' output to the browser.
521
+ 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.
522
+ every: continously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.
523
+ 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()` and `.key_up()` events) would allow a second submission after the pending event is complete.
524
+ 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.
525
+ concurrency_limit: if set, this is the maximum number of this event that can be running simultaneously. Can be set to None to mean no concurrency_limit (any number of this event can be running simultaneously). Set to "default" to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).
526
+ concurrency_id: if set, this is the id of the concurrency group. Events with the same concurrency_id will be limited by the lowest set concurrency_limit.
527
+ show_api: whether to show this event in the "view API" page of the Gradio app, or in the ".view_api()" method of the Gradio clients. Unlike setting api_name to False, setting show_api to False will still allow downstream apps as well as the Clients to use this event. If fn is None, show_api will automatically be set to False.
528
+
529
+ """
530
+ ...
531
+
532
+ def input(self,
533
+ fn: Callable[..., Any] | None = None,
534
+ inputs: Block | Sequence[Block] | set[Block] | None = None,
535
+ outputs: Block | Sequence[Block] | None = None,
536
+ api_name: str | None | Literal[False] = None,
537
+ scroll_to_output: bool = False,
538
+ show_progress: Literal["full", "minimal", "hidden"] = "full",
539
+ queue: bool | None = None,
540
+ batch: bool = False,
541
+ max_batch_size: int = 4,
542
+ preprocess: bool = True,
543
+ postprocess: bool = True,
544
+ cancels: dict[str, Any] | list[dict[str, Any]] | None = None,
545
+ every: Timer | float | None = None,
546
+ trigger_mode: Literal["once", "multiple", "always_last"] | None = None,
547
+ js: str | None = None,
548
+ concurrency_limit: int | None | Literal["default"] = "default",
549
+ concurrency_id: str | None = None,
550
+ show_api: bool = True,
551
+
552
+ ) -> Dependency:
553
+ """
554
+ Parameters:
555
+ 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.
556
+ inputs: list of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
557
+ outputs: list of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.
558
+ 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.
559
+ scroll_to_output: if True, will scroll to output component on completion
560
+ show_progress: how to show the progress animation while event is running: "full" shows a spinner which covers the output component area as well as a runtime display in the upper right corner, "minimal" only shows the runtime display, "hidden" shows no progress animation at all
561
+ 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.
562
+ 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.
563
+ max_batch_size: maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
564
+ 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).
565
+ postprocess: if False, will not run postprocessing of component data before returning 'fn' output to the browser.
566
+ 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.
567
+ every: continously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.
568
+ 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()` and `.key_up()` events) would allow a second submission after the pending event is complete.
569
+ 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.
570
+ concurrency_limit: if set, this is the maximum number of this event that can be running simultaneously. Can be set to None to mean no concurrency_limit (any number of this event can be running simultaneously). Set to "default" to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).
571
+ concurrency_id: if set, this is the id of the concurrency group. Events with the same concurrency_id will be limited by the lowest set concurrency_limit.
572
+ show_api: whether to show this event in the "view API" page of the Gradio app, or in the ".view_api()" method of the Gradio clients. Unlike setting api_name to False, setting show_api to False will still allow downstream apps as well as the Clients to use this event. If fn is None, show_api will automatically be set to False.
573
+
574
+ """
575
+ ...
576
+
577
+ def select(self,
578
+ fn: Callable[..., Any] | None = None,
579
+ inputs: Block | Sequence[Block] | set[Block] | None = None,
580
+ outputs: Block | Sequence[Block] | None = None,
581
+ api_name: str | None | Literal[False] = None,
582
+ scroll_to_output: bool = False,
583
+ show_progress: Literal["full", "minimal", "hidden"] = "full",
584
+ queue: bool | None = None,
585
+ batch: bool = False,
586
+ max_batch_size: int = 4,
587
+ preprocess: bool = True,
588
+ postprocess: bool = True,
589
+ cancels: dict[str, Any] | list[dict[str, Any]] | None = None,
590
+ every: Timer | float | None = None,
591
+ trigger_mode: Literal["once", "multiple", "always_last"] | None = None,
592
+ js: str | None = None,
593
+ concurrency_limit: int | None | Literal["default"] = "default",
594
+ concurrency_id: str | None = None,
595
+ show_api: bool = True,
596
+
597
+ ) -> Dependency:
598
+ """
599
+ Parameters:
600
+ 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.
601
+ inputs: list of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
602
+ outputs: list of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.
603
+ 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.
604
+ scroll_to_output: if True, will scroll to output component on completion
605
+ show_progress: how to show the progress animation while event is running: "full" shows a spinner which covers the output component area as well as a runtime display in the upper right corner, "minimal" only shows the runtime display, "hidden" shows no progress animation at all
606
+ 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.
607
+ 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.
608
+ max_batch_size: maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
609
+ 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).
610
+ postprocess: if False, will not run postprocessing of component data before returning 'fn' output to the browser.
611
+ 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.
612
+ every: continously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.
613
+ 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()` and `.key_up()` events) would allow a second submission after the pending event is complete.
614
+ 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.
615
+ concurrency_limit: if set, this is the maximum number of this event that can be running simultaneously. Can be set to None to mean no concurrency_limit (any number of this event can be running simultaneously). Set to "default" to use the default concurrency limit (defined by the `default_concurrency_limit` parameter in `Blocks.queue()`, which itself is 1 by default).
616
+ concurrency_id: if set, this is the id of the concurrency group. Events with the same concurrency_id will be limited by the lowest set concurrency_limit.
617
+ show_api: whether to show this event in the "view API" page of the Gradio app, or in the ".view_api()" method of the Gradio clients. Unlike setting api_name to False, setting show_api to False will still allow downstream apps as well as the Clients to use this event. If fn is None, show_api will automatically be set to False.
618
+
619
+ """
620
+ ...
621
+