-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
components.py
6810 lines (6316 loc) 路 280 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 hashlib
import inspect
import json
import math
import operator
import os
import random
import secrets
import shutil
import tempfile
import urllib.request
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
import aiofiles
import altair as alt
import numpy as np
import pandas as pd
import PIL
import PIL.ImageOps
import requests
from fastapi import UploadFile
from ffmpy import FFmpeg
from gradio_client import media_data
from gradio_client import utils as client_utils
from gradio_client.data_classes import FileData
from gradio_client.documentation import document, set_documentation_group
from gradio_client.serializing import (
BooleanSerializable,
FileSerializable,
GallerySerializable,
ImgSerializable,
JSONSerializable,
ListStringSerializable,
NumberSerializable,
Serializable,
SimpleSerializable,
StringSerializable,
VideoSerializable,
)
from pandas.api.types import is_numeric_dtype
from PIL import Image as _Image # using _ to minimize namespace pollution
from typing_extensions import Literal
from gradio import processing_utils, utils
from gradio.blocks import Block, BlockContext
from gradio.events import (
Blurrable,
Changeable,
Clearable,
Clickable,
Editable,
EventListener,
EventListenerMethod,
Inputable,
Playable,
Recordable,
Releaseable,
Selectable,
Streamable,
Submittable,
Uploadable,
)
from gradio.interpretation import NeighborInterpretable, TokenInterpretable
from gradio.layouts import Column, Form, Row
if TYPE_CHECKING:
from typing import TypedDict
class DataframeData(TypedDict):
headers: list[str]
data: list[list[str | int | bool]]
set_documentation_group("component")
_Image.init() # fixes https://github.com/gradio-app/gradio/issues/2843
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, Serializable):
"""
A base class for defining the methods that all gradio components should have.
"""
def __init__(self, *args, **kwargs):
Block.__init__(self, *args, **kwargs)
EventListener.__init__(self)
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(),
}
def preprocess(self, x: Any) -> Any:
"""
Any preprocessing needed to be performed on function input.
"""
return x
def postprocess(self, y):
"""
Any postprocessing needed to be performed on function output.
"""
return y
def style(self, *args, **kwargs):
"""
This method is deprecated. Please set these arguments in the Components constructor instead.
"""
warnings.warn(
"The `style` method is deprecated. Please set these arguments in the Components constructor instead."
)
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, 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, 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 len(kwargs):
for key in kwargs:
warnings.warn(f"Unknown style parameter: {key}")
if (
put_deprecated_params_in_box
and isinstance(self.parent, (Row, Column))
and self.parent.variant == "default"
):
self.parent.variant = "compact"
return self
class IOComponent(Component):
"""
A base class for defining methods that all input/output components should have.
"""
def __init__(
self,
*,
value: Any = None,
label: str | None = None,
info: str | None = None,
show_label: bool = True,
container: bool = True,
scale: int | None = None,
min_width: int | None = None,
interactive: bool | None = None,
visible: bool = True,
elem_id: str | None = None,
elem_classes: list[str] | str | None = None,
load_fn: Callable | None = None,
every: float | None = None,
**kwargs,
):
self.temp_files: set[str] = set()
self.DEFAULT_TEMP_DIR = os.environ.get("GRADIO_TEMP_DIR") or str(
Path(tempfile.gettempdir()) / "gradio"
)
Component.__init__(
self, elem_id=elem_id, elem_classes=elem_classes, visible=visible, **kwargs
)
self.label = label
self.info = info
self.show_label = show_label
self.container = container
if scale is not None and scale != round(scale):
warnings.warn(
f"'scale' value should be an integer. Using {scale} will cause issues."
)
self.scale = scale
self.min_width = min_width
self.interactive = interactive
# load_event is set in the Blocks.attach_load_events method
self.load_event: None | dict[str, Any] = None
self.load_event_to_attach = None
load_fn, initial_value = self.get_load_fn_and_initial_value(value)
self.value = (
initial_value
if self._skip_init_processing
else self.postprocess(initial_value)
)
if callable(load_fn):
self.attach_load_event(load_fn, every)
@staticmethod
def hash_file(file_path: str, chunk_num_blocks: int = 128) -> str:
sha1 = hashlib.sha1()
with open(file_path, "rb") as f:
for chunk in iter(lambda: f.read(chunk_num_blocks * sha1.block_size), b""):
sha1.update(chunk)
return sha1.hexdigest()
@staticmethod
def hash_url(url: str, chunk_num_blocks: int = 128) -> str:
sha1 = hashlib.sha1()
remote = urllib.request.urlopen(url)
max_file_size = 100 * 1024 * 1024 # 100MB
total_read = 0
while True:
data = remote.read(chunk_num_blocks * sha1.block_size)
total_read += chunk_num_blocks * sha1.block_size
if not data or total_read > max_file_size:
break
sha1.update(data)
return sha1.hexdigest()
@staticmethod
def hash_bytes(bytes: bytes):
sha1 = hashlib.sha1()
sha1.update(bytes)
return sha1.hexdigest()
@staticmethod
def hash_base64(base64_encoding: str, chunk_num_blocks: int = 128) -> str:
sha1 = hashlib.sha1()
for i in range(0, len(base64_encoding), chunk_num_blocks * sha1.block_size):
data = base64_encoding[i : i + chunk_num_blocks * sha1.block_size]
sha1.update(data.encode("utf-8"))
return sha1.hexdigest()
def make_temp_copy_if_needed(self, file_path: str) -> str:
"""Returns a temporary file path for a copy of the given file path if it does
not already exist. Otherwise returns the path to the existing temp file."""
temp_dir = self.hash_file(file_path)
temp_dir = Path(self.DEFAULT_TEMP_DIR) / temp_dir
temp_dir.mkdir(exist_ok=True, parents=True)
name = client_utils.strip_invalid_filename_characters(Path(file_path).name)
full_temp_file_path = str(utils.abspath(temp_dir / name))
if not Path(full_temp_file_path).exists():
shutil.copy2(file_path, full_temp_file_path)
self.temp_files.add(full_temp_file_path)
return full_temp_file_path
async def save_uploaded_file(self, file: UploadFile, upload_dir: str) -> str:
temp_dir = secrets.token_hex(
20
) # Since the full file is being uploaded anyways, there is no benefit to hashing the file.
temp_dir = Path(upload_dir) / temp_dir
temp_dir.mkdir(exist_ok=True, parents=True)
if file.filename:
file_name = Path(file.filename).name
name = client_utils.strip_invalid_filename_characters(file_name)
else:
name = f"tmp{secrets.token_hex(5)}"
full_temp_file_path = str(utils.abspath(temp_dir / name))
async with aiofiles.open(full_temp_file_path, "wb") as output_file:
while True:
content = await file.read(100 * 1024 * 1024)
if not content:
break
await output_file.write(content)
return full_temp_file_path
def download_temp_copy_if_needed(self, url: str) -> str:
"""Downloads a file and makes a temporary file path for a copy if does not already
exist. Otherwise returns the path to the existing temp file."""
temp_dir = self.hash_url(url)
temp_dir = Path(self.DEFAULT_TEMP_DIR) / temp_dir
temp_dir.mkdir(exist_ok=True, parents=True)
name = client_utils.strip_invalid_filename_characters(Path(url).name)
full_temp_file_path = str(utils.abspath(temp_dir / name))
if not Path(full_temp_file_path).exists():
with requests.get(url, stream=True) as r, open(
full_temp_file_path, "wb"
) as f:
shutil.copyfileobj(r.raw, f)
self.temp_files.add(full_temp_file_path)
return full_temp_file_path
def base64_to_temp_file_if_needed(
self, base64_encoding: str, file_name: str | None = None
) -> str:
"""Converts a base64 encoding to a file and returns the path to the file if
the file doesn't already exist. Otherwise returns the path to the existing file.
"""
temp_dir = self.hash_base64(base64_encoding)
temp_dir = Path(self.DEFAULT_TEMP_DIR) / temp_dir
temp_dir.mkdir(exist_ok=True, parents=True)
guess_extension = client_utils.get_extension(base64_encoding)
if file_name:
file_name = client_utils.strip_invalid_filename_characters(file_name)
elif guess_extension:
file_name = f"file.{guess_extension}"
else:
file_name = "file"
full_temp_file_path = str(utils.abspath(temp_dir / file_name)) # type: ignore
if not Path(full_temp_file_path).exists():
data, _ = client_utils.decode_base64_to_binary(base64_encoding)
with open(full_temp_file_path, "wb") as fb:
fb.write(data)
self.temp_files.add(full_temp_file_path)
return full_temp_file_path
def pil_to_temp_file(self, img: _Image.Image, dir: str, format="png") -> str:
bytes_data = processing_utils.encode_pil_to_bytes(img, format)
temp_dir = Path(dir) / self.hash_bytes(bytes_data)
temp_dir.mkdir(exist_ok=True, parents=True)
filename = str(temp_dir / f"image.{format}")
img.save(filename, pnginfo=processing_utils.get_pil_metadata(img))
return filename
def img_array_to_temp_file(self, arr: np.ndarray, dir: str) -> str:
pil_image = _Image.fromarray(
processing_utils._convert(arr, np.uint8, force_copy=False)
)
return self.pil_to_temp_file(pil_image, dir, format="png")
def audio_to_temp_file(
self, data: np.ndarray, sample_rate: int, dir: str, format: str
):
temp_dir = Path(dir) / self.hash_bytes(data.tobytes())
temp_dir.mkdir(exist_ok=True, parents=True)
filename = str(temp_dir / f"audio.{format}")
processing_utils.audio_to_file(sample_rate, data, filename, format=format)
return filename
def file_bytes_to_file(self, data: bytes, dir: str, file_name: str):
path = Path(dir) / self.hash_bytes(data)
path.mkdir(exist_ok=True, parents=True)
path = path / Path(file_name).name
path.write_bytes(data)
return path
def get_config(self):
config = {
"label": self.label,
"show_label": self.show_label,
"container": self.container,
"scale": self.scale,
"min_width": self.min_width,
"interactive": self.interactive,
**super().get_config(),
}
if self.info:
config["info"] = self.info
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: float | None):
"""Add a load event that runs `callable`, optionally every `every` seconds."""
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:
def get_expected_parent(self) -> type[Form]:
return Form
class Textbox(
FormComponent,
Changeable,
Inputable,
Selectable,
Submittable,
Blurrable,
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 = True,
container: bool = True,
scale: int | None = None,
min_width: int = 160,
interactive: bool | None = None,
visible: bool = True,
elem_id: str | None = None,
elem_classes: list[str] | str | None = None,
type: str = "text",
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.
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'.
show_copy_button: If True, includes a copy button to copy the text in the textbox. Only applies if show_label is True.
"""
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.select: EventListenerMethod
"""
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.cleared_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,
"show_copy_button": self.show_copy_button,
**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,
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: str | None = None,
show_copy_button: bool | None = None,
):
return {
"lines": lines,
"max_lines": max_lines,
"placeholder": placeholder,
"label": label,
"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,
"__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.
"""
warnings.warn(
"The `style` method is deprecated. Please set these arguments in the constructor instead."
)
if show_copy_button is not None:
self.show_copy_button = show_copy_button
if container is not None:
self.container = container
return self
class Number(
FormComponent,
Changeable,
Inputable,
Submittable,
Blurrable,
IOComponent,
NumberSerializable,
NeighborInterpretable,
):
"""
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: float | Callable | None = None,
*,
label: str | None = None,
info: str | None = None,
every: float | None = None,
show_label: bool = True,
container: bool = True,
scale: int | None = None,
min_width: int = 160,
interactive: bool | None = None,
visible: bool = True,
elem_id: str | None = None,
elem_classes: list[str] | str | None = None,
precision: int | None = 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.
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 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.
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.
precision: Precision to round input/output to. If set to 0, will round to nearest integer and convert type to int. If None, no rounding happens.
"""
self.precision = precision
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,
)
NeighborInterpretable.__init__(self)
@staticmethod
def _round_to_precision(num: float | int, precision: int | None) -> float | int:
"""
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 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: float | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE,
label: str | None = None,
show_label: bool | None = None,
container: bool | None = None,
scale: int | None = None,
min_width: int | None = None,
interactive: bool | None = None,
visible: bool | None = None,
):
return {
"label": label,
"show_label": show_label,
"container": container,
"scale": scale,
"min_width": min_width,
"visible": visible,
"value": value,
"interactive": interactive,
"__type__": "update",
}
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 convert to int here
negatives = (
np.array(x) + np.arange(-self.interpretation_steps, 0) * delta
).tolist()
positives = (
np.array(x) + np.arange(1, self.interpretation_steps + 1) * delta
).tolist()
return negatives + positives, {}
def get_interpretation_scores(
self, x: float, neighbors: list[float], scores: list[float | None], **kwargs
) -> list[tuple[float, float | None]]:
"""
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
class Slider(
FormComponent,
Changeable,
Inputable,
Releaseable,
IOComponent,
NumberSerializable,
NeighborInterpretable,
):
"""
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, slider_release, 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: float | Callable | None = None,
*,
step: float | None = None,
label: str | None = None,
info: str | None = None,
every: float | None = None,
show_label: bool = True,
container: bool = True,
scale: int | None = None,
min_width: int = 160,
interactive: bool | None = None,
visible: bool = True,
elem_id: str | None = None,
elem_classes: list[str] | str | None = 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.
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, 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.
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.
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)
self.step = 10**power
else:
self.step = step
if randomize:
value = self.get_random_value
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,
)
NeighborInterpretable.__init__(self)
self.cleared_value = self.value
def api_info(self) -> dict[str, dict | bool]:
return {
"info": {
"type": "number",
"description": f"numeric value between {self.minimum} and {self.maximum}",
},
"serialized_info": False,
}
def example_inputs(self) -> dict[str, Any]:
return {
"raw": self.minimum,
"serialized": self.minimum,
}
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: float | Literal[_Keywords.NO_VALUE] | None = _Keywords.NO_VALUE,
minimum: float | None = None,
maximum: float | None = None,
step: float | None = None,
label: str | None = None,
show_label: bool | None = None,
container: bool | None = None,
scale: int | None = None,
min_width: int | None = None,
interactive: bool | None = None,
visible: bool | None = None,
):
return {
"minimum": minimum,
"maximum": maximum,
"step": step,
"label": label,
"show_label": show_label,
"container": container,
"scale": scale,
"min_width": min_width,
"interactive": interactive,
"visible": visible,
"value": value,
"__type__": "update",
}
def postprocess(self, y: float | None) -> float | None: