-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
components.py
4621 lines (4222 loc) 路 177 KB
/
components.py
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Contains all of the components that can be used with Gradio Interface / Blocks.
Along with the docs for each component, you can find the names of example demos that use
each component. These demos are located in the `demo` directory."""
from __future__ import annotations
import inspect
import json
import math
import numbers
import operator
import os
import random
import tempfile
import uuid
import warnings
from copy import deepcopy
from enum import Enum
from pathlib import Path
from types import ModuleType
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple
import altair as alt
import matplotlib.figure
import numpy as np
import pandas as pd
import PIL
import PIL.ImageOps
from ffmpy import FFmpeg
from markdown_it import MarkdownIt
from mdit_py_plugins.dollarmath import dollarmath_plugin
from pandas.api.types import is_numeric_dtype
from gradio import media_data, processing_utils, utils
from gradio.blocks import Block
from gradio.context import Context
from gradio.documentation import document, set_documentation_group
from gradio.events import (
Blurrable,
Changeable,
Clearable,
Clickable,
Editable,
Playable,
Streamable,
Submittable,
Uploadable,
)
from gradio.layouts import Column, Form, Row
from gradio.processing_utils import TempFileManager
from gradio.serializing import (
FileSerializable,
ImgSerializable,
JSONSerializable,
Serializable,
SimpleSerializable,
)
if TYPE_CHECKING:
from typing import TypedDict
class DataframeData(TypedDict):
headers: List[str]
data: List[List[str | int | bool]]
set_documentation_group("component")
class _Keywords(Enum):
NO_VALUE = "NO_VALUE" # Used as a sentinel to determine if nothing is provided as a argument for `value` in `Component.update()`
FINISHED_ITERATING = "FINISHED_ITERATING" # Used to skip processing of a component's value (needed for generators + state)
class Component(Block):
"""
A base class for defining the methods that all gradio components should have.
"""
def __str__(self):
return self.__repr__()
def __repr__(self):
return f"{self.get_block_name()}"
def get_config(self):
"""
:return: a dictionary with context variables for the javascript file associated with the context
"""
return {
"name": self.get_block_name(),
**super().get_config(),
}
class IOComponent(Component, Serializable):
"""
A base class for defining methods that all input/output components should have.
"""
def __init__(
self,
*,
value: Any = None,
label: Optional[str] = None,
show_label: bool = True,
interactive: Optional[bool] = None,
visible: bool = True,
elem_id: Optional[str] = None,
load_fn: Optional[Callable] = None,
every: Optional[float] = None,
**kwargs,
):
super().__init__(elem_id=elem_id, visible=visible, **kwargs)
self.label = label
self.show_label = show_label
self.interactive = interactive
self.load_event = None
self.load_event_to_attach = None
load_fn, initial_value = self.get_load_fn_and_initial_value(value)
self.value = self.postprocess(initial_value)
if callable(load_fn):
self.load_event = self.attach_load_event(load_fn, every)
self.set_interpret_parameters()
def get_config(self):
return {
"label": self.label,
"show_label": self.show_label,
"interactive": self.interactive,
**super().get_config(),
}
def preprocess(self, x: Any) -> Any:
"""
Any preprocessing needed to be performed on function input.
"""
return x
def set_interpret_parameters(self):
"""
Set any parameters for interpretation.
"""
return self
def get_interpretation_neighbors(self, x: Any) -> Tuple[List[Any], Dict[Any], bool]:
"""
Generates values similar to input to be used to interpret the significance of the input in the final output.
Parameters:
x: Input to interface
Returns: (neighbor_values, interpret_kwargs, interpret_by_removal)
neighbor_values: Neighboring values to input x to compute for interpretation
interpret_kwargs: Keyword arguments to be passed to get_interpretation_scores
interpret_by_removal: If True, returned neighbors are values where the interpreted subsection was removed. If False, returned neighbors are values where the interpreted subsection was modified to a different value.
"""
return [], {}, True
def get_interpretation_scores(
self, x: Any, neighbors: List[Any], scores: List[float], **kwargs
) -> List[Any]:
"""
Arrange the output values from the neighbors into interpretation scores for the interface to render.
Parameters:
x: Input to interface
neighbors: Neighboring values to input x used for interpretation.
scores: Output value corresponding to each neighbor in neighbors
Returns:
Arrangement of interpretation scores for interfaces to render.
"""
pass
def generate_sample(self) -> Any:
"""
Returns a sample value of the input that would be accepted by the api. Used for api documentation.
"""
pass
def postprocess(self, y):
"""
Any postprocessing needed to be performed on function output.
"""
return y
def style(
self,
*,
container: Optional[bool] = None,
**kwargs,
):
"""
This method can be used to change the appearance of the component.
Parameters:
container: If True, will place the component in a container - providing some extra padding around the border.
"""
put_deprecated_params_in_box = False
if "rounded" in kwargs:
warnings.warn(
"'rounded' styling is no longer supported. To round adjacent components together, place them in a Column(variant='box')."
)
if isinstance(kwargs["rounded"], list) or isinstance(
kwargs["rounded"], tuple
):
put_deprecated_params_in_box = True
kwargs.pop("rounded")
if "margin" in kwargs:
warnings.warn(
"'margin' styling is no longer supported. To place adjacent components together without margin, place them in a Column(variant='box')."
)
if isinstance(kwargs["margin"], list) or isinstance(
kwargs["margin"], tuple
):
put_deprecated_params_in_box = True
kwargs.pop("margin")
if "border" in kwargs:
warnings.warn(
"'border' styling is no longer supported. To place adjacent components in a shared border, place them in a Column(variant='box')."
)
kwargs.pop("border")
if container is not None:
self._style["container"] = container
if len(kwargs):
for key in kwargs:
warnings.warn(f"Unknown style parameter: {key}")
if (
put_deprecated_params_in_box
and getattr(self, "parent", None).__class__ in [Row, Column]
and self.parent.variant == "default"
):
self.parent.variant = "compact"
return self
@staticmethod
def add_interactive_to_config(config, interactive):
if interactive is not None:
config["mode"] = "dynamic" if interactive else "static"
return config
@staticmethod
def get_load_fn_and_initial_value(value):
if callable(value):
initial_value = value()
load_fn = value
else:
initial_value = value
load_fn = None
return load_fn, initial_value
def attach_load_event(self, callable: Callable, every: int | None):
"""Add a load event that runs `callable`, optionally every `every` seconds."""
if Context.root_block:
return Context.root_block.load(
callable,
None,
self,
no_target=True,
every=every,
)
else:
self.load_event_to_attach = (callable, every)
def as_example(self, input_data):
"""Return the input data in a way that can be displayed by the examples dataset component in the front-end."""
return input_data
class FormComponent:
expected_parent = Form
@document("change", "submit", "blur", "style")
class Textbox(
Changeable, Submittable, Blurrable, IOComponent, SimpleSerializable, FormComponent
):
"""
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: Optional[str | Callable] = "",
*,
lines: int = 1,
max_lines: int = 20,
placeholder: Optional[str] = None,
label: Optional[str] = None,
every: float | None = None,
show_label: bool = True,
interactive: Optional[bool] = None,
visible: bool = True,
elem_id: Optional[str] = None,
type: str = "text",
**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.
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.
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.
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.
type: The type of textbox. One of: 'text', 'password', 'email', Default is 'text'.
"""
if type not in ["text", "password", "email"]:
raise ValueError('`type` must be one of "text", "password", or "email".')
#
self.lines = lines
self.max_lines = max_lines if type == "text" else 1
self.placeholder = placeholder
self.interpret_by_tokens = True
IOComponent.__init__(
self,
label=label,
every=every,
show_label=show_label,
interactive=interactive,
visible=visible,
elem_id=elem_id,
value=value,
**kwargs,
)
self.cleared_value = ""
self.test_input = value
self.type = type
def get_config(self):
return {
"lines": self.lines,
"max_lines": self.max_lines,
"placeholder": self.placeholder,
"value": self.value,
"type": self.type,
**IOComponent.get_config(self),
}
@staticmethod
def update(
value: Optional[str] = _Keywords.NO_VALUE,
lines: Optional[int] = None,
max_lines: Optional[int] = None,
placeholder: Optional[str] = None,
label: Optional[str] = None,
show_label: Optional[bool] = None,
visible: Optional[bool] = None,
interactive: Optional[bool] = None,
type: Optional[str] = None,
):
updated_config = {
"lines": lines,
"max_lines": max_lines,
"placeholder": placeholder,
"label": label,
"show_label": show_label,
"visible": visible,
"value": value,
"type": type,
"__type__": "update",
}
return IOComponent.add_interactive_to_config(updated_config, interactive)
def generate_sample(self) -> str:
return "Hello World"
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: Optional[str] = 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
@document("change", "submit", "style")
class Number(
Changeable, Submittable, Blurrable, IOComponent, SimpleSerializable, FormComponent
):
"""
Creates a numeric field for user to enter numbers as input or display numeric output.
Preprocessing: passes field value as a {float} or {int} into the function, depending on `precision`.
Postprocessing: expects an {int} or {float} returned from the function and sets field value to it.
Examples-format: a {float} or {int} representing the number's value.
Demos: tax_calculator, titanic_survival, blocks_simple_squares
"""
def __init__(
self,
value: Optional[float | Callable] = None,
*,
label: Optional[str] = None,
every: float | None = None,
show_label: bool = True,
interactive: Optional[bool] = None,
visible: bool = True,
elem_id: Optional[str] = None,
precision: Optional[int] = None,
**kwargs,
):
"""
Parameters:
value: default value. If callable, the function will be called whenever the app loads to set the initial value of the component.
label: component name in interface.
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.
interactive: if True, will be editable; 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.
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.
precision: Precision to round input/output to. If set to 0, will round to nearest integer and covert type to int. If None, no rounding happens.
"""
self.precision = precision
self.interpret_by_tokens = False
IOComponent.__init__(
self,
label=label,
every=every,
show_label=show_label,
interactive=interactive,
visible=visible,
elem_id=elem_id,
value=value,
**kwargs,
)
self.test_input = self.value if self.value is not None else 1
@staticmethod
def _round_to_precision(
num: float | int | None, precision: int | None
) -> float | int | None:
"""
Round to a given precision.
If precision is None, no rounding happens. If 0, num is converted to int.
Parameters:
num: Number to round.
precision: Precision to round to.
Returns:
rounded number
"""
if num is None:
return None
if precision is None:
return float(num)
elif precision == 0:
return int(round(num, precision))
else:
return round(num, precision)
def get_config(self):
return {
"value": self.value,
**IOComponent.get_config(self),
}
@staticmethod
def update(
value: Optional[float] = _Keywords.NO_VALUE,
label: Optional[str] = None,
show_label: Optional[bool] = None,
interactive: Optional[bool] = None,
visible: Optional[bool] = None,
):
updated_config = {
"label": label,
"show_label": show_label,
"visible": visible,
"value": value,
"__type__": "update",
}
return IOComponent.add_interactive_to_config(updated_config, interactive)
def preprocess(self, x: float | None) -> float | None:
"""
Parameters:
x: numeric input
Returns:
number representing function input
"""
if x is None:
return None
return self._round_to_precision(x, self.precision)
def postprocess(self, y: float | None) -> float | None:
"""
Any postprocessing needed to be performed on function output.
Parameters:
y: numeric output
Returns:
number representing function output
"""
if y is None:
return None
return self._round_to_precision(y, self.precision)
def set_interpret_parameters(
self, steps: int = 3, delta: float = 1, delta_type: str = "percent"
):
"""
Calculates interpretation scores of numeric values close to the input number.
Parameters:
steps: Number of nearby values to measure in each direction (above and below the input number).
delta: Size of step in each direction between nearby values.
delta_type: "percent" if delta step between nearby values should be a calculated as a percent, or "absolute" if delta should be a constant step change.
"""
self.interpretation_steps = steps
self.interpretation_delta = delta
self.interpretation_delta_type = delta_type
return self
def get_interpretation_neighbors(self, x: float | int) -> Tuple[List[float], Dict]:
x = self._round_to_precision(x, self.precision)
if self.interpretation_delta_type == "percent":
delta = 1.0 * self.interpretation_delta * x / 100
elif self.interpretation_delta_type == "absolute":
delta = self.interpretation_delta
else:
delta = self.interpretation_delta
if self.precision == 0 and math.floor(delta) != delta:
raise ValueError(
f"Delta value {delta} is not an integer and precision=0. Cannot generate valid set of neighbors. "
"If delta_type='percent', pick a value of delta such that x * delta is an integer. "
"If delta_type='absolute', pick a value of delta that is an integer."
)
# run_interpretation will preprocess the neighbors so no need to covert to int here
negatives = (x + np.arange(-self.interpretation_steps, 0) * delta).tolist()
positives = (x + np.arange(1, self.interpretation_steps + 1) * delta).tolist()
return negatives + positives, {}
def get_interpretation_scores(
self, x: Number, neighbors: List[float], scores: List[float], **kwargs
) -> List[Tuple[float, float]]:
"""
Returns:
Each tuple set represents a numeric value near the input and its corresponding interpretation score.
"""
interpretation = list(zip(neighbors, scores))
interpretation.insert(int(len(interpretation) / 2), [x, None])
return interpretation
def generate_sample(self) -> float:
return self._round_to_precision(1, self.precision)
@document("change", "style")
class Slider(Changeable, IOComponent, SimpleSerializable, FormComponent):
"""
Creates a slider that ranges from `minimum` to `maximum` with a step size of `step`.
Preprocessing: passes slider value as a {float} into the function.
Postprocessing: expects an {int} or {float} returned from function and sets slider value to it as long as it is within range.
Examples-format: A {float} or {int} representing the slider's value.
Demos: sentence_builder, generate_tone, titanic_survival, interface_random_slider, blocks_random_slider
Guides: create_your_own_friends_with_a_gan
"""
def __init__(
self,
minimum: float = 0,
maximum: float = 100,
value: Optional[float | Callable] = None,
*,
step: Optional[float] = None,
label: Optional[str] = None,
every: float | None = None,
show_label: bool = True,
interactive: Optional[bool] = None,
visible: bool = True,
elem_id: Optional[str] = None,
randomize: bool = False,
**kwargs,
):
"""
Parameters:
minimum: minimum value for slider.
maximum: maximum value for slider.
value: default value. If callable, the function will be called whenever the app loads to set the initial value of the component. Ignored if randomized=True.
step: increment between slider values.
label: component name in interface.
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.
interactive: if True, slider will be adjustable; if False, adjusting 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.
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.
randomize: If True, the value of the slider when the app loads is taken uniformly at random from the range given by the minimum and maximum.
"""
self.minimum = minimum
self.maximum = maximum
if step is None:
difference = maximum - minimum
power = math.floor(math.log10(difference) - 2)
step = 10**power
self.step = step
if randomize:
value = self.get_random_value
IOComponent.__init__(
self,
label=label,
every=every,
show_label=show_label,
interactive=interactive,
visible=visible,
elem_id=elem_id,
value=value,
**kwargs,
)
self.cleared_value = self.value
self.test_input = self.value
self.interpret_by_tokens = False
def get_config(self):
return {
"minimum": self.minimum,
"maximum": self.maximum,
"step": self.step,
"value": self.value,
**IOComponent.get_config(self),
}
def get_random_value(self):
n_steps = int((self.maximum - self.minimum) / self.step)
step = random.randint(0, n_steps)
value = self.minimum + step * self.step
# Round to number of decimals in step so that UI doesn't display long decimals
n_decimals = max(str(self.step)[::-1].find("."), 0)
if n_decimals:
value = round(value, n_decimals)
return value
@staticmethod
def update(
value: Optional[float] = _Keywords.NO_VALUE,
minimum: Optional[float] = None,
maximum: Optional[float] = None,
step: Optional[float] = None,
label: Optional[str] = None,
show_label: Optional[bool] = None,
interactive: Optional[bool] = None,
visible: Optional[bool] = None,
):
updated_config = {
"minimum": minimum,
"maximum": maximum,
"step": step,
"label": label,
"show_label": show_label,
"interactive": interactive,
"visible": visible,
"value": value,
"__type__": "update",
}
return IOComponent.add_interactive_to_config(updated_config, interactive)
def generate_sample(self) -> float:
return self.maximum
def postprocess(self, y: float | None) -> float | None:
"""
Any postprocessing needed to be performed on function output.
Parameters:
y: numeric output
Returns:
numeric output or minimum number if None
"""
return self.minimum if y is None else y
def set_interpret_parameters(self, steps: int = 8) -> "Slider":
"""
Calculates interpretation scores of numeric values ranging between the minimum and maximum values of the slider.
Parameters:
steps: Number of neighboring values to measure between the minimum and maximum values of the slider range.
"""
self.interpretation_steps = steps
return self
def get_interpretation_neighbors(self, x) -> Tuple[object, dict]:
return (
np.linspace(self.minimum, self.maximum, self.interpretation_steps).tolist(),
{},
)
def get_interpretation_scores(
self, x, neighbors, scores: List[float], **kwargs
) -> List[float]:
"""
Returns:
Each value represents the score corresponding to an evenly spaced range of inputs between the minimum and maximum slider values.
"""
return scores
def style(
self,
*,
container: Optional[bool] = None,
):
"""
This method can be used to change the appearance of the slider.
Parameters:
container: If True, will place the component in a container - providing some extra padding around the border.
"""
return IOComponent.style(
self,
container=container,
)
@document("change", "style")
class Checkbox(Changeable, IOComponent, SimpleSerializable, FormComponent):
"""
Creates a checkbox that can be set to `True` or `False`.
Preprocessing: passes the status of the checkbox as a {bool} into the function.
Postprocessing: expects a {bool} returned from the function and, if it is True, checks the checkbox.
Examples-format: a {bool} representing whether the box is checked.
Demos: sentence_builder, titanic_survival
"""
def __init__(
self,
value: bool | Callable = False,
*,
label: Optional[str] = None,
every: float | None = None,
show_label: bool = True,
interactive: Optional[bool] = None,
visible: bool = True,
elem_id: Optional[str] = None,
**kwargs,
):
"""
Parameters:
value: if True, checked by default. If callable, the function will be called whenever the app loads to set the initial value of the component.
label: component name in interface.
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.
interactive: if True, this checkbox can be checked; if False, checking 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.
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.
"""
self.test_input = True
self.interpret_by_tokens = False
IOComponent.__init__(
self,
label=label,
every=every,
show_label=show_label,
interactive=interactive,
visible=visible,
elem_id=elem_id,
value=value,
**kwargs,
)
def get_config(self):
return {
"value": self.value,
**IOComponent.get_config(self),
}
@staticmethod
def update(
value: Optional[bool] = _Keywords.NO_VALUE,
label: Optional[str] = None,
show_label: Optional[bool] = None,
interactive: Optional[bool] = None,
visible: Optional[bool] = None,
):
updated_config = {
"label": label,
"show_label": show_label,
"interactive": interactive,
"visible": visible,
"value": value,
"__type__": "update",
}
return IOComponent.add_interactive_to_config(updated_config, interactive)
def generate_sample(self):
return True
def set_interpret_parameters(self):
"""
Calculates interpretation score of the input by comparing the output against the output when the input is the inverse boolean value of x.
"""
return self
def get_interpretation_neighbors(self, x):
return [not x], {}
def get_interpretation_scores(self, x, neighbors, scores, **kwargs):
"""
Returns:
The first value represents the interpretation score if the input is False, and the second if the input is True.
"""
if x:
return scores[0], None
else:
return None, scores[0]
@document("change", "style")
class CheckboxGroup(Changeable, IOComponent, SimpleSerializable, FormComponent):
"""
Creates a set of checkboxes of which a subset can be checked.
Preprocessing: passes the list of checked checkboxes as a {List[str]} or their indices as a {List[int]} into the function, depending on `type`.
Postprocessing: expects a {List[str]}, each element of which becomes a checked checkbox.
Examples-format: a {List[str]} representing the values to be checked.
Demos: sentence_builder, titanic_survival
"""
def __init__(
self,
choices: Optional[List[str]] = None,
*,
value: List[str] | Callable = None,
type: str = "value",
label: Optional[str] = None,
every: float | None = None,
show_label: bool = True,
interactive: Optional[bool] = None,
visible: bool = True,
elem_id: Optional[str] = None,
**kwargs,
):
"""
Parameters:
choices: list of options to select from.
value: default selected list of options. If callable, the function will be called whenever the app loads to set the initial value of the component.
type: Type of value to be returned by component. "value" returns the list of strings of the choices selected, "index" returns the list of indicies of the choices selected.
label: component name in interface.
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.
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.
visible: If False, component will be hidden.
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.
"""
self.choices = choices or []
self.cleared_value = []
valid_types = ["value", "index"]
if type not in valid_types:
raise ValueError(
f"Invalid value for parameter `type`: {type}. Please choose from one of: {valid_types}"
)
self.type = type
self.test_input = self.choices
self.interpret_by_tokens = False
IOComponent.__init__(
self,
label=label,
every=every,
show_label=show_label,
interactive=interactive,
visible=visible,
elem_id=elem_id,
value=value,
**kwargs,
)
def get_config(self):
return {
"choices": self.choices,
"value": self.value,
**IOComponent.get_config(self),
}
@staticmethod
def update(
value: Optional[List[str]] = _Keywords.NO_VALUE,
choices: Optional[List[str]] = None,
label: Optional[str] = None,
show_label: Optional[bool] = None,
interactive: Optional[bool] = None,
visible: Optional[bool] = None,
):
updated_config = {
"choices": choices,
"label": label,
"show_label": show_label,
"interactive": interactive,
"visible": visible,
"value": value,
"__type__": "update",
}
return IOComponent.add_interactive_to_config(updated_config, interactive)
def generate_sample(self):
return self.choices
def preprocess(self, x: List[str]) -> List[str] | List[int]:
"""
Parameters:
x: list of selected choices
Returns:
list of selected choices as strings or indices within choice list
"""
if self.type == "value":
return x
elif self.type == "index":
return [self.choices.index(choice) for choice in x]
else:
raise ValueError(
"Unknown type: "
+ str(self.type)
+ ". Please choose from: 'value', 'index'."
)
def postprocess(self, y: List[str] | None) -> List[str]:
"""
Any postprocessing needed to be performed on function output.
Parameters:
y: List of selected choices
Returns:
List of selected choices
"""
return [] if y is None else y
def set_interpret_parameters(self):
"""
Calculates interpretation score of each choice in the input by comparing the output against the outputs when each choice in the input is independently either removed or added.