-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathipnb2tex.py
More file actions
1559 lines (1242 loc) · 57.5 KB
/
Copy pathipnb2tex.py
File metadata and controls
1559 lines (1242 loc) · 57.5 KB
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/python2
"""Notebook to LaTeX and PDF
http://ipython.org/ipython-doc/3/notebook/nbformat.html#nbformat
http://ipython.org/ipython-doc/3/whatsnew/version3.html
"""
from __future__ import print_function, division
import re
import os
import io
import base64
import shutil
import re
import itertools
import operator
import unicodedata
import os.path, fnmatch
# from IPython.nbformat import current as ipnbcurrent
import nbformat
import docopt
import lxml.html
import markdown
from lxml import etree as ET
import numpy as np
import sys
from builtins import bytes,chr
from builtins import str
nbformat
#list of bibtex entries to be built up in this file
bibtexlist = []
#dict of bibtex label crossreferences between local and existing bibtex files.
bibxref = {}
bibtexindex = 0
listindentcurrent = 0
listindentprevious = 0
figure_index = 0
table_index = 0
protectEvnStringStart = 'beginincludegraphics\n'
protectEvnStringEnd = 'endincludegraphics\n'
docoptstring = """Usage: ipnb2tex.py [<ipnbfilename>] [<outfilename>] [<imagedir>] [-i] [-u] [-a]
ipnb2tex.py (-h | --help)
The ipnb2tex.py reads the IPython notebook and converts
it to a \LaTeX{} set of files: a *.tex file and a number of images.
Arguments:
ipnbfilename [optional] is the name of the input Jupyter notebook file.
If no input filename is supplied, all .ipynb files in current directory
will be processed. In this event the output filenames will be the same
as the .ipynb files, just with a tex filetype
outfilename [optional] is the name of output LaTeX file. If none is
given the output filename will be the same as the input file, but with
the .tex extension.
imagedir [optional] is the directory where images are written to.
If not given, this image directory will be the ./pic directory.
Options:
-h, --help [optional] help information.
-u [optional] add \\url{} to the bibtex entries.
-i [optional], the lower case letter i, if this option is given the code
listings are printed inline with the body text where they occur,
otherwise listings are floated to the end of the document.
-a [optional] append other bibtex entries to this one
"""
standardHeader =\
r"""
\documentclass[english]{report}
\usepackage{ragged2e}
\usepackage{listings}
\usepackage{color}
\usepackage{graphicx}
\usepackage{textcomp} % additional fonts, required for upquote in listings and \textmu
\usepackage{placeins} % FloatBarrier
\usepackage{url} % for websites
\usepackage[detect-weight,detect-all=true]{siunitx} % nice! SI units and print numbers
\usepackage{afterpage} % afterpage{\clearpage}
\usepackage{gensymb} % get the degree symbol as in \celcius
\usepackage{amsmath}
\usepackage[printonlyused]{acronym}
\usepackage{lastpage}
\usepackage[Export]{adjustbox}
\adjustboxset{max size={\textwidth}{0.7\textheight}}
%the following is required for carriage return symbol
%ftp://ftp.botik.ru/rented/znamensk/CTAN/fonts/mathabx/texinputs/mathabx.dcl
%https://secure.kitserve.org.uk/content/mathabx-font-symbol-redefinition-clash-latex
\DeclareFontFamily{U}{mathb}{\hyphenchar\font45}
\DeclareFontShape{U}{mathb}{m}{n}{
<5> <6> <7> <8> <9> <10> gen * mathb
<10.95> mathb10 <12> <14.4> <17.28> <20.74> <24.88> mathb12
}{}
\DeclareSymbolFont{mathb}{U}{mathb}{m}{n}
\DeclareMathSymbol{\dlsh}{3}{mathb}{"EA}
\usepackage[T1]{fontenc}
\definecolor{LightGrey}{rgb}{0.95,0.95,0.95}
\definecolor{LightRed}{rgb}{1.0,0.9,0.9}
\lstset{ %
upquote=true, % gives the upquote instead of the curly quote
basicstyle=\ttfamily\footnotesize, % the size of the fonts that are used for the code
numbers=none, % where to put the line-numbers
showspaces=false, % show spaces adding particular underscores
showstringspaces=false, % underline spaces within strings
showtabs=false, % show tabs within strings adding particular underscores
frame=lines, % adds a frame around the code
tabsize=4, % sets default tabsize to 2 spaces
captionpos=b, % sets the caption-position to bottom
framesep=1pt,
xleftmargin=0pt,
xrightmargin=0pt,
captionpos=t, % sets the caption-position to top
%deletekeywords={...}, % if you want to delete keywords from the given language
%escapeinside={\%*}{*)}, % if you want to add LaTeX within your code
%escapeinside={\%}{)}, % if you want to add a comment within your code
breaklines=true, % sets automatic line breaking
breakatwhitespace=false, % sets if automatic breaks should only happen at whitespace
prebreak=\raisebox{0ex}[0ex][0ex]{$\dlsh$} % add linebreak symbol
}
\lstdefinestyle{incellstyle}{
backgroundcolor=\color{LightGrey}, % choose the background color, add \usepackage{color}
language=Python,
}
\lstdefinestyle{outcellstyle}{
backgroundcolor=\color{LightRed}, % choose the background color; you must add \usepackage{color} or \usepackage{xcolor}
}
\usepackage[a4paper, margin=0.75in]{geometry}
\newlength{\textwidthm}
\setlength{\textwidthm}{\textwidth}
% this is entered just before the end{document}
\newcommand{\atendofdoc}{
\bibliographystyle{IEEEtran}
\bibliography{bibliography}
}
%and finally the document begin.
\begin{document}
\author{Author}
\title{Title}
\date{\today}
\maketitle
"""
# ################################################################################
# #lists the files in a directory and subdirectories (from Python Cookbook)
# def listFiles(root, patterns='*', recurse=1, return_folders=0):
# """lists the files in a directory and subdirectories (from Python Cookbook)
# Extensively reworked for Python 3.
# """
# # Expand patterns from semicolon-separated string to list
# pattern_list = patterns.split(';')
# filenames = []
# filertn = []
# for dirpath,dirnames,files in os.walk(root):
# if dirpath==root or recurse:
# for filen in files:
# filenames.append(os.path.abspath(os.path.join(os.getcwd(),dirpath,filen)))
# if return_folders:
# for dirn in dirnames:
# filenames.append(os.path.abspath(os.path.join(os.getcwd(),dirpath,dirn)))
# for name in filenames:
# if return_folders or os.path.isfile(name):
# for pattern in pattern_list:
# if fnmatch.fnmatch(name, pattern):
# filertn.append(name)
# break
# return filertn
################################################################################
def latexEscapeCaption(string):
# https://stackoverflow.com/questions/18360976/match-latex-reserved-characters-with-regex
# string = re.sub(r'((?<!\)[#\$%\^&_\{\}~\\])','\1', string)
# string = re.sub(r'([#%&_])',r'\\\1', string)
return string
################################################################################
def latexEscapeForHtmlTableOutput(string):
# string = string.replace('_', '\\_')
#first remove escaped \% if present, then do escape again on all % present
string = string.replace('\\%','%')
string = string.replace('%','\\%')
for mathcar in ['<', '>', '|', '=']:
string = string.replace(mathcar, '$'+mathcar+'$')
#replace computer-style float with scientific notation
matches = re.search(r'^([0-9,.,\-]+)e(\+|\-)([0-9]+)$', string.strip())
if matches:
lead, sign, pw = matches.groups()
sign = sign.replace('+', '')
# string = string.replace(matches.group(), lead + r'\times 10^{' + sign + pw.strip('0') + '}')
string = string.replace(matches.group(), '$'+lead + r'\times 10^{' + sign + pw.strip('0') + '}'+'$')
return string
################################################################################
def pptree(e):
print(ET.tostring(e, pretty_print=True))
print()
################################################################################
def convertHtmlTable(html, cell):
global table_index
# print()
if not (isinstance(html, str)):
html = lxml.html.tostring(html)
if not b"<div" in html:
html = b"<div>" + html + b"</div>"
html = html.replace(b"<thead>", b"").replace(b"</thead>", b"").replace(b"<tbody>", b"").replace(b"</tbody>", b"")
# html = html.replace('overflow:auto;','').replace(' style="max-height:1000px;max-width:1500px;','')
tree = lxml.html.fromstring(html)
# print('pptree-html')
# pptree(tree)
# for tags in tree.getiterator():
# print(tags.tag, tags.text)
rtnString = ''
for table in tree.findall("table"):
# first lets traverse it and look for rowspan/colspans, find the shape
row_counts = len(table.findall('tr'))
col_counts = [0] * row_counts
for ind, row in enumerate(table.findall('tr')):
for tag in row:
if not (tag.tag == 'td' or tag.tag == 'th'): continue
if 'colspan' in tag.attrib:
col_counts[ind] += int(tag.attrib['colspan']) - 1
if 'rowspan' in tag.attrib:
for j in range(int(tag.attrib['rowspan'])):
col_counts[ind+j] += 1
else:
col_counts[ind] += 1
if len(set(col_counts)) != 1:
raise ValueError('inconsistent number of column counts')
col_counts = col_counts[0]
# print(row_counts, col_counts)
if row_counts == 0 or col_counts == 0:
continue
#first determine arrays of colspan and row span
# these arrays have nonzero values in spanned cell, no data here
rowspan = np.zeros((row_counts, col_counts), dtype=np.int64)
colspan = np.zeros((row_counts, col_counts), dtype=np.int64)
irow = 0
for row in table.findall('tr'):
icol = 0
for col in row:
if col.tag != 'td' and col.tag != 'th':
raise NotImplementedError('Expecting either TD or TH tag under row')
if rowspan[irow,icol] != 0:
colspan[irow,icol] = 0
icol += 1
colspan[irow,icol] = 0
icol += 1
if 'colspan' in col.attrib:
icolspan = int(col.attrib['colspan'])
for i in range(1,icolspan):
colspan[irow,icol] = 1
icol += 1
if 'rowspan' in col.attrib:
rowspan[irow,icol-1] = 0
for i in range(1, int(col.attrib['rowspan'])):
rowspan[irow+i,icol-1] = int(col.attrib['rowspan'])-i
irow += 1
# print('colspan=\n{}\n'.format(colspan))
# print('rowspan=\n{}\n'.format(rowspan))
formatStr = getMetaData(cell, table_index, 'tableCaption', 'format','')
if not formatStr:
formatStr = '|' + "|".join(['c'] * col_counts) + '|'
terminator = '&'
latexTabular = ""
latexTabular += "\n\\begin{{tabular}}{{{}}}\n".format(formatStr)
latexTabular += "\\hline\n"
irow = 0
for row_index, row in enumerate(table.findall('tr')):
icol = 0
for col_index, col in enumerate(row):
while rowspan[irow,icol]:
latexTabular += '&'
icol += 1
txt = latexEscapeForHtmlTableOutput(col.text_content().strip())
if 'colspan' in col.attrib:
icolspan = int(col.attrib['colspan'])
txt = '\multicolumn{{{}}}{{|c|}}{{{}}}'.format(icolspan,txt)
latexTabular += txt + '&'
while(colspan[irow,icol]):
icol += 1
icol += 1
#calculate the clines
if irow==0 or irow==row_counts-1:
hline = r'\hline'
else:
if np.count_nonzero(rowspan[irow+1,:])==0:
hline = r'\hline'
else:
hline = ''
clines = 1 - rowspan[irow+1,:]
for i in range(0,clines.shape[0]):
if clines[i] > 0:
hline += '\\cline{{{}-{}}}'.format(i+1,i+1)
irow += 1
latexTabular = latexTabular[:-1] + '\\\\'+hline
latexTabular += '\n'
latexTabular += "\n"
latexTabular += "\\end{tabular}\n"
#process the caption string, either a string or a list of strings
captionStr = getMetaData(cell, table_index, 'tableCaption', 'caption','')
fontsizeStr = getMetaData(cell, table_index, 'tableCaption', 'fontsize','normalsize')
locator = getMetaData(cell, table_index, 'tableCaption', 'locator', 'tb')
labelStr = getMetaData(cell, table_index, 'tableCaption', 'label','')
if labelStr:
tlabstr = labelStr
labelStr = '\\label{{{}-{}}}'.format(tlabstr, table_index)
if table_index == 0:
labelStr += '\\label{{{}}}'.format(tlabstr)
table_index += 1
texStr = ''
if captionStr:
texStr = texStr + '\n\\begin{table}['+locator+']\n'
texStr += '\\centering\n'
texStr += '\\caption{'+'{}{}'.format(latexEscapeCaption(captionStr),labelStr)+'}\n'
else:
texStr += '\\begin{center}\n'
texStr += "\n\\begin{{{}}}\n".format(fontsizeStr)
texStr += latexTabular
texStr += "\\end{{{}}}\n".format(fontsizeStr)
if captionStr:
texStr += '\\end{table}\n\n'
else:
texStr += '\\end{center}\n\n'
rtnString += texStr
return rtnString
################################################################################
def findAllStr(string, substr):
ind = string.find(substr)
while ind >= 0:
yield ind
ind = string.find(substr, ind+1)
################################################################################
def findNotUsedChar(string):
delims = '~!@#$%-+=:;'
################################################################################
def processVerbatim(child):
childtail = '' if child.tail==None else child.tail
#multiline text must be in verbatim environment, not just \verb++
if len(child.text.splitlines()) > 1:
strVerb = r'\begin{verbatim}' + '\n' + child.text + r'\end{verbatim}' + childtail
else:
strVerb = r'\verb+' + child.text.rstrip() + r'+' + childtail
return strVerb
################################################################
def cleanFilename(sourcestring, removestring=r" %:/,.\[]"):
"""Clean a string by removing selected characters.
Creates a legal and 'clean' source string from a string by removing some
clutter and characters not allowed in filenames.
A default set is given but the user can override the default string.
Args:
| sourcestring (string): the string to be cleaned.
| removestring (string): remove all these characters from the string (optional).
Returns:
| (string): A cleaned-up string.
Raises:
| No exception is raised.
"""
#remove the undesireable characters
return ''.join([i for i in sourcestring if i not in removestring])
def processLaTeXOutCell(cellOutput,output_index,outs,cell,addurlcommand):
# see if this is a booktabs table
global figure_index
global table_index
outstr = ''
payload = cellOutput.data['text/latex']
booktabstr = ''
if 'bottomrule' in payload or 'toprule' in payload or 'midrule' in payload:
booktabstr += '% to get unbroken vertical lines with booktabs, set separators to zero\n'
booktabstr += '% also set all horizontal lines to same width\n'
booktabstr += '\\aboverulesep=0ex\n'
booktabstr += '\\belowrulesep=0ex\n'
booktabstr += '\\heavyrulewidth=.05em\n'
booktabstr += '\\lightrulewidth=.05em\n'
booktabstr += '\\cmidrulewidth=.05em\n'
booktabstr += '\\belowbottomsep=0pt\n'
booktabstr += '\\abovetopsep=0pt\n'
# get cell fontsize
fontsizeStr = getMetaData(cell, output_index, 'latex', 'fontsize','normalsize')
# process table with caption, either a string or a list of strings
if getMetaData(cell, table_index, 'tableCaption', 'caption',''):
captionStr = getMetaData(cell, table_index, 'tableCaption', 'caption','')
fontsizeStr = getMetaData(cell, table_index, 'tableCaption', 'fontsize',fontsizeStr)
locator = getMetaData(cell, table_index, 'tableCaption', 'locator', 'tb')
labelStr = getMetaData(cell, table_index, 'tableCaption', 'label','')
if labelStr:
tlabstr = labelStr
labelStr = '\\label{{{}-{}}}'.format(tlabstr, table_index)
if table_index == 0:
labelStr += '\\label{{{}}}'.format(tlabstr)
table_index += 1
outstr += '{\n'
if captionStr:
outstr = outstr + '\n\\begin{table}['+locator+']\n'
outstr += '\\centering\n'
outstr += '\\caption{'+'{}{}'.format(latexEscapeCaption(captionStr),labelStr)+'}\n'
outstr += booktabstr
outstr += '\n\\begin{{{}}}\n'.format(fontsizeStr)
outstr += '\\renewcommand{\\arraystretch}{1.1}\n'
outstr += payload + '\n'
outstr += '\\renewcommand{\\arraystretch}{1}\n'
outstr += '\\end{{{}}}\n'.format(fontsizeStr)
if captionStr:
outstr += '\\end{table}\n\n'
outstr += '}\n\n'
# process figure with caption, either a string or a list of strings
elif getMetaData(cell, figure_index, 'figureCaption', 'caption',''):
fstring, figure_index = prepareFigureFloat(cell,figure_index,filename=None,payload=payload,fontsizeStr=fontsizeStr)
outstr += fstring
elif booktabstr or '\\begin{tabular}' in payload:
# no captioned latex, just output inline
# check for tabular
outstr += '{\n'
outstr += '\\renewcommand{\\arraystretch}{1.1}\n'
outstr += '\\centering\n'
if booktabstr:
outstr += booktabstr
outstr += '\n\\begin{{{}}}\n'.format(fontsizeStr)
outstr += payload + '\n'
outstr += '\\end{{{}}}\n'.format(fontsizeStr)
outstr += '\\renewcommand{\\arraystretch}{1}\n'
outstr += '}\n\n'
table_index += 1
else:
outstr += payload + '\n'
return outstr
################################################################################
def prepOutput(cellOutput, cell, cell_index, output_index, imagedir, infile,addurlcommand):
captionStr = getMetaData(cell, 0, 'listingCaption', 'outputCaption','')
labelStr = getMetaData(cell, 0, 'listingCaption', 'label','')
if captionStr:
captionStr = '{'+r'{} \label{{{}-out}}'.format(captionStr, labelStr)+'}'
global figure_index
global table_index
table_index = 0
figure_index = 0
outstr = ''
if 'text' in cellOutput.keys():
outstr += encapsulateListing(cellOutput['text'], captionStr)
elif 'data' in cellOutput.keys():
if 'text/html' in cellOutput.data.keys():
outs = cellOutput.data['text/html']
outstr += processHTMLTree(outs,cell,addurlcommand)
elif 'text/latex' in cellOutput.data.keys():
lstr = processLaTeXOutCell(
cellOutput,output_index,outstr,cell,addurlcommand)
outstr += lstr
elif 'text/plain' in cellOutput.data.keys():
outstr += encapsulateListing(cellOutput.data['text/plain'], captionStr)
else:
raise NotImplementedError("Unable to process cell {}, \nlooking for subkeys: {}".\
format(cellOutput, cellOutput.data.keys()))
else:
raise NotImplementedError("Unable to process cell {}, \nlooking for keys: {}".\
format(cellOutput, cellOutput.keys()))
outstr += '\n'
return outstr
################################################################################
def encapsulateListing(outstr, captionStr):
outstr = unicodedata.normalize('NFKD',outstr).encode('ascii','ignore')
rtnStr = u'\n\\begin{lstlisting}'
outstr = outstr.decode("utf-8")
if captionStr:
rtnStr += '[style=outcellstyle,caption={:s}]\n{}\n'.format(captionStr,outstr)
else:
rtnStr += '[style=outcellstyle]\n{}\n'.format(outstr)
rtnStr += '\\end{lstlisting}\n\n'
return rtnStr
################################################################################
def prepInput(cell, cell_index, inlinelistings):
rtnStr = ''
rtnSource = ''
captiopurp = None
if 'source' in cell.keys():
lsting = cell.source
captionStr = getMetaData(cell, 0, 'listingCaption', 'caption','')
labelStr = getMetaData(cell, 0, 'listingCaption', 'label','')
if not inlinelistings and not len(labelStr):
labelStr = 'lst:autolistingcell{}'.format(cell_index)
showListing = True
if not inlinelistings: # and not captionStr:
if len(lsting):
lstistrp = lsting.split('\n')
if lstistrp[0].startswith(('%%','% ')):
commentLine = lstistrp[1]
else:
commentLine = lstistrp[0]
if len(commentLine) > 0: # long enough string?
if commentLine[0]=='#':
if len(commentLine) > 1: # long enough string?
if not commentLine[1]=='#':
captiopurp = ' ' + commentLine[1:]
if len(commentLine) > 2: # long enough string?
if commentLine[2]=='#':
showListing = False
else:
captiopurp = ''
if not captionStr:
captionStr = 'Code Listing in cell {}'.format(cell_index)
if captionStr:
captionStr = '{'+r'{}}}, label={}'.format(latexEscapeCaption(captionStr), labelStr)
if showListing and len(lsting)>0:
if inlinelistings:
rtnStr += '\n\\begin{lstlisting}'
rtnStr += '[style=incellstyle]\n{}\n'.format(lsting)
rtnStr += '\\end{lstlisting}\n\n'
else:
rtnSource += '\n\\begin{lstlisting}'
if captionStr:
rtnSource += '[style=incellstyle,caption={}]\n{}\n'.format(captionStr,lsting)
else:
rtnSource += '[style=incellstyle]\n{}\n'.format(lsting)
rtnSource += '\\end{lstlisting}\n\n'
if captiopurp is not None:
rtnStr += '\n\nSee Listing~\\ref{{{}}} for the code{}.\n\n'.format(labelStr,captiopurp)
return rtnStr,rtnSource
################################################################################
# def convertBytes2Str(instring):
# """Convert a byte string to regular string (if in Python 3)
# """
# # print('1',type(instring))
# if isinstance(instring, bytes):
# instring = instring.decode("utf-8")
# return instring
################################################################################
def prepExecuteResult(cellOutput, cell, cell_index, output_index, imagedir, infile,addurlcommand):
if 'html' in cellOutput.keys():
return processHTMLTree(cellOutput['html'],cell,addurlcommand)
if u'png' in cellOutput.keys():
return processDisplayOutput(cellOutput, cell, cell_index, output_index, imagedir, infile,addurlcommand)
return prepOutput(cellOutput, cell, cell_index, output_index, imagedir, infile,addurlcommand)
# if 'text' in cellOutput.keys():
# outstr = cellOutput['text']
# elif 'data' in cellOutput.keys():
# if 'text/html' in cellOutput.data.keys():
# doListing = False
# outstr = cellOutput.data['text/html']
# outstr = processHTMLTree(outstr,cell,addurlcommand)
# if 'text/plain' in cellOutput.data.keys():
# outstr = cellOutput.data['text/plain']
# else:
# raise NotImplementedError("Unable to process cell {}, \nlooking for keys: {}".\
# format(cellOutput, cellOutput.keys()))
################################################################################
def prepError(cellOutput, cell, cell_index, output_index, imagedir, infile,addurlcommand):
import os, re
r= re.compile(r'\033\[[0-9;]+m')
rtnStr = '\n\\begin{verbatim}\n'
for output in cell["outputs"]:
# v3 if output['output_type'] == 'error':
if output['output_type'] == 'error':
for trace in output['traceback']:
#convert to ascii and remove control chars
# rtnStr += re.sub(r'\033\[[0-9;]+m',"", bytes(trace).decode('ascii','ignore'))
rtnStr += re.sub(r'\033\[[0-9;]+m',"", trace)
rtnStr += '\\end{verbatim}\n'
return rtnStr
################################################################################
def prepNotYet(cellOutput, cell, cell_index, output_index, imagedir, infile,addurlcommand):
for output in cell["outputs"]:
raise NotImplementedError("Unable to process cell type {}".\
format(output["output_type"]))
################################################################################
def extractBibtexXref(cell):
#read the citation cross-reference map
if 'bibxref' in cell['metadata'].keys():
for key in cell['metadata']['bibxref'].keys():
bibxref[key] = cell['metadata']['bibxref'][key]
#read user-supplied bibtex entries.
if 'bibtexentry' in cell['metadata'].keys():
for key in cell['metadata']['bibtexentry'].keys():
bibtexlist.append(cell['metadata']['bibtexentry'][key] + '\n\n')
################################################################################
def getMetaData(cell, output_index, captionID, metaID, defaultValue=''):
"""process the metadata string, either a single value or a list of values,
and extract the value associated with output_index, if in a list
"""
outVal = defaultValue
if captionID in cell['metadata'].keys():
if metaID in cell['metadata'][captionID].keys():
inVal = cell['metadata'][captionID][metaID]
# sometimes lists are correctly imported and sometimes not
if isinstance(inVal, str) and '[' in inVal:
import ast
inVal = ast.literal_eval(inVal)
# for it,item in enumerate(inVal):
# if isinstance(item,str):
# inVal[it] = item.replace('\\\\','\\')
# else:
# inVal[it] = item
if isinstance(inVal, str):
outVal = inVal
else:
if output_index < len(inVal):
outVal = inVal[output_index]
else:
outVal = defaultValue
return outVal
################################################################################
def processDisplayOutput(cellOutput, cell, cell_index, output_index, imagedir, infile,addurlcommand):
# print('********',cellOutput.keys())
texStr = ''
if 'name' in cellOutput.keys() :
if cellOutput.name == 'stdout':
if 'text' in cellOutput.keys() :
return cellOutput.text
if 'text/html' in cellOutput.keys() :
return processHTMLTree(cellOutput['text/html'],cell,addurlcommand)
#handle pdf image
picCell = None
#nbformat 4
if 'data' in cellOutput.keys() and 'application/pdf' in cellOutput.data.keys():
picCell = cellOutput.data['application/pdf']
imageName = infile.replace('.ipynb', '') + \
'_{}_{}.pdf'.format(cell_index, output_index)
#nbformat 3
if 'pdf' in cellOutput.keys():
picCell = cellOutput.pdf
imageName = infile.replace('.ipynb', '') + \
'_{}_{}.pdf'.format(cell_index, output_index)
#handle png images
#nbformat 4
if 'data' in cellOutput.keys() and 'image/png' in cellOutput.data.keys():
picCell = cellOutput.data['image/png']
imageName = infile.replace('.ipynb', '') + \
'_{}_{}.png'.format(cell_index, output_index)
#nbformat 3
if 'png' in cellOutput.keys():
picCell = cellOutput.png
imageName = infile.replace('.ipynb', '') + \
'_{}_{}.png'.format(cell_index, output_index)
#handle jpeg images
#nbformat 4
if 'data' in cellOutput.keys() and 'image/jpeg' in cellOutput.data.keys():
picCell = cellOutput.data['image/jpeg']
imageName = infile.replace('.ipynb', '') + \
'_{}_{}.jpeg'.format(cell_index, output_index)
#nbformat 3
if 'jpeg' in cellOutput.keys():
picCell = cellOutput.jpeg
imageName = infile.replace('.ipynb', '') + \
'_{}_{}.jpeg'.format(cell_index, output_index)
if picCell:
filename = os.path.join(imagedir,imageName)
with open(filename, 'wb') as fpng:
fpng.write(base64.decodebytes(bytes(picCell, 'utf-8')))
fstring, _ = prepareFigureFloat(cell,output_index,filename)
texStr += fstring
return texStr
# not sure wht this is still here, there is another processor caught in
# the 'data' key processing done further down below (processLaTeXOutCell)
# #handle latex in output cell
# #nbformat 4
# if 'data' in cellOutput.keys() and 'text/latex' in cellOutput.data.keys():
# print('process latex 2')
# texStr += processLaTeX(cellOutput['data']['text/latex'],cell,addurlcommand)
# return texStr
# #nbformat 3
# if 'latex' in cellOutput.keys():
# texStr += processLaTeX(cellOutput['text/latex'],cell,addurlcommand)
# return texStr
if 'text/plain' in cellOutput.keys():
return prepOutput(cellOutput, cell, cell_index, output_index, imagedir, infile,addurlcommand)
if 'data' in cellOutput.keys():
if 'text/plain' in cellOutput.data.keys():
return prepOutput(cellOutput, cell, cell_index, output_index, imagedir, infile,addurlcommand)
if 'display_data' in cellOutput['output_type']:
if 'application/vnd.jupyter.widget-view+json' in cellOutput['data'].keys():
if 'model_id' in cellOutput['data']['application/vnd.jupyter.widget-view+json'].keys():
texStr += f"\n\nCell contains a Jupyter widget with model\_id "
texStr += f"{cellOutput['data']['application/vnd.jupyter.widget-view+json']['model_id']} "
texStr += f"please open the notebook for display of this widget.\n\n"
return texStr
strErr = f"""
Unknown cell type(s) in this cell:
cell_keys: {cell.keys()}
cell_type: {cell['cell_type']}
cell execution_count: {cell['execution_count']}
cell source: {cell['source']}
cell meta: {cell['metadata']}
cellOutput keys: {cellOutput.keys()}
cellOutput output_type: {cellOutput['output_type']}
cellOutput data: {cellOutput['data']}
cellOutput metadata: {cellOutput['metadata']}
output_index: {output_index}
"""
# cell output: {cell['outputs']}
raise NotImplementedError(strErr)
################################################################################
#process an html tree
def processLaTeX(latex,cell,addurlcommand):
# print('processLaTeX',latex)
return latex
################################################################################
def convertRawCell(cell, cell_index, imagedir, infile, inlinelistings,addurlcommand):
extractBibtexXref(cell)
strraw = cell['source']+'\n\n'
return strraw , ''
################################################################################
def convertCodeCell(cell, cell_index, imagedir, infile, inlinelistings,addurlcommand):
extractBibtexXref(cell)
output,lstoutput = prepInput(cell, cell_index, inlinelistings)
for count, cellOutput in enumerate(cell.outputs):
#output += "<li>{}</li>".format(cellOutput.output_type)
if cellOutput.output_type not in fnTableOutput:
print(cellOutput.output_type)
raise NotImplementedError("Unknown output type {}.".format(cellOutput.output_type))
output += fnTableOutput[cellOutput.output_type](cellOutput, cell, cell_index, count, imagedir, infile,addurlcommand)
return output, lstoutput
################################################################################
def convertMarkdownCell(cell, cell_index, imagedir, infile, inlinelistings,addurlcommand):
extractBibtexXref(cell)
mkd = cell['source']
# the problem is markdown will escape out slashes in the math environments
# to try to fix this, let's find all the math environments
# run markdown on them independently, to know what to search/replace for
# this will probably break kind of badly for poorly formatted input,
# particularly if $ and begin{eq..} are mixed within each other, but
# hopefully you'll notice your input is broken in the notebook already?
math_envs = []
#the following block replaces $$ with begin/end {equation} sequences
repstring = [r'\begin{equation}',r'\end{equation}']
i = 0
nlines = []
ddollars = list(findAllStr(mkd, '$$'))
if len(ddollars) > 0:
lines = mkd.split('\n')
for line in lines:
#ignore verbatim text
if line[0:4] == ' ':
nlines.append(line)
else:
#replace in sequence over one or more lines, one at a time
while '$$' in line:
line = line.replace('$$',repstring[i%2],1)
i += 1
nlines.append(line)
#rebuild the markdown
mkd = '\n'.join(nlines)
dollars = list(findAllStr(mkd, '$'))
ends = dollars[1::2]
starts = dollars[::2]
if len(starts) > len(ends):
starts = starts[:-1]
math_envs += [(s,e) for (s,e) in zip(starts, ends)]
starts = list(findAllStr(mkd, '\\begin{equation}'))
ends = [e + 13 for e in findAllStr(mkd, '\\end{equation}')]
if len(starts) > len(ends):
starts = starts[:-1]
math_envs += [(s,e) for (s,e) in zip(starts, ends)]
math_envs = sorted(math_envs)
starts = list(findAllStr(mkd, '\\begin{equation*}'))
ends = [e + 14 for e in findAllStr(mkd, '\\end{equation*}')]
if len(starts) > len(ends):
starts = starts[:-1]
math_envs += [(s,e) for (s,e) in zip(starts, ends)]
math_envs = sorted(math_envs)
starts = list(findAllStr(mkd, '\\begin{eqnarray}'))
ends = [e + 13 for e in findAllStr(mkd, '\\end{eqnarray}')]
if len(starts) > len(ends):
starts = starts[:-1]
math_envs += [(s,e) for (s,e) in zip(starts, ends)]
math_envs = sorted(math_envs)
if math_envs:
mkd_tmp = ""
old_end = -1
for start, end in math_envs:
mkd_tmp += mkd[old_end+1:start]
old_end = end
cleaned = mkd[start:end+1]
for escapeable in '\\`*_{}[]()#+-.!':
cleaned = cleaned.replace(escapeable, '\\' + escapeable)
cleaned = cleaned.replace('\n', '')
mkd_tmp += cleaned
mkd = mkd_tmp + mkd[end+1:]
html = markdown.markdown(mkd, extensions=['extra'])
tmp = processHTMLTree(html,cell,addurlcommand)
# lines = tmp.split('\n')
# for line in lines:
# if 'http' in line and r'\cite' in line:
# print(line)
return tmp,''
################################################################################
#process an html tree
def processHTMLTree(html,cell,addurlcommand):
global figure_index
global table_index
figure_index = 0
table_index = 0
tree = lxml.html.fromstring("<div>"+html+"</div>")
# pptree(tree)
tmp = ""
for child in tree:
# print('------------------------------------')
# print('child.tag={}'.format(child.tag),type(child.tag))
# print('child.text={}'.format(child.text))
# print('child.tail={}'.format(child.tail))
# print(cell)
if child.tag == 'h1' or (cell['cell_type']=="heading" and cell['level']==1):
tmp += processHeading(r'\chapter', child.text_content())
elif child.tag == 'h2' or (cell['cell_type']=="heading" and cell['level']==2):
tmp += processHeading(r'\section', child.text_content())
elif child.tag == 'h3' or (cell['cell_type']=="heading" and cell['level']==3):
tmp += processHeading(r'\subsection', child.text_content())
elif child.tag == 'h4' or (cell['cell_type']=="heading" and cell['level']==4):
tmp += processHeading(r'\subsubsection', child.text_content())
elif child.tag == 'h5' or (cell['cell_type']=="heading" and cell['level']==5):
tmp += processHeading(r'\paragraph', child.text_content())
elif child.tag == 'h6' or (cell['cell_type']=="heading" and cell['level']==6):
tmp += processHeading(r'\subparagraph', child.text_content())