-
-
Notifications
You must be signed in to change notification settings - Fork 473
/
input.py
1417 lines (1070 loc) · 47.2 KB
/
input.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
"""
The input widgets generally allow entering arbitrary information into
a text field or similar.
"""
from __future__ import annotations
import ast
import json
from base64 import b64decode
from datetime import date, datetime
from typing import (
TYPE_CHECKING, Any, ClassVar, Iterable, Mapping, Optional,
)
import numpy as np
import param
from bokeh.models.formatters import TickFormatter
from bokeh.models.widgets import (
Checkbox as _BkCheckbox, ColorPicker as _BkColorPicker,
DatePicker as _BkDatePicker, DateRangePicker as _BkDateRangePicker,
Div as _BkDiv, FileInput as _BkFileInput, NumericInput as _BkNumericInput,
PasswordInput as _BkPasswordInput, Spinner as _BkSpinner,
Switch as _BkSwitch,
)
from pyviz_comms import JupyterComm
from ..config import config
from ..layout import Column, Panel
from ..models import (
DatetimePicker as _bkDatetimePicker, TextAreaInput as _bkTextAreaInput,
TextInput as _BkTextInput,
)
from ..util import lazy_load, param_reprs, try_datetime64_to_datetime
from .base import CompositeWidget, Widget
if TYPE_CHECKING:
from bokeh.document import Document
from bokeh.model import Model
from pyviz_comms import Comm
from ..models.file_dropper import DeleteEvent, UploadEvent
from ..viewable import Viewable
class _TextInputBase(Widget):
description = param.String(default=None, doc="""
An HTML string describing the function of this component.""")
max_length = param.Integer(default=5000, doc="""
Max count of characters in the input field.""")
placeholder = param.String(default='', doc="""
Placeholder for empty input field.""")
value = param.String(default='', allow_None=True, doc="""
Initial or entered text value updated when <enter> key is pressed.""")
value_input = param.String(default='', allow_None=True, doc="""
Initial or entered text value updated on every key press.""")
width = param.Integer(default=300, allow_None=True, doc="""
Width of this component. If sizing_mode is set to stretch
or scale mode this will merely be used as a suggestion.""")
@classmethod
def from_param(cls, parameter: param.Parameter, onkeyup=False, **params) -> Viewable:
"""
Construct a widget from a Parameter and link the two
bi-directionally.
Parameters
----------
parameter: param.Parameter
A parameter to create the widget from.
onkeyup: boolean
Whether to trigger events on every key press.
params: dict
Keyword arguments to be passed to the widget constructor
Returns
-------
Widget instance linked to the supplied parameter
"""
params['onkeyup'] = onkeyup
return super().from_param(parameter, **params)
class TextInput(_TextInputBase):
"""
The `TextInput` widget allows entering any string using a text input box.
Reference: https://panel.holoviz.org/reference/widgets/TextInput.html
:Example:
>>> TextInput(name='Name', placeholder='Enter your name here ...')
"""
enter_pressed = param.Event(doc="""
Event when the enter key has been pressed.""")
_widget_type: ClassVar[type[Model]] = _BkTextInput
_rename = {'enter_pressed': None}
def _get_model(
self, doc: Document, root: Optional[Model] = None,
parent: Optional[Model] = None, comm: Optional[Comm] = None
) -> Model:
model = super()._get_model(doc, root, parent, comm)
self._register_events('enter-pressed', model=model, doc=doc, comm=comm)
return model
def _process_event(self, event) -> None:
if event.event_name == 'enter-pressed':
self.value = event.value_input
self.value_input = event.value_input
self.enter_pressed = True
class PasswordInput(_TextInputBase):
"""
The `PasswordInput` allows entering any string using an obfuscated text
input box.
Reference: https://panel.holoviz.org/reference/widgets/PasswordInput.html
:Example:
>>> PasswordInput(
... name='Password', placeholder='Enter your password here...'
... )
"""
_widget_type: ClassVar[type[Model]] = _BkPasswordInput
class TextAreaInput(_TextInputBase):
"""
The `TextAreaInput` allows entering any multiline string using a text input
box.
Lines are joined with the newline character `\n`.
Reference: https://panel.holoviz.org/reference/widgets/TextAreaInput.html
:Example:
>>> TextAreaInput(
... name='Description', placeholder='Enter your description here...'
... )
"""
auto_grow = param.Boolean(default=False, doc="""
Whether the text area should automatically grow vertically to
accommodate the current text.""")
cols = param.Integer(default=20, doc="""
Number of columns in the text input field.""")
max_rows = param.Integer(default=None, doc="""
When combined with auto_grow this determines the maximum number
of rows the input area can grow.""")
rows = param.Integer(default=2, doc="""
Number of rows in the text input field.""")
resizable = param.ObjectSelector(
objects=["both", "width", "height", False], doc="""
Whether the layout is interactively resizable,
and if so in which dimensions: `width`, `height`, or `both`.
Can only be set during initialization.""")
_widget_type: ClassVar[type[Model]] = _bkTextAreaInput
class FileInput(Widget):
"""
The `FileInput` allows the user to upload one or more files to the server.
It makes the filename, MIME type and (bytes) content available in Python.
Please note
- you can in fact *drag and drop* files onto the `FileInput`.
- you easily save the files using the `save` method.
Reference: https://panel.holoviz.org/reference/widgets/FileInput.html
:Example:
>>> FileInput(accept='.png,.jpeg', multiple=True)
"""
accept = param.String(default=None, doc="""
A comma separated string of all extension types that should
be supported.""")
description = param.String(default=None, doc="""
An HTML string describing the function of this component
rendered as a tooltip icon.""")
filename = param.ClassSelector(
default=None, class_=(str, list), is_instance=True, doc="""
Name of the uploaded file(s).""")
mime_type = param.ClassSelector(
default=None, class_=(str, list), is_instance=True, doc="""
Mimetype of the uploaded file(s).""")
multiple = param.Boolean(default=False, doc="""
Whether to allow uploading multiple files. If enabled value
parameter will return a list.""")
value = param.Parameter(default=None, doc="""
The uploaded file(s) stored as a single bytes object if
multiple is False or a list of bytes otherwise.""")
_rename: ClassVar[Mapping[str, str | None]] = {
'filename': None, 'name': None
}
_source_transforms: ClassVar[Mapping[str, str | None]] = {
'value': "'data:' + source.mime_type + ';base64,' + value"
}
_widget_type: ClassVar[type[Model]] = _BkFileInput
def _process_param_change(self, msg):
msg = super()._process_param_change(msg)
if 'value' in msg:
msg.pop('value')
if 'mime_type' in msg:
msg.pop('mime_type')
return msg
@property
def _linked_properties(self):
properties = super()._linked_properties
return properties + ('filename',)
def _process_property_change(self, msg):
msg = super()._process_property_change(msg)
if 'value' in msg:
if isinstance(msg['value'], str):
msg['value'] = b64decode(msg['value'])
else:
msg['value'] = [b64decode(content) for content in msg['value']]
return msg
def save(self, filename):
"""
Saves the uploaded FileInput data object(s) to file(s) or
BytesIO object(s).
Arguments
---------
filename (str or list[str]): File path or file-like object
"""
value = self.value
if isinstance(filename, list) and not isinstance(value, list):
raise TypeError(
"FileInput contains a list of files but only a single "
"filename was given. Please provide a list of filenames or "
"file-like objects."
)
elif not isinstance(filename, list) and isinstance(value, list):
raise TypeError(
"FileInput contains a single files but a list of "
"filenames was given. Please provide a single filename "
"or file-like object."
)
if not isinstance(value, list):
value = [self.value]
if not isinstance(filename, list):
filename = [filename]
for val, fn in zip(value, filename):
if isinstance(fn, str):
with open(fn, 'wb') as f:
f.write(val)
else:
fn.write(val)
class FileDropper(Widget):
"""
The `FileDropper` allows the user to upload one or more files to the server.
It is similar to the `FileInput` widget but additionally adds support
for chunked uploads, making it possible to upload large files. The
UI also supports previews for image files. Unlike `FileInput` the
uploaded files are stored as dictionary of bytes object indexed
by the filename.
Reference: https://panel.holoviz.org/reference/widgets/FileDropper.html
:Example:
>>> FileDropper(accepted_filetypes=['image/*'], multiple=True)
"""
accepted_filetypes = param.List(default=[], doc="""
List of accepted file types. Can be mime types, file extensions
or wild cards.For instance ['image/*'] will accept all images.
['.png', 'image/jpeg'] will only accepts PNGs and JPEGs.""")
chunk_size = param.Integer(default=10_000_000, doc="""
Size in bytes per chunk transferred across the WebSocket.""")
layout = param.Selector(
default=None, objects=["circle", "compact", "integrated"], doc="""
Compact mode will remove padding, integrated mode is used to render
FilePond as part of a bigger element. Circle mode adjusts the item
position offsets so buttons and progress indicators don't fall outside
of the circular shape.""")
max_file_size = param.String(default=None, doc="""
Maximum size of a file as a string with units given in KB or MB,
e.g. 5MB or 750KB.""")
max_files = param.Integer(default=None, doc="""
Maximum number of files that can be uploaded if multiple=True.""")
max_total_file_size = param.String(default=None, doc="""
Maximum size of all uploaded files, as a string with units given
in KB or MB, e.g. 5MB or 750KB.""")
mime_type = param.Dict(default={}, doc="""
A dictionary containing the mimetypes for each of the uploaded
files indexed by their filename.""")
multiple = param.Boolean(default=False, doc="""
Whether to allow uploading multiple files.""")
value = param.Dict(default={}, doc="""
A dictionary containing the uploaded file(s) as bytes or string
objects indexed by the filename. Files that have a text/* mimetype
will automatically be decoded as utf-8.""")
width = param.Integer(default=300, allow_None=True, doc="""
Width of this component. If sizing_mode is set to stretch
or scale mode this will merely be used as a suggestion.""")
_rename = {'value': None}
def __init__(self, **params):
super().__init__(**params)
self._file_buffer = {}
def _get_model(
self, doc: Document, root: Optional[Model] = None,
parent: Optional[Model] = None, comm: Optional[Comm] = None
) -> Model:
self._widget_type = lazy_load(
'panel.models.file_dropper', 'FileDropper', isinstance(comm, JupyterComm), root
)
model = super()._get_model(doc, root, parent, comm)
self._register_events('delete_event', 'upload_event', model=model, doc=doc, comm=comm)
return model
def _process_event(self, event: DeleteEvent | UploadEvent):
data = event.data
name = data['name']
if event.event_name == 'delete_event':
if name in self.mime_type:
del self.mime_type[name]
if name in self.value:
del self.value[name]
self.param.trigger('mime_type', 'value')
return
if data['chunk'] == 1:
self._file_buffer[name] = []
self._file_buffer[name].append(data['data'])
if data['chunk'] != data['total_chunks']:
return
buffers = self._file_buffer.pop(name)
file_buffer = b''.join(buffers)
if data['type'].startswith('text/'):
try:
file_buffer = file_buffer.decode('utf-8')
except UnicodeDecodeError:
pass
self.value[name] = file_buffer
self.mime_type[name] = data['type']
self.param.trigger('mime_type', 'value')
class StaticText(Widget):
"""
The `StaticText` widget displays a text value, but does not allow editing
it.
Reference: https://panel.holoviz.org/reference/widgets/StaticText.html
:Example:
>>> StaticText(name='Model', value='animagen2')
"""
value = param.Parameter(default=None, doc="""
The current value""")
_format: ClassVar[str] = '<b>{title}</b>: {value}'
_rename: ClassVar[Mapping[str, str | None]] = {'name': None, 'value': 'text'}
_target_transforms: ClassVar[Mapping[str, str | None]] = {
'value': 'target.text.split(": ")[0]+": "+value'
}
_source_transforms: ClassVar[Mapping[str, str | None]] = {
'value': 'value.split(": ")[1]'
}
_widget_type: ClassVar[type[Model]] = _BkDiv
def _process_param_change(self, msg):
msg = super()._process_param_change(msg)
if 'text' in msg:
text = str(msg.pop('text'))
partial = self._format.replace('{value}', '').format(title=self.name)
if self.name:
text = self._format.format(title=self.name, value=text.replace(partial, ''))
msg['text'] = text
return msg
class DatePicker(Widget):
"""
The `DatePicker` allows selecting a `date` value using a text box
and a date-picking utility.
Reference: https://panel.holoviz.org/reference/widgets/DatePicker.html
:Example:
>>> DatePicker(
... value=date(2025,1,1),
... start=date(2025,1,1), end=date(2025,12,31),
... name='Date'
... )
"""
value = param.CalendarDate(default=None, doc="""
The current value""")
start = param.CalendarDate(default=None, doc="""
Inclusive lower bound of the allowed date selection""")
end = param.CalendarDate(default=None, doc="""
Inclusive upper bound of the allowed date selection""")
disabled_dates = param.List(default=None, item_type=(date, str))
enabled_dates = param.List(default=None, item_type=(date, str))
width = param.Integer(default=300, allow_None=True, doc="""
Width of this component. If sizing_mode is set to stretch
or scale mode this will merely be used as a suggestion.""")
description = param.String(default=None, doc="""
An HTML string describing the function of this component.""")
_source_transforms: ClassVar[Mapping[str, str | None]] = {}
_rename: ClassVar[Mapping[str, str | None]] = {
'start': 'min_date', 'end': 'max_date'
}
_widget_type: ClassVar[type[Model]] = _BkDatePicker
def __init__(self, **params):
# Since options is the standard for other widgets,
# it makes sense to also support options here, converting
# it to enabled_dates
if 'options' in params:
options = list(params.pop('options'))
params['enabled_dates'] = options
if 'value' in params:
value = try_datetime64_to_datetime(params['value'])
if hasattr(value, "date"):
value = value.date()
params["value"] = value
super().__init__(**params)
def _process_property_change(self, msg):
msg = super()._process_property_change(msg)
for p in ('start', 'end', 'value'):
if p not in msg:
continue
value = msg[p]
if isinstance(value, str):
msg[p] = datetime.date(datetime.strptime(value, '%Y-%m-%d'))
return msg
class DateRangePicker(Widget):
"""
The `DateRangePicker` allows selecting a `date` range using a text box
and a date-picking utility.
Reference: https://panel.holoviz.org/reference/widgets/DateRangePicker.html
:Example:
>>> DateRangePicker(
... value=(date(2025,1,1), date(2025,1,5)),
... start=date(2025,1,1), end=date(2025,12,31),
... name='Date range'
... )
"""
value = param.DateRange(default=None, doc="""
The current value""")
start = param.CalendarDate(default=None, doc="""
Inclusive lower bound of the allowed date selection""")
end = param.CalendarDate(default=None, doc="""
Inclusive upper bound of the allowed date selection""")
disabled_dates = param.List(default=None, item_type=(date, str))
enabled_dates = param.List(default=None, item_type=(date, str))
width = param.Integer(default=300, allow_None=True, doc="""
Width of this component. If sizing_mode is set to stretch
or scale mode this will merely be used as a suggestion.""")
description = param.String(default=None, doc="""
An HTML string describing the function of this component.""")
_source_transforms: ClassVar[Mapping[str, str | None]] = {
'value': None, 'start': None, 'end': None, 'mode': None
}
_rename: ClassVar[Mapping[str, str | None]] = {
'start': 'min_date', 'end': 'max_date'
}
_widget_type: ClassVar[type[Model]] = _BkDateRangePicker
def __init__(self, **params):
super().__init__(**params)
self._update_value_bounds()
@param.depends('start', 'end', watch=True)
def _update_value_bounds(self):
self.param.value.bounds = (self.start, self.end)
self.param.value._validate(self.value)
def _process_property_change(self, msg):
msg = super()._process_property_change(msg)
for p in ('start', 'end', 'value'):
if p not in msg:
continue
value = msg[p]
if isinstance(value, tuple):
msg[p] = tuple(self._convert_string_to_date(v) for v in value)
return msg
def _process_param_change(self, msg):
msg = super()._process_param_change(msg)
if 'value' in msg:
msg['value'] = tuple(self._convert_date_to_string(v) for v in msg['value'])
if 'min_date' in msg:
msg['min_date'] = self._convert_date_to_string(msg['min_date'])
if 'max_date' in msg:
msg['max_date'] = self._convert_date_to_string(msg['max_date'])
return msg
@staticmethod
def _convert_string_to_date(v):
return datetime.strptime(v, '%Y-%m-%d').date()
@staticmethod
def _convert_date_to_string(v):
return v.strftime('%Y-%m-%d')
class _DatetimePickerBase(Widget):
disabled_dates = param.List(default=None, item_type=(date, str), doc="""
Dates to make unavailable for selection.""")
enabled_dates = param.List(default=None, item_type=(date, str), doc="""
Dates to make available for selection.""")
enable_time = param.Boolean(default=True, doc="""
Enable editing of the time in the widget.""")
enable_seconds = param.Boolean(default=True, doc="""
Enable editing of the seconds in the widget.""")
end = param.Date(default=None, doc="""
Inclusive upper bound of the allowed date selection.""")
military_time = param.Boolean(default=True, doc="""
Whether to display time in 24 hour format.""")
start = param.Date(default=None, doc="""
Inclusive lower bound of the allowed date selection.""")
width = param.Integer(default=300, allow_None=True, doc="""
Width of this component. If sizing_mode is set to stretch
or scale mode this will merely be used as a suggestion.""")
description = param.String(default=None, doc="""
An HTML string describing the function of this component.""")
as_numpy_datetime64 = param.Boolean(default=None, doc="""
Whether to return values as numpy.datetime64. If left unset,
will be True if value is a numpy.datetime64, else False.""")
_source_transforms: ClassVar[Mapping[str, str | None]] = {
'value': None, 'start': None, 'end': None, 'mode': None
}
_rename: ClassVar[Mapping[str, str | None]] = {
'start': 'min_date', 'end': 'max_date', 'as_numpy_datetime64': None,
}
_widget_type: ClassVar[type[Model]] = _bkDatetimePicker
__abstract = True
def __init__(self, **params):
# Since options is the standard for other widgets,
# it makes sense to also support options here, converting
# it to enabled_dates
if 'options' in params:
options = list(params.pop('options'))
params['enabled_dates'] = options
if params.get('as_numpy_datetime64', None) is None:
params['as_numpy_datetime64'] = isinstance(
params.get("value"), np.datetime64)
super().__init__(**params)
self._update_value_bounds()
def _convert_to_datetime(self, v):
if v is None:
return
if isinstance(v, Iterable) and not isinstance(v, str):
container_type = type(v)
return container_type(
self._convert_to_datetime(vv)
for vv in v
)
v = try_datetime64_to_datetime(v)
if isinstance(v, datetime):
return v
elif isinstance(v, date):
return datetime(v.year, v.month, v.day)
elif isinstance(v, str):
return datetime.strptime(v, r'%Y-%m-%d %H:%M:%S')
else:
raise ValueError(f"Could not convert {v} to datetime")
@param.depends('start', 'end', watch=True)
def _update_value_bounds(self):
self.param.value.bounds = (
self._convert_to_datetime(self.start),
self._convert_to_datetime(self.end)
)
self.param.value._validate(
self._convert_to_datetime(self.value)
)
def _process_property_change(self, msg):
msg = super()._process_property_change(msg)
if 'value' in msg:
msg['value'] = self._serialize_value(msg['value'])
return msg
def _process_param_change(self, msg):
msg = super()._process_param_change(msg)
if 'value' in msg:
msg['value'] = self._deserialize_value(self._convert_to_datetime(msg['value']))
if 'min_date' in msg:
msg['min_date'] = self._convert_to_datetime(msg['min_date'])
if 'max_date' in msg:
msg['max_date'] = self._convert_to_datetime(msg['max_date'])
return msg
class DatetimePicker(_DatetimePickerBase):
"""
The `DatetimePicker` allows selecting selecting a `datetime` value using a
textbox and a datetime-picking utility.
Reference: https://panel.holoviz.org/reference/widgets/DatetimePicker.html
:Example:
>>> DatetimePicker(
... value=datetime(2025,1,1,22,0),
... start=date(2025,1,1), end=date(2025,12,31),
... military_time=True, name='Date and time'
... )
"""
value = param.Date(default=None)
mode = param.String('single', constant=True)
def _serialize_value(self, value):
if isinstance(value, str) and value:
if self.as_numpy_datetime64:
value = np.datetime64(value)
else:
value = datetime.strptime(value, r'%Y-%m-%d %H:%M:%S')
return value
def _deserialize_value(self, value):
if isinstance(value, (datetime, date)):
value = value.strftime(r'%Y-%m-%d %H:%M:%S')
return value
class DatetimeRangePicker(_DatetimePickerBase):
"""
The `DatetimeRangePicker` allows selecting selecting a `datetime` range
using a text box and a datetime-range-picking utility.
Reference: https://panel.holoviz.org/reference/widgets/DatetimeRangePicker.html
:Example:
>>> DatetimeRangePicker(
... value=(datetime(2025,1,1,22,0), datetime(2025,1,2,22,0)),
... start=date(2025,1,1), end=date(2025,12,31),
... military_time=True, name='Datetime Range'
... )
"""
value = param.DateRange(default=None, doc="""
The current value""")
mode = param.String('range', constant=True)
def _serialize_value(self, value):
if isinstance(value, str) and value:
value = [
np.datetime64(value)
if self.as_numpy_datetime64
else datetime.strptime(value, r'%Y-%m-%d %H:%M:%S')
for value in value.split(' to ')
]
value = tuple(value)
return value
def _deserialize_value(self, value):
if isinstance(value, tuple):
value = " to ".join(v.strftime(r'%Y-%m-%d %H:%M:%S') for v in value)
if value is None:
value = ""
return value
class ColorPicker(Widget):
"""
The `ColorPicker` widget allows selecting a hexadecimal RGB color value
using the browser’s color-picking widget.
Reference: https://panel.holoviz.org/reference/widgets/ColorPicker.html
:Example:
>>> ColorPicker(name='Color', value='#99ef78')
"""
description = param.String(default=None, doc="""
An HTML string describing the function of this component.""")
value = param.Color(default=None, doc="""
The selected color""")
width = param.Integer(default=52, allow_None=True, doc="""
Width of this component. If sizing_mode is set to stretch
or scale mode this will merely be used as a suggestion.""")
_widget_type: ClassVar[type[Model]] = _BkColorPicker
_rename: ClassVar[Mapping[str, str | None]] = {'value': 'color'}
class _NumericInputBase(Widget):
description = param.String(default=None, doc="""
An HTML string describing the function of this component.""")
value = param.Number(default=0, allow_None=True, doc="""
The current value of the spinner.""")
placeholder = param.String(default='0', doc="""
Placeholder for empty input field.""")
format = param.ClassSelector(default=None, class_=(str, TickFormatter,), doc="""
Allows defining a custom format string or bokeh TickFormatter.""")
start = param.Parameter(default=None, allow_None=True, doc="""
Optional minimum allowable value.""")
end = param.Parameter(default=None, allow_None=True, doc="""
Optional maximum allowable value.""")
_rename: ClassVar[Mapping[str, str | None]] = {'start': 'low', 'end': 'high'}
_widget_type: ClassVar[type[Model]] = _BkNumericInput
__abstract = True
class _IntInputBase(_NumericInputBase):
value = param.Integer(default=0, allow_None=True, doc="""
The current value of the spinner.""")
start = param.Integer(default=None, allow_None=True, doc="""
Optional minimum allowable value.""")
end = param.Integer(default=None, allow_None=True, doc="""
Optional maximum allowable value.""")
mode = param.String(default='int', constant=True, doc="""
Define the type of number which can be enter in the input""")
__abstract = True
class _FloatInputBase(_NumericInputBase):
value = param.Number(default=0, allow_None=True, doc="""
The current value of the spinner.""")
start = param.Number(default=None, allow_None=True, doc="""
Optional minimum allowable value.""")
end = param.Number(default=None, allow_None=True, doc="""
Optional maximum allowable value.""")
mode = param.String(default='float', constant=True, doc="""
Define the type of number which can be enter in the input""")
__abstract = True
class _SpinnerBase(_NumericInputBase):
page_step_multiplier = param.Integer(default=10, bounds=(0, None), doc="""
Defines the multiplication factor applied to step when the page up
and page down keys are pressed.""")
wheel_wait = param.Integer(default=100, doc="""
Defines the debounce time in ms before updating `value_throttled` when
the mouse wheel is used to change the input.""")
width = param.Integer(default=300, allow_None=True, doc="""
Width of this component. If sizing_mode is set to stretch
or scale mode this will merely be used as a suggestion.""")
_rename: ClassVar[Mapping[str, str | None]] = {'value_throttled': None}
_widget_type: ClassVar[type[Model]] = _BkSpinner
__abstract = True
def __init__(self, **params):
if 'value' not in params:
value = params.get('start', self.value)
if value is not None:
params['value'] = value
if 'value' in params and 'value_throttled' in self.param:
params['value_throttled'] = params['value']
super().__init__(**params)
def __repr__(self, depth=0):
return '{cls}({params})'.format(cls=type(self).__name__,
params=', '.join(param_reprs(self, ['value_throttled'])))
@property
def _linked_properties(self) -> tuple[str]:
return super()._linked_properties + ('value_throttled',)
def _update_model(
self, events: dict[str, param.parameterized.Event], msg: dict[str, Any],
root: Model, model: Model, doc: Document, comm: Optional[Comm]
) -> None:
if 'value_throttled' in msg:
del msg['value_throttled']
return super()._update_model(events, msg, root, model, doc, comm)
def _process_param_change(self, msg):
# Workaround for -inf serialization errors
if 'value' in msg and msg['value'] == float('-inf'):
msg['value'] = None
msg['value_throttled'] = None
return super()._process_param_change(msg)
def _process_property_change(self, msg):
if config.throttled:
if "value" in msg:
del msg["value"]
if "value_throttled" in msg:
msg["value"] = msg["value_throttled"]
return super()._process_property_change(msg)
class IntInput(_SpinnerBase, _IntInputBase):
"""
The `IntInput` allows selecting an integer value using a spinbox.
It behaves like a slider except that lower and upper bounds are optional
and a specific value can be entered. The value can be changed using the
keyboard (up, down, page up, page down), mouse wheel and arrow buttons.
Reference: https://panel.holoviz.org/reference/widgets/IntInput.html
:Example:
>>> IntInput(name='Value', value=100, start=0, end=1000, step=10)
"""
step = param.Integer(default=1, doc="""
The step size.""")
value_throttled = param.Integer(default=None, constant=True, doc="""
The current value. Updates only on `<enter>` or when the widget looses focus.""")
_rename: ClassVar[Mapping[str, str | None]] = {'start': 'low', 'end': 'high'}
class FloatInput(_SpinnerBase, _FloatInputBase):
"""
The `FloatInput` allows selecting a floating point value using a spinbox.
It behaves like a slider except that the lower and upper bounds are
optional and a specific value can be entered. The value can be changed
using the keyboard (up, down, page up, page down), mouse wheel and arrow
buttons.
Reference: https://panel.holoviz.org/reference/widgets/FloatInput.html
:Example:
>>> FloatInput(name='Value', value=5., step=1e-1, start=0, end=10)
"""
placeholder = param.String(default='', doc="""
Placeholder when the value is empty.""")
step = param.Number(default=0.1, doc="""
The step size.""")
value_throttled = param.Number(default=None, constant=True, doc="""
The current value. Updates only on `<enter>` or when the widget looses focus.""")
_rename: ClassVar[Mapping[str, str | None]] = {'start': 'low', 'end': 'high'}
def _process_param_change(self, msg):
if msg.get('value', False) is None:
msg['value'] = float('NaN')
if msg.get('value_throttled', False) is None:
msg['value_throttled'] = float('NaN')
return super()._process_param_change(msg)
def _process_property_change(self, msg):
if msg.get('value', False) and np.isnan(msg['value']):
msg['value'] = None
if msg.get('value_throttled', False) and np.isnan(msg['value_throttled']):
msg['value_throttled'] = None
return super()._process_property_change(msg)
class NumberInput(_SpinnerBase):
def __new__(self, **params):
param_list = ["value", "start", "stop", "step"]
if all(isinstance(params.get(p, 0), int) for p in param_list):
return IntInput(**params)
else:
return FloatInput(**params)
# Backward compatibility
Spinner = NumberInput