|
| 1 | +# This code is a Qiskit project. |
| 2 | +# |
| 3 | +# (C) Copyright IBM 2024. |
| 4 | +# |
| 5 | +# This code is licensed under the Apache License, Version 2.0. You may |
| 6 | +# obtain a copy of this license in the LICENSE file in the root directory |
| 7 | +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. |
| 8 | +# |
| 9 | +# Any modifications or derivative works of this code must retain this |
| 10 | +# copyright notice, and modified files need to carry a notice indicating |
| 11 | +# that they have been altered from the originals. |
| 12 | + |
| 13 | +import argparse |
| 14 | +import shutil |
| 15 | +from dataclasses import dataclass |
| 16 | +from itertools import chain |
| 17 | +from pathlib import Path |
| 18 | +from typing import TypeGuard, ClassVar |
| 19 | + |
| 20 | +import nbformat |
| 21 | + |
| 22 | +from .cell_output_data import remove_circuit_drawing_html, extract_image_output, Image |
| 23 | + |
| 24 | +NOTEBOOK_PATHS = chain( |
| 25 | + Path("docs").rglob("*.ipynb"), |
| 26 | + Path("learning").rglob("*.ipynb"), |
| 27 | +) |
| 28 | + |
| 29 | + |
| 30 | +# Result types for normalization process |
| 31 | +@dataclass |
| 32 | +class NormalizationNeeded: |
| 33 | + changes: ClassVar[bool] = True |
| 34 | + nb: nbformat.NotebookNode |
| 35 | + images: list[Image] |
| 36 | + |
| 37 | + |
| 38 | +@dataclass |
| 39 | +class AlreadyNormalized: |
| 40 | + changes: ClassVar[bool] = False |
| 41 | + |
| 42 | + |
| 43 | +NormalizationResult = NormalizationNeeded | AlreadyNormalized |
| 44 | + |
| 45 | + |
| 46 | +def changes_made(result: NormalizationResult) -> TypeGuard[NormalizationNeeded]: |
| 47 | + return result.changes |
| 48 | + |
| 49 | + |
| 50 | +def main(): |
| 51 | + """ |
| 52 | + Search for notebooks and extract image outputs if necessary. |
| 53 | + """ |
| 54 | + parser = argparse.ArgumentParser(prog="Qiskit/documentation notebook normalization") |
| 55 | + parser.add_argument("--check", action="store_true") |
| 56 | + args = parser.parse_args() |
| 57 | + |
| 58 | + problem_notebooks = [] |
| 59 | + for nb_path in NOTEBOOK_PATHS: |
| 60 | + if is_hidden(nb_path): |
| 61 | + continue |
| 62 | + |
| 63 | + nb = nbformat.read(nb_path, 4) |
| 64 | + images_folder = determine_image_folder(nb_path) |
| 65 | + |
| 66 | + result = normalize_notebook(nb, images_folder, args.check) |
| 67 | + if not changes_made(result): |
| 68 | + continue |
| 69 | + |
| 70 | + problem_notebooks.append(nb_path) |
| 71 | + if args.check: |
| 72 | + continue |
| 73 | + |
| 74 | + ensure_exists_and_empty(images_folder) |
| 75 | + for image in result.images: |
| 76 | + image.write() |
| 77 | + nbformat.write(result.nb, nb_path) |
| 78 | + print(f"✍️ Written '{nb_path}' and {len(result.images)} image(s)") |
| 79 | + |
| 80 | + if args.check and problem_notebooks: |
| 81 | + print( |
| 82 | + "\nThe following notebooks need normalizing:\n ", |
| 83 | + "\n ".join(map(str, problem_notebooks)), |
| 84 | + "\nRun ./fix to fix them automatically.", |
| 85 | + ) |
| 86 | + raise SystemExit(1) |
| 87 | + |
| 88 | + |
| 89 | +def normalize_notebook( |
| 90 | + nb: nbformat.NotebookNode, image_folder: Path, check_only: bool = False |
| 91 | +) -> NormalizationResult: |
| 92 | + """ |
| 93 | + Extracts images (converting if necessary) and returns an updated notebook. |
| 94 | + """ |
| 95 | + images = [] |
| 96 | + change_made = False |
| 97 | + for cell_index, cell in enumerate(nb.cells): |
| 98 | + if cell.cell_type != "code": |
| 99 | + continue |
| 100 | + if "outputs" not in cell: |
| 101 | + continue |
| 102 | + for index, output in enumerate(cell["outputs"]): |
| 103 | + if "data" not in output: |
| 104 | + continue |
| 105 | + data = output["data"] |
| 106 | + |
| 107 | + html_removed = remove_circuit_drawing_html(data) |
| 108 | + if html_removed: |
| 109 | + change_made = True |
| 110 | + |
| 111 | + # 2. Extract image outputs |
| 112 | + filestem = Path(image_folder, f"{cell.id}-{index}") |
| 113 | + if image := extract_image_output( |
| 114 | + data, filestem, skip_conversion=check_only |
| 115 | + ): |
| 116 | + change_made = True |
| 117 | + images.append(image) |
| 118 | + |
| 119 | + if change_made and check_only: |
| 120 | + # We now know the notebook needs linting so we don't need to |
| 121 | + # keep looking at other cells |
| 122 | + return NormalizationNeeded(nb=nb, images=[]) |
| 123 | + |
| 124 | + if change_made: |
| 125 | + return NormalizationNeeded(nb=nb, images=images) |
| 126 | + return AlreadyNormalized() |
| 127 | + |
| 128 | + |
| 129 | +def determine_image_folder(nb_path: Path) -> Path: |
| 130 | + """ |
| 131 | + Determine the appropriate output folder for the extracted images, and ensure it exists and is empty. |
| 132 | +
|
| 133 | + For example, the following notebook path: |
| 134 | + docs/guides/my-notebook.ipynb |
| 135 | + Should have its images extracted to: |
| 136 | + public/docs/images/guides/my-notebook/extracted-outputs/ |
| 137 | + """ |
| 138 | + return Path( |
| 139 | + "public", |
| 140 | + nb_path.parts[0], # i.e. "docs" or "learning" |
| 141 | + "images", |
| 142 | + *nb_path.with_suffix("").parts[1:], # e.g. "guides/visualize-results" |
| 143 | + "extracted-outputs", |
| 144 | + ) |
| 145 | + |
| 146 | + |
| 147 | +def ensure_exists_and_empty(folder: Path) -> None: |
| 148 | + if folder.exists(): |
| 149 | + shutil.rmtree(folder) |
| 150 | + folder.mkdir(parents=True) |
| 151 | + |
| 152 | + |
| 153 | +def is_hidden(path: Path) -> bool: |
| 154 | + return any(part.startswith(".") for part in path.parts) |
0 commit comments