def resources(self, absolute_url=None): if absolute_url: return Resources(mode="server", root_url=absolute_url + self._prefix, path_versioner=StaticHandler.append_version) return Resources(mode="server", root_url=self._prefix, path_versioner=StaticHandler.append_version)
def table(): """ bk table app """ _js_resources = Resources(mode="cdn", log_level='trace').render_js() _css_resources = Resources(mode="cdn", log_level='trace').render_css() table_app = server_document(FLASK_URL + '/bkapp-table', resources=None) return render_template("embed.html", js_resources=_js_resources, css_resources=_css_resources, table=table_app)
def models(): """ models page """ _js_resources = Resources(mode="cdn", log_level='trace').render_js() _css_resources = Resources(mode="cdn", log_level='trace').render_css() _models = server_document(FLASK_URL + '/bkapp-models', resources=None) return render_template("embed.html", js_resources=_js_resources, css_resources=_css_resources, models=_models)
def resources(self, absolute_url: Optional[str] = None) -> Resources: mode = settings.resources(default="server") if mode == "server": root_url = urljoin(absolute_url, self._prefix) if absolute_url else self._prefix return Resources(mode="server", root_url=root_url, path_versioner=StaticHandler.append_version) return Resources(mode=mode)
def test_invalid_resources(self): self.assertRaises(ValueError, embed.autoload_static, _embed_test_plot, INLINE, "some/path") dev_resources = (Resources("absolute-dev"), Resources("server-dev"), Resources("relative-dev")) for x in dev_resources: self.assertRaises(ValueError, embed.autoload_static, _embed_test_plot, x, "some/path")
def red(): """ bk red app """ _js_resources = Resources(mode="cdn", log_level='trace').render_js() _css_resources = Resources(mode="cdn", log_level='trace').render_css() red_app = server_document(FLASK_URL + '/bkapp-red', resources=None) return render_template("embed.html", js_resources=_js_resources, css_resources=_css_resources, red=red_app)
def histograms(): """ histograms page """ _js_resources = Resources(mode="cdn", log_level='info').render_js() _css_resources = Resources(mode="cdn", log_level='info').render_css() _histograms = server_document(FLASK_URL + '/bkapp-histograms', resources=None) return render_template("embed.html", js_resources=_js_resources, css_resources=_css_resources, histograms=_histograms)
def _generate_html(self): """ Generate the HTML for the specified graphs. :return: :rtype: """ logger.debug('Generating templated HTML') env = Environment(loader=PackageLoader('pypi_download_stats', 'templates'), extensions=['jinja2.ext.loopcontrols']) env.filters['format_date_long'] = filter_format_date_long env.filters['format_date_ymd'] = filter_format_date_ymd env.filters['data_columns'] = filter_data_columns template = env.get_template('base.html') logger.debug('Rendering template') html = template.render(project=self.project_name, cache_date=self._stats.as_of_datetime, user=getuser(), host=platform_node(), version=VERSION, proj_url=PROJECT_URL, graphs=self._graphs, graph_keys=self.GRAPH_KEYS, resources=Resources(mode='inline').render(), badges=self._badges) logger.debug('Template rendered') return html
def embedPlot_old(plot): """Embed plot method for older versions of bokeh""" from bokeh.resources import Resources from bokeh.embed import autoload_static fp = os.path.join(request.folder,'static/temp/') fp = os.path.join(fp, plot._id+".js") res = Resources("relative") res.js_files = ["../static/js/bokeh.min.js"] res.css_files = ["../static/css/bokeh.min.css"] jspath = os.path.join('../static/temp/', plot._id+".js") js,tag = autoload_static(plot, res, jspath) with open(fp, "w") as f: f.write(js) print return js,tag
def _plot_loss_and_acc(loss_train, loss_dev, acc_train, acc_dev, model_name, loss=True, acc=True): header = "loss" if loss else "acc" header = "loss and accuracy" if (loss and acc) else header if "fig" not in os.listdir(os.path.join("..")): os.mkdir(os.path.join("..", "fig")) p = figure(plot_width=600, plot_height=250, title="SNLI - Train/Dev " + header, x_axis_label="epochs", y_axis_label=header) if loss: x1, y1 = get_x_y_axis(loss_train) x2, y2 = get_x_y_axis(loss_dev) p.line(x1, y1, line_color='red', legend="loss Train") p.line(x2, y2, line_color='orange', legend="loss Dev") if acc: x3, y3 = get_x_y_axis(acc_train) x4, y4 = get_x_y_axis(acc_dev) p.line(x3, y3, line_color='green', legend="accuracy Train") p.line(x4, y4, line_color='blue', legend="accuracy Dev") p.legend.background_fill_alpha = 0.5 save(p, os.path.join("..", "fig", model_name + " " + header + ".html"), title=model_name + " " + header + ".html", resources=Resources(mode="inline"))
def _plot_loss_and_acc(train_line, dev_line, header, file_name, color_train='red', color_dev='orange', legend=""): if "fig" not in os.listdir(os.path.join("..")): os.mkdir(os.path.join("..", "fig")) p = figure(plot_width=600, plot_height=250, title="RE - Train/Dev " + header, x_axis_label="epochs", y_axis_label=header) x1, y1 = get_x_y_axis(train_line) x2, y2 = get_x_y_axis(dev_line) p.line(x1, y1, line_color=color_train, legend=legend + " Train") p.line(x2, y2, line_color=color_dev, legend=legend + " Dev") p.legend.background_fill_alpha = 0.5 save(p, os.path.join("..", "fig", file_name + ".html"), title=header + ".html", resources=Resources(mode="inline"))
def test_with_args(self, mock_run_notebook_hook): load_jupyter_args = (Resources(), True, True, 1000) bio.output_notebook(*load_jupyter_args) assert mock_run_notebook_hook.call_count == 1 assert mock_run_notebook_hook.call_args[0] == ( "jupyter", "load") + load_jupyter_args assert mock_run_notebook_hook.call_args[1] == {}
def resources(self, request): root_url = self.root_url_for_request(request) if root_url not in self._resources: self._resources[root_url] = Resources(mode="server", root_url=root_url, path_versioner=StaticHandler.append_version) return self._resources[root_url]
def newapplet(): theme = request.args.get('theme', 'default') INLINE = Resources( mode="inline", minified=False, ) templname = "stocks_custom.html" plot_resources = RESOURCES.render( js_raw=INLINE.js_raw, css_raw=INLINE.css_raw, js_files=INLINE.js_files, css_files=INLINE.css_files, ) p = create_main_plot(theme) plot_script, extra_divs = components({ "main_plot": p, "selection_plot": create_selection_plot(p, theme), }) themes = ["default", "dark"] options = {k: 'selected="selected"' if theme == k else "" for k in themes} return render_template( templname, theme=theme, extra_divs=extra_divs, plot_script=plot_script, plot_resources=plot_resources, theme_options=options, )
def test_get_screenshot_as_png_with_unicode_unminified(webdriver) -> None: p = figure(title="유니 코드 지원을위한 작은 테스트") with silenced(MISSING_RENDERERS): png = bie.get_screenshot_as_png(p, driver=webdriver, resources=Resources(mode="inline", minified=False)) assert len(png.tobytes()) > 0
def test_zeppelin_with_notebook_handle(self): load_zeppelin_args = (Resources(), True, True, 1000, 'zeppelin') io.output_notebook(*load_zeppelin_args) with pytest.raises(Exception) as ex: p = Plot() io.show(p, notebook_handle=True) assert "Zeppelin doesn't support notebook_handle." == str(ex.value)
def newplot(user_id, data_id): theme = request.args.get('theme', 'default') CDN = Resources( mode="cdn", minified=True, ) templname = "plot.html" js_resources = JS_RESOURCES.render(js_raw=CDN.js_raw, js_files=CDN.js_files) css_resources = CSS_RESOURCES.render(css_raw=CDN.css_raw, css_files=CDN.css_files) tz = request.args.get("tz", None) source = get_data_source(user_id, data_id, tz) #ajax_source = get_ajax_latest_source(user_id, data_id) p = plot.create_main_plot(theme, source) plot_script, extra_divs = components({ "main_plot": p, }) themes = ["default", "dark"] options = {k: 'selected="selected"' if theme == k else "" for k in themes} return render_template( templname, theme=theme, extra_divs=extra_divs, plot_script=plot_script, js_resources=js_resources, css_resources=css_resources, theme_options=options, )
def index(): """ histograms page """ _js_resources = Resources(mode="cdn", log_level='info').render_js() _css_resources = Resources(mode="cdn", log_level='info').render_css() _histograms = server_document(FLASK_URL + '/bkapp-histograms', resources=None) _models = server_document(FLASK_URL + '/bkapp-models', resources=None) _maps = server_document(FLASK_URL + '/bkapp-maps', resources=None) _trends = server_document(FLASK_URL + '/bkapp-trends', resources=None) return render_template("embed.html", js_resources=_js_resources, css_resources=_css_resources, maps=_maps, trends=_trends, histograms=_histograms, models=_models)
def wrapper(*args, **kwargs): ## setup the randomly titled document docname = prefix + str(uuid.uuid4()) bokehuser = bokeh_app.current_user() try: doc = _makedoc(bokeh_app.servermodel_storage, bokehuser, docname) except DataIntegrityException as e: return abort(409, e.message) docid = doc.docid clientdoc = bokeh_app.backbone_storage.get_document(docid) ## initialize our plotting APIs to use that document init_bokeh(clientdoc) obj = func(*args, **kwargs) clientdoc.add(obj) bokeh_app.backbone_storage.store_document(clientdoc) if hasattr(obj, 'extra_generated_classes'): extra_generated_classes = obj.extra_generated_classes else: extra_generated_classes = [] resources = Resources() return render_template("oneobj.html", elementid=str(uuid.uuid4()), docid=docid, objid=obj._id, hide_navbar=True, extra_generated_classes=extra_generated_classes, splitjs=bokeh_app.splitjs, username=bokehuser.username, loglevel=resources.log_level)
def test_get_screenshot_as_png_with_unicode_unminified(webdriver): layout = Div(text="유니 코드 지원을위한 작은 테스트") png = bie.get_screenshot_as_png(layout, driver=webdriver, resources=Resources(mode="inline", minified=False)) assert len(png.tobytes()) > 0
def test_args(self, mock_load_notebook): # call _install_notebook_hook to register the patched `bokeh.io.load_notebook` from bokeh.io import _install_notebook_hook _install_notebook_hook() load_jupyter_args = (Resources(), True, True, 1000) io.output_notebook(*load_jupyter_args) self._check_func_called(io._state.output_notebook, ('jupyter',), {}) self._check_func_called(mock_load_notebook, load_jupyter_args, {'notebook_type': 'jupyter'})
def test_get_screenshot_as_png_with_unicode_minified(webdriver): p = figure(title="유니 코드 지원을위한 작은 테스트") png = bie.get_screenshot_as_png(p, driver=webdriver, resources=Resources(mode="inline", minified=True)) assert len(png.tobytes()) > 0
def request_resources(): """Creates resources instance based on url info from current app/request context """ if bokeh_app.url_prefix: # strip of leading slash root_url = request.url_root + bokeh_app.url_prefix[1:] else: root_url = request.url_root resources = Resources(root_url=root_url, mode='server') return resources
def test_static_path_in_holoviews_save(tmpdir): import holoviews as hv hv.Store.set_current_backend('bokeh') plot = hv.Curve(np.random.seed(42)) res = Resources(mode='server', root_url='/') out_file = Path(tmpdir) / 'plot.html' hv.save(plot, out_file, resources=res) content = out_file.read_text() assert 'src="/static/js/bokeh' in content and 'src="static/js/bokeh' not in content assert 'href="/static/extensions/panel/css/' in content and 'href="static/extensions/panel/css/' not in content
def simple_plot(plot, tmp_dir): js_static_js = "static-flask-bokeh/js/" js_static_css = "static-flask-bokeh/css/" js_filename = plot._id + ".js" js_path = tmp_dir + js_filename res = Resources() res.mode = "server" res.js_files = [js_static_js + "bokeh-0.4.min.js"] res.css_files = [js_static_css + "bokeh-0.4.min.css"] js, tag = autoload_static(plot, res, js_path) with open(js_path, "w") as f: f.write(js) print("Path: %s" % js_path) print("Wrote %s" % js_filename) return tag, plot._id
def make_snippet(plot): # js_static_js = "static/js/" js_static_js = "/usr/lib/python3.4/site-packages/bokeh/server/static/js/" # js_static_css = "static/css/" js_static_css = "/usr/lib/python3.4/site-packages/bokeh/server/static/css/" # js_filename = plot._id + ".js" # js_path = js_static_js + js_filename js_path = "output.js" res = Resources("relative") res.js_files = [js_static_js + "bokeh.min.js"] res.css_files = [js_static_css + "bokeh.min.css"] js, tag = autoload_static(plot, res, js_path) with open(js_path, "w") as f: f.write(js) print("Wrote %s" % js_path) return tag, plot._id
def test_get_screenshot_as_png_with_unicode_unminified(): layout = Div(text="유니 코드 지원을위한 작은 테스트") driver = create_webdriver() try: png = bie.get_screenshot_as_png(layout, driver=driver, resources=Resources(mode="inline", minified=False)) finally: # Have to manually clean up the driver session terminate_webdriver(driver) assert len(png.tobytes()) > 0
def get_sphinx_resources(include_bokehjs_api=False): docs_cdn = settings.docs_cdn() # if BOKEH_DOCS_CDN is unset just use default CDN resources if docs_cdn is None: resources = Resources(mode="cdn") else: # "BOKEH_DOCS_CDN=local" is used for building and displaying the docs locally if docs_cdn == "local": resources = Resources(mode="server", root_url="/en/latest/") # "BOKEH_DOCS_CDN=test:newthing" is used for building and deploying test docs to # a one-off location "en/newthing" on the docs site elif docs_cdn.startswith("test:"): resources = Resources(mode="server", root_url="/en/%s/" % docs_cdn.split(":")[1]) # Otherwise assume it is a dev/rc/full release version and use CDN for it else: resources = Resources(mode="cdn", version=docs_cdn) if include_bokehjs_api: resources.js_components.append("bokeh-api") return resources
def set_display_settings(): """Enable notebook output settings if running in a jupyter notebook""" from IPython.core.getipython import get_ipython from ipykernel.zmqshell import ZMQInteractiveShell from bokeh.io import output_notebook from bokeh.resources import Resources ipython_instance = get_ipython() if ipython_instance is not None: if isinstance(ipython_instance, ZMQInteractiveShell): _IPYTHON_INSTANCE = True # Inline resources uses bokeh.js from the local version. # This enables offline usage. output_notebook(Resources('inline'))
async def handle(self, body): scope = self.scope session = await self._get_session() res = Resources(mode="server", root_url="/", path_versioner=StaticHandler.append_version) import threading page = server_html_page_for_session(session, resources=res, # title=session.document.title, title=str(session._id) + threading.current_thread().name, template=session.document.template, template_variables=session.document.template_variables) await self.send_response(200, page.encode(), headers=[ (b"Content-Type", b"text/html"), ])
def get_bubble_html(plot=None): if plot: layout = plot else: layout = _get_plot() with open('assets/bubble_template.html', 'r') as f: template = Template(f.read()) resources = Resources(mode='server', root_url='/tree/') bokeh_js = RESOURCES.render(js_files=resources.js_files) script, div = components(layout) html = template.render( title="Bokeh - Gapminder demo", bokeh_js=bokeh_js, plot_script=script, plot_div=div, ) return html
def page_desc(module_desc): module_path, name = module_desc['file'], module_desc['name'] var_name = module_desc.get('var_name', None) plotting._default_document = Document() namespace = {} with open(module_path, "r") as module_file: code = compile(module_file.read(), module_path, "exec") eval(code, namespace) if var_name: if 'chart' in module_desc['file']: obj = namespace[var_name] objs = [obj.chart.plot] else: objs = [namespace[var_name]] else: objs = plotting.curdoc().context.children embed_snippet = "" for i, obj in enumerate(objs): filename = name + "." + str(i) + ".js" js, tag = autoload_static( obj, Resources(mode="server", root_url=HOSTED_STATIC_ROOT), os.path.join(DETAIL_URL_ROOT, filename) ) embed_snippet += tag with open(os.path.join(SNIPPET_BUILD_DIR, filename), "w") as f: f.write(js) detail_snippet = highlight( open(module_path).read(), PythonLexer(), HtmlFormatter() ) return dict( name = name, embed_snippet = embed_snippet, detail_snippet = detail_snippet, detail_page_url = DETAIL_URL_ROOT + name + ".html", prev_detail_url = "", prev_detail_name = "", next_detail_url = "", next_detail_name ='', )