convert.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. """Code for converting notebooks to and from the v2 format."""
  2. # Copyright (c) IPython Development Team.
  3. # Distributed under the terms of the Modified BSD License.
  4. from __future__ import annotations
  5. from .nbbase import nbformat, nbformat_minor
  6. def _unbytes(obj):
  7. """There should be no bytes objects in a notebook
  8. v2 stores png/jpeg as b64 ascii bytes
  9. """
  10. if isinstance(obj, dict):
  11. for k, v in obj.items():
  12. obj[k] = _unbytes(v)
  13. elif isinstance(obj, list):
  14. for i, v in enumerate(obj):
  15. obj[i] = _unbytes(v)
  16. elif isinstance(obj, bytes):
  17. # only valid bytes are b64-encoded ascii
  18. obj = obj.decode("ascii")
  19. return obj
  20. def upgrade(nb, from_version=2, from_minor=0):
  21. """Convert a notebook to v3.
  22. Parameters
  23. ----------
  24. nb : NotebookNode
  25. The Python representation of the notebook to convert.
  26. from_version : int
  27. The original version of the notebook to convert.
  28. from_minor : int
  29. The original minor version of the notebook to convert (only relevant for v >= 3).
  30. """
  31. if from_version == 2:
  32. # Mark the original nbformat so consumers know it has been converted.
  33. nb.nbformat = nbformat
  34. nb.nbformat_minor = nbformat_minor
  35. nb.orig_nbformat = 2
  36. nb = _unbytes(nb)
  37. for ws in nb["worksheets"]:
  38. for cell in ws["cells"]:
  39. cell.setdefault("metadata", {})
  40. return nb
  41. if from_version == 3:
  42. if from_minor != nbformat_minor:
  43. nb.orig_nbformat_minor = from_minor
  44. nb.nbformat_minor = nbformat_minor
  45. return nb
  46. msg = (
  47. "Cannot convert a notebook directly from v%s to v3. "
  48. "Try using the nbformat.convert module." % from_version
  49. )
  50. raise ValueError(msg)
  51. def heading_to_md(cell):
  52. """turn heading cell into corresponding markdown"""
  53. cell.cell_type = "markdown"
  54. level = cell.pop("level", 1)
  55. cell.source = "#" * level + " " + cell.source
  56. def raw_to_md(cell):
  57. """let raw passthrough as markdown"""
  58. cell.cell_type = "markdown"
  59. def downgrade(nb):
  60. """Convert a v3 notebook to v2.
  61. Parameters
  62. ----------
  63. nb : NotebookNode
  64. The Python representation of the notebook to convert.
  65. """
  66. if nb.nbformat != 3:
  67. return nb
  68. nb.nbformat = 2
  69. for ws in nb.worksheets:
  70. for cell in ws.cells:
  71. if cell.cell_type == "heading":
  72. heading_to_md(cell)
  73. elif cell.cell_type == "raw":
  74. raw_to_md(cell)
  75. return nb