forked from slojo404/nbconvert
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nbconvert.py
executable file
·1494 lines (1159 loc) · 43.4 KB
/
nbconvert.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
"""Convert IPython notebooks to other formats, such as ReST, and HTML.
Example:
./nbconvert.py --format rst file.ipynb
Produces 'file.rst', along with auto-generated figure files
called nb_figure_NN.png.
"""
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
from __future__ import print_function
# Stdlib
import codecs
import io
import logging
import os
import pprint
import re
import subprocess
import sys
import json
import copy
from shutil import rmtree
inkscape = 'inkscape'
if sys.platform == 'darwin':
inkscape = '/Applications/Inkscape.app/Contents/Resources/bin/inkscape'
if not os.path.exists(inkscape):
inkscape = None
# From IPython
from IPython.external import argparse
from IPython.nbformat import current as nbformat
from IPython.utils.text import indent
from IPython.nbformat.v3.nbjson import BytesEncoder
from IPython.utils import path, py3compat
# local
from decorators import DocInherit
from lexers import IPythonLexer
#-----------------------------------------------------------------------------
# Utility functions
#-----------------------------------------------------------------------------
def DocInherit(f):
return f
def remove_fake_files_url(cell):
"""Remove from the cell source the /files/ pseudo-path we use.
"""
src = cell.source
cell.source = src.replace('/files/', '')
# ANSI color functions:
def remove_ansi(src):
"""Strip all ANSI color escape sequences from input string.
Parameters
----------
src : string
Returns
-------
string
"""
return re.sub(r'\033\[(0|\d;\d\d)m', '', src)
def ansi2html(txt):
"""Render ANSI colors as HTML colors
This is equivalent to util.fixConsole in utils.js
Parameters
----------
txt : string
Returns
-------
string
"""
ansi_colormap = {
'30': 'ansiblack',
'31': 'ansired',
'32': 'ansigreen',
'33': 'ansiyellow',
'34': 'ansiblue',
'35': 'ansipurple',
'36': 'ansicyan',
'37': 'ansigrey',
'01': 'ansibold',
}
# do ampersand first
txt = txt.replace('&', '&')
html_escapes = {
'<': '<',
'>': '>',
"'": ''',
'"': '"',
'`': '`',
}
for c, escape in html_escapes.iteritems():
txt = txt.replace(c, escape)
ansi_re = re.compile('\x1b' + r'\[([\dA-Fa-f;]*?)m')
m = ansi_re.search(txt)
opened = False
cmds = []
opener = ''
closer = ''
while m:
cmds = m.groups()[0].split(';')
closer = '</span>' if opened else ''
opened = len(cmds) > 1 or cmds[0] != '0'*len(cmds[0]);
classes = []
for cmd in cmds:
if cmd in ansi_colormap:
classes.append(ansi_colormap.get(cmd))
if classes:
opener = '<span class="%s">' % (' '.join(classes))
else:
opener = ''
txt = re.sub(ansi_re, closer + opener, txt, 1)
m = ansi_re.search(txt)
if opened:
txt += '</span>'
return txt
# Pandoc-dependent code
def markdown2latex(src):
"""Convert a markdown string to LaTeX via pandoc.
This function will raise an error if pandoc is not installed.
Any error messages generated by pandoc are printed to stderr.
Parameters
----------
src : string
Input string, assumed to be valid markdown.
Returns
-------
out : string
Output as returned by pandoc.
"""
p = subprocess.Popen('pandoc -f markdown -t latex'.split(),
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
out, err = p.communicate(src.encode('utf-8'))
if err:
print(err, file=sys.stderr)
#print('*'*20+'\n', out, '\n'+'*'*20) # dbg
return unicode(out,'utf-8')
def markdown2rst(src):
"""Convert a markdown string to LaTeX via pandoc.
This function will raise an error if pandoc is not installed.
Any error messages generated by pandoc are printed to stderr.
Parameters
----------
src : string
Input string, assumed to be valid markdown.
Returns
-------
out : string
Output as returned by pandoc.
"""
p = subprocess.Popen('pandoc -f markdown -t rst'.split(),
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
out, err = p.communicate(src.encode('utf-8'))
if err:
print(err, file=sys.stderr)
#print('*'*20+'\n', out, '\n'+'*'*20) # dbg
return unicode(out,'utf-8')
def rst_directive(directive, text=''):
out = [directive, '']
if text:
out.extend([indent(text), ''])
return out
def coalesce_streams(outputs):
"""merge consecutive sequences of stream output into single stream
to prevent extra newlines inserted at flush calls
TODO: handle \r deletion
"""
new_outputs = []
last = outputs[0]
new_outputs = [last]
for output in outputs[1:]:
if (output.output_type == 'stream' and
last.output_type == 'stream' and
last.stream == output.stream
):
last.text += output.text
else:
new_outputs.append(output)
return new_outputs
#-----------------------------------------------------------------------------
# Class declarations
#-----------------------------------------------------------------------------
class ConversionException(Exception):
pass
class Converter(object):
default_encoding = 'utf-8'
extension = str()
figures_counter = 0
infile = str()
infile_dir = str()
infile_root = str()
files_dir = str()
with_preamble = True
user_preamble = None
output = str()
raw_as_verbatim = False
def __init__(self, infile):
self.infile = infile
self.infile_dir, infile_root = os.path.split(infile)
infile_root = os.path.splitext(infile_root)[0]
files_dir = os.path.join(self.infile_dir, infile_root + '_files')
if not os.path.isdir(files_dir):
os.mkdir(files_dir)
self.infile_root = infile_root
self.files_dir = files_dir
self.outbase = os.path.join(self.infile_dir, infile_root)
def dispatch(self, cell_type):
"""return cell_type dependent render method, for example render_code
"""
return getattr(self, 'render_' + cell_type, self.render_unknown)
def dispatch_display_format(self, format):
"""return output_type dependent render method, for example render_output_text
"""
return getattr(self, 'render_display_format_' + format, self.render_unknown_display)
def convert(self, cell_separator='\n'):
lines = []
lines.extend(self.optional_header())
converted_cells = []
for worksheet in self.nb.worksheets:
for cell in worksheet.cells:
#print(cell.cell_type) # dbg
conv_fn = self.dispatch(cell.cell_type)
if cell.cell_type in ('markdown', 'raw'):
remove_fake_files_url(cell)
converted_cells.append('\n'.join(conv_fn(cell)))
cell_lines = cell_separator.join(converted_cells).split('\n')
lines.extend(cell_lines)
lines.extend(self.optional_footer())
return u'\n'.join(lines)
def render(self):
"read, convert, and save self.infile"
if not hasattr(self, 'nb'):
self.read()
self.output = self.convert()
return self.save()
def read(self):
"read and parse notebook into NotebookNode called self.nb"
with open(self.infile) as f:
self.nb = nbformat.read(f, 'json')
def save(self, outfile=None, encoding=None):
"read and parse notebook into self.nb"
if outfile is None:
outfile = self.outbase + '.' + self.extension
if encoding is None:
encoding = self.default_encoding
with io.open(outfile, 'w', encoding=encoding) as f:
f.write(self.output)
return os.path.abspath(outfile)
def optional_header(self):
return []
def optional_footer(self):
return []
def _new_figure(self, data, fmt):
"""Create a new figure file in the given format.
Returns a path relative to the input file.
"""
figname = '%s_fig_%02i.%s' % (self.infile_root,
self.figures_counter, fmt)
self.figures_counter += 1
fullname = os.path.join(self.files_dir, figname)
# Binary files are base64-encoded, SVG is already XML
if fmt in ('png', 'jpg', 'pdf'):
data = data.decode('base64')
fopen = lambda fname: open(fname, 'wb')
else:
fopen = lambda fname: codecs.open(fname, 'wb', self.default_encoding)
with fopen(fullname) as f:
f.write(data)
return fullname
def render_heading(self, cell):
"""convert a heading cell
Returns list."""
raise NotImplementedError
def render_code(self, cell):
"""Convert a code cell
Returns list."""
raise NotImplementedError
def render_markdown(self, cell):
"""convert a markdown cell
Returns list."""
raise NotImplementedError
def _img_lines(self, img_file):
"""Return list of lines to include an image file."""
# Note: subclasses may choose to implement format-specific _FMT_lines
# methods if they so choose (FMT in {png, svg, jpg, pdf}).
raise NotImplementedError
def render_display_data(self, output):
"""convert display data from the output of a code cell
Returns list.
"""
lines = []
for fmt in output.keys():
if fmt in ['png', 'svg', 'jpg', 'pdf']:
img_file = self._new_figure(output[fmt], fmt)
# Subclasses can have format-specific render functions (e.g.,
# latex has to auto-convert all SVG to PDF first).
lines_fun = getattr(self, '_%s_lines' % fmt, None)
if not lines_fun:
lines_fun = self._img_lines
lines.extend(lines_fun(img_file))
elif fmt != 'output_type':
conv_fn = self.dispatch_display_format(fmt)
lines.extend(conv_fn(output))
return lines
def render_raw(self, cell):
"""convert a cell with raw text
Returns list."""
raise NotImplementedError
def render_unknown(self, cell):
"""Render cells of unkown type
Returns list."""
data = pprint.pformat(cell)
logging.warning('Unknown cell: %s' % cell.cell_type)
return self._unknown_lines(data)
def render_unknown_display(self, output, type):
"""Render cells of unkown type
Returns list."""
data = pprint.pformat(output)
logging.warning('Unknown output: %s' % output.output_type)
return self._unknown_lines(data)
def render_stream(self, output):
"""render the stream part of an output
Returns list.
Identical to render_display_format_text
"""
return self.render_display_format_text(output)
def render_pyout(self, output):
"""convert pyout part of a code cell
Returns list."""
raise NotImplementedError
def render_pyerr(self, output):
"""convert pyerr part of a code cell
Returns list."""
raise NotImplementedError
def _unknown_lines(self, data):
"""Return list of lines for an unknown cell.
Parameters
----------
data : str
The content of the unknown data as a single string.
"""
raise NotImplementedError
# These are the possible format types in an output node
def render_display_format_text(self, output):
"""render the text part of an output
Returns list.
"""
raise NotImplementedError
def render_display_format_html(self, output):
"""render the html part of an output
Returns list.
"""
raise NotImplementedError
def render_display_format_latex(self, output):
"""render the latex part of an output
Returns list.
"""
raise NotImplementedError
def render_display_format_json(self, output):
"""render the json part of an output
Returns list.
"""
raise NotImplementedError
def render_display_format_javascript(self, output):
"""render the javascript part of an output
Returns list.
"""
raise NotImplementedError
class ConverterRST(Converter):
extension = 'rst'
heading_level = {1: '=', 2: '-', 3: '`', 4: '\'', 5: '.', 6: '~'}
@DocInherit
def render_heading(self, cell):
marker = self.heading_level[cell.level]
return ['{0}\n{1}\n'.format(cell.source, marker * len(cell.source))]
@DocInherit
def render_code(self, cell):
if not cell.input:
return []
lines = ['In[%s]:' % cell.prompt_number, '']
lines.extend(rst_directive('.. code:: python', cell.input))
for output in cell.outputs:
conv_fn = self.dispatch(output.output_type)
lines.extend(conv_fn(output))
return lines
@DocInherit
def render_markdown(self, cell):
#return [cell.source]
return [markdown2rst(cell.source)]
@DocInherit
def render_raw(self, cell):
if self.raw_as_verbatim:
return ['::', '', indent(cell.source), '']
else:
return [cell.source]
@DocInherit
def render_pyout(self, output):
lines = ['Out[%s]:' % output.prompt_number, '']
# output is a dictionary like object with type as a key
if 'latex' in output:
lines.extend(rst_directive('.. math::', output.latex))
if 'text' in output:
lines.extend(rst_directive('.. parsed-literal::', output.text))
return lines
@DocInherit
def render_pyerr(self, output):
# Note: a traceback is a *list* of frames.
return ['::', '', indent(remove_ansi('\n'.join(output.traceback))), '']
@DocInherit
def _img_lines(self, img_file):
return ['.. image:: %s' % img_file, '']
@DocInherit
def render_display_format_text(self, output):
return rst_directive('.. parsed-literal::', output.text)
@DocInherit
def _unknown_lines(self, data):
return rst_directive('.. warning:: Unknown cell') + [data]
def render_display_format_html(self, output):
"""render the html part of an output
Returns list.
"""
return rst_directive('.. raw:: html', output.html)
def render_display_format_latex(self, output):
"""render the latex part of an output
Returns list.
"""
return rst_directive('.. math::', output.latex)
def render_display_format_json(self, output):
"""render the json part of an output
Returns list.
"""
return rst_directive('.. raw:: json', output.json)
def render_display_format_javascript(self, output):
"""render the javascript part of an output
Returns list.
"""
return rst_directive('.. raw:: javascript', output.javascript)
def highlight(src, lang='ipython'):
"""Return a syntax-highlighted version of the input source.
"""
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter
if lang == 'ipython':
lexer = IPythonLexer()
else:
lexer = get_lexer_by_name(lang, stripall=True)
return highlight(src, lexer, HtmlFormatter())
class ConverterMarkdown(Converter):
extension = 'md'
def __init__(self, infile, highlight_source=True, show_prompts=False,
inline_prompt=False):
super(ConverterMarkdown, self).__init__(infile)
self.highlight_source = highlight_source
self.show_prompts = show_prompts
self.inline_prompt = inline_prompt
@DocInherit
def render_heading(self, cell):
return ['{0} {1}'.format('#'*cell.level, cell.source), '']
@DocInherit
def render_code(self, cell):
if not cell.input:
return []
lines = []
if self.show_prompts and not self.inline_prompt:
lines.extend(['*In[%s]:*' % cell.prompt_number, ''])
if self.show_prompts and self.inline_prompt:
prompt = 'In[%s]: ' % cell.prompt_number
input_lines = cell.input.split('\n')
src = prompt + input_lines[0] + '\n' + indent('\n'.join(input_lines[1:]), nspaces=len(prompt))
else:
src = cell.input
src = highlight(src) if self.highlight_source else indent(src)
lines.extend([src, ''])
if cell.outputs and self.show_prompts and not self.inline_prompt:
lines.extend(['*Out[%s]:*' % cell.prompt_number, ''])
for output in cell.outputs:
conv_fn = self.dispatch(output.output_type)
lines.extend(conv_fn(output))
#lines.append('----')
lines.append('')
return lines
@DocInherit
def render_markdown(self, cell):
return [cell.source, '']
@DocInherit
def render_raw(self, cell):
if self.raw_as_verbatim:
return [indent(cell.source), '']
else:
return [cell.source, '']
@DocInherit
def render_pyout(self, output):
lines = []
## if 'text' in output:
## lines.extend(['*Out[%s]:*' % output.prompt_number, ''])
# output is a dictionary like object with type as a key
if 'latex' in output:
pass
if 'text' in output:
lines.extend(['<pre>', indent(output.text), '</pre>'])
lines.append('')
return lines
@DocInherit
def render_pyerr(self, output):
# Note: a traceback is a *list* of frames.
return [indent(remove_ansi('\n'.join(output.traceback))), '']
@DocInherit
def _img_lines(self, img_file):
return ['', '![](%s)' % img_file, '']
@DocInherit
def render_display_format_text(self, output):
return [indent(output.text)]
@DocInherit
def _unknown_lines(self, data):
return ['Warning: Unknown cell', data]
def render_display_format_html(self, output):
"""render the html part of an output
Returns list.
"""
return [output.html]
def render_display_format_latex(self, output):
"""render the latex part of an output
Returns list.
"""
return ['LaTeX::', indent(output.latex)]
def render_display_format_json(self, output):
"""render the json part of an output
Returns list.
"""
return ['JSON:', indent(output.json)]
def render_display_format_javascript(self, output):
"""render the javascript part of an output
Returns list.
"""
return ['JavaScript:', indent(output.javascript)]
def return_list(x):
"""Ensure that x is returned as a list or inside one"""
return x if isinstance(x, list) else [x]
# decorators for HTML output
def output_container(f):
"""add a prompt-area next to an output"""
def wrapped(self, output):
rendered = f(self, output)
if not rendered:
# empty output
return []
lines = []
lines.append('<div class="hbox output_area">')
lines.extend(self._out_prompt(output))
classes = "output_subarea output_%s" % output.output_type
if output.output_type == 'stream':
classes += " output_%s" % output.stream
lines.append('<div class="%s">' % classes)
lines.extend(rendered)
lines.append('</div>') # subarea
lines.append('</div>') # output_area
return lines
return wrapped
def text_cell(f):
"""wrap text cells in appropriate divs"""
def wrapped(self, cell):
rendered = f(self, cell)
classes = "text_cell_render border-box-sizing rendered_html"
lines = ['<div class="%s">' % classes] + rendered + ['</div>']
return lines
return wrapped
class ConverterGithubMarkdown(ConverterMarkdown):
def __init__(self, infile, highlight_source=False, show_prompts=True,
inline_prompt=False):
super(ConverterGithubMarkdown, self).__init__(infile)
self.highlight_source = highlight_source
self.show_prompts = show_prompts
self.inline_prompt = inline_prompt
@DocInherit
def render_code(self, cell):
if not cell.input:
return []
lines = ["```%s" % cell.get("language") or "python"]
if self.show_prompts and not self.inline_prompt:
lines.extend(['*In[%s]:*' % cell.prompt_number, ''])
if self.show_prompts and self.inline_prompt:
prompt = 'In[%s]: ' % cell.prompt_number
input_lines = cell.input.split('\n')
src = prompt + input_lines[0] + '\n' + indent('\n'.join(input_lines[1:]), nspaces=len(prompt))
else:
src = cell.input
src = highlight(src) if self.highlight_source else src
lines.extend([src, '```', ''])
for output in cell.outputs:
conv_fn = self.dispatch(output.output_type)
lines.extend(conv_fn(output))
#lines.append('----')
lines.append('')
return lines
@DocInherit
def render_pyout(self, output, prompt_number=None):
lines = []
# output is a dictionary like object with type as a key
if 'latex' in output:
pass
if 'text' in output:
lines.extend(['<pre>',
'*Out[%s]:*' % output.prompt_number, '',
indent(output.text),
'</pre>'])
lines.append('')
return lines
class ConverterHTML(Converter):
extension = 'html'
def in_tag(self, tag, src, attrs={}):
"""Return a list of elements bracketed by the given tag"""
attr_s = ""
for attr, value in attrs.iteritems():
attr_s += "%s=%s" % (attr, value)
return ['<%s %s>' % (tag, attr_s), src, '</%s>' % tag]
def _ansi_colored(self, text):
return ['<pre>%s</pre>' % ansi2html(text)]
def _stylesheet(self, fname):
with io.open(fname, encoding='utf-8') as f:
s = f.read()
return self.in_tag('style', s, dict(type='text/css'))
def _out_prompt(self, output):
if output.output_type == 'pyout':
n = output.prompt_number if output.prompt_number is not None else ' '
content = 'Out [%s]:' % n
else:
content = ''
return ['<div class="prompt output_prompt">%s</div>' % content]
def optional_header(self):
from pygments.formatters import HtmlFormatter
header = ['<html>', '<head>']
static = os.path.join(path.get_ipython_package_dir(),
'frontend', 'html', 'notebook', 'static',
)
here = os.path.split(os.path.abspath(__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'),
]:
header.extend(self._stylesheet(sheet))
# pygments css
pygments_css = HtmlFormatter().get_style_defs('.highlight')
header.extend(['<meta charset="UTF-8">'])
header.extend(self.in_tag('style', pygments_css, dict(type='text/css')))
# TODO: this should be allowed to use local mathjax:
header.extend(self.in_tag('script', '', {'type':'text/javascript',
'src': '"https://c328740.ssl.cf1.rackcdn.com/mathjax/latest/MathJax.js?config=TeX-AMS_HTML"',
}))
with io.open(os.path.join(here, 'js', 'initmathjax.js'), encoding='utf-8') as f:
header.extend(self.in_tag('script', f.read(), {'type': 'text/javascript'}))
header.extend(['</head>', '<body>'])
return header
def optional_footer(self):
lines = []
lines.extend([
'</body>',
'</html>',
])
return lines
@DocInherit
@text_cell
def render_heading(self, cell):
marker = cell.level
return [u'<h{1}>\n {0}\n</h{1}>'.format(cell.source, marker)]
@DocInherit
def render_code(self, cell):
if not cell.input:
return []
lines = ['<div class="cell border-box-sizing code_cell vbox">']
lines.append('<div class="input hbox">')
n = cell.prompt_number if getattr(cell, 'prompt_number', None) is not None else ' '
lines.append('<div class="prompt input_prompt">In [%s]:</div>' % n)
lines.append('<div class="input_area box-flex1">')
lines.append(highlight(cell.input))
lines.append('</div>') # input_area
lines.append('</div>') # input
if cell.outputs:
lines.append('<div class="vbox output_wrapper">')
lines.append('<div class="output vbox">')
for output in coalesce_streams(cell.outputs):
conv_fn = self.dispatch(output.output_type)
lines.extend(conv_fn(output))
lines.append('</div>') # output
lines.append('</div>') # output_wrapper
lines.append('</div>') # cell
return lines
@DocInherit
@text_cell
def render_markdown(self, cell):
p = subprocess.Popen(['markdown'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
out, _ = p.communicate(cell.source.encode('utf-8'))
return [out.decode('utf-8')]
@DocInherit
def render_raw(self, cell):
if self.raw_as_verbatim:
return self.in_tag('pre', cell.source)
else:
return [cell.source]
@DocInherit
@output_container
def render_pyout(self, output):
for fmt in ['html', 'latex', 'png', 'jpeg', 'svg', 'text']:
if fmt in output:
conv_fn = self.dispatch_display_format(fmt)
return conv_fn(output)
return []
render_display_data = render_pyout
@DocInherit
@output_container
def render_stream(self, output):
return self._ansi_colored(output.text)
@DocInherit
@output_container
def render_pyerr(self, output):
# Note: a traceback is a *list* of frames.
# lines = []
# stb =
return self._ansi_colored('\n'.join(output.traceback))
@DocInherit
def _img_lines(self, img_file):
return ['<img src="%s">' % img_file, '</img>']
@DocInherit
def _unknown_lines(self, data):
return ['<h2>Warning:: Unknown cell</h2>'] + self.in_tag('pre', data)
def render_display_format_png(self, output):
"""render the png part of an output
Returns list.
"""
return ['<img src="data:image/png;base64,%s"></img>' % output.png]
def render_display_format_svg(self, output):
"""render the svg part of an output
Returns list.
"""
return [output.svg]
def render_display_format_jpeg(self, output):
"""render the jpeg part of an output
Returns list.
"""
return ['<img src="data:image/jpeg;base64,%s"></img>' % output.jpeg]
def render_display_format_text(self, output):
"""render the text part of an output
Returns list.
"""
return self._ansi_colored(output.text)
def render_display_format_html(self, output):
"""render the html part of an output
Returns list.
"""
return [output.html]
def render_display_format_latex(self, output):
"""render the latex part of an output
Returns list.
"""
return [output.latex]
def render_display_format_json(self, output):
"""render the json part of an output
Returns [].
"""
# html ignores json
return []
def render_display_format_javascript(self, output):
"""render the javascript part of an output
Returns list.
"""
return [output.javascript]