convertfigures.py 1.4 KB

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