##// END OF EJS Templates
Split transformer code
Jonathan Frederic -
Show More
@@ -1,1 +1,18 b''
1
1
2 class ActivatableTransformer(ConfigurableTransformers):
3 """A simple ConfigurableTransformers that have an enabled flag
4
5 Inherit from that if you just want to have a transformer which is
6 no-op by default but can be activated in profiles with
7
8 c.YourTransformerName.enabled = True
9 """
10
11 enabled = Bool(False, config=True)
12
13 def __call__(self, nb, other):
14 if not self.enabled :
15 return nb, other
16 else :
17 return super(ActivatableTransformer, self).__call__(nb, other)
18
@@ -60,25 +60,6 b' class ConfigurableTransformers(GlobalConfigurable):'
60 raise NotImplementedError('should be implemented by subclass')
60 raise NotImplementedError('should be implemented by subclass')
61 return cell, other
61 return cell, other
62
62
63
64 class ActivatableTransformer(ConfigurableTransformers):
65 """A simple ConfigurableTransformers that have an enabled flag
66
67 Inherit from that if you just want to have a transformer which is
68 no-op by default but can be activated in profiles with
69
70 c.YourTransformerName.enabled = True
71 """
72
73 enabled = Bool(False, config=True)
74
75 def __call__(self, nb, other):
76 if not self.enabled :
77 return nb, other
78 else :
79 return super(ActivatableTransformer, self).__call__(nb, other)
80
81
82 def cell_preprocessor(function):
63 def cell_preprocessor(function):
83 """ wrap a function to be executed on all cells of a notebook
64 """ wrap a function to be executed on all cells of a notebook
84
65
@@ -137,140 +118,3 b' def coalesce_streams(cell, other, count):'
137
118
138 cell.outputs = new_outputs
119 cell.outputs = new_outputs
139 return cell, other
120 return cell, other
140
141 class ExtractFigureTransformer(ActivatableTransformer):
142
143
144 extra_ext_map = Dict({},
145 config=True,
146 help="""extra map to override extension based on type.
147 Usefull for latex where svg will be converted to pdf before inclusion
148 """
149 )
150
151 key_format_map = Dict({},
152 config=True,
153 )
154
155 figname_format_map = Dict({},
156 config=True,
157 )
158
159
160 #to do change this to .format {} syntax
161 default_key_tpl = Unicode('_fig_{count:02d}.{ext}', config=True)
162
163 def _get_ext(self, ext):
164 if ext in self.extra_ext_map :
165 return self.extra_ext_map[ext]
166 return ext
167
168 def _new_figure(self, data, fmt, count):
169 """Create a new figure file in the given format.
170
171 """
172 tplf = self.figname_format_map.get(fmt, self.default_key_tpl)
173 tplk = self.key_format_map.get(fmt, self.default_key_tpl)
174
175 # option to pass the hash as data ?
176 figname = tplf.format(count=count, ext=self._get_ext(fmt))
177 key = tplk.format(count=count, ext=self._get_ext(fmt))
178
179 # Binary files are base64-encoded, SVG is already XML
180 binary = False
181 if fmt in ('png', 'jpg', 'pdf'):
182 data = data.decode('base64')
183 binary = True
184
185 return figname, key, data, binary
186
187
188 def cell_transform(self, cell, other, count):
189 if other.get('figures', None) is None :
190 other['figures'] = {'text':{},'binary':{}}
191 for out in cell.get('outputs', []):
192 for out_type in self.display_data_priority:
193 if out.hasattr(out_type):
194 figname, key, data, binary = self._new_figure(out[out_type], out_type, count)
195 out['key_'+out_type] = figname
196 if binary :
197 other['figures']['binary'][key] = data
198 else :
199 other['figures']['text'][key] = data
200 count = count+1
201 return cell, other
202
203
204 class RevealHelpTransformer(ConfigurableTransformers):
205
206 def __call__(self, nb, other):
207 for worksheet in nb.worksheets :
208 for i, cell in enumerate(worksheet.cells):
209 if not cell.get('metadata', None):
210 break
211 cell.metadata.slide_type = cell.metadata.get('slideshow', {}).get('slide_type', None)
212 if cell.metadata.slide_type is None:
213 cell.metadata.slide_type = '-'
214 if cell.metadata.slide_type in ['slide']:
215 worksheet.cells[i - 1].metadata.slide_helper = 'slide_end'
216 if cell.metadata.slide_type in ['subslide']:
217 worksheet.cells[i - 1].metadata.slide_helper = 'subslide_end'
218 return nb, other
219
220
221 class CSSHtmlHeaderTransformer(ActivatableTransformer):
222
223 def __call__(self, nb, resources):
224 """Fetch and add css to the resource dict
225
226 Fetch css from IPython adn Pygment to add at the beginning
227 of the html files.
228
229 Add this css in resources in the "inlining.css" key
230 """
231 resources['inlining'] = {}
232 resources['inlining']['css'] = self.header
233 return nb, resources
234
235 header = []
236
237 def __init__(self, config=None, **kw):
238 super(CSSHtmlHeaderTransformer, self).__init__(config=config, **kw)
239 if self.enabled :
240 self.regen_header()
241
242 def regen_header(self):
243 ## lazy load asa this might not be use in many transformers
244 import os
245 from IPython.utils import path
246 import io
247 from pygments.formatters import HtmlFormatter
248 header = []
249 static = os.path.join(path.get_ipython_package_dir(),
250 'frontend', 'html', 'notebook', 'static',
251 )
252 here = os.path.split(os.path.realpath(__file__))[0]
253 css = os.path.join(static, 'css')
254 for sheet in [
255 # do we need jquery and prettify?
256 # os.path.join(static, 'jquery', 'css', 'themes', 'base',
257 # 'jquery-ui.min.css'),
258 # os.path.join(static, 'prettify', 'prettify.css'),
259 os.path.join(css, 'boilerplate.css'),
260 os.path.join(css, 'fbm.css'),
261 os.path.join(css, 'notebook.css'),
262 os.path.join(css, 'renderedhtml.css'),
263 os.path.join(css, 'style.min.css'),
264 ]:
265 try:
266 with io.open(sheet, encoding='utf-8') as f:
267 s = f.read()
268 header.append(s)
269 except IOError:
270 # new version of ipython with style.min.css, pass
271 pass
272
273 pygments_css = HtmlFormatter().get_style_defs('.highlight')
274 header.append(pygments_css)
275 self.header = header
276
@@ -1,1 +1,58 b''
1
1
2
3 class CSSHtmlHeaderTransformer(ActivatableTransformer):
4
5 def __call__(self, nb, resources):
6 """Fetch and add css to the resource dict
7
8 Fetch css from IPython adn Pygment to add at the beginning
9 of the html files.
10
11 Add this css in resources in the "inlining.css" key
12 """
13 resources['inlining'] = {}
14 resources['inlining']['css'] = self.header
15 return nb, resources
16
17 header = []
18
19 def __init__(self, config=None, **kw):
20 super(CSSHtmlHeaderTransformer, self).__init__(config=config, **kw)
21 if self.enabled :
22 self.regen_header()
23
24 def regen_header(self):
25 ## lazy load asa this might not be use in many transformers
26 import os
27 from IPython.utils import path
28 import io
29 from pygments.formatters import HtmlFormatter
30 header = []
31 static = os.path.join(path.get_ipython_package_dir(),
32 'frontend', 'html', 'notebook', 'static',
33 )
34 here = os.path.split(os.path.realpath(__file__))[0]
35 css = os.path.join(static, 'css')
36 for sheet in [
37 # do we need jquery and prettify?
38 # os.path.join(static, 'jquery', 'css', 'themes', 'base',
39 # 'jquery-ui.min.css'),
40 # os.path.join(static, 'prettify', 'prettify.css'),
41 os.path.join(css, 'boilerplate.css'),
42 os.path.join(css, 'fbm.css'),
43 os.path.join(css, 'notebook.css'),
44 os.path.join(css, 'renderedhtml.css'),
45 os.path.join(css, 'style.min.css'),
46 ]:
47 try:
48 with io.open(sheet, encoding='utf-8') as f:
49 s = f.read()
50 header.append(s)
51 except IOError:
52 # new version of ipython with style.min.css, pass
53 pass
54
55 pygments_css = HtmlFormatter().get_style_defs('.highlight')
56 header.append(pygments_css)
57 self.header = header
58
@@ -1,1 +1,64 b''
1
1
2
3 class ExtractFigureTransformer(ActivatableTransformer):
4
5
6 extra_ext_map = Dict({},
7 config=True,
8 help="""extra map to override extension based on type.
9 Usefull for latex where svg will be converted to pdf before inclusion
10 """
11 )
12
13 key_format_map = Dict({},
14 config=True,
15 )
16
17 figname_format_map = Dict({},
18 config=True,
19 )
20
21
22 #to do change this to .format {} syntax
23 default_key_tpl = Unicode('_fig_{count:02d}.{ext}', config=True)
24
25 def _get_ext(self, ext):
26 if ext in self.extra_ext_map :
27 return self.extra_ext_map[ext]
28 return ext
29
30 def _new_figure(self, data, fmt, count):
31 """Create a new figure file in the given format.
32
33 """
34 tplf = self.figname_format_map.get(fmt, self.default_key_tpl)
35 tplk = self.key_format_map.get(fmt, self.default_key_tpl)
36
37 # option to pass the hash as data ?
38 figname = tplf.format(count=count, ext=self._get_ext(fmt))
39 key = tplk.format(count=count, ext=self._get_ext(fmt))
40
41 # Binary files are base64-encoded, SVG is already XML
42 binary = False
43 if fmt in ('png', 'jpg', 'pdf'):
44 data = data.decode('base64')
45 binary = True
46
47 return figname, key, data, binary
48
49
50 def cell_transform(self, cell, other, count):
51 if other.get('figures', None) is None :
52 other['figures'] = {'text':{},'binary':{}}
53 for out in cell.get('outputs', []):
54 for out_type in self.display_data_priority:
55 if out.hasattr(out_type):
56 figname, key, data, binary = self._new_figure(out[out_type], out_type, count)
57 out['key_'+out_type] = figname
58 if binary :
59 other['figures']['binary'][key] = data
60 else :
61 other['figures']['text'][key] = data
62 count = count+1
63 return cell, other
64
@@ -1,1 +1,17 b''
1
1
2
3 class RevealHelpTransformer(ConfigurableTransformers):
4
5 def __call__(self, nb, other):
6 for worksheet in nb.worksheets :
7 for i, cell in enumerate(worksheet.cells):
8 if not cell.get('metadata', None):
9 break
10 cell.metadata.slide_type = cell.metadata.get('slideshow', {}).get('slide_type', None)
11 if cell.metadata.slide_type is None:
12 cell.metadata.slide_type = '-'
13 if cell.metadata.slide_type in ['slide']:
14 worksheet.cells[i - 1].metadata.slide_helper = 'slide_end'
15 if cell.metadata.slide_type in ['subslide']:
16 worksheet.cells[i - 1].metadata.slide_helper = 'subslide_end'
17 return nb, other No newline at end of file
General Comments 0
You need to be logged in to leave comments. Login now