|
| 1 | +# This file is part of sbi, a toolkit for simulation-based inference. sbi is licensed |
| 2 | +# under the Apache License Version 2.0, see <https://www.apache.org/licenses/> |
| 3 | + |
| 4 | +# Script to strip outputs of Jupyter notebooks except for plots and prints so that there |
| 5 | +# are displayed nicely on the documentation website. |
| 6 | + |
| 7 | +import os |
| 8 | + |
| 9 | +import nbformat |
| 10 | +from nbconvert.preprocessors import Preprocessor |
| 11 | + |
| 12 | + |
| 13 | +class StripOutputExceptPlotsAndPrintsPreprocessor(Preprocessor): |
| 14 | + def preprocess_cell(self, cell, resources, cell_index): |
| 15 | + if cell.cell_type == 'code': |
| 16 | + # Retain outputs that contain either 'image/png' or 'stdout' |
| 17 | + cell.outputs = [ |
| 18 | + output |
| 19 | + for output in cell.outputs |
| 20 | + if ('data' in output and 'image/png' in output['data']) |
| 21 | + or ( |
| 22 | + output.get('output_type') == 'stream' |
| 23 | + and output.get('name') == 'stdout' |
| 24 | + ) |
| 25 | + ] |
| 26 | + return cell, resources |
| 27 | + |
| 28 | + |
| 29 | +def strip_output_except_plots_and_prints(notebook_path): |
| 30 | + with open(notebook_path, 'r') as f: |
| 31 | + nb = nbformat.read(f, as_version=4) |
| 32 | + |
| 33 | + preprocessor = StripOutputExceptPlotsAndPrintsPreprocessor() |
| 34 | + nb, _ = preprocessor.preprocess(nb, {}) |
| 35 | + |
| 36 | + with open(notebook_path, 'w') as f: |
| 37 | + nbformat.write(nb, f) |
| 38 | + |
| 39 | + |
| 40 | +def strip_notebooks_in_directory(directory): |
| 41 | + """Strips outputs of all notebooks in a directory except for plots and prints.""" |
| 42 | + for root, _, files in os.walk(directory): |
| 43 | + for file in files: |
| 44 | + if file.endswith(".ipynb"): |
| 45 | + notebook_path = os.path.join(root, file) |
| 46 | + strip_output_except_plots_and_prints(notebook_path) |
| 47 | + |
| 48 | + |
| 49 | +# Example usage |
| 50 | +if __name__ == "__main__": |
| 51 | + import sys |
| 52 | + |
| 53 | + if len(sys.argv) != 2: |
| 54 | + print("Usage: python strip_notebook_outputs.py <notebooks_directory>") |
| 55 | + sys.exit(1) |
| 56 | + |
| 57 | + notebooks_directory = sys.argv[1] |
| 58 | + strip_notebooks_in_directory(notebooks_directory) |
0 commit comments