reader.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. """API for reading notebooks of different versions"""
  2. # Copyright (c) IPython Development Team.
  3. # Distributed under the terms of the Modified BSD License.
  4. from __future__ import annotations
  5. import json
  6. from .validator import ValidationError
  7. class NotJSONError(ValueError):
  8. """An error raised when an object is not valid JSON."""
  9. def parse_json(s, **kwargs):
  10. """Parse a JSON string into a dict."""
  11. try:
  12. nb_dict = json.loads(s, **kwargs)
  13. except ValueError as e:
  14. message = f"Notebook does not appear to be JSON: {s!r}"
  15. # Limit the error message to 80 characters. Display whatever JSON will fit.
  16. if len(message) > 80:
  17. message = message[:77] + "..."
  18. raise NotJSONError(message) from e
  19. return nb_dict
  20. # High level API
  21. def get_version(nb):
  22. """Get the version of a notebook.
  23. Parameters
  24. ----------
  25. nb : dict
  26. NotebookNode or dict containing notebook data.
  27. Returns
  28. -------
  29. Tuple containing major (int) and minor (int) version numbers
  30. """
  31. major = nb.get("nbformat", 1)
  32. minor = nb.get("nbformat_minor", 0)
  33. return (major, minor)
  34. def reads(s, **kwargs):
  35. """Read a notebook from a json string and return the
  36. NotebookNode object.
  37. This function properly reads notebooks of any version. No version
  38. conversion is performed.
  39. Parameters
  40. ----------
  41. s : unicode | bytes
  42. The raw string or bytes object to read the notebook from.
  43. Returns
  44. -------
  45. nb : NotebookNode
  46. The notebook that was read.
  47. Raises
  48. ------
  49. ValidationError
  50. Notebook JSON for a given version is missing an expected key and cannot be read.
  51. NBFormatError
  52. Specified major version is invalid or unsupported.
  53. """
  54. from . import NBFormatError, versions
  55. nb_dict = parse_json(s, **kwargs)
  56. (major, minor) = get_version(nb_dict)
  57. if major in versions:
  58. try:
  59. return versions[major].to_notebook_json(nb_dict, minor=minor)
  60. except AttributeError as e:
  61. msg = f"The notebook is invalid and is missing an expected key: {e}"
  62. raise ValidationError(msg) from None
  63. else:
  64. raise NBFormatError("Unsupported nbformat version %s" % major)
  65. def read(fp, **kwargs):
  66. """Read a notebook from a file and return the NotebookNode object.
  67. This function properly reads notebooks of any version. No version
  68. conversion is performed.
  69. Parameters
  70. ----------
  71. fp : file
  72. Any file-like object with a read method.
  73. Returns
  74. -------
  75. nb : NotebookNode
  76. The notebook that was read.
  77. """
  78. return reads(fp.read(), **kwargs)