notebook.py 9.5 KB

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