-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparse
More file actions
executable file
·544 lines (407 loc) · 18.7 KB
/
parse
File metadata and controls
executable file
·544 lines (407 loc) · 18.7 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
#! /usr/bin/env python
#
# Copyright (c) 2013 Joost van Zwieten
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
from __future__ import print_function, division, unicode_literals
import sys
import subprocess
import json
import code
import inspect
import cStringIO as StringIO
import os.path
import shutil
import pygments, pygments.lexers, pygments.formatters
import urllib
import hashlib
import traceback
import re
# TEMPORARY HACK
def input_wrapper( *args ):
raise NotImplementedError
def raw_input_wrapper( *args ):
raise NotImplementedError
import __builtin__
__builtin__.input = input_wrapper
__builtin__.raw_input = raw_input_wrapper
# END TEMPORARY HACK
def _append_raw_block_pandoc_lt_12( lst, html = None ):
if html:
lst.append( { 'RawBlock' : [ 'html', html ] } )
def _append_raw_block_pandoc_ge_12( lst, html = None ):
if html:
lst.append( { 't': 'RawBlock', 'c' : [ 'html', html ] } )
pandoc = subprocess.Popen( [ 'pandoc', '--version' ], stdout = subprocess.PIPE )
stdout, stderr = pandoc.communicate()
match = re.match( 'pandoc ([0-9.]+)', stdout.splitlines()[0] )
if match:
pandoc_version = tuple( map( int, match.group( 1 ).split('.') ) )
else:
# assume pandoc version 1.11
pandoc_version = ( 1, 11 )
if pandoc_version < ( 1, 12 ):
append_raw_block = _append_raw_block_pandoc_lt_12
else:
append_raw_block = _append_raw_block_pandoc_ge_12
del pandoc, stdout, stderr
def escape_html( s ):
return reduce( lambda t, a: t.replace( *a ), ( ('&','&'), ('<','<'), ('>','>'), ('"','"') ), s )
def escape_url( url ):
return urllib.quote( url )
class HtmlFormatter( pygments.formatters.HtmlFormatter ):
def wrap( self, source, outfile ):
return self._wrap_code( source )
def _wrap_code( self, source ):
lineno = 0
for i, t in source:
if i == 1:
lineno += 1
if t.endswith( '\r\n' ):
t, end = t[ :-2 ], t[ -2: ]
elif t.endswith( '\n' ):
t, end = t[ :-1 ], t[ -1: ]
t = '<div class="line lineno{}">{}</div>{}'.format( lineno, t, end )
yield i, t
class HtmlFormatterIC( pygments.formatters.HtmlFormatter ):
def wrap( self, source, outfile ):
return self._wrap_code( source )
def _wrap_code( self, source ):
for i, t in source:
if i == 1:
if t.endswith( '\r\n' ):
t, end = t[ :-2 ], t[ -2: ]
elif t.endswith( '\n' ):
t, end = t[ :-1 ], t[ -1: ]
if t.startswith( '<span class="gp">... </span>' ) or t.startswith( '<span class="gp">>>> </span>' ):
cls = 'code'
else:
cls = 'output'
t = '<div class="line {}">{}</div>{}'.format( cls, t, end )
yield i, t
class IC( code.InteractiveConsole ):
def __init__( self, prefix ):
self.prefix = prefix
self._locals = { '__name__' : '__console__', '__doc__' : None }
self.prompt = False
code.InteractiveConsole.__init__( self, self._locals )
self._locals[ 'init_console' ] = self._init_console
self.push_hidden( 'init_console()' )
del self._locals[ 'init_console' ]
self._pending_figures = []
self.fignum = 0
@property
def pending_figures( self ):
return self._pending_figures_iterator()
def _pending_figures_iterator( self ):
while self._pending_figures:
yield self._pending_figures.pop( 0 )
def push( self, line ):
print( '...' if self.prompt else '>>>', line )
self.prompt = code.InteractiveConsole.push( self, line )
return self.prompt
def push_hidden( self, line ):
self.prompt = code.InteractiveConsole.push( self, line )
return self.prompt
def write( self, line ):
print( line, end = '' )
def _init_console( self ):
import sys
sys.path.append( '.' )
import matplotlib
matplotlib.use( 'cairo' )
import matplotlib.pyplot
def return_None_wrapper( func ):
def wrapped( *args, **kargs ):
func( *args, **kargs )
return wrapped
for attr in ( 'plot', 'title', 'xlabel', 'ylabel', 'subplot', 'imshow' ):
setattr( matplotlib.pyplot, attr, return_None_wrapper( getattr( matplotlib.pyplot, attr ) ) )
def show_wrapper():
figures=[manager.canvas.figure for manager in matplotlib._pylab_helpers.Gcf.get_all_fig_managers()]
for figure in figures:
name = '{}_matplotlib_{:04d}'.format( self.prefix, self.fignum )
figure.savefig( name + '.svg' )
figure.savefig( name + '.pdf' )
matplotlib.pyplot.close( figure )
self.fignum += 1
self._pending_figures.append( name )
matplotlib.pyplot.show = show_wrapper
class Debugger:
def __init__( self, code, globals = None, locals = None ):
if globals is None:
globals = {}
if locals is None:
locals = globals
self._code = code
self._globals = globals
self._locals = locals
def run( self ):
self.items = []
self._console = StringIO.StringIO()
self._calling_frame = inspect.currentframe()
self._code_filename = self._code.co_filename
# capture stdout, stderr
orig_stdout = sys.stdout
orig_stderr = sys.stderr
try:
try:
sys.stdout = self._console
sys.stderr = self._console
sys.settrace( self._trace_callback )
exec( self._code, self._globals, self._locals )
finally:
sys.settrace( None )
sys.stdout = orig_stdout
sys.stderr = orig_stderr
except:
print( self._last_exception_string, end = '', file = self._console )
self._append_item( 'script exited with exception', None, None )
def _trace_callback( self, frame, event, arg ):
if event == 'line':
if frame.f_code.co_filename != self._code_filename:
# disable trace for this frame
return
self._append_item( 'line', frame, None )
elif event == 'call' or event == 'c_call':
self._append_item( event, frame, None )
if frame.f_code.co_filename != self._code_filename:
# disable trace for this function
return
elif event == 'return' or event == 'c_return':
self._append_item( event, frame, 'return value: {!r}'.format( arg ) )
elif event == 'exception' or event == c_exception:
self._last_exception_string = ''.join( traceback.format_exception( *arg ) )
self._append_item( event, frame, self._last_exception_string )
return self._trace_callback
def _append_item( self, event, frame, arg ):
stack = StringIO.StringIO()
print_stack = lambda *args, **kargs: print( *args, file = stack, **kargs )
f = frame
while f and f is not self._calling_frame:
print_stack( 'File {!r}, line {}, in {}'.format( f.f_code.co_filename, f.f_lineno, f.f_code.co_name ) )
if f.f_code.co_filename == self._code_filename:
if f.f_globals is f.f_locals:
print_stack( ' locals, globals:' )
for k, v in sorted( f.f_locals.items() ):
if k.startswith( '_' ):
continue
print_stack( ' {}: {!r}'.format( k, v ) )
else:
print_stack( ' locals:' )
for k, v in sorted( f.f_locals.items() ):
if k.startswith( '_' ):
continue
print_stack( ' {}: {!r}'.format( k, v ) )
print_stack( ' globals:' )
for k, v in sorted( f.f_globals.items() ):
if k.startswith( '_' ):
continue
print_stack( ' {}: {!r}'.format( k, v ) )
f = f.f_back
if frame:
event = '{}, file {!r}, line {}, in {}'.format( event, frame.f_code.co_filename, frame.f_lineno, frame.f_code.co_name )
if arg:
event = '{}\n{}'.format( event, arg )
# event = event, frame.f_code.co_filename, frame.f_lineno, frame.f_code.co_name, repr( arg )
if frame and frame.f_code.co_filename == self._code_filename:
line = frame.f_lineno
else:
line = None
self.items.append( ( line, event, self._console.getvalue(), stack.getvalue() ) )
def convert_ast( doc, doc_name, at_build_dir, html_header ):
# python_lexer = pygments.lexers.get_lexer_by_name( 'python' )
python_lexer = pygments.lexers.PythonLexer()
python_console_lexer = pygments.lexers.PythonConsoleLexer()
# html_formatter = pygments.formatters.get_formatter_by_name( 'html' )
html_formatter = HtmlFormatter( linenos = False, cssclass = "pythoncode" )
html_console_formatter = HtmlFormatterIC( linenos = False, cssclass = "pythoncode" )
ic = IC( prefix = at_build_dir( doc_name ) )
new_body = []
def new_slide( slide_counter ):
html_code = '<div id="slide-{}" class="slide"><div class="container">'.format( slide_counter )
if slide_counter > 0:
html_code = '</div></div>' + html_code
append_raw_block( new_body, html = html_code )
return slide_counter + 1
slide_counter = new_slide( 0 )
next_new_slide = False
for item in doc[ 1 ]:
if pandoc_version >= ( 1, 12 ) and not isinstance( item, dict ):
new_body.append( item )
continue
if next_new_slide:
slide_counter = new_slide( slide_counter )
next_new_slide = False
if pandoc_version < ( 1, 12 ) and item == 'HorizontalRule' or pandoc_version >= ( 1, 12 ) and item[ 't' ] == 'HorizontalRule':
continue
if pandoc_version < ( 1, 12 ) and ( isinstance( item, dict ) and 'CodeBlock' in item and item[ 'CodeBlock' ][ 1 ].startswith( '# python' ) ) \
or pandoc_version >= ( 1, 12 ) and ( isinstance( item, dict ) and item['t'] == 'CodeBlock' and item[ 'c' ][ 1 ].startswith( '# python' ) ):
default_output_hidden = False
if pandoc_version < ( 1, 12 ):
data = item[ 'CodeBlock' ]
else:
data = item[ 'c' ]
src = ( data[ 1 ] + '\n' ).splitlines()
# FIXME: support (tags in) fenced code blocks
src0 = src[0]
tags = tuple( tag.strip() for tag in src0[1:].split( ',' ) )
code_in_ic = 'interactive_console' in tags or 'ic' in tags
code_in_debugger = 'debugger' in tags
default_output_hidden = 'default_output_hidden' in tags
attributes = {}
src = src[ 1: ]
if code_in_ic:
# run `src` through an interpreter, and capture stdout
original_stdout = sys.stdout
original_stderr = sys.stderr
sys.stderr = sys.stdout = StringIO.StringIO()
more_input_required = False
for line in src:
more_input_required = ic.push( line )
# push a blank line if more input is required, but the code block has ended
if more_input_required:
ic.push( '' )
output = sys.stdout.getvalue()
sys.stdout = original_stdout
sys.stderr = original_stderr
# highlighting of src and output
code_html = pygments.highlight( output, python_console_lexer, html_console_formatter )
elif code_in_debugger:
try:
c = compile( '\n'.join( src ), mode = 'exec', filename = '<script>', dont_inherit = True )
except:
pass
# TODO: show error in html
else:
db = Debugger( c )
db.run()
json_data = json.dumps( db.items )
json_hash = hashlib.sha1( json_data ).hexdigest()
html_header.append( '<script type="text/javascript">window.python_trace_{} = {};</script>'.format( json_hash, escape_html( json_data ) ) )
attributes[ 'python_trace' ] = 'python_trace_{}'.format( json_hash )
# highlighting of src
code_html = pygments.highlight( '\n'.join( src ), python_lexer, html_formatter )
else:
# highlighting of src
code_html = pygments.highlight( '\n'.join( src ), python_lexer, html_formatter )
classes = [ 'pythoncode' ]
if code_in_ic:
classes.append( 'interactive_console' )
if code_in_debugger:
classes.append( 'debugger' )
if default_output_hidden:
classes.append( 'output_hidden' )
attributes[ 'class' ] = ' '.join( classes )
attributes = ' '.join( '{}="{}"'.format( key, escape_html( value ) ) for key, value in attributes.iteritems() )
code_html = '<div {}><div class="container">\n{}\n</div></div>'.format( attributes, code_html )
if 'hidden' not in tags:
append_raw_block( new_body, html = code_html )
for figure in ic.pending_figures:
slide_counter = new_slide( slide_counter )
next_new_slide = True
code_html = '<div class="output image"><img src="{}.svg"/></div>'.format( figure )
#code_html = '<div class="output image"><object data="{}.svg" type="image/svg+xml"></object></div>'.format( figure )
append_raw_block( new_body, html = code_html )
elif pandoc_version < ( 1, 12 ) and item == 'HorizontalRule' or pandoc_version >= ( 1, 12 ) and item[ 't' ] == 'HorizontalRule':
slide_counter = new_slide( slide_counter )
else:
new_body.append( item )
append_raw_block( new_body, html = '</div></div>' )
return doc[ 0 ], new_body
def process_document( src, share_dir, build_dir, hashed_dependencies ):
at_share_dir = lambda f: os.path.join( share_dir, f )
at_build_dir = lambda f: os.path.join( build_dir, f )
doc_name, ext = os.path.splitext( src )
if not os.path.isfile( src ):
print( 'No such file: {}'.format( src ) )
raise SystemExit
# convert source to json using pandoc
pandoc = subprocess.Popen( [ 'pandoc', '--to=json', src ], stdout = subprocess.PIPE )
doc, tmp = pandoc.communicate()
doc = json.loads( doc )
# process document
html_header = []
doc = json.dumps( convert_ast( doc, doc_name, at_build_dir, html_header ) )
# generate html header supplement
html_header.append( '<script type="text/javascript" src="{}"></script>'.format( hashed_dependencies[ 'slideshow.js' ] ) )
html_include = at_build_dir( '{}.html_include'.format( doc_name ) )
with open( html_include, 'w' ) as f:
for line in html_header:
print( line, file = f )
# generate html using pandoc
pandoc = subprocess.Popen( [
'pandoc',
'--from=json',
'--to=html',
'--standalone',
'--email-obfuscation=none',
'--mathjax',
'--css={}'.format( hashed_dependencies[ 'pygments.css' ] ),
'--css={}'.format( hashed_dependencies[ 'slideshow.css' ] ),
'--include-in-header={}'.format( html_include ),
'--output={}'.format( at_build_dir( doc_name + '.xhtml' ) ),
], stdin = subprocess.PIPE )
pandoc.communicate( doc )
if __name__ == '__main__':
# default settings
root = os.path.split( __file__ )[ 0 ]
build_dir = '.'
at_share_dir = lambda f: os.path.join( root, f )
at_build_dir = lambda f: os.path.join( build_dir, f )
# process command line arguments
sources = []
args = iter( sys.argv[1:] )
for arg in args:
if arg.startswith( '--' ):
arg = arg[2:]
value = None
if '=' in arg:
arg, value = arg.split( '=', 1 )
if arg == 'build':
if value is None:
try:
value = next( args )
except StopIteration:
print( 'ERROR: `--build` requires a value' )
raise SystemExit( 1 )
build_dir = value
if not os.path.isdir( build_dir ):
print( 'ERROR: build directory does not exist or is not a directory' )
raise SystemExit( 1 )
else:
print( 'ERROR: unknown argument: --{}'.format( arg ) )
raise SystemExit( 1 )
else:
if not os.path.isfile( arg ):
print( 'ERROR: specified source does not exist or is not a file: {}'.format( arg ) )
raise SystemExit( 1 )
sources.append( arg )
# copy css and javascript files to the build directory
hashed_dependencies = {}
for name in ( 'slideshow.css', 'slideshow.js', 'pygments.css' ):
with open( at_share_dir( name ) ) as f:
hashed_name = '{}-{}'.format( hashlib.sha1( f.read() ).hexdigest(), name )
hashed_dependencies[ name ] = hashed_name
if not os.path.exists( at_build_dir( hashed_name ) ):
shutil.copy( at_share_dir( name ), at_build_dir( hashed_name ) )
# process documents
for source in sources:
process_document( source, root, build_dir, hashed_dependencies )
# vim: ts=4:sts=4:sw=4:et