convertfigures.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. """Module containing a preprocessor that converts outputs in the notebook from
  2. one format to another.
  3. Converts all of the outputs in a notebook from one format to another.
  4. """
  5. # Copyright (c) Jupyter Development Team.
  6. # Distributed under the terms of the Modified BSD License.
  7. from traitlets import Unicode
  8. from .base import Preprocessor
  9. class ConvertFiguresPreprocessor(Preprocessor):
  10. """
  11. Converts all of the outputs in a notebook from one format to another.
  12. """
  13. from_format = Unicode(help="Format the converter accepts").tag(config=True)
  14. to_format = Unicode(help="Format the converter writes").tag(config=True)
  15. def __init__(self, **kw):
  16. """
  17. Public constructor
  18. """
  19. super().__init__(**kw)
  20. def convert_figure(self, data_format, data):
  21. """Convert the figure."""
  22. raise NotImplementedError()
  23. def preprocess_cell(self, cell, resources, cell_index):
  24. """
  25. Apply a transformation on each cell,
  26. See base.py
  27. """
  28. # Loop through all of the datatypes of the outputs in the cell.
  29. for output in cell.get("outputs", []):
  30. if (
  31. output.output_type in {"execute_result", "display_data"}
  32. and self.from_format in output.data
  33. and self.to_format not in output.data
  34. ):
  35. output.data[self.to_format] = self.convert_figure(
  36. self.from_format, output.data[self.from_format]
  37. )
  38. return cell, resources