Debian Codegraph @

jupyter_cache/cache/main.py

raw
1 from contextlib import contextmanager
2 import copy
3 import hashlib
4 import io
5 from pathlib import Path
6 import shutil
7 from typing import Iterable, List, Mapping, Optional, Tuple, Union
8
9 import nbformat as nbf
10
11 from jupyter_cache.base import ( # noqa: F401
12 NB_VERSION,
13 CacheBundleIn,
14 CacheBundleOut,
15 CachingError,
16 JupyterCacheAbstract,
17 NbArtifactsAbstract,
18 NbValidityError,
19 ProjectNb,
20 RetrievalError,
21 )
22 from jupyter_cache.readers import DEFAULT_READ_DATA, NbReadError, get_reader
23 from jupyter_cache.utils import to_relative_paths
24
25 from .db import NbCacheRecord, NbProjectRecord, Setting, create_db, get_version
26
27 CACHE_LIMIT_KEY = "cache_limit"
28 DEFAULT_CACHE_LIMIT = 1000
29
30
31 class NbArtifacts(NbArtifactsAbstract):
32 """Container for artefacts of a notebook execution."""
33
34 def __init__(self, paths: List[str], in_folder, check_existence=True):
35 """Initiate NbArtifacts
36
37 :param paths: list of paths
38 :param check_existence: check the paths exist
39 :param in_folder: The folder that all paths should be in (or subfolder).
40 :raises IOError: if check_existence and file does not exist
41 """
42 self.paths = [Path(p).absolute() for p in paths]
43 self.in_folder = Path(in_folder).absolute()
44 to_relative_paths(self.paths, self.in_folder, check_existence=check_existence)
45
46 @property
47 def relative_paths(self) -> List[Path]:
48 """Return the list of paths (relative to the notebook folder)."""
49 return to_relative_paths(self.paths, self.in_folder)
50
51 def __iter__(self) -> Iterable[Tuple[Path, io.BufferedReader]]:
52 """Yield the relative path and open files (in bytes mode)"""
53 for path in self.paths:
54 with path.open("rb") as handle:
55 yield path.relative_to(self.in_folder), handle
56
57
58 class JupyterCacheBase(JupyterCacheAbstract):
59 def __init__(self, path):
60 self._path = Path(path).absolute()
61 self._db = None
62
63 @property
64 def path(self):
65 if not self._path.exists():
66 self._path.mkdir(parents=True)
67 return self._path
68
69 @property
70 def db(self):
71 """a simple database for storing persistent global data."""
72 if self._db is None:
73 self._db = create_db(self.path)
74 return self._db
75
76 def __repr__(self):
77 return f"{self.__class__.__name__}({repr(str(self._path))})"
78
79 def __getstate__(self):
80 """For pickling instances, db must be removed."""
81 state = self.__dict__.copy()
82 state["_db"] = None
83 return state
84
85 def get_version(self) -> Optional[str]:
86 return get_version(self.path)
87
88 def clear_cache(self):
89 """Clear the cache completely."""
90 shutil.rmtree(self.path)
91 self._db = None
92
93 def _get_notebook_path_cache(self, hashkey, raise_on_missing=False) -> Path:
94 """Retrieve a relative path in the cache to a notebook, from its hash."""
95 path = self.path.joinpath(Path("executed", hashkey, "base.ipynb"))
96 if not path.exists() and raise_on_missing:
97 raise RetrievalError(f"hashkey not in cache: {hashkey}")
98 return path
99
100 def _get_artifact_path_cache(self, hashkey) -> Path:
101 """Retrieve a relative path in the cache to a notebook, from its hash."""
102 path = self.path.joinpath(Path("executed", hashkey, "artifacts"))
103 return path
104
105 def truncate_caches(self):
106 """If the number of cached notebooks exceeds set limit, delete the oldest."""
107 cache_limit = Setting.get_value(CACHE_LIMIT_KEY, self.db, DEFAULT_CACHE_LIMIT)
108 # TODO you could have better control over this by e.g. tagging certain caches
109 # that should not be deleted.
110 pks = NbCacheRecord.records_to_delete(cache_limit, self.db)
111 for pk in pks:
112 self.remove_cache(pk)
113
114 def get_cache_limit(self):
115 return Setting.get_value(CACHE_LIMIT_KEY, self.db, DEFAULT_CACHE_LIMIT)
116
117 def change_cache_limit(self, size: int):
118 assert isinstance(size, int) and size > 0
119 Setting.set_value(CACHE_LIMIT_KEY, size, self.db)
120
121 def create_hashed_notebook(
122 self,
123 nb: nbf.NotebookNode,
124 nb_metadata: Optional[Iterable[str]] = ("kernelspec",),
125 cell_metadata: Optional[Iterable[str]] = None,
126 ) -> Tuple[nbf.NotebookNode, str]:
127 """Convert a notebook to a standard format and hash.
128
129 Note: we always hash notebooks as version 4.4,
130 to allow for matching notebooks of different versions
131
132 :param nb_metadata: The notebook metadata keys to hash (if None, use all)
133 :param cell_metadata: The cell metadata keys to hash (if None, use all)
134
135 :return: (notebook, hash)
136 """
137 # copy the notebook
138 nb = copy.deepcopy(nb)
139 # update the notebook to consistent version 4.4
140 nb = nbf.convert(nb, to_version=NB_VERSION)
141 if nb.nbformat_minor > 5:
142 raise CachingError("notebook version greater than 4.5 not yet supported")
143 # remove non-code cells
144 nb.cells = [cell for cell in nb.cells if cell.cell_type == "code"]
145 # create notebook for hashing, with selected metadata
146 hash_nb = nbf.from_dict(
147 {
148 "nbformat": nb.nbformat,
149 "nbformat_minor": 4, # v4.5 include cell ids, which we do not cache
150 "metadata": {
151 k: v
152 for k, v in nb.metadata.items()
153 if nb_metadata is None or (k in nb_metadata)
154 },
155 "cells": [
156 {
157 "cell_type": cell.cell_type,
158 "source": cell.source,
159 "metadata": {
160 k: v
161 for k, v in cell.metadata.items()
162 if cell_metadata is None or (k in cell_metadata)
163 },
164 "execution_count": None,
165 "outputs": [],
166 }
167 for cell in nb.cells
168 if cell.cell_type == "code"
169 ],
170 }
171 )
172
173 # hash notebook
174 string = nbf.writes(hash_nb, nbf.NO_CONVERT)
175 hash_string = hashlib.md5(string.encode()).hexdigest()
176
177 return (nb, hash_string)
178
179 def _validate_nb_bundle(self, nb_bundle: CacheBundleIn):
180 """Validate that a notebook bundle should be cached.
181
182 We check that the notebook has been executed correctly,
183 by asserting `execution_count`s are consecutive and start at 1.
184 """
185 execution_count = 1
186 for i, cell in enumerate(nb_bundle.nb.cells):
187 if cell.cell_type != "code":
188 continue
189 if cell.execution_count != execution_count:
190 raise NbValidityError(
191 "Expected cell {} to have execution_count {} not {}".format(
192 i, execution_count, cell.execution_count
193 ),
194 nb_bundle,
195 )
196 execution_count += 1
197 # TODO check for output exceptions?
198 # TODO assets
199
200 def cache_notebook_bundle(
201 self,
202 bundle: CacheBundleIn,
203 check_validity: bool = True,
204 overwrite: bool = False,
205 description="",
206 ) -> NbCacheRecord:
207 """Cache an executed notebook."""
208 # TODO it would be ideal to have some 'rollback' mechanism on exception
209
210 if check_validity:
211 self._validate_nb_bundle(bundle)
212
213 hashed_nb, hashkey = self.create_hashed_notebook(bundle.nb)
214
215 path = self._get_notebook_path_cache(hashkey)
216 if path.exists():
217 if not overwrite:
218 raise CachingError(
219 "Notebook already exists in cache and overwrite=False."
220 )
221 shutil.rmtree(path.parent)
222
223 try:
224 record = NbCacheRecord.record_from_hashkey(hashkey, self.db)
225 except KeyError:
226 pass
227 else:
228 NbCacheRecord.remove_record(record.pk, self.db)
229
230 record = NbCacheRecord.create_record(
231 uri=bundle.uri,
232 hashkey=hashkey,
233 db=self.db,
234 data=bundle.data,
235 description=description,
236 )
237 path.parent.mkdir(parents=True)
238 path.write_text(nbf.writes(hashed_nb, nbf.NO_CONVERT), encoding="utf8")
239
240 # write artifacts
241 artifact_folder = self._get_artifact_path_cache(hashkey)
242 if artifact_folder.exists():
243 shutil.rmtree(artifact_folder)
244 for rel_path, handle in bundle.artifacts or []:
245 write_path = artifact_folder.joinpath(rel_path)
246 write_path.parent.mkdir(parents=True, exist_ok=True)
247 write_path.write_bytes(handle.read())
248
249 self.truncate_caches()
250
251 return record
252
253 def cache_notebook_file(
254 self,
255 path: str,
256 uri: Optional[str] = None,
257 artifacts: List[str] = (),
258 data: Optional[dict] = None,
259 check_validity: bool = True,
260 overwrite: bool = False,
261 ) -> NbCacheRecord:
262 """Cache an executed notebook, returning its primary key.
263
264 Note: non-code source text (e.g. markdown) is not stored in the cache.
265
266 :param path: path to the notebook
267 :param uri: alternative URI to store in the cache record (defaults to path)
268 :param artifacts: list of paths to outputs of the executed notebook.
269 Artifacts must be in the same folder as the notebook (or a sub-folder)
270 :param data: additional, JSONable, data to store in the cache record
271 :param check_validity: check that the notebook has been executed correctly,
272 by asserting `execution_count`s are consecutive and start at 1.
273 :param overwrite: Allow overwrite of cached notebooks with matching hash
274 :return: The primary key of the cache record
275 """
276 notebook = nbf.read(str(path), nbf.NO_CONVERT)
277 return self.cache_notebook_bundle(
278 CacheBundleIn(
279 notebook,
280 uri or str(path),
281 artifacts=NbArtifacts(artifacts, in_folder=Path(path).parent),
282 data=data or {},
283 ),
284 check_validity=check_validity,
285 overwrite=overwrite,
286 )
287
288 def list_cache_records(self) -> List[NbCacheRecord]:
289 return NbCacheRecord.records_all(self.db)
290
291 def get_cache_record(self, pk: int) -> NbCacheRecord:
292 return NbCacheRecord.record_from_pk(pk, self.db)
293
294 def get_cache_bundle(self, pk: int) -> CacheBundleOut:
295 record = NbCacheRecord.record_from_pk(pk, self.db)
296 NbCacheRecord.touch(pk, self.db)
297 path = self._get_notebook_path_cache(record.hashkey)
298 artifact_folder = self._get_artifact_path_cache(record.hashkey)
299 if not path.exists():
300 raise KeyError(f"Notebook file does not exist for cache record PK: {pk}")
301
302 return CacheBundleOut(
303 nbf.reads(path.read_text(encoding="utf8"), nbf.NO_CONVERT),
304 record=record,
305 artifacts=NbArtifacts(
306 [p for p in artifact_folder.glob("**/*") if p.is_file()],
307 in_folder=artifact_folder,
308 ),
309 )
310
311 @contextmanager
312 def cache_artefacts_temppath(self, pk: int) -> Path:
313 """Context manager to provide a temporary folder path to the notebook artifacts.
314
315 Note this path is only guaranteed to exist within the scope of the context,
316 and should only be used for read/copy operations::
317
318 with cache.cache_artefacts_temppath(1) as path:
319 shutil.copytree(path, destination)
320 """
321 record = NbCacheRecord.record_from_pk(pk, self.db)
322 yield self._get_artifact_path_cache(record.hashkey)
323
324 def remove_cache(self, pk: int):
325 record = NbCacheRecord.record_from_pk(pk, self.db)
326 path = self._get_notebook_path_cache(record.hashkey)
327 if not path.exists():
328 raise KeyError(f"Notebook file does not exist for cache record PK: {pk}")
329 shutil.rmtree(path.parent)
330 NbCacheRecord.remove_records([pk], self.db)
331
332 def match_cache_notebook(self, nb: nbf.NotebookNode) -> NbCacheRecord:
333 """Match to an executed notebook, returning its primary key.
334
335 :raises KeyError: if no match is found
336 """
337 _, hashkey = self.create_hashed_notebook(nb)
338 cache_record = NbCacheRecord.record_from_hashkey(hashkey, self.db)
339 return cache_record
340
341 def merge_match_into_notebook(
342 self,
343 nb: nbf.NotebookNode,
344 nb_meta: Optional[Iterable[str]] = ("kernelspec", "language_info", "widgets"),
345 cell_meta: Optional[Iterable[str]] = None,
346 ) -> Tuple[int, nbf.NotebookNode]:
347 """Match to an executed notebook and return a merged version
348
349 :param nb: The input notebook
350 :param nb_meta: metadata keys to merge from the cached notebook (all if None)
351 :param cell_meta: cell metadata keys to merge from cached notebook (all if None)
352 :raises KeyError: if no match is found
353 :return: pk, input notebook with cached code cells and metadata merged.
354
355 """
356 pk = self.match_cache_notebook(nb).pk
357 cache_nb = self.get_cache_bundle(pk).nb
358 nb = nbf.convert(copy.deepcopy(nb), NB_VERSION)
359 if nb_meta is None:
360 nb.metadata = cache_nb.metadata
361 else:
362 for key in nb_meta:
363 if key in cache_nb.metadata:
364 nb.metadata[key] = cache_nb.metadata[key]
365 for idx in range(len(nb.cells)):
366 if nb.cells[idx].cell_type == "code":
367 cache_cell = cache_nb.cells.pop(0)
368 in_cell = nb.cells[idx]
369 if cell_meta is not None:
370 # update the input metadata with select cached notebook metadata
371 # then add the input metadata to the cached cell
372 in_cell.metadata.update(
373 {k: v for k, v in cache_cell.metadata.items() if k in cell_meta}
374 )
375 cache_cell.metadata = in_cell.metadata
376 if nb.nbformat_minor >= 5:
377 cache_cell.id = in_cell.id
378 else:
379 cache_cell.pop("id", None)
380 nb.cells[idx] = cache_cell
381 return pk, nb
382
383 def diff_nbnode_with_cache(
384 self, pk: int, nb: nbf.NotebookNode, uri: str = "", as_str=False, **kwargs
385 ):
386 """Return a diff of a notebook to a cached one.
387
388 Note: this will not diff markdown content, since it is not stored in the cache.
389 """
390 try:
391 import nbdime
392 except ImportError:
393 raise ImportError(
394 "nbdime is required to diff notebooks, install with `pip install nbdime`"
395 )
396 from nbdime.prettyprint import PrettyPrintConfig, pretty_print_diff
397
398 cached_nb = self.get_cache_bundle(pk).nb
399 nb, _ = self.create_hashed_notebook(nb)
400
401 diff = nbdime.diff_notebooks(cached_nb, nb)
402 if not as_str:
403 return diff
404 stream = io.StringIO()
405 stream.writelines(["nbdiff\n", f"--- cached pk={pk}\n", f"+++ other: {uri}\n"])
406 pretty_print_diff(
407 cached_nb, diff, "nb", PrettyPrintConfig(out=stream, **kwargs)
408 )
409 return stream.getvalue()
410
411 def add_nb_to_project(
412 self,
413 path: str,
414 *,
415 read_data: Mapping = DEFAULT_READ_DATA,
416 assets: List[str] = (),
417 ) -> NbProjectRecord:
418 # check the reader can be loaded
419 read_data = dict(read_data)
420 _ = get_reader(read_data)
421 # TODO should we test that the file can be read by the reader?
422 return NbProjectRecord.create_record(
423 str(Path(path).absolute()),
424 self.db,
425 raise_on_exists=False,
426 read_data=read_data,
427 assets=assets,
428 )
429 # TODO physically copy to cache?
430 # TODO assets
431
432 def list_project_records(
433 self,
434 filter_uris: Optional[List[str]] = None,
435 filter_pks: Optional[List[int]] = None,
436 ) -> List[NbProjectRecord]:
437 records = NbProjectRecord.records_all(self.db)
438 if filter_uris is not None:
439 records = [r for r in records if r.uri in filter_uris]
440 if filter_pks is not None:
441 records = [r for r in records if r.pk in filter_pks]
442 return records
443
444 def get_project_record(self, uri_or_pk: Union[int, str]) -> NbProjectRecord:
445 if isinstance(uri_or_pk, int):
446 record = NbProjectRecord.record_from_pk(uri_or_pk, self.db)
447 else:
448 record = NbProjectRecord.record_from_uri(uri_or_pk, self.db)
449 return record
450
451 def remove_nb_from_project(self, uri_or_pk: Union[int, str]):
452 if isinstance(uri_or_pk, int):
453 NbProjectRecord.remove_pks([uri_or_pk], self.db)
454 else:
455 NbProjectRecord.remove_uris([uri_or_pk], self.db)
456
457 # TODO add discard all/multiple project records method
458
459 def get_project_notebook(self, uri_or_pk: Union[int, str]) -> ProjectNb:
460 if isinstance(uri_or_pk, int):
461 record = NbProjectRecord.record_from_pk(uri_or_pk, self.db)
462 else:
463 record = NbProjectRecord.record_from_uri(uri_or_pk, self.db)
464 if not Path(record.uri).exists():
465 raise OSError(
466 f"The URI of the project record no longer exists: {record.uri}"
467 )
468 try:
469 reader = get_reader(record.read_data)
470 notebook = reader(record.uri)
471 assert isinstance(
472 notebook, nbf.NotebookNode
473 ), f"Reader did not return a v4 NotebookNode: {type(notebook)} {notebook}"
474 except Exception as exc:
475 raise NbReadError(f"Failed to read the notebook: {exc}") from exc
476 return ProjectNb(record.pk, record.uri, notebook, record.assets)
477
478 def get_cached_project_nb(
479 self, uri_or_pk: Union[int, str]
480 ) -> Optional[NbCacheRecord]:
481 nb = self.get_project_notebook(uri_or_pk).nb
482 _, hashkey = self.create_hashed_notebook(nb)
483 try:
484 return NbCacheRecord.record_from_hashkey(hashkey, self.db)
485 except KeyError:
486 return None
487
488 def list_unexecuted(
489 self,
490 filter_uris: Optional[List[str]] = None,
491 filter_pks: Optional[List[int]] = None,
492 ) -> List[NbProjectRecord]:
493 records = []
494 for record in self.list_project_records(filter_uris, filter_pks):
495 nb = self.get_project_notebook(record.uri).nb
496 _, hashkey = self.create_hashed_notebook(nb)
497 try:
498 NbCacheRecord.record_from_hashkey(hashkey, self.db)
499 except KeyError:
500 records.append(record)
501 return records
502
503 # removed until defined use case
504 # def get_cache_codecell(self, pk: int, index: int) -> nbf.NotebookNode:
505 # """Return a code cell from a cached notebook.
506
507 # NOTE: the index **only** refers to the list of code cells, e.g.
508 # `[codecell_0, textcell_1, codecell_2]`
509 # would map {0: codecell_0, 1: codecell_2}
510 # """
511 # nb_bundle = self.get_cache_bundle(pk)
512 # _code_index = 0
513 # for cell in nb_bundle.nb.cells:
514 # if cell.cell_type != "code":
515 # continue
516 # if _code_index == index:
517 # return cell
518 # _code_index += 1
519 # raise RetrievalError(f"Notebook contains less than {index+1} code cell(s)")