File size: 11,861 Bytes
870ab6b |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 |
"""gr.Textbox() component."""
from __future__ import annotations
from typing import Callable, Literal
import numpy as np
from gradio_client.documentation import document, set_documentation_group
from gradio_client.serializing import StringSerializable
from gradio.components.base import (
FormComponent,
IOComponent,
_Keywords,
)
from gradio.deprecation import warn_style_method_deprecation
from gradio.events import (
Changeable,
EventListenerMethod,
Focusable,
Inputable,
Selectable,
Submittable,
)
from gradio.interpretation import TokenInterpretable
set_documentation_group("component")
@document()
class Textbox(
FormComponent,
Changeable,
Inputable,
Selectable,
Submittable,
Focusable,
IOComponent,
StringSerializable,
TokenInterpretable,
):
"""
Creates a textarea for user to enter string input or display string output.
Preprocessing: passes textarea value as a {str} into the function.
Postprocessing: expects a {str} returned from function and sets textarea value to it.
Examples-format: a {str} representing the textbox input.
Demos: hello_world, diff_texts, sentence_builder
Guides: creating-a-chatbot, real-time-speech-recognition
"""
def __init__(
self,
value: str | Callable | None = "",
*,
lines: int = 1,
max_lines: int = 20,
placeholder: str | None = None,
label: str | None = None,
info: str | None = None,
every: float | None = None,
show_label: bool | None = None,
container: bool = True,
scale: int | None = None,
min_width: int = 160,
interactive: bool | None = None,
visible: bool = True,
elem_id: str | None = None,
autofocus: bool = False,
autoscroll: bool = True,
elem_classes: list[str] | str | None = None,
type: Literal["text", "password", "email"] = "text",
text_align: Literal["left", "right"] | None = None,
rtl: bool = False,
show_copy_button: bool = False,
**kwargs,
):
"""
Parameters:
value: default text to provide in textarea. If callable, the function will be called whenever the app loads to set the initial value of the component.
lines: minimum number of line rows to provide in textarea.
max_lines: maximum number of line rows to provide in textarea.
placeholder: placeholder hint to provide behind textarea.
label: component name in interface.
info: additional component description.
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.
show_label: if True, will display label.
container: If True, will place the component in a container - providing some extra padding around the border.
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.
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.
interactive: if True, will be rendered as an editable textbox; if False, editing will be disabled. If not provided, this is inferred based on whether the component is used as an input or output.
visible: If False, component will be hidden.
autofocus: If True, will focus on the textbox when the page loads.
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.
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.
type: The type of textbox. One of: 'text', 'password', 'email', Default is 'text'.
text_align: How to align the text in the textbox, can be: "left", "right", or None (default). If None, the alignment is left if `rtl` is False, or right if `rtl` is True. Can only be changed if `type` is "text".
rtl: If True and `type` is "text", sets the direction of the text to right-to-left (cursor appears on the left of the text). Default is False, which renders cursor on the right.
show_copy_button: If True, includes a copy button to copy the text in the textbox. Only applies if show_label is True.
autoscroll: If True, will automatically scroll to the bottom of the textbox when the value changes.
"""
if type not in ["text", "password", "email"]:
raise ValueError('`type` must be one of "text", "password", or "email".')
self.lines = lines
if type == "text":
self.max_lines = max(lines, max_lines)
else:
self.max_lines = 1
self.placeholder = placeholder
self.show_copy_button = show_copy_button
self.autofocus = autofocus
self.select: EventListenerMethod
self.autoscroll = autoscroll
"""
Event listener for when the user selects text in the Textbox.
Uses event data gradio.SelectData to carry `value` referring to selected substring, and `index` tuple referring to selected range endpoints.
See EventData documentation on how to use this event data.
"""
IOComponent.__init__(
self,
label=label,
info=info,
every=every,
show_label=show_label,
container=container,
scale=scale,
min_width=min_width,
interactive=interactive,
visible=visible,
elem_id=elem_id,
elem_classes=elem_classes,
value=value,
**kwargs,
)
TokenInterpretable.__init__(self)
self.type = type
self.rtl = rtl
self.text_align = text_align
def get_config(self):
return {
"lines": self.lines,
"max_lines": self.max_lines,
"placeholder": self.placeholder,
"value": self.value,
"type": self.type,
"autofocus": self.autofocus,
"show_copy_button": self.show_copy_button,
"container": self.container,
"text_align": self.text_align,
"rtl": self.rtl,
"autoscroll": self.autoscroll,
**IOComponent.get_config(self),
}
@staticmethod
def update(
value: str | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE,
lines: int | None = None,
max_lines: int | None = None,
placeholder: str | None = None,
label: str | None = None,
info: str | None = None,
show_label: bool | None = None,
container: bool | None = None,
scale: int | None = None,
min_width: int | None = None,
visible: bool | None = None,
interactive: bool | None = None,
type: Literal["text", "password", "email"] | None = None,
text_align: Literal["left", "right"] | None = None,
rtl: bool | None = None,
show_copy_button: bool | None = None,
autofocus: bool | None = None,
autoscroll: bool | None = None,
):
return {
"lines": lines,
"max_lines": max_lines,
"placeholder": placeholder,
"label": label,
"info": info,
"show_label": show_label,
"container": container,
"scale": scale,
"min_width": min_width,
"visible": visible,
"value": value,
"type": type,
"interactive": interactive,
"show_copy_button": show_copy_button,
"autofocus": autofocus,
"text_align": text_align,
"rtl": rtl,
"autoscroll": autoscroll,
"__type__": "update",
}
def preprocess(self, x: str | None) -> str | None:
"""
Preprocesses input (converts it to a string) before passing it to the function.
Parameters:
x: text
Returns:
text
"""
return None if x is None else str(x)
def postprocess(self, y: str | None) -> str | None:
"""
Postproccess the function output y by converting it to a str before passing it to the frontend.
Parameters:
y: function output to postprocess.
Returns:
text
"""
return None if y is None else str(y)
def set_interpret_parameters(
self, separator: str = " ", replacement: str | None = None
):
"""
Calculates interpretation score of characters in input by splitting input into tokens, then using a "leave one out" method to calculate the score of each token by removing each token and measuring the delta of the output value.
Parameters:
separator: Separator to use to split input into tokens.
replacement: In the "leave one out" step, the text that the token should be replaced with. If None, the token is removed altogether.
"""
self.interpretation_separator = separator
self.interpretation_replacement = replacement
return self
def tokenize(self, x: str) -> tuple[list[str], list[str], None]:
"""
Tokenizes an input string by dividing into "words" delimited by self.interpretation_separator
"""
tokens = x.split(self.interpretation_separator)
leave_one_out_strings = []
for index in range(len(tokens)):
leave_one_out_set = list(tokens)
if self.interpretation_replacement is None:
leave_one_out_set.pop(index)
else:
leave_one_out_set[index] = self.interpretation_replacement
leave_one_out_strings.append(
self.interpretation_separator.join(leave_one_out_set)
)
return tokens, leave_one_out_strings, None
def get_masked_inputs(
self, tokens: list[str], binary_mask_matrix: list[list[int]]
) -> list[str]:
"""
Constructs partially-masked sentences for SHAP interpretation
"""
masked_inputs = []
for binary_mask_vector in binary_mask_matrix:
masked_input = np.array(tokens)[np.array(binary_mask_vector, dtype=bool)]
masked_inputs.append(self.interpretation_separator.join(masked_input))
return masked_inputs
def get_interpretation_scores(
self, x, neighbors, scores: list[float], tokens: list[str], masks=None, **kwargs
) -> list[tuple[str, float]]:
"""
Returns:
Each tuple set represents a set of characters and their corresponding interpretation score.
"""
result = []
for token, score in zip(tokens, scores):
result.append((token, score))
result.append((self.interpretation_separator, 0))
return result
def style(
self,
*,
show_copy_button: bool | None = None,
container: bool | None = None,
**kwargs,
):
"""
This method is deprecated. Please set these arguments in the constructor instead.
"""
warn_style_method_deprecation()
if show_copy_button is not None:
self.show_copy_button = show_copy_button
if container is not None:
self.container = container
return self
|