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