current.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. """Deprecated API for working with notebooks
  2. - use nbformat for read/write/validate public API
  3. - use nbformat.vX directly for Python API for composing notebooks
  4. """
  5. # Copyright (c) IPython Development Team.
  6. # Distributed under the terms of the Modified BSD License.
  7. from __future__ import annotations
  8. import re
  9. import warnings
  10. from traitlets.log import get_logger
  11. from nbformat import v3 as _v_latest
  12. from nbformat.v3 import (
  13. NotebookNode,
  14. nbformat,
  15. nbformat_minor,
  16. nbformat_schema,
  17. new_author,
  18. new_code_cell,
  19. new_heading_cell,
  20. new_metadata,
  21. new_notebook,
  22. new_output,
  23. new_text_cell,
  24. new_worksheet,
  25. parse_filename,
  26. to_notebook_json,
  27. )
  28. from . import versions
  29. from .converter import convert
  30. from .reader import reads as reader_reads
  31. from .validator import ValidationError, validate
  32. warnings.warn(
  33. """nbformat.current is deprecated since before nbformat 3.0
  34. - use nbformat for read/write/validate public API
  35. - use nbformat.vX directly to composing notebooks of a particular version
  36. """,
  37. DeprecationWarning,
  38. stacklevel=2,
  39. )
  40. __all__ = [
  41. "NotebookNode",
  42. "new_code_cell",
  43. "new_text_cell",
  44. "new_notebook",
  45. "new_output",
  46. "new_worksheet",
  47. "parse_filename",
  48. "new_metadata",
  49. "new_author",
  50. "new_heading_cell",
  51. "nbformat",
  52. "nbformat_minor",
  53. "nbformat_schema",
  54. "to_notebook_json",
  55. "convert",
  56. "validate",
  57. "NBFormatError",
  58. "parse_py",
  59. "reads_json",
  60. "writes_json",
  61. "reads_py",
  62. "writes_py",
  63. "reads",
  64. "writes",
  65. "read",
  66. "write",
  67. ]
  68. current_nbformat = nbformat
  69. current_nbformat_minor = nbformat_minor
  70. current_nbformat_module = _v_latest.__name__
  71. class NBFormatError(ValueError):
  72. """An error raised for an nbformat error."""
  73. def _warn_format():
  74. warnings.warn(
  75. """Non-JSON file support in nbformat is deprecated since nbformat 1.0.
  76. Use nbconvert to create files of other formats.""",
  77. stacklevel=2,
  78. )
  79. def parse_py(s, **kwargs):
  80. """Parse a string into a (nbformat, string) tuple."""
  81. nbf = current_nbformat
  82. nbm = current_nbformat_minor
  83. pattern = r"# <nbformat>(?P<nbformat>\d+[\.\d+]*)</nbformat>"
  84. m = re.search(pattern, s)
  85. if m is not None:
  86. digits = m.group("nbformat").split(".")
  87. nbf = int(digits[0])
  88. if len(digits) > 1:
  89. nbm = int(digits[1])
  90. return nbf, nbm, s
  91. def reads_json(nbjson, **kwargs):
  92. """DEPRECATED, use reads"""
  93. warnings.warn(
  94. "reads_json is deprecated since nbformat 3.0, use reads",
  95. DeprecationWarning,
  96. stacklevel=2,
  97. )
  98. return reads(nbjson)
  99. def writes_json(nb, **kwargs):
  100. """DEPRECATED, use writes"""
  101. warnings.warn(
  102. "writes_json is deprecated since nbformat 3.0, use writes",
  103. DeprecationWarning,
  104. stacklevel=2,
  105. )
  106. return writes(nb, **kwargs)
  107. def reads_py(s, **kwargs):
  108. """DEPRECATED: use nbconvert"""
  109. _warn_format()
  110. nbf, nbm, s = parse_py(s, **kwargs)
  111. if nbf in (2, 3):
  112. nb = versions[nbf].to_notebook_py(s, **kwargs)
  113. else:
  114. raise NBFormatError("Unsupported PY nbformat version: %i" % nbf)
  115. return nb
  116. def writes_py(nb, **kwargs):
  117. """DEPRECATED: use nbconvert"""
  118. _warn_format()
  119. return versions[3].writes_py(nb, **kwargs)
  120. # High level API
  121. def reads(s, format="DEPRECATED", version=current_nbformat, **kwargs):
  122. """Read a notebook from a string and return the NotebookNode object.
  123. This function properly handles notebooks of any version. The notebook
  124. returned will always be in the current version's format.
  125. Parameters
  126. ----------
  127. s : unicode
  128. The raw unicode string to read the notebook from.
  129. Returns
  130. -------
  131. nb : NotebookNode
  132. The notebook that was read.
  133. """
  134. if format not in {"DEPRECATED", "json"}:
  135. _warn_format()
  136. nb = reader_reads(s, **kwargs)
  137. nb = convert(nb, version)
  138. try:
  139. with warnings.catch_warnings():
  140. warnings.filterwarnings("ignore", category=DeprecationWarning)
  141. validate(nb, repair_duplicate_cell_ids=False)
  142. except ValidationError as e:
  143. get_logger().error("Notebook JSON is invalid: %s", e)
  144. return nb
  145. def writes(nb, format="DEPRECATED", version=current_nbformat, **kwargs):
  146. """Write a notebook to a string in a given format in the current nbformat version.
  147. This function always writes the notebook in the current nbformat version.
  148. Parameters
  149. ----------
  150. nb : NotebookNode
  151. The notebook to write.
  152. version : int
  153. The nbformat version to write.
  154. Used for downgrading notebooks.
  155. Returns
  156. -------
  157. s : unicode
  158. The notebook string.
  159. """
  160. if format not in {"DEPRECATED", "json"}:
  161. _warn_format()
  162. nb = convert(nb, version)
  163. try:
  164. with warnings.catch_warnings():
  165. warnings.filterwarnings("ignore", category=DeprecationWarning)
  166. validate(nb, repair_duplicate_cell_ids=False)
  167. except ValidationError as e:
  168. get_logger().error("Notebook JSON is invalid: %s", e)
  169. return versions[version].writes_json(nb, **kwargs)
  170. def read(fp, format="DEPRECATED", **kwargs):
  171. """Read a notebook from a file and return the NotebookNode object.
  172. This function properly handles notebooks of any version. The notebook
  173. returned will always be in the current version's format.
  174. Parameters
  175. ----------
  176. fp : file
  177. Any file-like object with a read method.
  178. Returns
  179. -------
  180. nb : NotebookNode
  181. The notebook that was read.
  182. """
  183. return reads(fp.read(), **kwargs)
  184. def write(nb, fp, format="DEPRECATED", **kwargs):
  185. """Write a notebook to a file in a given format in the current nbformat version.
  186. This function always writes the notebook in the current nbformat version.
  187. Parameters
  188. ----------
  189. nb : NotebookNode
  190. The notebook to write.
  191. fp : file
  192. Any file-like object with a write method.
  193. """
  194. s = writes(nb, **kwargs)
  195. if isinstance(s, bytes):
  196. s = s.decode("utf8")
  197. return fp.write(s)