-
Notifications
You must be signed in to change notification settings - Fork 0
/
easy_widget.py
1964 lines (1736 loc) · 74.2 KB
/
easy_widget.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
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @file easy_widget.py
# @brief
# @author QRS
# @blog blog.erlangai.cn
# @version 1.0
# @date 2019-12-18 19:55:57
from IPython.display import display, clear_output
from traitlets.utils.bunch import Bunch
import traitlets
import base64
import requests
import ipywidgets as widgets
import json
import io
import os
import pprint
import copy
import traceback
from pyhocon import ConfigFactory
from pyhocon import HOCONConverter
widgets.Dropdown.value.tag(sync=True)
try:
is_install_cv2 = False
import cv2
import numpy as np
import matplotlib.pyplot as plt
is_install_cv2 = True
except Exception:
pass
def _request_content(url, default=None):
if isinstance(url, bytes):
url = url.decode("utf-8", "ignore")
url = url.strip()
if url.startswith('http'):
response = requests.get(url)
if response:
return response.content
elif os.path.isfile(url):
with open(url, 'rb') as f:
return f.read()
return default
def _schema_tooltips(widget_map):# {{{
tables = []
for key, wid in widget_map.items():
if not hasattr(wid, 'description_tooltip') \
or wid.description_tooltip is None \
or wid.disabled:
continue
if isinstance(wid, widgets.Text):
if wid.value.startswith('[') and wid.value.endswith(']'):
value = json.loads(wid.value)
if isinstance(value[0], int):
tables.append((key, wid.description, '整型数组', wid.value, '[int, int, ...]', wid.description_tooltip))
elif isinstance(value[0], float):
tables.append((key, wid.description, '浮点数组', wid.value, '[float, float, ...]', wid.description_tooltip))
else:
tables.append((key, wid.description, '字符串', wid.value, '', wid.description_tooltip))
elif isinstance(wid, widgets.BoundedIntText):
tables.append((key,
wid.description,
'整型',
wid.value,
f'{"(-inf" if wid.min == -2147483647 else "[%d" % wid.min}, {"+inf)" if wid.max == 2147483647 else "%d]" % wid.max}',
wid.description_tooltip))
elif isinstance(wid, widgets.BoundedFloatText):
tables.append((key,
wid.description,
'浮点型',
wid.value,
f'{"(-inf" if wid.min == -2147483647.0 else "[%f" % wid.min}, {"+inf)" if wid.max == 2147483647.0 else "%f]" % wid.max}',
wid.description_tooltip))
elif isinstance(wid, widgets.Checkbox):
tables.append((key,
wid.description,
'布尔型',
wid.value,
'',
wid.description_tooltip))
elif isinstance(wid, widgets.Dropdown):
for opt in wid.options:
if opt[1] == wid.value:
value = opt[0]
tables.append((
key,
wid.description,
'枚举型',
value,
f'{[o[0] for o in wid.options]}',
wid.description_tooltip))
return tables# }}}
def _widget_add_child(widget, wdgs):# {{{
if not isinstance(wdgs, list):
wdgs = [wdgs]
for child in wdgs:
widget.children = list(widget.children) + [child]
return widget# }}}
def observe_widget(method):# {{{
def _widget(self, *args, **kwargs):
wdg, cb = method(self, *args, **kwargs)
if self.border:
wdg.layout.border = '1px solid yellow'
def _on_value_change(change, cb):
wdg = change['owner']
try:
if hasattr(wdg, 'id'):
if isinstance(change['new'], bytes):
self.wid_value_map[wdg.id] = change['new'] if len(change['new']) < 256 else change['new'][:16]
else:
self.wid_value_map[wdg.id] = change['new']
except Exception:
self.logger(traceback.format_exc(limit=6))
if cb:
try:
cb(change)
except Exception:
self.logger(traceback.format_exc(limit=6))
self._output(change)
wdg.observe(lambda change, cb=cb: _on_value_change(change, cb), 'value')
return wdg.parent_box if hasattr(wdg, 'parent_box') else wdg
return _widget# }}}
class BytesText(widgets.Text):# {{{
bvalue = traitlets.CBytes(help="Bytes value").tag(sync=True)# }}}
@widgets.register
class ImageA(widgets.Image):# {{{
url = traitlets.Unicode(help="image url").tag(sync=True)
def __init__(self, **kwargs):
width = kwargs.get('width', -1)
height = kwargs.get('height', -1)
format = kwargs.get('format', 'url')
value = kwargs.pop('value', '')
if format == 'url':
value = _request_content(value, b'')
if value and (width < 0 or height < 0):
img = cv2.imdecode(np.frombuffer(value, dtype=np.uint8), cv2.IMREAD_COLOR)
height, width = img.shape[:2]
kwargs['width'] = width
kwargs['height'] = height
kwargs['layout'].width = '%dpx' % width
kwargs['layout'].height = '%dpx' % height
self.description = ' '
super().__init__(**kwargs)
self.format, self.value = 'png', value
@traitlets.observe('url')
def _url_to_byte(self, change):
self.value = _request_content(change['new'].encode('utf-8'), b'')
# }}}
@widgets.register
class ImageE(widgets.Output, widgets.ValueWidget):# {{{
value = traitlets.CBytes(help="image bytes value").tag(sync=True)
def __init__(self, dpi=80, **kwargs):
width = kwargs.get('width', -1)
height = kwargs.get('height', -1)
value = kwargs.pop('value', '')
format = kwargs.get('format', 'url')
if format == 'url':
value = _request_content(value, b'')
if value and (width < 0 or height < 0):
img = cv2.imdecode(np.frombuffer(value, dtype=np.uint8), cv2.IMREAD_COLOR)
height, width = img.shape[:2]
kwargs['width'] = width
kwargs['height'] = height
super().__init__(**kwargs)
self.format, self.value = 'png', value
self.fig, self.dpi = None, dpi
self.width, self.height = width, height
self.description = ' '
self.imshow()
def imshow(self, img=None, width=None, height=None):
if self.fig:
plt.close(self.fig)
if width is None:
width = self.width
if height is None:
height = self.height
self.clear_output()
with self:
update_value = True
if img is None:
if isinstance(self.value, bytes):
if len(self.value) < 256:
self.value = _request_content(self.value, b'')
img = cv2.imdecode(np.frombuffer(self.value, dtype=np.uint8), cv2.IMREAD_COLOR)
update_value = False
else:
print(f'value error:{self.value}')
return
fig, ax = plt.subplots(
constrained_layout=True,
figsize=(width / self.dpi, height / self.dpi), dpi=self.dpi)
fig.canvas.toolbar_visible = True
fig.canvas.header_visible = False
fig.canvas.footer_visible = True
fig.canvas.toolbar_position = 'top'
ax.axis('off')
if len(img.shape) == 2:
ax.imshow(img, cmap='gray', vmin=0, vmax=255)
else:
ax.imshow(img)
plt.show(fig)
if update_value:
self.value = io.BytesIO(cv2.imencode('.png', img)[1]).getvalue()
self.fig = fig# }}}
@widgets.register
class VideoA(widgets.Video):# {{{
url = traitlets.Unicode(help="video url").tag(sync=True)
@traitlets.observe('url')
def _url_to_byte(self, change):
self.value = change['new'].encode('utf-8')
# }}}
@widgets.register
class VideoE(VideoA):# {{{
"""
detail see custom.js
"""
_view_name = traitlets.Unicode('VideoEView').tag(sync=True) # noqa
_view_module = traitlets.Unicode('VideoEModel').tag(sync=True)
_view_module_version = traitlets.Unicode('0.1.1').tag(sync=True)
imgb4str = traitlets.Unicode(help="Image base64 value").tag(sync=True)
snapshot = traitlets.CBytes(help="Image bytes value").tag(sync=True)
@traitlets.observe('imgb4str')
def _img64_to_bytes(self, change):
self.snapshot = base64.b64decode(self.imgb4str.split(',')[1])
@classmethod
def from_file(cls, filename, **kwargs):
return super(VideoE, cls).from_file(filename, **kwargs)
# }}}
@widgets.register
class AccordionE(widgets.Accordion, widgets.ValueWidget):# {{{
@traitlets.observe('selected_index')
def _index_to_value(self, change):
self.value = change['new']# }}}
@widgets.register
class TabE(widgets.Tab, widgets.ValueWidget):# {{{
@traitlets.observe('selected_index')
def _index_to_value(self, change):
self.value = change['new']# }}}
class WidgetGenerator():
def __init__(self, lan='en', debug=False, events={}, border=False):# {{{
self.page = widgets.Box()
self.out = widgets.Output(
layout={
'border': '1px solid black',
'width': '100%', 'height': 'auto', 'max_height': '200px', 'overflow_y': 'scroll'})
self.output_type = 'none'
self.lan = lan
self.tag = 'tag'
self.defaultconfg = {}
self.debug = debug
self.border = border
self.events = events
self.source_on_clicks = {}
self.dataset_dir = ''
self.dataset_url = ''
self.basic_types = [
'int', 'float', 'bool',
'string', 'label', 'int-array', 'float-array',
'string-array', 'string-enum', 'image']
# margin: top, right, bottom, left
self.vlo = widgets.Layout(
width='auto',
align_items='stretch',
justify_content='flex-start',
margin='3px 0px 3px 0px')
if self.border:
self.vlo.border = 'solid 2px red'
self.hlo = widgets.Layout(
width='100%',
flex_flow='row wrap',
align_items='stretch',
justify_content='flex-start',
margin='3px 0px 3px 0px')
if self.border:
self.hlo.border = 'solid 2px blue'
self.page_layout = widgets.Layout(
display='flex',
width='100%')
if self.border:
self.page_layout.border = 'solid 2px black'
self.tab_layout = widgets.Layout(
display='flex',
width='99%')
if self.border:
self.tab_layout.border = 'solid 2px yellow'
self.accordion_layout = widgets.Layout(
display='flex',
width='99%')
if self.border:
self.accordion_layout.border = 'solid 2px green'
self.nav_layout = widgets.Layout(
display='flex',
width='99%',
margin='3px 0px 3px 0px',
border='1px solid black')
self.btn_layout = widgets.Layout(margin='3px 0px 3px 0px')
self.label_layout = widgets.Layout(
width="60px",
justify_content="center")# }}}
def init_page(self):# {{{
self.wid_widget_map = {}
self.wid_value_map = {}# }}}
def get_widget_byid(self, wid):# {{{
if wid in self.wid_widget_map:
return self.wid_widget_map[wid]
return None# }}}
def get_widget_defaultconf(self, rmlist=[]):# {{{
conf = self.defaultconfg.copy()
if len(rmlist) > 0:
for wid in rmlist:
conf.pop(wid, None)
return conf# }}}
def set_widget_values(self, jconf):# {{{
update_items = {}
for wid, val in jconf.items():
wdg = self.get_widget_byid(wid)
if wdg:
if isinstance(wdg, (widgets.Video, widgets.Image, widgets.Audio)):
value = val.encode()
else:
if isinstance(val, (list, tuple)):
value = json.dumps(val)
else:
value = val
if wdg.value != value:
wdg.value = value
update_items[wid] = wdg.value
return update_items# }}}
def get_all_kv(self, remove_underline=True):# {{{
kv_map = {}
def _get_kv(widget):
if hasattr(widget, 'node_type') and widget.node_type == 'multiselect':
if hasattr(widget, 'id') and hasattr(widget, 'multi_options'):
if widget.id[0] == '_' and widget.id[1] == '_':
return
if remove_underline and widget.id[0] == '_':
return
kv_map[widget.id] = widget.get_value()
return
if isinstance(widget, widgets.Box):
if hasattr(widget, 'node_type') and widget.node_type == 'navigation':
for child in widget.boxes:
_get_kv(child)
else:
for child in widget.children:
_get_kv(child)
else:
if hasattr(widget, 'id') and hasattr(widget, 'value'):
if widget.id[0] == '_' and widget.id[1] == '_':
return
if remove_underline and widget.id[0] == '_':
return
value = widget.value
if isinstance(value, bytes):
value = value.decode("utf-8", "ignore")
if len(value) > 512:
return
if hasattr(widget, 'switch_value'):
kv_map[widget.id] = widget.switch_value(value)
else:
kv_map[widget.id] = value
_get_kv(self.page)
return kv_map# }}}
def get_all_json(self, kvs=None):# {{{
if not kvs:
kvs = self.get_all_kv()
kvs = json.loads(json.dumps(kvs))
config = ConfigFactory.from_dict(kvs)
config = HOCONConverter.convert(config, 'json')
try:
return json.loads(config)
except Exception:
return f'error: {config}'# }}}
def logger(self, msg, clear=0):# {{{
with self.out:
if self.output_type == 'logger':
if clear:
clear_output()
print(msg)# }}}
def _output(self, body, clear=1):# {{{
if self.output_type not in (
'observe', 'kv', 'kvs', 'json', 'jsons'):
return
with self.out:
if clear:
clear_output()
if self.output_type == 'observe':
if isinstance(body, Bunch):
pprint.pprint(body)
elif isinstance(body, dict):
if 'new' in body and isinstance(body['new'], bytes):
body['new'] = body['new'] if len(body['new']) < 256 else body['new'][:16]
if 'old' in body and isinstance(body['old'], bytes):
body['old'] = body['old'] if len(body['old']) < 256 else body['old'][:16]
print(json.dumps(body, indent=4, ensure_ascii=False))
else:
print(body)
elif self.output_type == 'kv':
pprint.pprint(self.wid_value_map)
elif self.output_type == 'json':
config = ConfigFactory.from_dict(self.wid_value_map)
print(HOCONConverter.convert(config, 'json'))
elif self.output_type == 'kvs':
pprint.pprint(self.get_all_kv(False))
elif self.output_type == 'jsons':
pprint.pprint(self.get_all_json())# }}}
@observe_widget
def Debug(self, description, options, index=0):# {{{
label = widgets.Label(value=description, layout=self.label_layout)
wdg = widgets.ToggleButtons(
options=options,
index=index,
# description=description,
disabled=False,
button_style='warning')
wdg.parent_box = widgets.HBox(children=(label, wdg))
def _value_change(change):
self.output_type = change['new']
with self.out:
clear_output()
self.output_type = options[index][1]
return wdg, _value_change# }}}
def _wid_map(self, wid, widget):# {{{
if wid:
widget.id = wid
widget.context = self
self.wid_widget_map[wid] = widget# }}}
def _rm_sub_wid(self, widget):# {{{
if isinstance(widget, widgets.Box):
for child in widget.children:
self._rm_sub_wid(child)
else:
if hasattr(widget, 'id'):
if widget.id in self.wid_value_map.keys():
del self.wid_value_map[widget.id]
if widget.id in self.wid_widget_map.keys():
del self.wid_widget_map[widget.id]
# }}}
@observe_widget
def Bool(self, wid, *args, **kwargs):# {{{
wdg = widgets.Checkbox(description_allow_html=True, *args, **kwargs)
self._wid_map(wid, wdg)
def _value_change(change):
pass
return wdg, _value_change# }}}
@observe_widget
def Int(self, wid, slider, range, *args, **kwargs):# {{{
if range:
wdg = widgets.IntRangeSlider(*args, **kwargs)
else:
if slider:
wdg = widgets.IntSlider(*args, **kwargs)
else:
wdg = widgets.BoundedIntText(*args, **kwargs)
self._wid_map(wid, wdg)
def _value_change(change):
pass
return wdg, _value_change# }}}
@observe_widget
def Float(self, wid, slider, range, *args, **kwargs):# {{{
if range:
wdg = widgets.IntRangeSlider(*args, **kwargs)
else:
if slider:
wdg = widgets.FloatSlider(*args, **kwargs)
else:
wdg = widgets.BoundedIntText(*args, **kwargs)
wdg = widgets.BoundedFloatText(*args, **kwargs)
self._wid_map(wid, wdg)
def _value_change(change):
pass
return wdg, _value_change# }}}
@observe_widget
def String(self, wid, *args, **kwargs):# {{{
wdg = widgets.Text(*args, **kwargs)
self._wid_map(wid, wdg)
def _value_change(change):
pass
return wdg, _value_change# }}}
@observe_widget
def Label(self, wid, *args, **kwargs):# {{{
wdg = widgets.Label(*args, **kwargs)
self._wid_map(wid, wdg)
def _value_change(change):
pass
return wdg, _value_change# }}}
@observe_widget
def Bytes(self, wid, *args, **kwargs):# {{{
wdg = BytesText(*args, **kwargs)
self._wid_map(wid, wdg)
def _value_change(change):
change['owner'].bvalue = change['new'].encode('utf-8')
if 'value' in kwargs:
wdg.bvalue = kwargs['value'].encode('utf-8')
return wdg, _value_change# }}}
@observe_widget
def Text(self, wid, *args, **kwargs):# {{{
wdg = widgets.Textarea(*args, **kwargs)
self._wid_map(wid, wdg)
def _value_change(change):
pass
return wdg, _value_change# }}}
@observe_widget
def Array(self, wid, *args, **kwargs):# {{{
wdg = widgets.Text(*args, **kwargs)
self._wid_map(wid, wdg)
wdg.switch_value = lambda val: json.loads(val if (val and val[0] == '[') else '[' + val + ']')
def _value_change(change):
wdg = change['owner']
val = change['new'].strip()
self.wid_value_map[wdg.id] = wdg.switch_value(val)
return wdg, _value_change# }}}
@observe_widget
def StringEnum(self, wid, *args, **kwargs):# {{{
wdg = widgets.Dropdown(*args, **kwargs)
self._wid_map(wid, wdg)
def _value_change(change):
pass
return wdg, _value_change# }}}
@observe_widget
def SimpleMultiSelect(self, wid, *args, **kwargs):# {{{
wdg = widgets.SelectMultiple(*args, **kwargs)
wdg.switch_value = lambda val: list(val)
self._wid_map(wid, wdg)
def _value_change(change):
wdg = change['owner']
val = change['new']
self.wid_value_map[wdg.id] = wdg.switch_value(val)
return wdg, _value_change# }}}
@observe_widget
def BoolTrigger(self, wid, triggers, *args, **kwargs):# {{{
wdg = widgets.Checkbox(*args, **kwargs)
self._wid_map(wid, wdg)
parent_box = widgets.VBox(layout=self.vlo)
parent_box.layout.margin = '3px 0px 6px 0px'
wdg.parent_box = parent_box
wdg.triggers = triggers
def _update_layout(wdg, val, old):
if old is not None:
self._rm_sub_wid(wdg.parent_box.children[1])
trigger_box = widgets.VBox(layout=self.vlo)
if val:
self._parse_config(trigger_box, wdg.triggers['true'])
else:
self._parse_config(trigger_box, wdg.triggers['false'])
wdg.parent_box.children = [wdg, trigger_box]
def _value_change(change):
wdg = change['owner']
val = change['new']
old = change['old']
_update_layout(wdg, val, old)
_update_layout(wdg, wdg.value, None)
return wdg, _value_change# }}}
@observe_widget
def StringEnumTrigger(self, wid, triggers, *args, **kwargs):# {{{
wdg = widgets.Dropdown(*args, **kwargs)
self._wid_map(wid, wdg)
parent_box = widgets.VBox(layout=self.vlo)
wdg.parent_box = parent_box
wdg.triggers = triggers
def _update_layout(wdg, val, old):
if old is not None:
self._rm_sub_wid(wdg.parent_box.children[1])
trigger_box = widgets.VBox(layout=self.vlo)
self._parse_config(trigger_box, wdg.triggers[val])
wdg.parent_box.children = [wdg, trigger_box]
def _value_change(change):
wdg = change['owner']
val = change['new']
old = change['old']
_update_layout(wdg, val, old)
_update_layout(wdg, wdg.value, None)
return wdg, _value_change# }}}
@observe_widget
def Image(self, wid, ext, *args, **kwargs):# {{{
if ext:
wdg = ImageE(*args, **kwargs)
else:
wdg = ImageA(*args, **kwargs)
wdg.image_data = None
self._wid_map(wid, wdg)
def _value_change(change):
wdg = change['owner']
new = change['new']
if len(new) == 0:
self.logger('Image change value length is 0')
return
# think of event links
if len(new) < 256:
wdg.value = _request_content(new, b'')
if isinstance(wdg, ImageE):
wdg.imshow()
wdg.image_data = cv2.imdecode(np.frombuffer(wdg.value, dtype=np.uint8), cv2.IMREAD_UNCHANGED)
return wdg, _value_change# }}}
def Canvas(self, wid, *args, **kwargs):# {{{
from ipycanvas import Canvas
wdg = Canvas(*args, **kwargs, sync_image_data=True)
wdg.layout.border = '1px solid black'
self._wid_map(wid, wdg)
return wdg# }}}
@observe_widget
def Video(self, wid, ext, *args, **kwargs):# {{{
if ext:
wdg = VideoE(loop=False, autoplay=False, *args, **kwargs)
else:
wdg = VideoA(loop=False, autoplay=False, *args, **kwargs)
self._wid_map(wid, wdg)
def _value_change(change):
pass
return wdg, _value_change# }}}
def _parse_config(self, widget, config):
__id_ = config.get('_id_', '')
_name = config.get('name', None)
_type = config.get('type', None)
_objs = config.get('objs', None) or []
if isinstance(_name, str):
_name = {'en': _name, 'cn': _name}
description = ' '
if _name and len(_name[self.lan].strip()) > 0:
description = _name[self.lan]
tlo = widgets.Layout()# {{{
# flex = config.get('flex', '0 1 auto')
width = config.get('width', None)
height = config.get('height', None)
if width:
if isinstance(width, int):
tlo.width = '%dpx' % width
else:
tlo.width = width
if height:
if isinstance(height, int):
tlo.height = '%dpx' % height
else:
tlo.height = height# }}}
tstyle = {}# {{{
description_width = config.get('description_width', 130)
if isinstance(description_width, str):
tstyle['description_width'] = description_width # 45% or 'initial'
else:
tstyle['description_width'] = '%dpx' % description_width# }}}
args = {}# {{{
readonly = config.get('readonly', False)
default = config.get('default', None)
if readonly:
args['disabled'] = True
if _type in [
'bool', 'int', 'float', 'string', 'label', 'bytes', 'text', 'string-enum',
'bool-trigger', 'string-enum-trigger', 'radiobuttons']:
if default:
args['value'] = default
elif _type in ['multiselect_simple', 'multiselect']:
if default:
args['index'] = [default] if isinstance(default, int) else default
tips = config.get('tips', None)
if tips:
args['description_tooltip'] = tips# }}}
if _type in ['int', 'float', 'progressbar']:# {{{
min = config.get('min', None)
max = config.get('max', None)
if min is not None:
args['min'] = min
else:
args['min'] = -2147483647
if max is not None:
args['max'] = max
else:
args['max'] = 2147483647
if min and max:
args['step'] = config.get('step', (max - min) * 0.01) # }}}
elif _type in ['image', 'audio', 'video', 'canvas']:# {{{
if width:
args['width'] = width
if height:
args['height'] = height
format = config.get('format', 'url')
args['format'] = format
if format == 'url' and default:
args['value'] = default.encode('utf-8')# }}}
else:
args['value'] = default
elif _type in ['H', 'V']:# {{{
# align_content 设置同一列子元素在Y轴的对齐方式
# justify_content 设置同一行子元素在X轴的对齐方式
# align_items 设置同一行子元素在Y轴的对齐方式
# flex-start flex-end center space-between space-around space-evenly stretch inherit initial unset
tlo.align_items = config.get('align_items', 'stretch')
tlo.justify_content = config.get('justify_content', 'flex-start')
tlo.align_content = config.get('align_content', 'flex-start')
tlo.margin = config.get('margin', '3px 0px 3px 0px')
if not width:
tlo.width = '100%'
if self.border:
tlo.border = '1px solid cyan'# }}}
if _type == 'page':# {{{
wdg = widgets.VBox(layout=widgets.Layout(
width='100%'))
for obj in _objs:
self._parse_config(wdg, obj)
_evts = config.get('evts', None) or []
for evt in _evts:
self._parse_config(wdg, evt)
return _widget_add_child(widget, wdg)
# }}}
elif _type == 'tab':# {{{
selected_index = config.get('selected_index', 0)
wdg = TabE(layout=self.tab_layout)
wdg.titles = [''] * 4
for i, _obj in enumerate(_objs):
box = widgets.VBox(layout=tlo)
for obj in _obj['objs']:
self._parse_config(box, obj)
_widget_add_child(wdg, box)
wdg.set_title(i, _obj['name'] if isinstance(_obj['name'], str) else _obj['name'][self.lan])
wdg.selected_index = selected_index
wdg.description = _name
self._wid_map(__id_, wdg)
return _widget_add_child(widget, wdg)
# }}}
elif _type == 'accordion':# {{{
selected_index = config.get('selected_index', 0)
wdg = AccordionE(layout=self.accordion_layout)
# wdg.titles = [obj['name'][self.lan] for obj in _objs]
for i, _obj in enumerate(_objs):
box = widgets.VBox(layout=tlo)
for obj in _obj['objs']:
self._parse_config(box, obj)
_widget_add_child(wdg, box)
wdg.set_title(i, _obj['name'] if isinstance(_obj['name'], str) else _obj['name'][self.lan])
wdg.selected_index = selected_index
wdg.description = _name
self._wid_map(__id_, wdg)
return _widget_add_child(widget, wdg)
# }}}
elif _type == 'navigation':# {{{
def _value_change(change):
wdg = change['owner']
val = change['new']
parent_box = wdg.parent_box
trigger_box = parent_box.boxes[val]
parent_box.children = [parent_box.children[0], trigger_box]
label = widgets.Label(value=_name[self.lan] if _name else ' ', layout=self.label_layout)
btns = widgets.ToggleButtons(style={'description_width': '0px'})
btns.description = __id_
wdg = widgets.VBox(layout=self.nav_layout)
wdg.node_type = 'navigation'
wdg.boxes = []
options = []
for i, obj in enumerate(_objs):
options.append((obj['name'] if isinstance(obj['name'], str) else obj['name'][self.lan], i))
box = widgets.VBox(layout=tlo)
self._parse_config(box, obj)
wdg.boxes.append(box)
wdg.children = [widgets.HBox([label, btns]), wdg.boxes[0]]
btns.options = options
btns.parent_box = wdg
btns.observe(_value_change, 'value')
self._wid_map(__id_, btns)
return _widget_add_child(widget, wdg)
# }}}
elif _type == 'debug': # debug {{{
options = []
for obj in _objs:
options.append((obj['name'], obj['value']))
index = config.get('index', 0)
wdg = self.Debug(_name[self.lan], options, index)
return _widget_add_child(widget, [wdg, self.out])
# }}}
elif _type == 'output': # output{{{
# tlo.border = '1px solid gray'
wdg = widgets.Output(layout=tlo)
self._wid_map(__id_, wdg)
return _widget_add_child(widget, wdg)
# }}}
elif _type == 'object':# {{{
if _name:
wdg = widgets.HTML(value=f"<b><font color='black'>{_name[self.lan]} :</b>")
_widget_add_child(widget, wdg)
for obj in _objs:
self._parse_config(widget, obj)
return widget
# }}}
elif _type == 'html':# {{{
value = config.get('text', '<hr>')
wdg = widgets.HTML(value=f'{value}')
return _widget_add_child(widget, wdg)
# }}}
elif _type == 'H':# {{{
if _name:
wdg = widgets.HTML(value=f"<b><font color='black'>{_name[self.lan]} :</b>")
_widget_add_child(widget, wdg)
# layout.display = 'flex'
# layout.flex_flow = 'row'
wdg = widgets.HBox(layout=tlo)
for obj in _objs:
self._parse_config(wdg, obj)
return _widget_add_child(widget, wdg)
# }}}
elif _type == 'V':# {{{
if _name:
wdg = widgets.HTML(value=f"<b><font color='black'>{_name[self.lan]} :</b>")
_widget_add_child(widget, wdg)
# layout.display = 'flex'
# layout.flex_flow = 'column'
wdg = widgets.VBox(layout=tlo)
for obj in _objs:
self._parse_config(wdg, obj)
return _widget_add_child(widget, wdg)
# }}}
elif _type == 'bool':# {{{
wdg = self.Bool(
__id_,
description=description,
layout=tlo,
style=tstyle,
**args)
return _widget_add_child(widget, wdg)
# }}}
elif _type == 'int':# {{{
_range = config.get('range', False)
slider = config.get('slider', False)
wdg = self.Int(
__id_,
slider, _range,
description=description,
layout=tlo,
style=tstyle,
continuous_update=False,
**args)
return _widget_add_child(widget, wdg)
# }}}
elif _type == 'float':# {{{
slider = config.get('slider', False)
_range = config.get('range', False)
wdg = self.Float(
__id_,
slider, _range,
description=description,
layout=tlo,
style=tstyle,
continuous_update=False,
**args)
return _widget_add_child(widget, wdg)
# }}}
elif _type == 'string':# {{{
wdg = self.String(
__id_,
description=description,
layout=tlo,
style=tstyle,
continuous_update=False,
**args)
return _widget_add_child(widget, wdg)
# }}}
elif _type == 'label':# {{{
wdg = self.Label(
__id_,
description=description,
layout=tlo,
style=tstyle,
continuous_update=False,
**args)
return _widget_add_child(widget, wdg)
# }}}
elif _type == 'bytes':# {{{
wdg = self.Bytes(
__id_,
description=description,
layout=tlo,
style=tstyle,
continuous_update=False,
**args,
)
return _widget_add_child(widget, wdg)
# }}}
elif _type == 'text':# {{{
wdg = self.Text(
__id_,
description=description,
layout=tlo,
style=tstyle,
continuous_update=False,
**args,