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