##// END OF EJS Templates
preprocessing and namespace fix...
Matthias BUSSONNIER -
Show More
@@ -1,165 +1,169
1 """Base classes for the notebook conversion pipeline.
1 """Base classes for the notebook conversion pipeline.
2
2
3 This module defines Converter, from which all objects designed to implement
3 This module defines Converter, from which all objects designed to implement
4 a conversion of IPython notebooks to some other format should inherit.
4 a conversion of IPython notebooks to some other format should inherit.
5 """
5 """
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
7 # Copyright (c) 2012, the IPython Development Team.
7 # Copyright (c) 2012, the IPython Development Team.
8 #
8 #
9 # Distributed under the terms of the Modified BSD License.
9 # Distributed under the terms of the Modified BSD License.
10 #
10 #
11 # The full license is in the file COPYING.txt, distributed with this software.
11 # The full license is in the file COPYING.txt, distributed with this software.
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13
13
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 # Imports
15 # Imports
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 from __future__ import print_function, absolute_import
18 from __future__ import print_function, absolute_import
19
19
20 # Stdlib imports
20 # Stdlib imports
21 import io
21 import io
22 import os
22 import os
23 from IPython.utils import path
23 from IPython.utils import path
24
24
25 from jinja2 import Environment, FileSystemLoader
25 from jinja2 import Environment, FileSystemLoader
26 env = Environment(
26 env = Environment(
27 loader=FileSystemLoader('./templates/'),
27 loader=FileSystemLoader('./templates/'),
28 extensions=['jinja2.ext.loopcontrols']
28 extensions=['jinja2.ext.loopcontrols']
29 )
29 )
30
30
31 # IPython imports
31 # IPython imports
32 from IPython.nbformat import current as nbformat
32 from IPython.nbformat import current as nbformat
33 from IPython.config.configurable import Configurable
33 from IPython.config.configurable import Configurable
34 from IPython.utils.traitlets import ( Unicode, Any)
34 from IPython.utils.traitlets import ( Unicode, Any)
35
35
36 # Our own imports
36 # Our own imports
37 from IPython.utils.text import indent
37 from IPython.utils.text import indent
38 from .utils import remove_ansi
38 from .utils import remove_ansi
39 from markdown import markdown
39 from markdown import markdown
40 from .utils import highlight, ansi2html
40 from .utils import highlight, ansi2html
41 #-----------------------------------------------------------------------------
41 #-----------------------------------------------------------------------------
42 # Class declarations
42 # Class declarations
43 #-----------------------------------------------------------------------------
43 #-----------------------------------------------------------------------------
44 def rm_fake(strng):
44 def rm_fake(strng):
45 return strng.replace('/files/', '')
45 return strng.replace('/files/', '')
46
46
47 class ConversionException(Exception):
47 class ConversionException(Exception):
48 pass
48 pass
49
49
50
50
51 def python_comment(string):
51 def python_comment(string):
52 return '# '+'\n# '.join(string.split('\n'))
52 return '# '+'\n# '.join(string.split('\n'))
53
53
54
54
55
55
56 def header_body():
56 def header_body():
57 """Return the body of the header as a list of strings."""
57 """Return the body of the header as a list of strings."""
58
58
59 from pygments.formatters import HtmlFormatter
59 from pygments.formatters import HtmlFormatter
60
60
61 header = []
61 header = []
62 static = os.path.join(path.get_ipython_package_dir(),
62 static = os.path.join(path.get_ipython_package_dir(),
63 'frontend', 'html', 'notebook', 'static',
63 'frontend', 'html', 'notebook', 'static',
64 )
64 )
65 here = os.path.split(os.path.realpath(__file__))[0]
65 here = os.path.split(os.path.realpath(__file__))[0]
66 css = os.path.join(static, 'css')
66 css = os.path.join(static, 'css')
67 for sheet in [
67 for sheet in [
68 # do we need jquery and prettify?
68 # do we need jquery and prettify?
69 # os.path.join(static, 'jquery', 'css', 'themes', 'base',
69 # os.path.join(static, 'jquery', 'css', 'themes', 'base',
70 # 'jquery-ui.min.css'),
70 # 'jquery-ui.min.css'),
71 # os.path.join(static, 'prettify', 'prettify.css'),
71 # os.path.join(static, 'prettify', 'prettify.css'),
72 os.path.join(css, 'boilerplate.css'),
72 os.path.join(css, 'boilerplate.css'),
73 os.path.join(css, 'fbm.css'),
73 os.path.join(css, 'fbm.css'),
74 os.path.join(css, 'notebook.css'),
74 os.path.join(css, 'notebook.css'),
75 os.path.join(css, 'renderedhtml.css'),
75 os.path.join(css, 'renderedhtml.css'),
76 # our overrides:
76 # our overrides:
77 os.path.join(here, '..', 'css', 'static_html.css'),
77 os.path.join(here, '..', 'css', 'static_html.css'),
78 ]:
78 ]:
79
79
80 with io.open(sheet, encoding='utf-8') as f:
80 with io.open(sheet, encoding='utf-8') as f:
81 s = f.read()
81 s = f.read()
82 header.append(s)
82 header.append(s)
83
83
84 pygments_css = HtmlFormatter().get_style_defs('.highlight')
84 pygments_css = HtmlFormatter().get_style_defs('.highlight')
85 header.append(pygments_css)
85 header.append(pygments_css)
86 return header
86 return header
87
87
88 inlining = {}
88 inlining = {}
89 inlining['css'] = header_body()
89 inlining['css'] = header_body()
90
90
91
91
92 def filter_data_type(output):
92 def filter_data_type(output):
93 for fmt in ['html', 'pdf', 'svg', 'latex', 'png', 'jpg', 'jpeg' , 'text']:
93 for fmt in ['html', 'pdf', 'svg', 'latex', 'png', 'jpg', 'jpeg' , 'text']:
94 if fmt in output:
94 if fmt in output:
95 return [fmt]
95 return [fmt]
96
96
97
97
98 env.filters['filter_data_type'] = filter_data_type
98 env.filters['filter_data_type'] = filter_data_type
99 env.filters['pycomment'] = python_comment
99 env.filters['pycomment'] = python_comment
100 env.filters['indent'] = indent
100 env.filters['indent'] = indent
101 env.filters['rm_fake'] = rm_fake
101 env.filters['rm_fake'] = rm_fake
102 env.filters['rm_ansi'] = remove_ansi
102 env.filters['rm_ansi'] = remove_ansi
103 env.filters['markdown'] = markdown
103 env.filters['markdown'] = markdown
104 env.filters['highlight'] = highlight
104 env.filters['highlight'] = highlight
105 env.filters['ansi2html'] = ansi2html
105 env.filters['ansi2html'] = ansi2html
106
106
107
108 def haspyout_transformer(nb,_):
109 print('calling...')
110 for worksheet in nb.worksheets:
111 print('worksheet')
112 for cell in worksheet.cells:
113 cell.type = cell.cell_type
114 cell.haspyout = False
115 for out in cell.get('outputs', []):
116 if out.output_type == 'pyout':
117 cell.haspyout = True
118 break
119 return nb
120
107 class ConverterTemplate(Configurable):
121 class ConverterTemplate(Configurable):
108
122
109 display_data_priority = ['pdf', 'svg', 'png', 'jpg', 'text']
123 display_data_priority = ['pdf', 'svg', 'png', 'jpg', 'text']
110 #-------------------------------------------------------------------------
124 #-------------------------------------------------------------------------
111 # Instance-level attributes that are set in the constructor for this
125 # Instance-level attributes that are set in the constructor for this
112 # class.
126 # class.
113 #-------------------------------------------------------------------------
127 #-------------------------------------------------------------------------
114 infile = Any()
128 infile = Any()
115
129
116
130
117 infile_dir = Unicode()
131 infile_dir = Unicode()
118
132
119 def __init__(self, tplfile='fullhtml', preprocessors=[], config=None, **kw):
133 def __init__(self, tplfile='fullhtml', preprocessors=[], config=None, **kw):
120 """
134 """
121 preprocessors: list of function to run on ipynb json data before conversion
135 preprocessors: list of function to run on ipynb json data before conversion
122 to extract/inline file,
136 to extract/inline file,
123
137
124
138
125
139
126 """
140 """
127 self.template = env.get_template(tplfile+'.tpl')
141 self.template = env.get_template(tplfile+'.tpl')
128 self.nb = None
142 self.nb = None
129 self.preprocessors = preprocessors
143 self.preprocessors = preprocessors
144 self.preprocessors.append(haspyout_transformer)
130 super(ConverterTemplate, self).__init__(config=config, **kw)
145 super(ConverterTemplate, self).__init__(config=config, **kw)
131
146
147
132 def process(self):
148 def process(self):
133 nb = self.nb
149 nb = self.nb
134
150
135 for preprocessor in self.preprocessors:
151 for preprocessor in self.preprocessors:
136 nb = preprocessor(nb,{})
152 nb = preprocessor(nb,{})
137
153
138 worksheets = []
154 return nb
139 for worksheet in nb.worksheets:
140 for cell in worksheet.cells:
141 cell.type = cell.cell_type
142 cell.haspyout = False
143 for out in cell.get('outputs', []):
144 if out.output_type == 'pyout':
145 cell.haspyout = True
146 break
147 worksheets.append(worksheet)
148
149
150 return worksheets
151
155
152 def convert(self):
156 def convert(self):
153 """ convert the ipynb file
157 """ convert the ipynb file
154
158
155 return both the converted ipynb file and a dict containing potential
159 return both the converted ipynb file and a dict containing potential
156 other resources
160 other resources
157 """
161 """
158 return self.template.render(worksheets=self.process(), inlining=inlining), {}
162 return self.template.render(nb=self.process(), inlining=inlining), {}
159
163
160
164
161 def read(self, filename):
165 def read(self, filename):
162 "read and parse notebook into NotebookNode called self.nb"
166 "read and parse notebook into NotebookNode called self.nb"
163 with io.open(filename) as f:
167 with io.open(filename) as f:
164 self.nb = nbformat.read(f, 'json')
168 self.nb = nbformat.read(f, 'json')
165
169
@@ -1,89 +1,89
1 {#
1 {#
2
2
3 DO NOT USE THIS AS A BASE WORK,
3 DO NOT USE THIS AS A BASE WORK,
4 IF YOU ARE COPY AND PASTING THIS FILE
4 IF YOU ARE COPY AND PASTING THIS FILE
5 YOU ARE PROBABLY DOING THINGS WRONG.
5 YOU ARE PROBABLY DOING THINGS WRONG.
6
6
7 Null template, Does nothing except defining a basic structure
7 Null template, Does nothing except defining a basic structure
8 To layout the diferents blocks of a notebook.
8 To layout the diferents blocks of a notebook.
9
9
10 Subtemplates can Override Blocks to define their custom reresentation.
10 Subtemplates can Override Blocks to define their custom reresentation.
11
11
12 If one of the block you do overrite is not a leave block, consider
12 If one of the block you do overrite is not a leave block, consider
13 calling super.
13 calling super.
14
14
15 {%- block nonLeaveBlock -%}
15 {%- block nonLeaveBlock -%}
16 #add stuff at beginning
16 #add stuff at beginning
17 {{ super() }}
17 {{ super() }}
18 #add stuff at end
18 #add stuff at end
19 {%- endblock nonLeaveBlock -%}
19 {%- endblock nonLeaveBlock -%}
20
20
21 consider calling super even if block is leave block, we might insert more block later.
21 consider calling super even if block is leave block, we might insert more block later.
22
22
23 #}
23 #}
24 {%- block header -%}
24 {%- block header -%}
25 {%- endblock header -%}
25 {%- endblock header -%}
26 {%- block body -%}
26 {%- block body -%}
27 {%- for worksheet in worksheets -%}
27 {%- for worksheet in nb.worksheets -%}
28 {%- for cell in worksheet.cells -%}
28 {%- for cell in worksheet.cells -%}
29 {%- block any_cell scoped -%}
29 {%- block any_cell scoped -%}
30 {%- if cell.type in ['code'] -%}
30 {%- if cell.type in ['code'] -%}
31 {%- block codecell scoped -%}
31 {%- block codecell scoped -%}
32 {%- block input_group -%}
32 {%- block input_group -%}
33 {%- block in_prompt -%}{%- endblock in_prompt -%}
33 {%- block in_prompt -%}{%- endblock in_prompt -%}
34 {%- block input -%}{%- endblock input -%}
34 {%- block input -%}{%- endblock input -%}
35 {%- endblock input_group -%}
35 {%- endblock input_group -%}
36 {%- if cell.outputs -%}
36 {%- if cell.outputs -%}
37 {%- block output_group -%}
37 {%- block output_group -%}
38 {%- block output_prompt -%}{%- endblock output_prompt -%}
38 {%- block output_prompt -%}{%- endblock output_prompt -%}
39 {%- block outputs -%}
39 {%- block outputs -%}
40 {%- for output in cell.outputs -%}
40 {%- for output in cell.outputs -%}
41 {%- if output.output_type in ['pyout'] -%}
41 {%- if output.output_type in ['pyout'] -%}
42 {%- block pyout scoped -%}{%- endblock pyout -%}
42 {%- block pyout scoped -%}{%- endblock pyout -%}
43 {%- elif output.output_type in ['stream'] -%}
43 {%- elif output.output_type in ['stream'] -%}
44 {%- block stream scoped -%}
44 {%- block stream scoped -%}
45 {%- if output.stream in ['stdout'] -%}
45 {%- if output.stream in ['stdout'] -%}
46 {%- block stream_stdout scoped -%}
46 {%- block stream_stdout scoped -%}
47 {%- endblock stream_stdout -%}
47 {%- endblock stream_stdout -%}
48 {%- elif output.stream in ['stderr'] -%}
48 {%- elif output.stream in ['stderr'] -%}
49 {%- block stream_stderr scoped -%}
49 {%- block stream_stderr scoped -%}
50 {%- endblock stream_stderr -%}
50 {%- endblock stream_stderr -%}
51 {%- endif -%}
51 {%- endif -%}
52 {%- endblock stream -%}
52 {%- endblock stream -%}
53 {%- elif output.output_type in ['display_data'] -%}
53 {%- elif output.output_type in ['display_data'] -%}
54 {%- block display_data scoped -%}
54 {%- block display_data scoped -%}
55 {%- block data_priority scoped -%}
55 {%- block data_priority scoped -%}
56 {%- endblock data_priority -%}
56 {%- endblock data_priority -%}
57 {%- endblock display_data -%}
57 {%- endblock display_data -%}
58 {%- elif output.output_type in ['pyerr'] -%}
58 {%- elif output.output_type in ['pyerr'] -%}
59 {%- block pyerr scoped -%}
59 {%- block pyerr scoped -%}
60 {%- for line in output.traceback -%}
60 {%- for line in output.traceback -%}
61 {%- block traceback_line scoped -%}{%- endblock traceback_line -%}
61 {%- block traceback_line scoped -%}{%- endblock traceback_line -%}
62 {%- endfor -%}
62 {%- endfor -%}
63 {%- endblock pyerr -%}
63 {%- endblock pyerr -%}
64 {%- endif -%}
64 {%- endif -%}
65 {%- endfor -%}
65 {%- endfor -%}
66 {%- endblock outputs -%}
66 {%- endblock outputs -%}
67 {%- endblock output_group -%}
67 {%- endblock output_group -%}
68 {%- endif -%}
68 {%- endif -%}
69 {%- endblock codecell -%}
69 {%- endblock codecell -%}
70 {%- elif cell.type in ['markdown'] -%}
70 {%- elif cell.type in ['markdown'] -%}
71 {%- block markdowncell scoped-%}
71 {%- block markdowncell scoped-%}
72 {%- endblock markdowncell -%}
72 {%- endblock markdowncell -%}
73 {%- elif cell.type in ['heading'] -%}
73 {%- elif cell.type in ['heading'] -%}
74 {%- block headingcell scoped-%}
74 {%- block headingcell scoped-%}
75 {%- endblock headingcell -%}
75 {%- endblock headingcell -%}
76 {%- elif cell.type in ['raw'] -%}
76 {%- elif cell.type in ['raw'] -%}
77 {%- block rawcell scoped-%}
77 {%- block rawcell scoped-%}
78 {%- endblock rawcell -%}
78 {%- endblock rawcell -%}
79 {%- else -%}
79 {%- else -%}
80 {%- block unknowncell scoped-%}
80 {%- block unknowncell scoped-%}
81 {%- endblock unknowncell -%}
81 {%- endblock unknowncell -%}
82 {%- endif -%}
82 {%- endif -%}
83 {%- endblock any_cell -%}
83 {%- endblock any_cell -%}
84 {%- endfor -%}
84 {%- endfor -%}
85 {%- endfor -%}
85 {%- endfor -%}
86 {%- endblock body -%}
86 {%- endblock body -%}
87
87
88 {%- block footer -%}
88 {%- block footer -%}
89 {%- endblock footer -%}
89 {%- endblock footer -%}
General Comments 0
You need to be logged in to leave comments. Login now