##// END OF EJS Templates
Start to think on api...
Matthias BUSSONNIER -
Show More
@@ -1,157 +1,162 b''
1 1 """Base classes for the notebook conversion pipeline.
2 2
3 3 This module defines Converter, from which all objects designed to implement
4 4 a conversion of IPython notebooks to some other format should inherit.
5 5 """
6 6 #-----------------------------------------------------------------------------
7 7 # Copyright (c) 2012, the IPython Development Team.
8 8 #
9 9 # Distributed under the terms of the Modified BSD License.
10 10 #
11 11 # The full license is in the file COPYING.txt, distributed with this software.
12 12 #-----------------------------------------------------------------------------
13 13
14 14 #-----------------------------------------------------------------------------
15 15 # Imports
16 16 #-----------------------------------------------------------------------------
17 17
18 18 from __future__ import print_function, absolute_import
19 19
20 20 # Stdlib imports
21 21 import jinja2
22 22 import codecs
23 23 import io
24 24 import logging
25 25 import os
26 26 from IPython.utils import path
27 27 import pprint
28 28 import re
29 29 from types import FunctionType
30 30
31 31 from jinja2 import Environment, PackageLoader, FileSystemLoader
32 32 env = Environment(
33 33 loader=FileSystemLoader('./templates/'),
34 34 extensions=['jinja2.ext.loopcontrols']
35 35 )
36 36
37 37 # IPython imports
38 38 from IPython.nbformat import current as nbformat
39 39 from IPython.config.configurable import Configurable, SingletonConfigurable
40 40 from IPython.utils.traitlets import (List, Unicode, Type, Bool, Dict, CaselessStrEnum,
41 41 Any)
42 42
43 43 # Our own imports
44 44 from IPython.utils.text import indent
45 45 from .utils import remove_ansi
46 46 from markdown import markdown
47 47 from .utils import highlight,ansi2html
48 48 #-----------------------------------------------------------------------------
49 49 # Class declarations
50 50 #-----------------------------------------------------------------------------
51 51 def rm_fake(strng):
52 52 return strng.replace('/files/', '')
53 53
54 54 class ConversionException(Exception):
55 55 pass
56 56
57 57
58 58 def python_comment(string):
59 59 return '# '+'\n# '.join(string.split('\n'))
60 60
61 61
62 62
63 63 def header_body():
64 64 """Return the body of the header as a list of strings."""
65 65
66 66 from pygments.formatters import HtmlFormatter
67 67
68 68 header = []
69 69 static = os.path.join(path.get_ipython_package_dir(),
70 70 'frontend', 'html', 'notebook', 'static',
71 71 )
72 72 here = os.path.split(os.path.realpath(__file__))[0]
73 73 css = os.path.join(static, 'css')
74 74 for sheet in [
75 75 # do we need jquery and prettify?
76 76 # os.path.join(static, 'jquery', 'css', 'themes', 'base',
77 77 # 'jquery-ui.min.css'),
78 78 # os.path.join(static, 'prettify', 'prettify.css'),
79 79 os.path.join(css, 'boilerplate.css'),
80 80 os.path.join(css, 'fbm.css'),
81 81 os.path.join(css, 'notebook.css'),
82 82 os.path.join(css, 'renderedhtml.css'),
83 83 # our overrides:
84 84 os.path.join(here, '..', 'css', 'static_html.css'),
85 85 ]:
86 86
87 87 with io.open(sheet, encoding='utf-8') as f:
88 88 s = f.read()
89 89 header.append(s)
90 90
91 91 pygments_css = HtmlFormatter().get_style_defs('.highlight')
92 92 header.append(pygments_css)
93 93 return header
94 94
95 95 inlining= {}
96 96 inlining['css'] = header_body()
97 97
98 98
99 99 def filter_data_type(output):
100 100 for fmt in ['html', 'pdf', 'svg', 'latex','png', 'jpg','jpeg' , 'text']:
101 101 if fmt in output:
102 102 return [fmt]
103 103
104 104
105 105 env.filters['filter_data_type'] = filter_data_type
106 106 env.filters['pycomment'] = python_comment
107 107 env.filters['indent'] = indent
108 108 env.filters['rm_fake'] = rm_fake
109 109 env.filters['rm_ansi'] = remove_ansi
110 110 env.filters['markdown'] = markdown
111 111 env.filters['highlight'] = highlight
112 112 env.filters['ansi2html'] = ansi2html
113 113
114 114 class ConverterTemplate(Configurable):
115 115
116 116 display_data_priority = ['pdf', 'svg', 'png', 'jpg', 'text']
117 117 #-------------------------------------------------------------------------
118 118 # Instance-level attributes that are set in the constructor for this
119 119 # class.
120 120 #-------------------------------------------------------------------------
121 121 infile = Any()
122 122
123 123
124 124 infile_dir = Unicode()
125 125
126 126 def __init__(self, tplfile='fullhtml', config=None, **kw):
127 127 self.template = env.get_template(tplfile+'.tpl')
128 128 super(ConverterTemplate,self).__init__(config=config)
129 129
130 130 def _get_prompt_number(self, cell):
131 131 return cell.prompt_number if hasattr(cell, 'prompt_number') \
132 132 else self.blank_symbol
133 133
134 134
135 135 def process(self):
136 136 converted_cells = []
137 137 for worksheet in self.nb.worksheets:
138 138 for cell in worksheet.cells:
139 139 cell.type = cell.cell_type
140 140 cell.haspyout = False
141 141 for out in cell.get('outputs',[]):
142 142 if out.output_type == 'pyout':
143 143 cell.haspyout = True
144 144 break
145 145 converted_cells.append(worksheet)
146 146
147 147 return converted_cells
148 148
149 149 def convert(self, cell_separator='\n'):
150 return self.template.render(worksheets=self.process(), inlining=inlining)
150 """ convert the ipynb file
151
152 return both the converted ipynb file and a dict containing potential
153 other resources
154 """
155 return self.template.render(worksheets=self.process(), inlining=inlining),{}
151 156
152 157
153 158 def read(self, filename):
154 159 "read and parse notebook into NotebookNode called self.nb"
155 160 with io.open(filename) as f:
156 161 self.nb = nbformat.read(f, 'json')
157 162
@@ -1,11 +1,13 b''
1 1 #!/usr/bin/env python
2 2 # coding: utf-8
3 3
4 4 from __future__ import print_function
5 5 import sys
6 6 import io
7 7 from converters.template import *
8 8 C = ConverterTemplate(tplfile=sys.argv[1])
9 9 C.read(sys.argv[2])
10 10
11 print(C.convert().encode('utf-8'))
11 output,rest = C.convert()
12
13 print(output.encode('utf-8'))
General Comments 0
You need to be logged in to leave comments. Login now