##// END OF EJS Templates
add possibility to preprocess ipynb files
add possibility to preprocess ipynb files

File last commit:

r9184:b5e3545c
r9184:b5e3545c
Show More
template.py
165 lines | 5.0 KiB | text/x-python | PythonLexer
Matthias BUSSONNIER
starting templates
r8994 """Base classes for the notebook conversion pipeline.
This module defines Converter, from which all objects designed to implement
a conversion of IPython notebooks to some other format should inherit.
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2012, the IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
from __future__ import print_function, absolute_import
# Stdlib imports
import io
import os
Matthias BUSSONNIER
read css from ipython dir
r9040 from IPython.utils import path
Matthias BUSSONNIER
starting templates
r8994
Matthias BUSSONNIER
remove and clean code
r9183 from jinja2 import Environment, FileSystemLoader
Matthias BUSSONNIER
try to play with data display priority
r9049 env = Environment(
Matthias BUSSONNIER
add possibility to preprocess ipynb files
r9184 loader=FileSystemLoader('./templates/'),
Matthias BUSSONNIER
try to play with data display priority
r9049 extensions=['jinja2.ext.loopcontrols']
)
Matthias BUSSONNIER
starting templates
r8994
# IPython imports
from IPython.nbformat import current as nbformat
Matthias BUSSONNIER
remove and clean code
r9183 from IPython.config.configurable import Configurable
from IPython.utils.traitlets import ( Unicode, Any)
Matthias BUSSONNIER
starting templates
r8994
# Our own imports
from IPython.utils.text import indent
from .utils import remove_ansi
Matthias BUSSONNIER
null template
r8997 from markdown import markdown
Matthias BUSSONNIER
remove and clean code
r9183 from .utils import highlight, ansi2html
Matthias BUSSONNIER
starting templates
r8994 #-----------------------------------------------------------------------------
# Class declarations
#-----------------------------------------------------------------------------
def rm_fake(strng):
return strng.replace('/files/', '')
class ConversionException(Exception):
pass
def python_comment(string):
return '# '+'\n# '.join(string.split('\n'))
Matthias BUSSONNIER
read css from ipython dir
r9040
def header_body():
Matthias BUSSONNIER
remove and clean code
r9183 """Return the body of the header as a list of strings."""
from pygments.formatters import HtmlFormatter
header = []
static = os.path.join(path.get_ipython_package_dir(),
'frontend', 'html', 'notebook', 'static',
)
here = os.path.split(os.path.realpath(__file__))[0]
css = os.path.join(static, 'css')
for sheet in [
# do we need jquery and prettify?
# os.path.join(static, 'jquery', 'css', 'themes', 'base',
# 'jquery-ui.min.css'),
# os.path.join(static, 'prettify', 'prettify.css'),
os.path.join(css, 'boilerplate.css'),
os.path.join(css, 'fbm.css'),
os.path.join(css, 'notebook.css'),
os.path.join(css, 'renderedhtml.css'),
# our overrides:
os.path.join(here, '..', 'css', 'static_html.css'),
]:
with io.open(sheet, encoding='utf-8') as f:
s = f.read()
header.append(s)
pygments_css = HtmlFormatter().get_style_defs('.highlight')
header.append(pygments_css)
return header
inlining = {}
Matthias BUSSONNIER
modularize inlining
r9048 inlining['css'] = header_body()
Matthias BUSSONNIER
read css from ipython dir
r9040
Matthias BUSSONNIER
try to play with data display priority
r9049
def filter_data_type(output):
Matthias BUSSONNIER
remove and clean code
r9183 for fmt in ['html', 'pdf', 'svg', 'latex', 'png', 'jpg', 'jpeg' , 'text']:
Matthias BUSSONNIER
try to play with data display priority
r9049 if fmt in output:
return [fmt]
env.filters['filter_data_type'] = filter_data_type
Matthias BUSSONNIER
starting templates
r8994 env.filters['pycomment'] = python_comment
env.filters['indent'] = indent
env.filters['rm_fake'] = rm_fake
env.filters['rm_ansi'] = remove_ansi
Matthias BUSSONNIER
null template
r8997 env.filters['markdown'] = markdown
env.filters['highlight'] = highlight
Matthias BUSSONNIER
svgoutput
r9039 env.filters['ansi2html'] = ansi2html
Matthias BUSSONNIER
starting templates
r8994
class ConverterTemplate(Configurable):
display_data_priority = ['pdf', 'svg', 'png', 'jpg', 'text']
#-------------------------------------------------------------------------
# Instance-level attributes that are set in the constructor for this
# class.
#-------------------------------------------------------------------------
infile = Any()
Matthias BUSSONNIER
deal with worksheets
r9010
Matthias BUSSONNIER
starting templates
r8994 infile_dir = Unicode()
Matthias BUSSONNIER
add possibility to preprocess ipynb files
r9184 def __init__(self, tplfile='fullhtml', preprocessors=[], config=None, **kw):
"""
preprocessors: list of function to run on ipynb json data before conversion
to extract/inline file,
"""
Matthias BUSSONNIER
null template
r8997 self.template = env.get_template(tplfile+'.tpl')
Matthias BUSSONNIER
remove and clean code
r9183 self.nb = None
Matthias BUSSONNIER
add possibility to preprocess ipynb files
r9184 self.preprocessors = preprocessors
Matthias BUSSONNIER
remove and clean code
r9183 super(ConverterTemplate, self).__init__(config=config, **kw)
Matthias BUSSONNIER
starting templates
r8994
def process(self):
Matthias BUSSONNIER
add possibility to preprocess ipynb files
r9184 nb = self.nb
for preprocessor in self.preprocessors:
nb = preprocessor(nb,{})
worksheets = []
for worksheet in nb.worksheets:
Matthias BUSSONNIER
starting templates
r8994 for cell in worksheet.cells:
cell.type = cell.cell_type
Matthias BUSSONNIER
svgoutput
r9039 cell.haspyout = False
Matthias BUSSONNIER
remove and clean code
r9183 for out in cell.get('outputs', []):
Matthias BUSSONNIER
svgoutput
r9039 if out.output_type == 'pyout':
cell.haspyout = True
break
Matthias BUSSONNIER
add possibility to preprocess ipynb files
r9184 worksheets.append(worksheet)
Matthias BUSSONNIER
starting templates
r8994
Matthias BUSSONNIER
add possibility to preprocess ipynb files
r9184 return worksheets
Matthias BUSSONNIER
starting templates
r8994
Matthias BUSSONNIER
remove and clean code
r9183 def convert(self):
Matthias BUSSONNIER
Start to think on api...
r9182 """ convert the ipynb file
return both the converted ipynb file and a dict containing potential
other resources
"""
Matthias BUSSONNIER
remove and clean code
r9183 return self.template.render(worksheets=self.process(), inlining=inlining), {}
Matthias BUSSONNIER
starting templates
r8994
def read(self, filename):
"read and parse notebook into NotebookNode called self.nb"
Matthias BUSSONNIER
fix utf8
r9014 with io.open(filename) as f:
Matthias BUSSONNIER
starting templates
r8994 self.nb = nbformat.read(f, 'json')