Beispiel #1
0
def test_set_logo(mock_reports):
    from onecodex.notebooks import report

    myurl = "file:///path/to/logo.png"
    mystyle = "text-align: center"
    obj = report.set_logo(myurl, style=mystyle)
    bundle = obj._repr_mimebundle_()

    assert len(bundle) == 1
    assert myurl in bundle["text/html"]
    assert mystyle in bundle["text/html"]
    assert "logo-left" in bundle["text/html"]
    ET.fromstring(bundle["text/html"])
    obj.display()

    report.set_logo(myurl, position="left")
    report.set_logo(myurl, position="right")
    report.set_logo(myurl, position="center")

    with pytest.raises(OneCodexException) as e:
        report.set_logo(myurl, position="bottom")
    assert "position must be one of" in str(e.value)
Beispiel #2
0
def test_set_logo(mock_reports):
    from onecodex.notebooks import report

    myurl = "file:///path/to/logo.png"
    mystyle = "text-align: center"
    obj = report.set_logo(myurl, style=mystyle)
    bundle = obj._repr_mimebundle_()

    assert len(bundle) == 1
    assert myurl in bundle["text/html"]
    assert mystyle in bundle["text/html"]
    assert "logo-left" in bundle["text/html"]
    ET.fromstring(bundle["text/html"])
    obj.display()

    report.set_logo(myurl, position="left")
    report.set_logo(myurl, position="right")
    report.set_logo(myurl, position="center")

    with pytest.raises(OneCodexException) as e:
        report.set_logo(myurl, position="bottom")
    assert "position must be one of" in str(e.value)
Beispiel #3
0
    def from_notebook_node(self, nb, resources=None, **kw):
        """Uses nbconvert's HTMLExporter to generate HTML, with slight modifications.

        Notes
        -----
        This exporter will only save cells generated with Altair/Vega if they have an SVG image type
        stored with them. This data is only stored if our fork of `ipyvega` is installed or the onecodex
        # renderer is used--otherwise, they will be low-resolution PNGs, which will not be exported.
        """
        nb = copy.deepcopy(nb)

        # setup our dictionary that's accessible from within jinja templates
        if resources is None:
            resources = {"metadata": {}}
        elif "metadata" not in resources:
            resources["metadata"] = {}

        # iterate over cells in the notebook and transform data as necessary
        do_not_insert_date = False

        # add one codex logo unless told not to
        if not os.environ.get("ONE_CODEX_REPORT_NO_LOGO", False):
            img = b64encode(
                bytes(open(os.path.join(ASSETS_PATH, "one_codex_logo.png"), "rb").read())
            ).decode()
            img = "data:image/png;charset=utf-8;base64,%s" % (img,)
            logo_html = report.set_logo(img, position="right")._repr_mimebundle_()["text/html"]
            head_block = resources["metadata"].get("head_block", "") + logo_html
            resources["metadata"]["head_block"] = head_block

        # add today's date unless told not to (i.e. a custom date was specified)
        if not do_not_insert_date:
            date_div = report.set_date()._repr_mimebundle_()[0]["text/html"]
            head_block = resources["metadata"].get("head_block", "") + date_div
            resources["metadata"]["head_block"] = head_block

        # add the report ID and not for diagnostic use footer
        report_info_div = '<div id="reportinfo">{}</div>'.format(
            "{} - NOT FOR DIAGNOSTIC USE".format(os.environ["ONE_CODEX_REPORT_UUID"])
            if os.environ.get("ONE_CODEX_REPORT_UUID")
            else "NOT FOR DIAGNOSTIC USE"
        )
        head_block = resources["metadata"].get("head_block", "") + report_info_div
        resources["metadata"]["head_block"] = head_block

        # embed the default CSS
        css = open(os.path.join(ASSETS_PATH, CSS_TEMPLATE_FILE), "r").read()
        css = '<style type="text/css">{}</style>'.format(css)
        head_block = resources["metadata"].get("head_block", "") + css
        resources["metadata"]["head_block"] = head_block

        # tag this report for traceability, if run from notebook service. these will be transferred
        # to PDF metadata if the HTML output of this function is used as input for PDF generation
        meta_tags = [("dcterms.created", datetime.datetime.now(pytz.utc).isoformat())]

        user_uuid = os.environ.get("ONE_CODEX_USER_UUID")
        if user_uuid is not None:
            meta_tags.append(("author", "one_codex_user_uuid_{}".format(user_uuid)))

        nb_uuid = os.environ.get("ONE_CODEX_NOTEBOOK_UUID")
        if nb_uuid is not None:
            meta_tags.append(("author", "one_codex_notebook_uuid_{}".format(nb_uuid)))

        meta_html = ""

        for meta_name, meta_val in meta_tags:
            meta_html += '<meta name="{}" content="{}" />\n'.format(meta_name, meta_val)

        head_block = resources["metadata"].get("head_block", "") + meta_html
        resources["metadata"]["head_block"] = head_block

        output, resources = super(OneCodexHTMLExporter, self).from_notebook_node(
            nb, resources=resources, **kw
        )

        return output, resources
Beispiel #4
0
    def from_notebook_node(self, nb, resources=None, **kw):
        """Uses nbconvert's HTMLExporter to generate HTML, with slight modifications.

        Notes
        -----
        This exporter will only save cells generated with Altair/Vega if they have an SVG image type
        stored with them. This data is only stored if our fork of `ipyvega` is installed or the onecodex
        # renderer is used--otherwise, they will be low-resolution PNGs, which will not be exported.
        """
        nb = copy.deepcopy(nb)

        # setup our dictionary that's accessible from within jinja templates
        if resources is None:
            resources = {"metadata": {}}
        elif "metadata" not in resources:
            resources["metadata"] = {}

        # iterate over cells in the notebook and transform data as necessary
        do_not_insert_date = False

        for cell in nb.cells:
            if cell["cell_type"] == "code":
                for out in cell["outputs"]:
                    # handle transforming images into a format Weasyprint can render. prefer SVGs
                    # over PNGs. SVGs must be base64 encoded, while PNGs come encoded already. drop
                    # other Vega output cells (like JavaScript)
                    if out.get("metadata") and out["metadata"].get(
                            "jupyter-vega"):
                        data = out.get("data", [])

                        if "image/svg+xml" in data:
                            img = b64encode(
                                bytes(data["image/svg+xml"],
                                      encoding="UTF-8")).decode()
                            out["data"] = {
                                "text/html":
                                '<img src="data:image/svg+xml;charset=utf-8;base64,{}">'
                                .format(img)
                            }
                        elif "image/png" in data:
                            out["data"] = {
                                "text/html":
                                '<img src="{}"'.format(data["image/png"])
                            }
                        elif "application/vnd.vegalite.v2+json" in data:
                            vega_svg = render_vega_with_node(
                                data["application/vnd.vegalite.v2+json"])

                            if vega_svg:
                                img = b64encode(vega_svg).decode()
                                out["data"] = {
                                    "text/html":
                                    '<img src="data:image/svg+xml;charset=utf-8;base64,{}">'
                                    .format(img)
                                }
                        else:
                            out["data"] = {}
                    # transfer text/css blocks to HTML <head> tag
                    elif out.get("metadata") and out["metadata"].get(
                            "onecodex") == "head.style":
                        for mimetype in out.get("data", []):
                            if mimetype == "text/css":
                                style_block = '<style type="text/css">{}</style>'.format(
                                    out["data"]["text/css"])
                                head_block = (resources["metadata"].get(
                                    "head_block", "") + style_block)
                                resources["metadata"][
                                    "head_block"] = head_block
                                break

                        # we don't want this to be output as text, so clear it
                        out["data"] = {"text/plain": ""}
                    # if there's a custom date specified, don't insert it
                    elif out.get("metadata") and out["metadata"].get(
                            "onecodex") == "customdate":
                        do_not_insert_date = True

        # add one codex logo unless told not to
        if not os.environ.get("ONE_CODEX_REPORT_NO_LOGO", False):
            img = b64encode(
                bytes(
                    open(os.path.join(ASSETS_PATH, "one_codex_logo.png"),
                         "rb").read())).decode()
            img = "data:image/png;charset=utf-8;base64,%s" % (img, )
            logo_html = report.set_logo(
                img, position="right")._repr_mimebundle_()["text/html"]
            head_block = resources["metadata"].get("head_block",
                                                   "") + logo_html
            resources["metadata"]["head_block"] = head_block

        # add today's date unless told not to (i.e. a custom date was specified)
        if not do_not_insert_date:
            date_div = report.set_date()._repr_mimebundle_()[0]["text/html"]
            head_block = resources["metadata"].get("head_block", "") + date_div
            resources["metadata"]["head_block"] = head_block

        # embed the default CSS
        css = open(os.path.join(ASSETS_PATH, CSS_TEMPLATE_FILE), "r").read()
        css = '<style type="text/css">{}</style>'.format(css)
        head_block = resources["metadata"].get("head_block", "") + css
        resources["metadata"]["head_block"] = head_block

        # tag this report for traceability, if run from notebook service. these will be transferred
        # to PDF metadata if the HTML output of this function is used as input for PDF generation
        meta_tags = [("dcterms.created",
                      datetime.datetime.now(pytz.utc).isoformat())]

        user_uuid = os.environ.get("ONE_CODEX_USER_UUID")
        if user_uuid is not None:
            meta_tags.append(
                ("author", "one_codex_user_uuid_{}".format(user_uuid)))

        nb_uuid = os.environ.get("ONE_CODEX_NOTEBOOK_UUID")
        if nb_uuid is not None:
            meta_tags.append(
                ("author", "one_codex_notebook_uuid_{}".format(nb_uuid)))

        meta_html = ""

        for meta_name, meta_val in meta_tags:
            meta_html += '<meta name="{}" content="{}" />\n'.format(
                meta_name, meta_val)

        head_block = resources["metadata"].get("head_block", "") + meta_html
        resources["metadata"]["head_block"] = head_block

        output, resources = super(OneCodexHTMLExporter,
                                  self).from_notebook_node(nb,
                                                           resources=resources,
                                                           **kw)

        return output, resources