def __get_ipython_widget_embedding(self, empty=False, role='Admin', condition=None): if empty == True: return {'manager_state': None, 'widget_views': [None]} else: assert role == 'Admin' or role == 'PM' or role == 'Member' if role == 'Admin': view = building_admin_view() elif role == 'PM': assert condition in self.project_list view = building_pm_view(condition) else: # if role == 'Member': assert condition in self.unique_members view = building_member_view(condition) data = embed_data(views=[view]) manager_state = json.dumps(data['manager_state']) widget_views = [ json.dumps(view_spec) for view_spec in data['view_specs'] ] return { 'manager_state': manager_state, 'widget_views': widget_views }
def get_html_template(self): """ This function gives HTML code to embed the chart widget. To see more details about embeding an ipywidget see: https://ipywidgets.readthedocs.io/en/latest/embedding.html Returns: widget_html (str): HTML code to embed the chart. """ html_template = """ <!-- Load require.js. Delete this if your page already loads require.js --> <script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" crossorigin="anonymous"></script> <script src="https://unpkg.com/@jupyter-widgets/html-manager@^0.18.0/dist/embed-amd.js" crossorigin="anonymous"></script> <script type="application/vnd.jupyter.widget-state+json"> {manager_state} </script> <script type="application/vnd.jupyter.widget-state+json"> </script> <script type="application/vnd.jupyter.widget-view+json"> {widget_views[0]} </script> """ data = embed_data(views=[self]) manager_state = json.dumps(data['manager_state']) widget_views = [json.dumps(view) for view in data['view_specs']] rendered_template = html_template.format(manager_state=manager_state, widget_views=widget_views) return rendered_template
def generate_static_html_output(output_dir, slicing_columns): result = tfma.load_eval_result(output_path=output_dir) slicing_metrics_views = [ tfma.view.render_slicing_metrics(result, slicing_column=slicing_column) for slicing_column in slicing_columns ] data = embed_data(views=slicing_metrics_views) manager_state = json.dumps(data['manager_state']) widget_views = [json.dumps(view) for view in data['view_specs']] views_html = "" for idx, view in enumerate(widget_views): views_html += _SINGLE_WIDGET_TEMPLATE.format(idx, view) rendered_template = _STATIC_HTML_TEMPLATE.format( manager_state=manager_state, widget_views=views_html) static_html_path = os.path.join(output_dir, _OUTPUT_HTML_FILE) file_io.write_string_to_file(static_html_path, rendered_template) metadata = { 'outputs' : [{ 'type': 'web-app', 'storage': 'gcs', 'source': static_html_path, }] } with file_io.FileIO('/mlpipeline-ui-metadata.json', 'w') as f: json.dump(metadata, f)
def test_embed_data_two_widgets(self): feature_track = pileup.Track( viz="features", label="myFeatures", source=pileup.sources.GA4GHFeatureJson('{}')) variant_track = pileup.Track( viz="variants", label="myVariants", source=pileup.sources.GA4GHVariantJson('{}')) w1 = pileup.PileupViewer(chrom="chr17", start=1, stop=250, reference="hg19", tracks=[feature_track]) w2 = pileup.PileupViewer(chrom="chr17", start=1, stop=250, reference="hg19", tracks=[variant_track]) jslink((w1, 'reference'), (w2, 'reference')) state = dependency_state([w1, w2], drop_defaults=True) data = embed_data(views=[w1, w2], drop_defaults=True, state=state) state = data['manager_state']['state'] views = data['view_specs'] assert len(views) == 2 model_names = [s['model_name'] for s in state.values()] widget_names = list( filter(lambda x: x == 'PileupViewerModel', model_names)) assert len(widget_names) == 2
def index(): interact = widgets.expected_damage('Darthur') sliders = interact.widget.children data = embed_data(sliders) figs = get_figures() manager_state = json.dumps(data['manager_state']) widget_views = [json.dumps(view) for view in data['view_specs']] return render_template('index.html', sha=git_repo.sha, matplot=mpld3.fig_to_html(figs[0]), manager_state=manager_state, widget_views=widget_views)
def test_embed_variants(self): w = pileup.Variants(json="{}", build='hg19', contig='chr1', start=1, stop=20) state = dependency_state(w, drop_defaults=True) data = embed_data(views=w, drop_defaults=True, state=state) state = data['manager_state']['state'] views = data['view_specs'] assert len(views) == 1 model_names = [s['model_name'] for s in state.values()] assert 'VariantModel' in model_names
def test_embed_pileup(self): track = pileup.Track(viz="features", label="myFeatures", source=pileup.sources.GA4GHFeatureJson('{}')) w = pileup.PileupViewer(locus="chr17:1-250", reference="hg19", tracks=[track]) state = dependency_state(w, drop_defaults=True) data = embed_data(views=w, drop_defaults=True, state=state) state = data['manager_state']['state'] views = data['view_specs'] assert len(views) == 1 model_names = [s['model_name'] for s in state.values()] assert 'PileupViewerModel' in model_names
def main(): if not os.path.exists('repos_info'): os.mkdir('repos_info') org = 'klaytn' repo = 'klaytn' com_rel_df, issues_df = utils.read_all_history_from_files(org, repo) if com_rel_df is None or issues_df is None: history = repo_parsing.get_all(org, repo) utils.write_all_history_to_files(org, repo, history) com_rel_df, issues_df = utils.read_all_history_from_files(org, repo) fig, sliders = plots.plot_with_slider( { 'commits': plots.commits(com_rel_df, for_sliders=True), 'releases': plots.releases( com_rel_df, yaxis='y2', for_sliders=True), }, org, repo, show=False) output = widgets.Output() display(output) controls = widgets.VBox(sliders) data = embed_data(views=sliders) manager_state = json.dumps(data['manager_state'], default=str) widget_views = [json.dumps(view) for view in data['view_specs']] rendered_template = html_template.format(manager_state=manager_state, widget_views=widget_views) with open(r'interactivity\rendered_template.html', 'w') as file: file.write(rendered_template) fig_json = fig.to_json() with open(r'interactivity\fig_JSON.txt', 'w') as file: file.write(json.dumps(fig_json, indent=4)) fig.write_html(r'interactivity\fig_html_full', full_html=True) fig.write_html(r'interactivity\fig_html') with output: display(controls, fig)
def test_embed_data_two_widgets(self): w1 = pileup.Variants(json="{}", build='hg19', contig='chr1', start=1, stop=20) w2 = pileup.Features(json="{}", build='hg19', contig='chr1', start=1, stop=20) jslink((w1, 'start'), (w2, 'start')) state = dependency_state([w1, w2], drop_defaults=True) data = embed_data(views=[w1, w2], drop_defaults=True, state=state) state = data['manager_state']['state'] views = data['view_specs'] assert len(views) == 2 model_names = [s['model_name'] for s in state.values()] assert 'VariantModel' in model_names assert 'FeatureModel' in model_names
def save_as_html(self, filename: str = "export.html") -> None: """ Save dataframe widget as static HTML file Parameters ---------- filename : str Filename for the output HTML file """ if self.widget is None: self.maintain_metadata() self.maintain_recs() from ipywidgets.embed import embed_data data = embed_data(views=[self.widget]) import json manager_state = json.dumps(data["manager_state"]) widget_view = json.dumps(data["view_specs"][0]) # Separate out header since CSS file conflict with {} notation in Python format strings header = """ <head> <title>Lux Widget</title> <link rel="lux" type="image/png" sizes="96x96" href="https://github.com/lux-org/lux-resources/blob/master/logo/favicon-96x96.png?raw=True"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous"> <!-- Load RequireJS, used by the IPywidgets for dependency management --> <script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" crossorigin="anonymous"> </script> <!-- Load IPywidgets bundle for embedding. --> <script src="https://unpkg.com/@jupyter-widgets/html-manager@^0.18.0/dist/embed-amd.js" crossorigin="anonymous"> </script> <style type="text/css"> #intentBtn, #warnBtn, #exportBtn{ display: none; } #deleteBtn { right: 10px !important; } #footer-description{ margin: 10px; text-align: right; } </style> </head> """ html_template = """ <html> {header} <body> <script type="application/vnd.jupyter.widget-state+json"> {manager_state} </script> <script type="application/vnd.jupyter.widget-view+json"> {widget_view} </script> <div id="footer-description"> These visualizations were generated by <a href="https://github.com/lux-org/lux/"><img src="https://raw.githubusercontent.com/lux-org/lux-resources/master/logo/logo.png" width="65px" style="vertical-align: middle;"></img></a> </div> </body> </html> """ manager_state = json.dumps(data["manager_state"]) widget_view = json.dumps(data["view_specs"][0]) rendered_template = html_template.format(header=header, manager_state=manager_state, widget_view=widget_view) with open(filename, "w") as fp: fp.write(rendered_template) print(f"Saved HTML to {filename}")
import json from ipywidgets import IntSlider from ipywidgets.embed import embed_data s1 = IntSlider(max=200, value=100) s2 = IntSlider(value=40) data = embed_data(views=[s1, s2]) html_template = """ <html> <head> <title>Widget export</title> <!-- Load RequireJS, used by the IPywidgets for dependency management --> <script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" crossorigin="anonymous"> </script> <!-- Load IPywidgets bundle for embedding. --> <script data-jupyter-widgets-cdn="https://unpkg.com/" data-jupyter-widgets-cdn-only src="https://cdn.jsdelivr.net/npm/@jupyter-widgets/html-manager@*/dist/embed-amd.js" crossorigin="anonymous"> </script> <!-- The state of all the widget models on the page -->
def test(): s1 = IntSlider(max=200, value=100) s2 = IntSlider(value=40) data = embed_data(views=[s1, s2]) html_template = """ <html> <head> <title>Widget export</title> <!-- Load RequireJS, used by the IPywidgets for dependency management --> <script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" crossorigin="anonymous"> </script> <!-- Load IPywidgets bundle for embedding. --> <script data-jupyter-widgets-cdn="https://cdn.jsdelivr.net/npm/" src="https://unpkg.com/@jupyter-widgets/html-manager@*/dist/embed-amd.js" crossorigin="anonymous"> </script> <!-- The state of all the widget models on the page --> <script type="application/vnd.jupyter.widget-state+json"> {manager_state} </script> </head> <body> <h1>Widget export</h1> <div id="first-slider-widget"> <!-- This script tag will be replaced by the view's DOM tree --> <script type="application/vnd.jupyter.widget-view+json"> {widget_views[0]} </script> </div> <hrule /> <div id="second-slider-widget"> <!-- This script tag will be replaced by the view's DOM tree --> <script type="application/vnd.jupyter.widget-view+json"> {widget_views[1]} </script> </div> </body> </html> """ manager_state = json.dumps(data['manager_state']) widget_views = [json.dumps(view) for view in data['view_specs']] rendered_template = html_template.format(manager_state=manager_state, widget_views=widget_views) return rendered_template
def create_2DgraphXXX(): img_width = 65000 img_height = 36000 id = 200 urlModel = UrlModel.objects.get(pk=id) df = urlModel.points df.reset_index(inplace=True) df['ID'] = df.index cols = ['ID', 'Layer', 'X', 'Y', 'Section'] section = df['Section'].min() fig = go.FigureWidget([go.Scatter(y=df['Y'], x=df['X'], mode='markers')]) fig.add_layout_image( dict( x=0, sizex=img_width, y=0, sizey=img_height, xref="x", yref="y", yanchor="top", opacity=0.5, layer="below", name="showme", source=f"https://activebrainatlas.ucsd.edu/data/DK52/www/{section}.png", sizing="contain") ) fig.update_layout(margin=dict(l=0, r=0, b=0, t=0)) fig.update_xaxes(range=[0, img_width]) fig.update_yaxes(range=[0, img_height], scaleanchor="x") fig.update_layout(template="plotly_white") fig['layout']['yaxis']['autorange'] = "reversed" scatter = fig.data[0] scatter.marker.opacity = 1 scatter.marker.size = 6 section_selector = widgets.Dropdown( options=list(df['Section'].sort_values().unique()), value=df['Section'].iloc[0], description='Section:', ) layer_selector = widgets.Dropdown( options=list(df['Layer'].sort_values().unique()), value=df['Layer'].iloc[0], description='Layer:', ) def response(change): filter_list = [s and l for s, l in zip(df['Section'] == section_selector.value, df['Layer'] == layer_selector.value)] tmp_df = df[filter_list] x = tmp_df['X'] y = tmp_df['Y'] with fig.batch_update(): fig.layout.xaxis.title = "X" fig.layout.yaxis.title = "Y" fig.layout.images[0].source = f"https://activebrainatlas.ucsd.edu/data/DK52/www/{section_selector.value}.png" scatter.x = x scatter.y = y with t.batch_update(): t.layout.title = f"{len(tmp_df)} points" t.data[0].cells.values = None section_selector.observe(response, names="value") layer_selector.observe(response, names="value") t = go.FigureWidget([go.Table(header=dict(), cells=dict())]) def selection_fn(trace, points, selector): t.layout.title = f"You have selected {len(points.point_inds)} points" scatter.on_selection(selection_fn) selection_container = widgets.HBox([section_selector, layer_selector]) figure_container = widgets.VBox([fig, t]) return embed_data(views=[figure_container])