Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/nbformat/v3/convert.py: 13%
45 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-07-01 06:54 +0000
« prev ^ index » next coverage.py v7.2.7, created at 2023-07-01 06:54 +0000
1"""Code for converting notebooks to and from the v2 format."""
3# Copyright (c) IPython Development Team.
4# Distributed under the terms of the Modified BSD License.
6from .nbbase import nbformat, nbformat_minor
9def _unbytes(obj):
10 """There should be no bytes objects in a notebook
12 v2 stores png/jpeg as b64 ascii bytes
13 """
14 if isinstance(obj, dict):
15 for k, v in obj.items():
16 obj[k] = _unbytes(v)
17 elif isinstance(obj, list):
18 for i, v in enumerate(obj):
19 obj[i] = _unbytes(v)
20 elif isinstance(obj, bytes):
21 # only valid bytes are b64-encoded ascii
22 obj = obj.decode("ascii")
23 return obj
26def upgrade(nb, from_version=2, from_minor=0):
27 """Convert a notebook to v3.
29 Parameters
30 ----------
31 nb : NotebookNode
32 The Python representation of the notebook to convert.
33 from_version : int
34 The original version of the notebook to convert.
35 from_minor : int
36 The original minor version of the notebook to convert (only relevant for v >= 3).
37 """
38 if from_version == 2: # noqa
39 # Mark the original nbformat so consumers know it has been converted.
40 nb.nbformat = nbformat
41 nb.nbformat_minor = nbformat_minor
43 nb.orig_nbformat = 2
44 nb = _unbytes(nb)
45 for ws in nb["worksheets"]:
46 for cell in ws["cells"]:
47 cell.setdefault("metadata", {})
48 return nb
49 elif from_version == 3: # noqa
50 if from_minor != nbformat_minor:
51 nb.orig_nbformat_minor = from_minor
52 nb.nbformat_minor = nbformat_minor
53 return nb
54 else:
55 msg = (
56 "Cannot convert a notebook directly from v%s to v3. "
57 "Try using the nbformat.convert module." % from_version
58 )
59 raise ValueError(msg)
62def heading_to_md(cell):
63 """turn heading cell into corresponding markdown"""
64 cell.cell_type = "markdown"
65 level = cell.pop("level", 1)
66 cell.source = "#" * level + " " + cell.source
69def raw_to_md(cell):
70 """let raw passthrough as markdown"""
71 cell.cell_type = "markdown"
74def downgrade(nb):
75 """Convert a v3 notebook to v2.
77 Parameters
78 ----------
79 nb : NotebookNode
80 The Python representation of the notebook to convert.
81 """
82 if nb.nbformat != 3: # noqa
83 return nb
84 nb.nbformat = 2
85 for ws in nb.worksheets:
86 for cell in ws.cells:
87 if cell.cell_type == "heading":
88 heading_to_md(cell)
89 elif cell.cell_type == "raw":
90 raw_to_md(cell)
91 return nb