|
| 1 | +import glob |
| 2 | +import os |
| 3 | +from pprint import pprint |
| 4 | +from tempfile import TemporaryDirectory |
| 5 | +from types import SimpleNamespace |
| 6 | +from typing import Any |
| 7 | + |
| 8 | +import papermill as pm |
| 9 | +from cfa_azure.blob_helpers import write_blob_stream |
| 10 | +from nbconvert import HTMLExporter |
| 11 | +from traitlets.config import Config |
| 12 | + |
| 13 | +_here_dir = os.path.split(os.path.abspath(__file__))[0] |
| 14 | +_report_paths = glob.glob( |
| 15 | + os.path.join(_here_dir, "**", "**.ipynb"), recursive=True |
| 16 | +) |
| 17 | + |
| 18 | + |
| 19 | +def remove_ws_and_nonalpha(s: str) -> str: |
| 20 | + """Remove whitespace and non-alphanumeric characters from a string. |
| 21 | +
|
| 22 | + Args: |
| 23 | + s (str): The input string. |
| 24 | +
|
| 25 | + Returns: |
| 26 | + str: The cleaned string with whitespace and non-alphanumeric characters removed. |
| 27 | +
|
| 28 | + Example: |
| 29 | + >>> remove_ws_and_nonalpha("Hello World! 123.ipynb") |
| 30 | + 'hello_world_123_ipynb' |
| 31 | + """ |
| 32 | + s = s.replace(" ", "_").replace(".", "_").lower() |
| 33 | + return "".join(c for c in s if c.isalnum() or c == "_") |
| 34 | + |
| 35 | + |
| 36 | +# get the namespace mapping for the available reports |
| 37 | +report_ns_map = {} |
| 38 | +for rp_i in _report_paths: |
| 39 | + if rp_i.startswith(os.path.join(_here_dir, "reports")): |
| 40 | + ns_list = [ |
| 41 | + remove_ws_and_nonalpha(i) |
| 42 | + for i in rp_i.split(f"reports{os.sep}")[-1].split(os.sep) |
| 43 | + ] |
| 44 | + current = report_ns_map |
| 45 | + for part in ns_list[:-1]: |
| 46 | + if part not in current: |
| 47 | + current[part] = {} |
| 48 | + current = current[part] |
| 49 | + current[ns_list[-1]] = rp_i |
| 50 | + |
| 51 | + |
| 52 | +def nb_to_html(nb_path: str) -> str: |
| 53 | + """Convert the executed notebook to HTML format. |
| 54 | +
|
| 55 | + Returns: |
| 56 | + str: The HTML content of the notebook. |
| 57 | + """ |
| 58 | + c = Config() |
| 59 | + c.TagRemovePreprocessor.remove_cell_tags = ("remove_cell",) |
| 60 | + c.TagRemovePreprocessor.remove_input_tags = ("remove_input",) |
| 61 | + c.TagRemovePreprocessor.remove_all_outputs_tags = ("remove_outputs",) |
| 62 | + c.TagRemovePreprocessor.enabled = True |
| 63 | + c.HTMLExporter.preprocessors = [ |
| 64 | + "nbconvert.preprocessors.TagRemovePreprocessor" |
| 65 | + ] |
| 66 | + c.TemplateExporter.extra_template_basedirs = os.path.join( |
| 67 | + _here_dir, "jupyter_templates" |
| 68 | + ) |
| 69 | + body, _ = HTMLExporter(template_name="lab", config=c).from_filename( |
| 70 | + nb_path |
| 71 | + ) |
| 72 | + return body |
| 73 | + |
| 74 | + |
| 75 | +class NotebookEndpoint: |
| 76 | + """Class to handle the execution and conversion of Jupyter notebooks to HTML.""" |
| 77 | + |
| 78 | + def __init__(self, notebook_path: str): |
| 79 | + self.notebook_path = notebook_path |
| 80 | + |
| 81 | + def get_params(self) -> dict: |
| 82 | + """Get the parameters for the notebook execution.""" |
| 83 | + return pm.inspect_notebook(self.notebook_path) |
| 84 | + |
| 85 | + def print_params(self): |
| 86 | + """Pretty print the parameters of the notebook.""" |
| 87 | + pprint(self.get_params()) |
| 88 | + |
| 89 | + def nb_to_html_str(self, **kwargs) -> str: |
| 90 | + """Convert the notebook to HTML format and optionally save it to a file. |
| 91 | +
|
| 92 | + Args: |
| 93 | + html_out_path (str): Path to save the HTML output. If None, does not save. |
| 94 | + **kwargs: Parameters to replace defaults in notebook. |
| 95 | +
|
| 96 | + Returns: |
| 97 | + str: The HTML content of the notebook. |
| 98 | + """ |
| 99 | + with TemporaryDirectory() as temp_dir: |
| 100 | + out_file_path = os.path.join(temp_dir, "output.ipynb") |
| 101 | + pm.execute_notebook( |
| 102 | + input_path=self.notebook_path, |
| 103 | + output_path=out_file_path, |
| 104 | + parameters=kwargs, |
| 105 | + progress_bar=True, |
| 106 | + ) |
| 107 | + html_content = nb_to_html(out_file_path) |
| 108 | + |
| 109 | + return html_content |
| 110 | + |
| 111 | + def nb_to_html_file(self, html_out_path: str, **kwargs) -> None: |
| 112 | + """Convert the notebook to HTML format. |
| 113 | +
|
| 114 | + Args: |
| 115 | + **kwargs: Parameters to replace defaults in notebook. |
| 116 | +
|
| 117 | + Returns: |
| 118 | + None, saves the html content to a file. |
| 119 | + """ |
| 120 | + assert html_out_path.endswith( |
| 121 | + ".html" |
| 122 | + ), "Output path must end with .html" |
| 123 | + html_content = self.nb_to_html_str(**kwargs) |
| 124 | + os.makedirs(os.path.dirname(html_out_path), exist_ok=True) |
| 125 | + with open(html_out_path, "w") as f: |
| 126 | + f.write(html_content) |
| 127 | + print(f"HTML report saved to {os.path.abspath(html_out_path)}") |
| 128 | + |
| 129 | + def nb_to_html_blob( |
| 130 | + self, blob_account: str, blob_container: str, blob_path: str, **kwargs |
| 131 | + ) -> None: |
| 132 | + """Convert the notebook to HTML format save to blob storage. |
| 133 | +
|
| 134 | + Args: |
| 135 | + **kwargs: Parameters to replace defaults in notebook. |
| 136 | +
|
| 137 | + Returns: |
| 138 | + None, saves the HTML content to a blob storage. |
| 139 | + """ |
| 140 | + assert blob_path.endswith(".html"), "Output path must end with .html" |
| 141 | + html_content = self.nb_to_html_str(**kwargs) |
| 142 | + write_blob_stream( |
| 143 | + account_name=blob_account, |
| 144 | + container_name=blob_container, |
| 145 | + blob_url=blob_path, |
| 146 | + data=html_content.encode("utf-8"), |
| 147 | + ) |
| 148 | + |
| 149 | + |
| 150 | +def report_dict_to_sn(d: Any) -> SimpleNamespace: |
| 151 | + """Simple recursive namespace construction |
| 152 | +
|
| 153 | + Args: |
| 154 | + d (Any): a dict, list or other |
| 155 | +
|
| 156 | + Returns: |
| 157 | + SimpleNamespace: namespace representation |
| 158 | + """ |
| 159 | + x = SimpleNamespace() |
| 160 | + _ = [ |
| 161 | + setattr( |
| 162 | + x, |
| 163 | + k, |
| 164 | + NotebookEndpoint(notebook_path=v) |
| 165 | + if k.endswith("ipynb") |
| 166 | + else report_dict_to_sn(v) |
| 167 | + if isinstance(v, dict) |
| 168 | + else [report_dict_to_sn(e) for e in v] |
| 169 | + if isinstance(v, list) |
| 170 | + else v, |
| 171 | + ) |
| 172 | + for k, v in d.items() |
| 173 | + ] |
| 174 | + return x |
| 175 | + |
| 176 | + |
| 177 | +def get_report_catalog() -> SimpleNamespace: |
| 178 | + """Get the report catalog as a SimpleNamespace object. |
| 179 | +
|
| 180 | + Returns: |
| 181 | + SimpleNamespace: The report catalog. |
| 182 | + """ |
| 183 | + return report_dict_to_sn(report_ns_map) |
0 commit comments