notebook.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. """
  2. Notebook Tag
  3. ------------
  4. This is a liquid-style tag to include a static html rendering of an IPython
  5. notebook in a blog post.
  6. Syntax
  7. ------
  8. {% notebook filename.ipynb [ cells[start:end] ]%}
  9. The file should be specified relative to the ``notebooks`` subdirectory of the
  10. content directory. Optionally, this subdirectory can be specified in the
  11. config file:
  12. NOTEBOOK_DIR = 'notebooks'
  13. The cells[start:end] statement is optional, and can be used to specify which
  14. block of cells from the notebook to include.
  15. Requirements
  16. ------------
  17. - The plugin requires IPython version 1.0 or above. It no longer supports the
  18. standalone nbconvert package, which has been deprecated.
  19. Details
  20. -------
  21. Because the notebook relies on some rather extensive custom CSS, the use of
  22. this plugin requires additional CSS to be inserted into the blog theme.
  23. After typing "make html" when using the notebook tag, a file called
  24. ``_nb_header.html`` will be produced in the main directory. The content
  25. of the file should be included in the header of the theme. An easy way
  26. to accomplish this is to add the following lines within the header template
  27. of the theme you use:
  28. {% if EXTRA_HEADER %}
  29. {{ EXTRA_HEADER }}
  30. {% endif %}
  31. and in your ``pelicanconf.py`` file, include the line:
  32. EXTRA_HEADER = open('_nb_header.html').read().decode('utf-8')
  33. this will insert the appropriate CSS. All efforts have been made to ensure
  34. that this CSS will not override formats within the blog theme, but there may
  35. still be some conflicts.
  36. """
  37. import re
  38. import os
  39. from .mdx_liquid_tags import LiquidTags
  40. from distutils.version import LooseVersion
  41. import IPython
  42. if not LooseVersion(IPython.__version__) >= '1.0':
  43. raise ValueError("IPython version 1.0+ required for notebook tag")
  44. from IPython import nbconvert
  45. try:
  46. from IPython.nbconvert.filters.highlight import _pygments_highlight
  47. except ImportError:
  48. # IPython < 2.0
  49. from IPython.nbconvert.filters.highlight import _pygment_highlight as _pygments_highlight
  50. from pygments.formatters import HtmlFormatter
  51. from IPython.nbconvert.exporters import HTMLExporter
  52. from IPython.config import Config
  53. from IPython.nbformat import current as nbformat
  54. try:
  55. from IPython.nbconvert.preprocessors import Preprocessor
  56. except ImportError:
  57. # IPython < 2.0
  58. from IPython.nbconvert.transformers import Transformer as Preprocessor
  59. from IPython.utils.traitlets import Integer
  60. from copy import deepcopy
  61. from jinja2 import DictLoader
  62. #----------------------------------------------------------------------
  63. # Some code that will be added to the header:
  64. # Some of the following javascript/css include is adapted from
  65. # IPython/nbconvert/templates/fullhtml.tpl, while some are custom tags
  66. # specifically designed to make the results look good within the
  67. # pelican-octopress theme.
  68. JS_INCLUDE = r"""
  69. <style type="text/css">
  70. /* Overrides of notebook CSS for static HTML export */
  71. div.entry-content {
  72. overflow: visible;
  73. padding: 8px;
  74. }
  75. .input_area {
  76. padding: 0.2em;
  77. }
  78. a.heading-anchor {
  79. white-space: normal;
  80. }
  81. .rendered_html
  82. code {
  83. font-size: .8em;
  84. }
  85. pre.ipynb {
  86. color: black;
  87. background: #f7f7f7;
  88. border: none;
  89. box-shadow: none;
  90. margin-bottom: 0;
  91. padding: 0;
  92. margin: 0px;
  93. font-size: 13px;
  94. }
  95. /* remove the prompt div from text cells */
  96. div.text_cell .prompt {
  97. display: none;
  98. }
  99. /* remove horizontal padding from text cells, */
  100. /* so it aligns with outer body text */
  101. div.text_cell_render {
  102. padding: 0.5em 0em;
  103. }
  104. img.anim_icon{padding:0; border:0; vertical-align:middle; -webkit-box-shadow:none; -box-shadow:none}
  105. div.collapseheader {
  106. width=100%;
  107. background-color:#d3d3d3;
  108. padding: 2px;
  109. cursor: pointer;
  110. font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;
  111. }
  112. </style>
  113. <script src="https://c328740.ssl.cf1.rackcdn.com/mathjax/latest/MathJax.js?config=TeX-AMS_HTML" type="text/javascript"></script>
  114. <script type="text/javascript">
  115. init_mathjax = function() {
  116. if (window.MathJax) {
  117. // MathJax loaded
  118. MathJax.Hub.Config({
  119. tex2jax: {
  120. inlineMath: [ ['$','$'], ["\\(","\\)"] ],
  121. displayMath: [ ['$$','$$'], ["\\[","\\]"] ]
  122. },
  123. displayAlign: 'left', // Change this to 'center' to center equations.
  124. "HTML-CSS": {
  125. styles: {'.MathJax_Display': {"margin": 0}}
  126. }
  127. });
  128. MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
  129. }
  130. }
  131. init_mathjax();
  132. </script>
  133. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
  134. <script type="text/javascript">
  135. jQuery(document).ready(function($) {
  136. $("div.collapseheader").click(function () {
  137. $header = $(this).children("span").first();
  138. $codearea = $(this).children(".input_area");
  139. console.log($(this).children());
  140. $codearea.slideToggle(500, function () {
  141. $header.text(function () {
  142. return $codearea.is(":visible") ? "Collapse Code" : "Expand Code";
  143. });
  144. });
  145. });
  146. });
  147. </script>
  148. """
  149. CSS_WRAPPER = """
  150. <style type="text/css">
  151. {0}
  152. </style>
  153. """
  154. #----------------------------------------------------------------------
  155. # Create a custom preprocessor
  156. class SliceIndex(Integer):
  157. """An integer trait that accepts None"""
  158. default_value = None
  159. def validate(self, obj, value):
  160. if value is None:
  161. return value
  162. else:
  163. return super(SliceIndex, self).validate(obj, value)
  164. class SubCell(Preprocessor):
  165. """A transformer to select a slice of the cells of a notebook"""
  166. start = SliceIndex(0, config=True,
  167. help="first cell of notebook to be converted")
  168. end = SliceIndex(None, config=True,
  169. help="last cell of notebook to be converted")
  170. def preprocess(self, nb, resources):
  171. nbc = deepcopy(nb)
  172. for worksheet in nbc.worksheets:
  173. cells = worksheet.cells[:]
  174. worksheet.cells = cells[self.start:self.end]
  175. return nbc, resources
  176. call = preprocess # IPython < 2.0
  177. #----------------------------------------------------------------------
  178. # Custom highlighter:
  179. # instead of using class='highlight', use class='highlight-ipynb'
  180. def custom_highlighter(source, language='ipython', metadata=None):
  181. formatter = HtmlFormatter(cssclass='highlight-ipynb')
  182. if not language:
  183. language = 'ipython'
  184. output = _pygments_highlight(source, formatter, language)
  185. return output.replace('<pre>', '<pre class="ipynb">')
  186. #----------------------------------------------------------------------
  187. # Below is the pelican plugin code.
  188. #
  189. SYNTAX = "{% notebook /path/to/notebook.ipynb [ cells[start:end] ] %}"
  190. FORMAT = re.compile(r"""^(\s+)?(?P<src>\S+)(\s+)?((cells\[)(?P<start>-?[0-9]*):(?P<end>-?[0-9]*)(\]))?(\s+)?$""")
  191. @LiquidTags.register('notebook')
  192. def notebook(preprocessor, tag, markup):
  193. match = FORMAT.search(markup)
  194. if match:
  195. argdict = match.groupdict()
  196. src = argdict['src']
  197. start = argdict['start']
  198. end = argdict['end']
  199. else:
  200. raise ValueError("Error processing input, "
  201. "expected syntax: {0}".format(SYNTAX))
  202. if start:
  203. start = int(start)
  204. else:
  205. start = 0
  206. if end:
  207. end = int(end)
  208. else:
  209. end = None
  210. settings = preprocessor.configs.config['settings']
  211. nb_dir = settings.get('NOTEBOOK_DIR', 'notebooks')
  212. nb_path = os.path.join('content', nb_dir, src)
  213. if not os.path.exists(nb_path):
  214. raise ValueError("File {0} could not be found".format(nb_path))
  215. # Create the custom notebook converter
  216. c = Config({'CSSHTMLHeaderTransformer':
  217. {'enabled':True, 'highlight_class':'.highlight-ipynb'},
  218. 'SubCell':
  219. {'enabled':True, 'start':start, 'end':end}})
  220. template_file = 'basic'
  221. if LooseVersion(IPython.__version__) >= '2.0':
  222. if os.path.exists('pelicanhtml_2.tpl'):
  223. template_file = 'pelicanhtml_2'
  224. else:
  225. if os.path.exists('pelicanhtml_1.tpl'):
  226. template_file = 'pelicanhtml_1'
  227. if LooseVersion(IPython.__version__) >= '2.0':
  228. subcell_kwarg = dict(preprocessors=[SubCell])
  229. else:
  230. subcell_kwarg = dict(transformers=[SubCell])
  231. exporter = HTMLExporter(config=c,
  232. template_file=template_file,
  233. filters={'highlight2html': custom_highlighter},
  234. **subcell_kwarg)
  235. # read and parse the notebook
  236. with open(nb_path) as f:
  237. nb_text = f.read()
  238. nb_json = nbformat.reads_json(nb_text)
  239. (body, resources) = exporter.from_notebook_node(nb_json)
  240. # if we haven't already saved the header, save it here.
  241. if not notebook.header_saved:
  242. print ("\n ** Writing styles to _nb_header.html: "
  243. "this should be included in the theme. **\n")
  244. header = '\n'.join(CSS_WRAPPER.format(css_line)
  245. for css_line in resources['inlining']['css'])
  246. header += JS_INCLUDE
  247. with open('_nb_header.html', 'w') as f:
  248. f.write(header)
  249. notebook.header_saved = True
  250. # this will stash special characters so that they won't be transformed
  251. # by subsequent processes.
  252. body = preprocessor.configs.htmlStash.store(body, safe=True)
  253. return body
  254. notebook.header_saved = False
  255. #----------------------------------------------------------------------
  256. # This import allows notebook to be a Pelican plugin
  257. from liquid_tags import register