Debian Codegraph @

jupyter_cache/cli/commands/cmd_notebook.py

raw
1 import logging
2 import os
3
4 import click
5 import nbformat
6
7 from jupyter_cache.cli import arguments, options, pass_cache, utils
8 from jupyter_cache.cli.commands.cmd_main import jcache
9 from jupyter_cache.readers import NbReadError
10 from jupyter_cache.utils import tabulate_project_records
11
12 logger = logging.getLogger(__name__)
13 utils.setup_logger(logger)
14
15
16 @jcache.group("notebook")
17 @options.CACHE_PATH
18 @pass_cache
19 def cmnd_notebook(cache, cache_path):
20 """Work with notebook(s) in a project."""
21 cache.set_cache_path(cache_path)
22
23
24 @cmnd_notebook.command("add")
25 @arguments.NB_PATHS
26 @options.READER_KEY
27 @pass_cache
28 def add_notebooks(cache, nbpaths, reader):
29 """Add notebook(s) to the project."""
30 db = cache.get_cache()
31 for path in nbpaths:
32 # TODO deal with errors (print all at end? or option to ignore)
33 click.echo(f"Adding: {path}")
34 db.add_nb_to_project(path, read_data={"name": reader, "type": "plugin"})
35 click.secho("Success!", fg="green")
36
37
38 @cmnd_notebook.command("add-with-assets")
39 @arguments.ASSET_PATHS
40 @options.NB_PATH
41 @options.READER_KEY
42 @pass_cache
43 def add_notebook(cache, nbpath, reader, asset_paths):
44 """Add notebook(s) to the project, with possible asset files."""
45 db = cache.get_cache()
46 db.add_nb_to_project(
47 nbpath, read_data={"name": reader, "type": "plugin"}, assets=asset_paths
48 )
49 click.secho("Success!", fg="green")
50
51
52 @cmnd_notebook.command("clear")
53 @options.FORCE
54 @pass_cache
55 def clear_nbs(cache, force):
56 """Remove all notebooks from the project."""
57 db = cache.get_cache()
58 if not force:
59 click.confirm(
60 "Are you sure you want to permanently clear the project!?", abort=True
61 )
62 for record in db.list_project_records():
63 db.remove_nb_from_project(record.pk)
64 click.secho("Project cleared!", fg="green")
65
66
67 @cmnd_notebook.command("remove")
68 @arguments.PK_OR_PATHS
69 @pass_cache
70 def remove_nbs(cache, pk_paths):
71 """Remove notebook(s) from the project (by ID/URI)."""
72 db = cache.get_cache()
73 for pk_path in pk_paths:
74 # TODO deal with errors (print all at end? or option to ignore)
75 click.echo(f"Removing: {pk_path}")
76 db.remove_nb_from_project(
77 int(pk_path) if pk_path.isdigit() else os.path.abspath(pk_path)
78 )
79 click.secho("Success!", fg="green")
80
81
82 @cmnd_notebook.command("invalidate")
83 @arguments.PK_OR_PATHS
84 @options.INVALIDATE_ALL
85 @pass_cache
86 def invalidate_nbs(cache, pk_paths, invalidate_all):
87 """Remove any matching cache of the notebook(s) (by ID/URI)."""
88 db = cache.get_cache()
89 if invalidate_all:
90 pk_paths = [str(record.pk) for record in db.list_project_records()]
91 for pk_path in pk_paths:
92 # TODO deal with errors (print all at end? or option to ignore)
93 click.echo(f"Invalidating: {pk_path}")
94 record = db.get_cached_project_nb(
95 int(pk_path) if pk_path.isdigit() else os.path.abspath(pk_path)
96 )
97 if record is not None:
98 db.remove_cache(record.pk)
99 click.secho("Success!", fg="green")
100
101
102 @cmnd_notebook.command("list")
103 # @click.option(
104 # "--compare/--no-compare",
105 # default=True,
106 # show_default=True,
107 # help="Compare to cached notebooks (to find cache ID).",
108 # )
109 @options.PATH_LENGTH
110 @click.option(
111 "--assets",
112 is_flag=True,
113 help="Show the number of assets associated with each notebook",
114 )
115 @pass_cache
116 def list_nbs_in_project(cache, path_length, assets):
117 """List notebooks in the project."""
118 db = cache.get_cache()
119 records = db.list_project_records()
120 if not records:
121 click.secho("No notebooks in project", fg="blue")
122 click.echo(
123 tabulate_project_records(
124 records, path_length=path_length, cache=db, assets=assets
125 )
126 )
127
128
129 @cmnd_notebook.command("info")
130 @arguments.PK_OR_PATH
131 @click.option(
132 "--tb/--no-tb",
133 default=True,
134 show_default=True,
135 help="Show traceback, if last execution failed.",
136 )
137 @pass_cache
138 def show_project_record(cache, pk_path, tb):
139 """Show details of a notebook (by ID)."""
140 import yaml
141
142 db = cache.get_cache()
143 try:
144 record = db.get_project_record(
145 int(pk_path) if pk_path.isdigit() else os.path.abspath(pk_path)
146 )
147 except KeyError:
148 click.secho(f"ID {pk_path} does not exist, Aborting!", fg="red")
149 raise click.Abort()
150 cache_record = None
151 try:
152 cache_record = db.get_cached_project_nb(record.uri)
153 except NbReadError as exc:
154 click.secho(f"File could not be read: {exc}", fg="red")
155 data = record.format_dict(
156 cache_record=cache_record, path_length=None, assets=False, read_name=False
157 )
158 click.echo(yaml.safe_dump(data, sort_keys=False, allow_unicode=True).rstrip())
159 if record.assets:
160 click.echo("Assets:")
161 for path in record.assets:
162 click.echo(f"- {path}")
163 if record.traceback:
164 click.secho("Failed Last Execution!", fg="red")
165 if tb:
166 click.echo(record.traceback)
167
168
169 @cmnd_notebook.command("merge")
170 @arguments.PK_OR_PATH
171 @arguments.OUTPUT_PATH
172 @pass_cache
173 def merge_executed(cache, pk_path, outpath):
174 """Create notebook merged with cached outputs (by ID/URI)."""
175 db = cache.get_cache()
176 nb = db.get_project_notebook(
177 int(pk_path) if pk_path.isdigit() else os.path.abspath(pk_path)
178 ).nb
179 cached_pk, nb = db.merge_match_into_notebook(nb)
180 nbformat.write(nb, outpath)
181 click.echo(f"Merged with cache PK {cached_pk}")
182 click.secho("Success!", fg="green")
183
184
185 @cmnd_notebook.command("execute")
186 @arguments.PK_OR_PATHS
187 @options.EXECUTOR_KEY
188 @options.EXEC_TIMEOUT
189 @options.EXEC_FORCE(default=True)
190 @options.set_log_level(logger)
191 @pass_cache
192 def execute_nbs(cache, pk_paths, executor, timeout, force):
193 """Execute specific notebooks in the project."""
194 import yaml
195
196 from jupyter_cache.executors import load_executor
197
198 uris = [os.path.abspath(p) for p in pk_paths if not p.isdigit()] or None
199 pks = [int(p) for p in pk_paths if p.isdigit()] or None
200
201 db = cache.get_cache()
202
203 try:
204 executor = load_executor(executor, db, logger=logger)
205 except ImportError as error:
206 logger.error(str(error))
207 return 1
208 result = executor.run_and_cache(
209 filter_pks=pks, filter_uris=uris, timeout=timeout, force=force
210 )
211 click.secho(
212 "Finished! Successfully executed notebooks have been cached.", fg="green"
213 )
214 click.echo(yaml.safe_dump(result.as_json(), sort_keys=False))