Convert IPython notebook cells to a list of Datapane Blocks Recognized cell tags: - `dp-exclude` - Exclude this cell (when opt_out=True) - `dp-include` - Include this cell (when opt_out=False) - `dp-show-code` - Show the input code for this cell - `dp-show-markdo
(
opt_out: bool = True, show_code: bool = False, show_markdown: bool = True
)
| 70 | |
| 71 | |
| 72 | def cells_to_blocks( |
| 73 | opt_out: bool = True, show_code: bool = False, show_markdown: bool = True |
| 74 | ) -> typing.List[BaseBlock]: |
| 75 | """Convert IPython notebook cells to a list of Datapane Blocks |
| 76 | |
| 77 | Recognized cell tags: |
| 78 | - `dp-exclude` - Exclude this cell (when opt_out=True) |
| 79 | - `dp-include` - Include this cell (when opt_out=False) |
| 80 | - `dp-show-code` - Show the input code for this cell |
| 81 | - `dp-show-markdown` - Show the markdown for this cell |
| 82 | |
| 83 | ..note:: IPython output caching must be enabled for this function to work. It is enabled by default. |
| 84 | """ |
| 85 | environment = get_environment() |
| 86 | if not environment.is_notebook_environment: |
| 87 | raise DPClientError("This function can only be used in a notebook environment") |
| 88 | |
| 89 | ip = environment.get_ipython() |
| 90 | user_ns = ip.user_ns |
| 91 | ipython_output_cache = user_ns["_oh"] |
| 92 | ipython_input_cache = user_ns["_ih"] |
| 93 | |
| 94 | notebook_json = environment.get_notebook_json() |
| 95 | # TODO: debug message for Colab, remove after testing |
| 96 | |
| 97 | notebook_is_dirty, dirty_cells = check_notebook_cache_parity(notebook_json, ipython_input_cache) |
| 98 | |
| 99 | if notebook_is_dirty: |
| 100 | notebook_parity_message = ( |
| 101 | "Please ensure all cells in the notebook have been executed and saved before running the conversion." |
| 102 | ) |
| 103 | |
| 104 | if dirty_cells: |
| 105 | notebook_parity_message += f""" |
| 106 | |
| 107 | The following cells have not been executed and saved: {', '.join(map(str, dirty_cells))}""" |
| 108 | |
| 109 | raise NotebookParityException(notebook_parity_message) |
| 110 | |
| 111 | blocks = [] |
| 112 | |
| 113 | for cell in notebook_json["cells"]: |
| 114 | tags = cell["metadata"].get("tags", []) |
| 115 | |
| 116 | if (opt_out and "dp-exclude" not in tags) or (not opt_out and "dp-include" in tags): |
| 117 | if (cell["cell_type"] == "markdown" and cell.get("source")) and ( |
| 118 | show_markdown or "dp-show-markdown" in tags |
| 119 | ): |
| 120 | from datapane.blocks.text import Text |
| 121 | |
| 122 | markdown_block: BaseBlock = Text("".join(cell["source"])) |
| 123 | blocks.append(markdown_block) |
| 124 | elif cell["cell_type"] == "code" and not cell.get("contains_ignored_functions", False): |
| 125 | if "dp-show-code" in tags or show_code: |
| 126 | from datapane.blocks.text import Code |
| 127 | |
| 128 | code_block: BaseBlock = Code("".join(cell["source"])) |
| 129 | blocks.append(code_block) |
no test coverage detected