def initialize(self, options: dict): if "parcelSource" not in options: return # keep only the relevant information ps_opt = options["parcelSource"] if "type" not in ps_opt: return source_opt = [a[1] for a in self.sources.options] if ps_opt["type"] in source_opt: self.sources.value = ps_opt["type"] view_options = VBox() info_txt = Label("From Text File only") info_txt_rest = Label("From Text File and RESTFul") info_shape = Label("From Shape File") info_json = Label("From GeoJSON File") if self.sources.value == 'txt': source = source_from_txt() source.initialize(ps_opt) view_options.children = [info_txt, source] elif self.sources.value == 'txt_rest': source = source_from_txt_rest() source.initialize(ps_opt) view_options.children = [info_txt_rest, source] elif self.sources.value == 'shape': source = source_from_shape() source.initialize(ps_opt) view_options.children = [info_shape, source] elif self.sources.value == 'json': source = source_from_shape('json') source.initialize(ps_opt) view_options.children = [info_json, source] self.children = [ self.sources_box, view_options, self.wb_save, self.whb_load ] def on_source_change(change): view_options.children = [] if self.sources.value == 'txt': view_options.children = [info_txt, source_from_txt()] elif self.sources.value == 'txt_rest': view_options.children = [info_txt_rest, source_from_txt_rest()] elif self.sources.value == 'shape': view_options.children = [info_shape, source_from_shape()] elif self.sources.value == 'json': view_options.children = [info_json, source_from_shape('json')] self.sources.observe(on_source_change, 'value')
def _display(self): c_string = 'c' + str(self.component_index) r_string = str(self.repr_index) try: _repr_dict = self._view._repr_dict[c_string][r_string][ 'parameters'] except KeyError: _repr_dict = dict() def func(opacity=_repr_dict.get('opacity', 1.), assembly=_repr_dict.get('assembly', 'default'), color_scheme=_repr_dict.get('colorScheme', ""), wireframe=_repr_dict.get('wireframe', False)): parameters = dict(opacity=opacity, assembly=assembly, colorScheme=color_scheme, wireframe=wireframe) if not color_scheme: parameters.pop('colorScheme') self.parameters = parameters assembly_list = ['default', 'AU', 'BU1', 'UNITCELL', 'SUPERCELL'] iwidget = interactive(func, opacity=(0., 1., 0.1), color_scheme=COLOR_SCHEMES, assembly=assembly_list) make_default_slider_width(iwidget) wbox = VBox([ iwidget, ]) if self.name == 'surface': def func_extra(probe_radius=1.4, isolevel=2., smooth=2., surface_type='ms', box_size=10, cutoff=0.): self.parameters = dict(probeRadius=probe_radius, isolevel=isolevel, smooth=smooth, surfaceType=surface_type, boxSize=box_size, cutoff=cutoff) surface_types = ['vws', 'sas', 'ms', 'ses'] # use continuous_update=False to avoid expensive surface calculation and update widget_extra = interactive(func_extra, probe_radius=(0., 5., 0.1), isolevel=(0., 10., 0.1), smooth=(0, 10, 1), surface_type=surface_types, box_size=(0, 100, 2), cutoff=(0., 100, 0.1), continuous_update=False) make_default_slider_width(widget_extra) wbox.children = [iwidget, widget_extra] return wbox
def make_box_for_grid(image_widget, title, size=(250, 250)): """ Make a VBox to hold caption/image for demonstrating option_fit values. """ modes = ['oblique', 'X', 'Y', 'Z'] # make layout box_layout = Layout() box_layout.width = f'{size[0]}px' box_layout.height = f'{size[1]}px' box_layout.border = '0px' # Make the caption if title is not None: title_str = "'{}'".format(title) else: title_str = str(title) h = HTML(value='' + str(title_str) + '') # Make the box with the image widget inside it boxb = Box() boxb.layout = box_layout boxb.children = [image_widget] # Compose into a vertical box vb = VBox() vb.layout.align_items = 'center' vb.children = [h, boxb] return vb
def _make_selection_repr_buttons(self): vbox = VBox() children = [] rep_names = REPR_NAMES[:] excluded_names = ['ball+stick', 'distance'] for name in excluded_names: rep_names.remove(name) for index, name in enumerate(rep_names): button = ToggleButton(description=name) def make_func(): def on_toggle_button_value_change(change, button=button): new = change['new'] # True/False if new: self._view.add_representation(button.description) else: self._view._remove_representations_by_name( button.description) return on_toggle_button_value_change button.observe(make_func(), names='value') children.append(button) boxes = [] for index, arr in enumerate(np.array_split(children, 4)): box = HBox([child for child in arr]) boxes.append(box) vbox.children = boxes return vbox
def widget_box(): source = int(config.get_value(['set', 'data_source'])) sources = RadioButtons( options=[ ("JRC RESTful API.", 0), ("Direct access to database and object storage.", 1) ], value=source, layout={'width': 'max-content'} ) sources_box = Box([ Label(value="Data sources:"), sources] ) info_api = Label("RESTful API Settings.") info_direct = Label("Direct access settings") view_options = VBox([info_direct]) if source == 0: view_options.children = [info_api, rest_api()] elif source == 1: view_options.children = [info_direct, direct()] def on_source_change(change): view_options.children = [] if sources.value == 0: view_options.children = [info_api, rest_api()] elif sources.value == 1: view_options.children = [info_direct, direct()] config.update(['set', 'data_source'], str(sources.value)) sources.observe(on_source_change, 'value') wbox_sources = VBox([sources_box, view_options], layout=Layout(border='1px solid black')) info_general = Label(value="General settings:") wbox = VBox([wbox_sources, info_general, settings.widget_box()]) return wbox
def widget_box(): source = config.get_value(['set', 'data_source']) sources = RadioButtons( options=[ ("DIAS API.", 'dias_api'), ("Direct access to database and object storage.", 'direct') ], layout={'width': 'max-content'} ) sources_box = Box([ Label(value="Available sources:"), sources] ) info_api = Label("DIAS API Settings.") info_direct = Label("Direct access settings") view_options = VBox([info_direct]) if source == 'direct': view_options.children = [info_direct] else: view_options.children = [info_api, dias_api()] def on_source_change(change): view_options.children = [] if sources.value == 'dias_api': view_options.children = [info_api, dias_api()] elif sources.value == 'direct': view_options.children = [info_direct] config.update(['preferences', 'data_source'], str(sources.value)) sources.observe(on_source_change, 'value') wbox_sources = VBox([sources_box, view_options], layout=Layout(border='1px solid black')) info_general = Label(value="General settings:") wbox = VBox([wbox_sources, info_general, settings.widget_box()]) return wbox
def _add_device_to_list(backend: BackendWithProviders, device_list: wid.VBox) -> None: """Add the backend to the device list widget. Args: backend: Backend to add. device_list: Widget showing the devices. """ device_pane = make_backend_widget(backend) device_list.children = list(device_list.children) + [device_pane]
def editable_metadata(ds: DataSet) -> Box: def _button_to_input(text: str, box: Box) -> Callable[[Button], None]: def on_click(_: Button) -> None: text_input = Textarea( value=text, placeholder="Enter text", disabled=False, layout=Layout(height="auto", width="auto"), ) save_button = button( "", "success", on_click=_save_button(box, ds), button_kwargs=dict(icon="save"), layout_kwargs=dict(width="50%"), ) cancel_button = button( "", "danger", on_click=_save_button(box, ds, do_save=False), button_kwargs=dict(icon="close"), layout_kwargs=dict(width="50%"), ) subbox = HBox([save_button, cancel_button], ) box.children = (text_input, subbox) return on_click def _save_button(box: Box, ds: DataSet, do_save: bool = True) -> Callable[[Button], None]: def on_click(_: Button) -> None: text = box.children[0].value if do_save: ds.add_metadata(tag=_META_DATA_KEY, metadata=text) box.children = (_changeable_button(text, box), ) return on_click def _changeable_button(text: str, box: Box) -> Button: return button( text, "success", on_click=_button_to_input(text, box), button_kwargs=dict(icon="edit") if text == "" else {}, ) text = ds.metadata.get(_META_DATA_KEY, "") box = VBox([], layout=Layout(height="auto", width="auto")) box.children = (_changeable_button(text, box), ) return box
def data_source(): source = config.get_value(['set', 'data_source']) sources = RadioButtons(options=[ ("RESTful API for CbM.", 'api'), ("Direct access to database and object storage.", 'direct') ], value=source, layout={'width': 'max-content'}, disabled=True) sources_box = Box([Label(value="Data sources:"), sources]) info_api = Label("RESTful API Settings.") info_direct = Label("Direct access settings") view_options = VBox([info_direct]) if source == 'api': view_options.children = [info_api, settings_ds.api()] elif source == 'direct': view_options.children = [info_direct, settings_ds.direct()] def on_source_change(change): view_options.children = [] if sources.value == 'api': view_options.children = [info_api, settings_ds.api()] elif sources.value == 'direct': view_options.children = [info_direct, settings_ds.direct()] config.set_value(['set', 'data_source'], sources.value) sources.observe(on_source_change, 'value') wbox_sources = VBox([sources_box, view_options], layout=Layout(border='1px solid black')) return wbox_sources
def make_attr_widget(obj, map, title, attrs, labels): box = VBox() children = [] if title is not None: children.append(Label(value=title)) for i, attr in enumerate(attrs): if hasattr(obj, attr) and isinstance(getattr(obj, attr), dict): widget = Textarea(description=labels[i]) else: widget = Text(description=labels[i]) map[labels[i]] = widget children.append(widget) box.children = children return box
def _make_repr_playground(self): vbox = VBox() children = [] rep_names = REPRESENTATION_NAMES[:] excluded_names = ['ball+stick', 'distance'] for name in excluded_names: rep_names.remove(name) repr_selection = Text(value='*') repr_selection.layout.width = default.DEFAULT_TEXT_WIDTH repr_selection_box = HBox([Label('selection'), repr_selection]) setattr(repr_selection_box, 'value', repr_selection.value) for index, name in enumerate(rep_names): button = ToggleButton(description=name) def make_func(): def on_toggle_button_value_change(change, button=button): selection = repr_selection.value new = change['new'] # True/False if new: self._view.add_representation(button.description, selection=selection) else: self._view._remove_representations_by_name( button.description) return on_toggle_button_value_change button.observe(make_func(), names='value') children.append(button) button_clear = Button(description='clear', button_style='info', icon='fa-eraser') @button_clear.on_click def on_clear(button_clear): self._view.clear() for kid in children: # unselect kid.value = False vbox.children = children + [repr_selection, button_clear] _make_autofit(vbox) self.widget_quick_repr = vbox return self.widget_quick_repr
def _make_repr_playground(self): vbox = VBox() children = [] rep_names = REPRESENTATION_NAMES[:] excluded_names = ['ball+stick', 'distance'] for name in excluded_names: rep_names.remove(name) repr_selection = Text(value='*') repr_selection.layout.width = default.DEFAULT_TEXT_WIDTH repr_selection_box = HBox([Label('selection'), repr_selection]) setattr(repr_selection_box, 'value', repr_selection.value) for index, name in enumerate(rep_names): button = ToggleButton(description=name) def make_func(): def on_toggle_button_value_change(change, button=button): selection = repr_selection.value new = change['new'] # True/False if new: self._view.add_representation(button.description, selection=selection) else: self._view._remove_representations_by_name(button.description) return on_toggle_button_value_change button.observe(make_func(), names='value') children.append(button) button_clear = Button(description='clear', button_style='info', icon='fa-eraser') @button_clear.on_click def on_clear(button_clear): self._view.clear() for kid in children: # unselect kid.value = False vbox.children = children + [repr_selection, button_clear] _make_autofit(vbox) self.widget_quick_repr = vbox return self.widget_quick_repr
def createDefaultLayout(self, layout): ui = {} lkeys = list(layout.keys()) tkeys = len(lkeys) for i in range(tkeys): k = lkeys[i] ui[k] = {} if i < tkeys - 1: ui[k]["next"] = Button(description="Go to " + lkeys[i + 1], layout=Layout(width="50%")) if 'click' in layout[lkeys[i + 1]]: ui[k]["next"].on_click(layout[lkeys[i + 1]]["click"]) else: ui[k]["next"] = Button(description="", layout=Layout(width="50%"), disabled=True) if i > 0: ui[k]["back"] = Button(description="Go to " + lkeys[i - 1], layout=Layout(width="50%")) if 'click' in layout[lkeys[i - 1]]: ui[k]["back"].on_click(layout[lkeys[i - 1]]["click"]) else: ui[k]["back"] = Button(description="", layout=Layout(width="50%"), disabled=True) ui[k]["button_container"] = HBox(layout=Layout(width="100%")) ui[k]["button_container"].children = [ui[k]["back"], ui[k]["next"]] ui[k]["container"] = VBox( layout=Layout(width="100%", border="1px solid #6666")) children = [] children.append(ui[k]["button_container"]) if "children" in layout[k]: for k2, v in layout[k]["children"].items(): ui[k][k2] = v children.append(v) children.append(ui[k]["button_container"]) ui[k]["container"].children = children ui[k]["action"] = layout[k]["action"] return ui
def editable_metadata(ds: DataSet) -> Box: def _button_to_input(text, box): def on_click(_): text_input = Textarea( value=text, placeholder="Enter text", disabled=False, layout=Layout(height="auto", width="auto"), ) save_button = button( "", "danger", on_click=_save_button(box, ds), button_kwargs=dict(icon="save"), ) box.children = (text_input, save_button) return on_click def _save_button(box, ds): def on_click(_): text = box.children[0].value ds.add_metadata(tag=_META_DATA_KEY, metadata=text) box.children = (_changeable_button(text, box), ) return on_click def _changeable_button(text, box): return button( text, "success", on_click=_button_to_input(text, box), button_kwargs=dict(icon="edit") if text == "" else {}, ) text = ds.metadata.get(_META_DATA_KEY, "") box = VBox([], layout=Layout(height="auto", width="auto")) box.children = (_changeable_button(text, box), ) return box
def button_to_text(title: str, body: str) -> Box: def _button_to_input(title: str, body: str, box: Box) -> Callable[[Button], None]: def on_click(_: Button) -> None: text_input = Textarea( value=body, placeholder="Enter text", disabled=True, layout=Layout(height="300px", width="auto"), ) back_button = button( "Back", "warning", on_click=_back_button(title, body, box), button_kwargs=dict(icon="undo"), ) box.children = (text_input, back_button) return on_click def _back_button(title: str, body: str, box: Box) -> Callable[[Button], None]: def on_click(_: Button) -> None: box.children = (_changeable_button(title, body, box), ) return on_click def _changeable_button(title: str, body: str, box: Box) -> Button: return button( title, "success", on_click=_button_to_input(title, body, box), ) box = VBox([], layout=Layout(height="auto", width="auto")) box.children = (_changeable_button(title, body, box), ) return box
def __init__(self, candidate_labels, propositions): # internal vars self.header = '<p style="font-size: 150%;font-weight: 300;line-height: 1.39;margin: 0 0 12.5px;">{} <a target="_blank" href="{}">source</a></p>' self.candidate_labels = candidate_labels self.propositions = propositions self.choice = None self.clicked = False self.confusion_matrix = np.zeros((len(candidate_labels), len(candidate_labels)), dtype=np.int) # candidate buttons buttons = [Button(description=label) for label in self.candidate_labels] for b in buttons: b.on_click(self.on_button_clicked) hbox1 = HBox() hbox1.children = buttons self.buttons = buttons # scorebox and new_question button and confusion matrix self.scorebox = IntText(description='score', value=0, disabled=True) self.number = IntText(description='questions', value=0, disabled=True) new_question = Button(description='nouvelle question !') new_question.on_click(self.create_new_question) confusion_matrix_button = Button(description='afficher matrice de confusion') confusion_matrix_button.on_click(self.show_confusion_matrix) hbox2 = HBox() hbox2.children = [self.scorebox, self.number, new_question, confusion_matrix_button] # proposition box self.html = HTML() # general layout vbox = VBox() vbox.children = [hbox1, hbox2, self.html] self.box = vbox # generate first question self.create_new_question()
def worker(self): def cancel(b): self.sc.cancelJobGroup(self.job_info.group_id) def toggle(widget): def f(b): for w in widget.children: h = w.layout.height if h is None or h == "16px": w.layout.height = "0px" b.icon = "arrow-circle-down" else: w.layout.height = "16px" b.icon = "arrow-circle-right" return f style = {"description_width": "initial"} bars = {} labels = {} lastJob = None progressbars = VBox([]) cancel_button = Button(button_style="", tooltip="Cancel Spark Job", icon="window-close") cancel_button.add_class("db-button") cancel_button.on_click(cancel) toggle_button = Button(button_style="", tooltip="Toggle progress bar", icon="arrow-circle-right") toggle_button.add_class("db-button") toggle_button.on_click(toggle(progressbars)) indicator = HBox([toggle_button, progressbars]) while self.running == 1: time.sleep(0.2) jobs = [(jobid, self.tracker.getJobInfo(jobid)) for jobid in self.tracker.getJobIdsForGroup(self.job_info.group_id) if self.tracker.getJobInfo(jobid).status == "RUNNING"] for j, job in jobs: if bars.get(j, None) is None: if lastJob is not None: bars[lastJob].value = 100.0 bars[j] = FloatProgress( value=0.0, min=0.0, max=100.0, description="Job: %04d Stage: %04d" % (j, 0), bar_style="info", orientation="horizontal", style=style, ) bars[j].add_class("db-bar") labels[j] = Label( value="", description="Code:", disabled=False, layout=Layout(width="800px", height="100%", margin="0 0 0 5px"), ) labels[j].add_class("db-label") progressbar = HBox([bars[j], labels[j]]) progressbars.children = progressbars.children + ( progressbar, ) if not self.progressbar_showing: self.progressbar_showing = True display(indicator) lastJob = j stageIds = sorted(job.stageIds) for s in stageIds: stageInfo = self.tracker.getStageInfo(s) bars[j].description = "Job: %04d Stage: %04d" % (j, s) labels[j].value = "code: '%s' / stages: %s" % ( stageInfo.name, str(stageIds)[1:-1], ) if stageInfo.numActiveTasks > 0: progress = int(100 * stageInfo.numCompletedTasks / stageInfo.numTasks) bars[j].value = progress if lastJob is not None and self.running == 0: bars[lastJob].value = 100.0
def toExploration(self, event=None): reload = self.showPanel("Exploration") if reload: self.ui["Exploration"]["grid"].children = [] main_dimensions = [] secondary_dimensions = [] for k in self.ui["Filters"]["grid"].get_changed_df().columns: if "input" in k: main_dimensions.append( Checkbox(value=True, description=k, layout=Layout(width="auto"))) else: main_dimensions.append( Checkbox(value=False, description=k, layout=Layout(width="auto"))) secondary_dimensions.append( Checkbox(value=True, description=k, layout=Layout(width="auto"))) self.ui["Exploration"]["main_dimensions"] = main_dimensions self.ui["Exploration"]["main_plot"] = Dropdown( description="Visualization", options=[ "sankey", "pca", "sankeytree", "sunburst", "parallelscat", "scattermatrix" ], value="sankey") self.ui["Exploration"][ "secondary_dimensions"] = secondary_dimensions self.ui["Exploration"]["secondary_plot1"] = Dropdown( description="Visualization", options=[ "table", "corrcoef", "sankey", "pca", "sankeytree", "sunburst", "parallelscat", "parallels", "scattermatrix" ], value="corrcoef") self.ui["Exploration"]["secondary_plot2"] = Dropdown( description="Visualization", options=[ "table", "corrcoef", "sankey", "pca", "sankeytree", "sunburst", "parallelscat", "parallels", "scattermatrix" ], value="table") vb1 = VBox(main_dimensions, layout=Layout(width="100%", padding="10px")) vb1 = GridBox(layout=Layout( width='auto', grid_template_columns='auto auto auto', grid_template_rows=" ".join([ 'auto' for i in self.ui["Exploration"]["main_dimensions"] ]), grid_gap='1px 1px')) children = [] for i, w in enumerate(self.ui["Exploration"]["main_dimensions"]): children.append(w) up = Button(icon="angle-up", layout=Layout(width="50px")) up.on_click( lambda b, this=self, pos=i, w=vb1, l="main_dimensions": this.moveOption(pos, True, w, l)) children.append(up) down = Button(icon="angle-down", layout=Layout(width="50px")) down.on_click( lambda b, this=self, pos=i, w=vb1, l="main_dimensions": this.moveOption(pos, False, w, l)) children.append(down) vb1.children = children vb2 = GridBox(layout=Layout(width='auto', grid_template_columns='auto auto auto', grid_template_rows=" ".join([ 'auto' for i in self.ui["Exploration"] ["secondary_dimensions"] ]), grid_gap='1px 1px')) children = [] for i, w in enumerate( self.ui["Exploration"]["secondary_dimensions"]): children.append(w) up = Button(icon="angle-up", layout=Layout(width="50px")) up.on_click( lambda b, this=self, pos=i, w=vb2, l= "secondary_dimensions": this.moveOption(pos, True, w, l)) children.append(up) down = Button(icon="angle-down", layout=Layout(width="50px")) down.on_click( lambda b, this=self, pos=i, w=vb2, l= "secondary_dimensions": this.moveOption(pos, False, w, l)) children.append(down) vb2.children = children self.ui["Exploration"]["grid"].children = [ VBox([ Button(description="Main Dimensions", layout=Layout(width='auto'), style=ButtonStyle(button_color='lightblue')), self.ui["Exploration"]["main_plot"], vb1, ], layout=Layout(width="50%")), VBox([ Button(description="Secondary Dimensions", layout=Layout(width='auto'), style=ButtonStyle(button_color='lightblue')), self.ui["Exploration"]["secondary_plot1"], self.ui["Exploration"]["secondary_plot2"], vb2, ], layout=Layout(width="50%")) ]
def _draw(self): """ Jupyter notebook code to draw widgets """ left = Output() right = Output() properties = Output() conditions = Output() deciphered = Output() tablekey = Output() tables = { True: [], False: [] } for key in self[self._cindex].cipher.keys(): characters = self[self._cindex].cipher[key].get() for i, character in zip(range(len(characters)), characters): partial = Output() df = self[self._cindex].all_positions(helpers.i2a(character)) style = df.style.set_caption( '{} ({})'.format(character, helpers.i2a(character)) ).set_table_attributes( 'style="font-size: 10px"' ).hide_index() if self[self._cindex].table == key and df.equals(self[self._cindex].all_positions()): style.set_properties(**{'background-color': '#FF0000', 'color': '#FFFFFF'}) with partial: display.display(style) tables[key].append(partial) with properties: display.display( self[self._cindex].properties_frame .style.set_caption('Properties') .set_table_attributes( 'style="font-size: 10px"' ).set_properties( subset=['Value'], **{'width': '120px'} ).hide_index() ) with conditions: df = self[self._cindex].condition_frame.reset_index() df.columns = ['', 'index', 'cipher', 'lacuna',] display.display( df.style.set_caption('Conditions') .set_table_attributes( 'style="font-size: 10px"' ).hide_index() ) with deciphered: display.display(self.as_dataframe()) with tablekey: display.display(self.table_key) with left: display.display(self[self._cindex].cipher[True].apply) with right: display.display(self[self._cindex].cipher[False].apply) subtables = VBox() subtables.children = [HBox(tables[True]), HBox(tables[False])] self._hbox.children = [left, right] self._inner.children = [ self._hbox, HBox([VBox([properties, conditions]), subtables, VBox([deciphered, tablekey])]), globalout ] self._html.value = '<h3>Current character {} ({}), lacuna {} ({}) index {}, deciphered to {} algorithm {}</h3>'.format( self[self._cindex].character, self[self._cindex].cindex, self[self._cindex].lacuna, self[self._cindex].lindex, self._cindex + 1, str(self[self._cindex]), self[self._cindex].algorithm + 1 )
def info(run_manager) -> None: """Display information about the `RunManager`. Returns an interactive ipywidget that can be visualized in a Jupyter notebook. """ from IPython.display import display from ipywidgets import HTML, Button, Layout, VBox status = HTML(value=_info_html(run_manager)) layout = Layout(width="200px") cancel_button = Button( description="cancel jobs", layout=layout, button_style="danger", icon="stop" ) cleanup_button = Button( description="cleanup log and batch files", layout=layout, button_style="danger", icon="remove", ) update_info_button = Button( description="update info", layout=layout, icon="refresh", ) update_info_button.style.button_color = "lightgreen" load_learners_button = Button( description="load learners", layout=layout, button_style="info", icon="download", ) show_logs_button = Button( description="show logs", layout=layout, button_style="info", icon="book" ) widgets = { "update info": update_info_button, "cancel": HBox([cancel_button], layout=layout), "cleanup": HBox([cleanup_button], layout=layout), "load learners": load_learners_button, "show logs": show_logs_button, } def switch_to(box, *buttons, _callable=None): def on_click(_): box.children = tuple(buttons) if _callable is not None: _callable() return on_click box = VBox([]) log_widget = None def update(_): status.value = _info_html(run_manager) def load_learners(_): run_manager.load_learners() def toggle_logs(_): nonlocal log_widget if log_widget is None: log_widget = log_explorer(run_manager) b = widgets["show logs"] if b.description == "show logs": b.description = "hide logs" box.children = (*box.children, log_widget) else: b.description = "show logs" box.children = box.children[:-1] def cancel(): run_manager.cancel() update(None) def cleanup(include_old_logs): def _callable(): run_manager.cleanup(include_old_logs.value) update(None) return _callable widgets["update info"].on_click(update) widgets["show logs"].on_click(toggle_logs) widgets["load learners"].on_click(load_learners) # Cancel button with confirm/deny option confirm_cancel_button = Button( description="Confirm", button_style="success", icon="check" ) deny_cancel_button = Button(description="Deny", button_style="danger", icon="close") cancel_button.on_click( switch_to(widgets["cancel"], confirm_cancel_button, deny_cancel_button) ) deny_cancel_button.on_click(switch_to(widgets["cancel"], cancel_button)) confirm_cancel_button.on_click( switch_to(widgets["cancel"], cancel_button, _callable=cancel) ) # Cleanup button with confirm/deny option include_old_logs = Checkbox( False, description=f"Remove {run_manager.move_old_logs_to}/ folder", indent=False, ) confirm_cleanup_button = Button( description="Confirm", button_style="success", icon="check" ) deny_cleanup_button = Button( description="Deny", button_style="danger", icon="close" ) cleanup_box = VBox( [HBox([confirm_cleanup_button, deny_cleanup_button]), include_old_logs] ) cleanup_button.on_click(switch_to(widgets["cleanup"], cleanup_box)) deny_cleanup_button.on_click(switch_to(widgets["cleanup"], cleanup_button)) confirm_cleanup_button.on_click( switch_to( widgets["cleanup"], cleanup_button, _callable=cleanup(include_old_logs) ) ) box.children = (status, *tuple(widgets.values())) display(box)
def info(self) -> None: """Display information about the `RunManager`. Returns an interactive ipywidget that can be visualized in a Jupyter notebook. """ from ipywidgets import Layout, Button, VBox, HTML from IPython.display import display status = HTML(value=self._info_html()) layout = Layout(width="200px") buttons = [ Button( description="update info", layout=layout, button_color="lightgreen", icon="refresh", ), Button( description="cancel jobs", layout=layout, button_style="danger", icon="stop", ), Button( description="cleanup log and batch files", layout=layout, button_style="danger", icon="remove", ), Button( description="load learners", layout=layout, button_style="info", icon="download", ), Button(description="show logs", layout=layout, button_style="info", icon="book"), ] buttons = {b.description: b for b in buttons} box = VBox([]) log_widget = None def update(_): status.value = self._info_html() def cancel(_): self.cancel() update(_) def cleanup(_): self.cleanup() update(_) def load_learners(_): self.load_learners() def toggle_logs(_): nonlocal log_widget if log_widget is None: log_widget = log_explorer(self) b = buttons["show logs"] if b.description == "show logs": b.description = "hide logs" box.children = (*box.children, log_widget) else: b.description = "show logs" box.children = box.children[:-1] buttons["cancel jobs"].on_click(cancel) buttons["cleanup log and batch files"].on_click(cleanup) buttons["update info"].on_click(update) buttons["show logs"].on_click(toggle_logs) buttons["load learners"].on_click(load_learners) box.children = (status, *tuple(buttons.values())) display(box)
def expandable_dict(dct, tab, ds): """Returns a `ipywidgets.Button` which on click changes into a text area and buttons, that when clicked show something in a subtab of ``tab``.""" def _button_to_input(dct, box): def on_click(_): description = yaml.dump( dct) # TODO: include and extract more data! text_input = Textarea( value=description, placeholder="Enter text", disabled=True, layout=Layout(height="300px", width="auto"), ) plot_button = button( "Plot", "warning", on_click=_do_in_tab(tab, ds, "plot"), button_kwargs=dict(icon="line-chart"), ) snapshot_button = button( "Open snapshot", "warning", on_click=_do_in_tab(tab, ds, "snapshot"), button_kwargs=dict(icon="camera"), ) dataset_button = button( "Inpect dataset", "warning", on_click=_do_in_tab(tab, ds, "dataset"), button_kwargs=dict(icon="search"), ) back_button = button( "Back", "warning", on_click=_input_to_button(dct, box), button_kwargs=dict(icon="undo"), ) box.children = ( text_input, snapshot_button, dataset_button, plot_button, back_button, ) return on_click def _input_to_button(dct, box): def on_click(_): box.children = (_changeable_button(dct, box), ) return on_click def _changeable_button(dct, box): return button( ", ".join(dct), "success", on_click=_button_to_input(dct, box), button_kwargs=dict(icon="edit") if text == "" else {}, ) box = VBox([], layout=Layout(height="auto", width="auto")) box.children = (_changeable_button(dct, box), ) return box