Datasets:

ArXiv:
DOI:
License:
File size: 3,302 Bytes
df0cac0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# execute the notebook according to the current execution order (sorted by execution_count)
# the order in the .ipynb file stays the same
# [re-execute] lines mean that cell is executed twice
# the outputs should be updated (after execution)

import nbformat
import os
import sys
import tempfile
import subprocess
from nbformat import NotebookNode

def set_notebook_path(path_in):
    notebook_dir = os.path.dirname(os.path.abspath(path_in))
    if notebook_dir not in sys.path:
        sys.path.insert(0, notebook_dir)

def reexecute_cells(path_in):
    # Load notebook
    with open(path_in, encoding="utf-8") as f:
        nb = nbformat.read(f, as_version=4)

    # Identify execution order from execution_count (ignore None)
    code_cells = [
        (i, cell) for i, cell in enumerate(nb.cells)
        if cell.cell_type == "code" and (cell.execution_count is not None)
    ]
    sorted_cells = sorted(code_cells, key=lambda x: x[1].execution_count)

    # For each cell: if [re-execute], duplicate once right after
    i = 0
    while i < len(sorted_cells):
        _, cell = sorted_cells[i]
        first_line = cell.source.strip().splitlines()[0] if cell.source.strip() else ""
        if ("[re-execute]" in first_line) or ("[reexecute]" in first_line): 
            # Append a duplicate of this cell to be executed again
            dup = NotebookNode(nbformat.from_dict(cell))
            # Find this cell's execution order position
            sorted_cells.insert(i + 1, (None, dup))
            i += 1
        i += 1

    nb.cells = [cell for (_, cell) in sorted_cells]
    return nb

def execute_notebook_via_nbconvert(nb: NotebookNode, output_path: str):
    notebook_dir = os.path.dirname(os.path.abspath(output_path))
    os.makedirs(notebook_dir, exist_ok=True)

    # Save to a temp file in the same folder as notebook
    with tempfile.NamedTemporaryFile(delete=False, suffix=".ipynb", dir=notebook_dir, mode='w', encoding='utf-8') as tmp:
        nbformat.write(nb, tmp)
        tmp_filename = os.path.basename(tmp.name)

    # Change working directory to notebook's folder
    cwd = os.getcwd()
    os.chdir(notebook_dir)

    try:
        # Run nbconvert in the notebook's own directory
        subprocess.run([
            "jupyter", "nbconvert",
            "--to", "notebook",
            "--execute",
            "--inplace",
            tmp_filename
        ], check=True)

        # Load and write final output
        executed_nb = nbformat.read(open(tmp_filename, encoding="utf-8"), as_version=4)
        with open(output_path, "w", encoding="utf-8") as f:
            nbformat.write(executed_nb, f)
    finally:
        os.chdir(cwd)
        os.remove(os.path.join(notebook_dir, tmp_filename))

def main():
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("input", help="Input notebook path")
    parser.add_argument("-o", "--output", help="Output notebook path (optional)")
    args = parser.parse_args()

    path_in = args.input
    path_out = args.output or path_in.replace(".ipynb", "_executed.ipynb")

    set_notebook_path(path_in)
    modified_nb = reexecute_cells(path_in)
    execute_notebook_via_nbconvert(modified_nb, path_out)
    print(f"Notebook executed and saved to: {path_out}")

if __name__ == "__main__":
    main()