notebook.py 10 KB

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