Ejemplo n.º 1
0
    def _figure_data(self, plot, fmt='html', doc=None, **kwargs):
        model = plot.state
        if doc is None:
            doc = plot.document
        else:
            plot.document = doc

        for m in model.references():
            m._document = None

        doc.theme = self.theme
        doc.add_root(model)

        comm_id = plot.comm.id if plot.comm else None
        # Bokeh raises warnings about duplicate tools and empty subplots
        # but at the holoviews level these are not issues
        logger = logging.getLogger(bokeh.core.validation.check.__file__)
        logger.disabled = True
        try:
            js, div, _ = notebook_content(model, comm_id)
            html = NOTEBOOK_DIV.format(plot_script=js, plot_div=div)
            div = encode_utf8(html)
            doc.hold()
        except:
            logger.disabled = False
            raise
        logger.disabled = False
        plot.document = doc
        return div
Ejemplo n.º 2
0
def _fig_repr_html(self):
    """ Figure can display itself """
    from bokeh.io.notebook import load_notebook
    from bokeh.embed.notebook import notebook_content

    load_notebook(hide_banner=True)
    (script, div, cell_doc) = notebook_content(self)
    return f'{div}<script>{script}</script>'
Ejemplo n.º 3
0
    def _figure_data(self,
                     plot,
                     fmt='html',
                     doc=None,
                     as_script=False,
                     **kwargs):
        """
        Given a plot instance, an output format and an optional bokeh
        document, return the corresponding data. If as_script is True,
        the content will be split in an HTML and a JS component.
        """
        model = plot.state
        if doc is None:
            doc = plot.document
        else:
            plot.document = doc

        for m in model.references():
            m._document = None

        doc.theme = self.theme
        doc.add_root(model)

        # Bokeh raises warnings about duplicate tools and empty subplots
        # but at the holoviews level these are not issues
        logger = logging.getLogger(bokeh.core.validation.check.__file__)
        logger.disabled = True

        if fmt == 'png':
            from bokeh.io.export import get_screenshot_as_png
            img = get_screenshot_as_png(plot.state, None)
            imgByteArr = BytesIO()
            img.save(imgByteArr, format='PNG')
            data = imgByteArr.getvalue()
            if as_script:
                b64 = base64.b64encode(data).decode("utf-8")
                (mime_type, tag) = MIME_TYPES[fmt], HTML_TAGS[fmt]
                src = HTML_TAGS['base64'].format(mime_type=mime_type, b64=b64)
                div = tag.format(src=src, mime_type=mime_type, css='')
                js = ''
        else:
            try:
                with silence_warnings(EMPTY_LAYOUT, MISSING_RENDERERS):
                    js, div, _ = notebook_content(model)
                html = NOTEBOOK_DIV.format(plot_script=js, plot_div=div)
                data = encode_utf8(html)
                doc.hold()
            except:
                logger.disabled = False
                raise
            logger.disabled = False

        plot.document = doc
        if as_script:
            return div, js
        return data
Ejemplo n.º 4
0
def _show_zeppelin_doc_with_state(obj, state, notebook_handle):
    if notebook_handle:
        raise ValueError("Zeppelin doesn't support notebook_handle.")
    if _isAfterBokeh1210:
        (script, div, cell_doc) = notebook_content(obj)
        print("%html " + div)
        print('%html ' + '<script type="text/javascript">' + script + "</script>")
    else:
        print("%html " + notebook_div(obj))

    return None
Ejemplo n.º 5
0
    def test_notebook_content(self, mock_sdjari, test_plot):
        (docs_json, render_items) = ("DOC_JSON", [dict(docid="foo", elementid="bar", modelid="bat")])
        mock_sdjari.return_value = (docs_json, render_items)

        expected_script = DOC_NB_JS.render(docs_json=serialize_json(docs_json),
                                        render_items=serialize_json(render_items))
        expected_div = PLOT_DIV.render(elementid=render_items[0]['elementid'])

        (script, div, _) = ben.notebook_content(test_plot)

        assert script == expected_script
        assert div == expected_div
Ejemplo n.º 6
0
    def _figure_data(self, plot, fmt='html', doc=None, as_script=False, **kwargs):
        """
        Given a plot instance, an output format and an optional bokeh
        document, return the corresponding data. If as_script is True,
        the content will be split in an HTML and a JS component.
        """
        model = plot.state
        if doc is None:
            doc = plot.document
        else:
            plot.document = doc

        for m in model.references():
            m._document = None

        doc.theme = self.theme
        doc.add_root(model)

        # Bokeh raises warnings about duplicate tools and empty subplots
        # but at the holoviews level these are not issues
        logger = logging.getLogger(bokeh.core.validation.check.__file__)
        logger.disabled = True

        if fmt == 'png':
            from bokeh.io.export import get_screenshot_as_png
            img = get_screenshot_as_png(plot.state, None)
            imgByteArr = BytesIO()
            img.save(imgByteArr, format='PNG')
            data = imgByteArr.getvalue()
            if as_script:
                b64 = base64.b64encode(data).decode("utf-8")
                (mime_type, tag) = MIME_TYPES[fmt], HTML_TAGS[fmt]
                src = HTML_TAGS['base64'].format(mime_type=mime_type, b64=b64)
                div = tag.format(src=src, mime_type=mime_type, css='')
                js = ''
        else:
            try:
                js, div, _ = notebook_content(model)
                html = NOTEBOOK_DIV.format(plot_script=js, plot_div=div)
                data = encode_utf8(html)
                doc.hold()
            except:
                logger.disabled = False
                raise
            logger.disabled = False

        plot.document = doc
        if as_script:
            return div, js
        return data
Ejemplo n.º 7
0
    def test_notebook_content_with_notebook_comms_target(self, mock_sdjari, test_plot):
        (docs_json, render_items) = ("DOC_JSON", [dict(docid="foo", elementid="bar", modelid="bat")])
        mock_sdjari.return_value = (docs_json, render_items)
        comms_target = "NOTEBOOK_COMMS_TARGET"

        ## assert that NOTEBOOK_COMMS_TARGET is added to render_items bundle
        assert 'notebook_comms_target' not in render_items[0]
        (script, _, _) = ben.notebook_content(test_plot, notebook_comms_target=comms_target)
        assert 'notebook_comms_target' in render_items[0]

        ## assert that NOTEBOOK_COMMS_TARGET ends up in generated script
        expected_script = DOC_NB_JS.render(docs_json=serialize_json(docs_json),
                                        render_items=serialize_json(render_items))

        assert script == expected_script
Ejemplo n.º 8
0
    def test_notebook_content(self, mock_sdjari, test_plot):
        (docs_json,
         render_items) = ("DOC_JSON",
                          [dict(docid="foo", elementid="bar", modelid="bat")])
        mock_sdjari.return_value = (docs_json, render_items)

        expected_script = DOC_NB_JS.render(
            docs_json=serialize_json(docs_json),
            render_items=serialize_json(render_items))
        expected_div = PLOT_DIV.render(elementid=render_items[0]['elementid'])

        (script, div, _) = ben.notebook_content(test_plot)

        assert script == expected_script
        assert div == expected_div
Ejemplo n.º 9
0
    def _figure_data(self,
                     plot,
                     fmt='html',
                     doc=None,
                     as_script=False,
                     **kwargs):
        """
        Given a plot instance, an output format and an optional bokeh
        document, return the corresponding data. If as_script is True,
        the content will be split in an HTML and a JS component.
        """
        model = plot.state
        if doc is None:
            doc = plot.document
        else:
            plot.document = doc

        for m in model.references():
            m._document = None

        doc.theme = self.theme
        doc.add_root(model)

        comm_id = plot.comm.id if plot.comm else None
        # Bokeh raises warnings about duplicate tools and empty subplots
        # but at the holoviews level these are not issues
        logger = logging.getLogger(bokeh.core.validation.check.__file__)
        logger.disabled = True
        try:
            js, div, _ = notebook_content(model, comm_id)
            html = NOTEBOOK_DIV.format(plot_script=js, plot_div=div)
            html = encode_utf8(html)
            doc.hold()
        except:
            logger.disabled = False
            raise
        logger.disabled = False
        plot.document = doc
        if as_script:
            return div, js
        return html
Ejemplo n.º 10
0
    def test_notebook_content_with_notebook_comms_target(
            self, mock_sdjari, test_plot):
        (docs_json,
         render_items) = ("DOC_JSON",
                          [dict(docid="foo", elementid="bar", modelid="bat")])
        mock_sdjari.return_value = (docs_json, render_items)
        comms_target = "NOTEBOOK_COMMS_TARGET"

        ## assert that NOTEBOOK_COMMS_TARGET is added to render_items bundle
        assert 'notebook_comms_target' not in render_items[0]
        (script, _,
         _) = ben.notebook_content(test_plot,
                                   notebook_comms_target=comms_target)
        assert 'notebook_comms_target' in render_items[0]

        ## assert that NOTEBOOK_COMMS_TARGET ends up in generated script
        expected_script = DOC_NB_JS.render(
            docs_json=serialize_json(docs_json),
            render_items=serialize_json(render_items))

        assert script == expected_script
Ejemplo n.º 11
0
def bokeh_notebook_div(image):
    """"
    Generates an HTML div to embed in the notebook.

    Parameters
    ----------
    image: InteractiveImage
        InteractiveImage instance with a plot

    Returns
    -------
    div: str
        HTML string containing the bokeh plot to be displayed
    """
    if bokeh_version > "0.12.9":
        js, div, _ = notebook_content(image.p, image.ref)
        div = NOTEBOOK_DIV.format(plot_script=js, plot_div=div)
        # Ensure events are held until an update is triggered
        image.doc.hold()
    else:
        div = notebook_div(image.p, image.ref)
    return div
Ejemplo n.º 12
0
def bokeh_notebook_div(image):
    """"
    Generates an HTML div to embed in the notebook.

    Parameters
    ----------
    image: InteractiveImage
        InteractiveImage instance with a plot

    Returns
    -------
    div: str
        HTML string containing the bokeh plot to be displayed
    """
    if bokeh_version > '0.12.9':
        js, div, _ = notebook_content(image.p, image.ref)
        html = NOTEBOOK_DIV.format(plot_script=js, plot_div=div)
        div = encode_utf8(html)
        # Ensure events are held until an update is triggered
        image.doc.hold() 
    else:
        div = notebook_div(image.p, image.ref)
    return div
Ejemplo n.º 13
0
    def _repr_html_(self) -> str:
        """
        Display itself inside a notebook
        """
        # Speical case inside Google Colab
        if "google.colab" in sys.modules:
            load_notebook(hide_banner=True)
            script, div, _ = notebook_content(self.to_render)
            return f"{div}<script>{script}</script>"

        # Windows forbids us open the file twice as the result bokeh cannot
        # write to the opened temporary file.
        with NamedTemporaryFile(suffix=".html", delete=False) as tmpf:
            pass

        save(
            self.to_render,
            filename=tmpf.name,
            resources=CDN,
            template=INLINE_TEMPLATE,
            title="DataPrep.EDA Report",
        )
        with open(tmpf.name, "r") as f:
            output_html = f.read()

        # Delete the temporary file
        Path(tmpf.name).unlink()

        # Fix the bokeh: bokeh wrongly call the "waiting for bokeh to load" function
        # inside "Bokeh.safely", which causes Bokeh not found because
        # Bokeh is even not loaded!
        patched_html = output_html.replace(
            "Bokeh.safely",
            "var __dataprep_bokeh_fix = (f) => document.Bokeh === undefined ? setTimeout(f, 1000) : f(); __dataprep_bokeh_fix",  # pylint: disable=line-too-long
        )
        # embed into report template created by us here
        return patched_html
Ejemplo n.º 14
0
def _report_repr_html_(self):
    from bokeh.io.notebook import load_notebook
    from bokeh.embed.notebook import notebook_content
    load_notebook(hide_banner=True)
    script, div, _ = notebook_content(self.to_render)
    return f'{div}<script>{script}</script>'