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,4 @@
1
+
2
+ from .checkboxgroupmarkdown import CheckboxGroupMarkdown
3
+
4
+ __all__ = ['CheckboxGroupMarkdown']
@@ -0,0 +1,185 @@
1
+ """gr.CheckboxGroupMarkdown() component"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable, Sequence
6
+ from typing import TYPE_CHECKING, Any, Literal, Union
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
+ # Define allowable types
18
+ ChoiceType = Literal["value", "index", "title", "content", "all"]
19
+
20
+
21
+ class CheckboxGroupMarkdown(FormComponent):
22
+ """
23
+ 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.
24
+ Demos: sentence_builder
25
+ """
26
+
27
+ EVENTS = [Events.change, Events.input, Events.select]
28
+
29
+ def __init__(
30
+ self,
31
+ choices: list[dict]
32
+ | None = None,
33
+ *,
34
+ value: Sequence[str | float | int] | str | float | int | Callable | None = None,
35
+ type: ChoiceType = "value",
36
+ label: str | None = None,
37
+ info: str | None = None,
38
+ every: Timer | float | None = None,
39
+ inputs: Component | Sequence[Component] | set[Component] | None = None,
40
+ show_label: bool | None = None,
41
+ container: bool = True,
42
+ scale: int | None = None,
43
+ min_width: int = 160,
44
+ interactive: bool | None = None,
45
+ visible: bool = True,
46
+ elem_id: str | None = None,
47
+ elem_classes: list[str] | str | None = None,
48
+ render: bool = True,
49
+ key: int | str | None = None,
50
+ ):
51
+ """
52
+ Parameters:
53
+ 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.
54
+ 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.
55
+ 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.
56
+ 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.
57
+ info: additional component description, appears below the label in smaller font. Supports markdown / HTML syntax.
58
+ 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.
59
+ 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.
60
+ show_label: If True, will display label.
61
+ container: If True, will place the component in a container - providing some extra padding around the border.
62
+ 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.
63
+ 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.
64
+ 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.
65
+ visible: If False, component will be hidden.
66
+ 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.
67
+ 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.
68
+ 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.
69
+ 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.
70
+ """
71
+ self.choices = choices if choices else []
72
+ valid_types = ["value", "index", "title", "content", "all"]
73
+ if type not in valid_types:
74
+ raise ValueError(
75
+ f"Invalid value for parameter `type`: {type}. Please choose from one of: {valid_types}"
76
+ )
77
+ self.type = type
78
+ super().__init__(
79
+ label=label,
80
+ info=info,
81
+ every=every,
82
+ inputs=inputs,
83
+ show_label=show_label,
84
+ container=container,
85
+ scale=scale,
86
+ min_width=min_width,
87
+ interactive=interactive,
88
+ visible=visible,
89
+ elem_id=elem_id,
90
+ elem_classes=elem_classes,
91
+ render=render,
92
+ key=key,
93
+ value=value,
94
+ )
95
+
96
+ def example_payload(self) -> Any:
97
+ """Return example payload using first choice id if choices exist"""
98
+ if not self.choices:
99
+ return None
100
+ return [self.choices[0]["id"]]
101
+
102
+ def example_value(self) -> Any:
103
+ """Return example value using first choice id if choices exist"""
104
+ if not self.choices:
105
+ return None
106
+ return [self.choices[0]["id"]]
107
+
108
+ def api_info(self) -> dict[str, Any]:
109
+ return {
110
+ "choices": {
111
+ "type": "array",
112
+ "items": {
113
+ "type": "object",
114
+ "properties": {
115
+ "id": {"type": "string"},
116
+ "title": {"type": "string"},
117
+ "content": {"type": "string"},
118
+ "selected": {"type": "boolean", "default": False}
119
+ },
120
+ "required": ["id", "title", "content"]
121
+ }
122
+ },
123
+ "value": {"type": "array", "items": {"type": "string"}},
124
+ }
125
+
126
+
127
+ def preprocess(
128
+ self, payload: list[str | int | float]
129
+ ) -> Union[list[str], list[int], list[dict]]:
130
+ """
131
+ Parameters:
132
+ payload: the list of checked checkboxes' values
133
+ Returns:
134
+ 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`.
135
+ """
136
+ id_to_choice = {choice["id"]: choice for choice in self.choices}
137
+
138
+ # Update selected state based on payload
139
+ for choice in self.choices:
140
+ choice["selected"] = choice["id"] in payload
141
+
142
+ # Create dict with default selected=False if not present
143
+ id_to_choice = {
144
+ choice["id"]: {**choice, "selected": choice.get("selected", False)}
145
+ for choice in self.choices
146
+ }
147
+
148
+ for value in payload:
149
+ if value not in id_to_choice.keys():
150
+ raise Error(f"Value: {value!r} not in choices: {id_to_choice.keys()}")
151
+ if self.type == "value":
152
+ # Return selected IDs directly
153
+ return payload
154
+ elif self.type == "index":
155
+ # Return the indices of the selected choices
156
+ return [i for i, c in enumerate(self.choices) if c["id"] in payload]
157
+ elif self.type == "title":
158
+ # Return the titles of the selected choices
159
+ return [id_to_choice[i]["title"] for i in payload if i in id_to_choice]
160
+ elif self.type == "content":
161
+ # Return the content of the selected choices
162
+ return [id_to_choice[i]["content"] for i in payload if i in id_to_choice]
163
+ elif self.type == "all":
164
+ # Return full choice objects as dictionaries
165
+ return [id_to_choice[i] for i in payload if i in id_to_choice]
166
+ else:
167
+ raise ValueError(
168
+ f"Unknown type: {self.type}. Please choose from: {['value', 'index', 'title', 'content', 'all']}"
169
+ )
170
+
171
+
172
+ def postprocess(
173
+ self, value: list[str | int | float] | str | int | float | None
174
+ ) -> list[str | int | float]:
175
+ """
176
+ Parameters:
177
+ value: Expects a `list[str | int | float]` of values or a single `str | int | float` value, the checkboxes with these values are checked.
178
+ Returns:
179
+ the list of checked checkboxes' values
180
+ """
181
+ if value is None:
182
+ return []
183
+ if not isinstance(value, list):
184
+ value = [value]
185
+ return value