convert.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. """Code for converting notebooks to and from the v2 format.
  2. Authors:
  3. * Brian Granger
  4. * Jonathan Frederic
  5. """
  6. # -----------------------------------------------------------------------------
  7. # Copyright (C) 2008-2011 The IPython Development Team
  8. #
  9. # Distributed under the terms of the BSD License. The full license is in
  10. # the file LICENSE, distributed as part of this software.
  11. # -----------------------------------------------------------------------------
  12. # -----------------------------------------------------------------------------
  13. # Imports
  14. # -----------------------------------------------------------------------------
  15. from __future__ import annotations
  16. from .nbbase import new_code_cell, new_notebook, new_text_cell, new_worksheet
  17. # -----------------------------------------------------------------------------
  18. # Code
  19. # -----------------------------------------------------------------------------
  20. def upgrade(nb, from_version=1):
  21. """Convert a notebook to the v2 format.
  22. Parameters
  23. ----------
  24. nb : NotebookNode
  25. The Python representation of the notebook to convert.
  26. from_version : int
  27. The version of the notebook to convert from.
  28. """
  29. if from_version == 1:
  30. newnb = new_notebook()
  31. ws = new_worksheet()
  32. for cell in nb.cells:
  33. if cell.cell_type == "code":
  34. newcell = new_code_cell(
  35. input=cell.get("code"), prompt_number=cell.get("prompt_number")
  36. )
  37. elif cell.cell_type == "text":
  38. newcell = new_text_cell("markdown", source=cell.get("text"))
  39. ws.cells.append(newcell)
  40. newnb.worksheets.append(ws)
  41. return newnb
  42. raise ValueError("Cannot convert a notebook from v%s to v2" % from_version)
  43. def downgrade(nb):
  44. """Convert a v2 notebook to v1.
  45. Parameters
  46. ----------
  47. nb : NotebookNode
  48. The Python representation of the notebook to convert.
  49. """
  50. msg = "Downgrade from notebook v2 to v1 is not supported."
  51. raise Exception(msg)