nbbase.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. """The basic dict based notebook format.
  2. The Python representation of a notebook is a nested structure of
  3. dictionary subclasses that support attribute access.
  4. The functions in this module are merely
  5. helpers to build the structs in the right form.
  6. """
  7. # Copyright (c) IPython Development Team.
  8. # Distributed under the terms of the Modified BSD License.
  9. from __future__ import annotations
  10. import warnings
  11. from nbformat._struct import Struct
  12. # -----------------------------------------------------------------------------
  13. # Code
  14. # -----------------------------------------------------------------------------
  15. # Change this when incrementing the nbformat version
  16. nbformat = 3
  17. nbformat_minor = 0
  18. nbformat_schema = {(3, 0): "nbformat.v3.schema.json"}
  19. class NotebookNode(Struct):
  20. """A notebook node object."""
  21. def from_dict(d):
  22. """Create notebook node(s) from an object."""
  23. if isinstance(d, dict):
  24. newd = NotebookNode()
  25. for k, v in d.items():
  26. newd[k] = from_dict(v)
  27. return newd
  28. if isinstance(d, (tuple, list)):
  29. return [from_dict(i) for i in d]
  30. return d
  31. def str_passthrough(obj):
  32. """
  33. Used to be cast_unicode, add this temporarily to make sure no further breakage.
  34. """
  35. if not isinstance(obj, str):
  36. raise AssertionError
  37. return obj
  38. def cast_str(obj):
  39. """Cast an object as a string."""
  40. if isinstance(obj, bytes):
  41. # really this should never happened, it should
  42. # have been base64 encoded before.
  43. warnings.warn(
  44. "A notebook got bytes instead of likely base64 encoded values."
  45. "The content will likely be corrupted.",
  46. UserWarning,
  47. stacklevel=3,
  48. )
  49. return obj.decode("ascii", "replace")
  50. if not isinstance(obj, str):
  51. raise AssertionError
  52. return obj
  53. def new_output(
  54. output_type,
  55. output_text=None,
  56. output_png=None,
  57. output_html=None,
  58. output_svg=None,
  59. output_latex=None,
  60. output_json=None,
  61. output_javascript=None,
  62. output_jpeg=None,
  63. prompt_number=None,
  64. ename=None,
  65. evalue=None,
  66. traceback=None,
  67. stream=None,
  68. metadata=None,
  69. ):
  70. """Create a new output, to go in the ``cell.outputs`` list of a code cell."""
  71. output = NotebookNode()
  72. output.output_type = str(output_type)
  73. if metadata is None:
  74. metadata = {}
  75. if not isinstance(metadata, dict):
  76. msg = "metadata must be dict"
  77. raise TypeError(msg)
  78. if output_type in {"pyout", "display_data"}:
  79. output.metadata = metadata
  80. if output_type != "pyerr":
  81. if output_text is not None:
  82. output.text = str_passthrough(output_text)
  83. if output_png is not None:
  84. output.png = cast_str(output_png)
  85. if output_jpeg is not None:
  86. output.jpeg = cast_str(output_jpeg)
  87. if output_html is not None:
  88. output.html = str_passthrough(output_html)
  89. if output_svg is not None:
  90. output.svg = str_passthrough(output_svg)
  91. if output_latex is not None:
  92. output.latex = str_passthrough(output_latex)
  93. if output_json is not None:
  94. output.json = str_passthrough(output_json)
  95. if output_javascript is not None:
  96. output.javascript = str_passthrough(output_javascript)
  97. if output_type == "pyout" and prompt_number is not None:
  98. output.prompt_number = int(prompt_number)
  99. if output_type == "pyerr":
  100. if ename is not None:
  101. output.ename = str_passthrough(ename)
  102. if evalue is not None:
  103. output.evalue = str_passthrough(evalue)
  104. if traceback is not None:
  105. output.traceback = [str_passthrough(frame) for frame in list(traceback)]
  106. if output_type == "stream":
  107. output.stream = "stdout" if stream is None else str_passthrough(stream)
  108. return output
  109. def new_code_cell(
  110. input=None,
  111. prompt_number=None,
  112. outputs=None,
  113. language="python",
  114. collapsed=False,
  115. metadata=None,
  116. ):
  117. """Create a new code cell with input and output"""
  118. cell = NotebookNode()
  119. cell.cell_type = "code"
  120. if language is not None:
  121. cell.language = str_passthrough(language)
  122. if input is not None:
  123. cell.input = str_passthrough(input)
  124. if prompt_number is not None:
  125. cell.prompt_number = int(prompt_number)
  126. if outputs is None:
  127. cell.outputs = []
  128. else:
  129. cell.outputs = outputs
  130. if collapsed is not None:
  131. cell.collapsed = bool(collapsed)
  132. cell.metadata = NotebookNode(metadata or {})
  133. return cell
  134. def new_text_cell(cell_type, source=None, rendered=None, metadata=None):
  135. """Create a new text cell."""
  136. cell = NotebookNode()
  137. # VERSIONHACK: plaintext -> raw
  138. # handle never-released plaintext name for raw cells
  139. if cell_type == "plaintext":
  140. cell_type = "raw"
  141. if source is not None:
  142. cell.source = str_passthrough(source)
  143. cell.metadata = NotebookNode(metadata or {})
  144. cell.cell_type = cell_type
  145. return cell
  146. def new_heading_cell(source=None, level=1, rendered=None, metadata=None):
  147. """Create a new section cell with a given integer level."""
  148. cell = NotebookNode()
  149. cell.cell_type = "heading"
  150. if source is not None:
  151. cell.source = str_passthrough(source)
  152. cell.level = int(level)
  153. cell.metadata = NotebookNode(metadata or {})
  154. return cell
  155. def new_worksheet(name=None, cells=None, metadata=None):
  156. """Create a worksheet by name with with a list of cells."""
  157. ws = NotebookNode()
  158. if cells is None:
  159. ws.cells = []
  160. else:
  161. ws.cells = list(cells)
  162. ws.metadata = NotebookNode(metadata or {})
  163. return ws
  164. def new_notebook(name=None, metadata=None, worksheets=None):
  165. """Create a notebook by name, id and a list of worksheets."""
  166. nb = NotebookNode()
  167. nb.nbformat = nbformat
  168. nb.nbformat_minor = nbformat_minor
  169. if worksheets is None:
  170. nb.worksheets = []
  171. else:
  172. nb.worksheets = list(worksheets)
  173. if metadata is None:
  174. nb.metadata = new_metadata()
  175. else:
  176. nb.metadata = NotebookNode(metadata)
  177. if name is not None:
  178. nb.metadata.name = str_passthrough(name)
  179. return nb
  180. def new_metadata(
  181. name=None,
  182. authors=None,
  183. license=None,
  184. created=None,
  185. modified=None,
  186. gistid=None,
  187. ):
  188. """Create a new metadata node."""
  189. metadata = NotebookNode()
  190. if name is not None:
  191. metadata.name = str_passthrough(name)
  192. if authors is not None:
  193. metadata.authors = list(authors)
  194. if created is not None:
  195. metadata.created = str_passthrough(created)
  196. if modified is not None:
  197. metadata.modified = str_passthrough(modified)
  198. if license is not None:
  199. metadata.license = str_passthrough(license)
  200. if gistid is not None:
  201. metadata.gistid = str_passthrough(gistid)
  202. return metadata
  203. def new_author(name=None, email=None, affiliation=None, url=None):
  204. """Create a new author."""
  205. author = NotebookNode()
  206. if name is not None:
  207. author.name = str_passthrough(name)
  208. if email is not None:
  209. author.email = str_passthrough(email)
  210. if affiliation is not None:
  211. author.affiliation = str_passthrough(affiliation)
  212. if url is not None:
  213. author.url = str_passthrough(url)
  214. return author