notebook.py 11 KB

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