-
Notifications
You must be signed in to change notification settings - Fork 0
/
srdine.py
1745 lines (1440 loc) · 71 KB
/
srdine.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
"""
PDF wrangler for the Dungeons and Dragons 5 Edition Systems Reference Document
Doc for PyMuPDF v1.17.4 at
https://web.archive.org/web/20200724120551/https://pymupdf.readthedocs.io/en/latest/intro.html
D&D 5E SRD at
https://dnd.wizards.com/resources/systems-reference-document
"""
# XXX Link monster to roll20? (no images)
# See https://roll20.net/compendium/dnd5e/Monsters:Hobgoblin#content
# XXX Link monster to dndbeyond?
# See https://www.dndbeyond.com/monsters/16925-hobgoblin
# XXX Any other thumbnails/links for other sections?
# XXX Export spells to JSON?
# XXX Export dndbeyond-style html monsters to PDF with a toc indexed by multiple stats
import time
import errno
import io
import json
import os
import random
import re
import string
import sys
import time
import urllib2
import urlparse
import fitz
# Lifted from cgi.escape, no need to bring the whole module for just this
# function
def escape_html(s, quote=None):
'''Replace special characters "&", "<" and ">" to HTML-safe sequences.
If the optional flag quote is true, the quotation mark character (")
is also translated.'''
s = s.replace("&", "&") # Must be done first!
s = s.replace("<", "<")
s = s.replace(">", ">")
if (quote):
s = s.replace('"', """)
return s
def makedirs(dirpath):
try:
os.makedirs(dirpath)
except OSError as e:
if (e.errno != errno.EEXIST):
raise
def parse_int(s):
i = None
try:
i = int(s)
except (TypeError, ValueError):
pass
return i
all_cookies = {}
def http_get(url, filepath, referrer=None, overwrite=False, throttle=False):
## print "http_get", repr(url)
# Note urlretrieve will download and save the body in the cases of servers
# that fill the body with some error message when returning a 404.
# Don't use urllretrieve, use urlopen, check the code and download. This has
# the disadvantage that it will always hit the network for missing content
if (overwrite or (not os.path.exists(filepath))):
# Throttle otherwise requests get blacklisted for spamming the server
# 1.25 is known to throttle after a bunch of requests, same as 1.5
if (throttle):
time.sleep(2)
req = urllib2.Request(url)
# dndbeyond will respond 403 without user agent, note user-agents can be
# blacklisted for hours, need to do some change to the user-agent string
# although it doesn't help that much and still gets blacklisted after a
# few downloads
user_agent_header = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%d.0.0.%d Safari/%d.%d' % (
random.randint(80, 120), random.randint(0, 255),
random.randint(200, 600), random.randint(1, 25)
)
##print "user_agent_header", user_agent_header
req.add_header('user-agent', user_agent_header)
#req.add_header('accept-encoding', "accept-encoding: gzip, deflate, br")
req.add_header('accept-language', "accept-language: en-US,en;q=0.9")
req.add_header('accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7')
parsed_url = urlparse.urlparse(url)
# Send referrer to appease the blacklisting, not clear it helps
if (referrer is None):
referrer = parsed_url.scheme + "://" + parsed_url.hostname + parsed_url.path
## print "referer_header", referer_header
req.add_header('referer', referrer)
# Send cookies to appease the blacklisting, not clear it helps but it
# doesn't hurt
try:
cookies = all_cookies[parsed_url.hostname]
except KeyError:
cookies = {}
all_cookies[parsed_url.hostname] = cookies
if (len(cookies) > 0):
cookie_header = string.join(["%s=%s" % (name, value) for name, value in cookies.iteritems()], "; ")
## print "cookie_header", cookie_header
req.add_header('cookie', cookie_header)
f_in = urllib2.urlopen(req)
if (f_in.getcode() == 200):
# Set-Cookie: Geo=...; path=/; domain=.dndbeyond.com; SameSite=None; Secure;\r\n
for cookie_header in f_in.info().getallmatchingheaders("set-cookie"):
## print "jarring cookie", cookie_header
_, cookie_content = cookie_header.split(":", 1)
cookie_name_value, _ = cookie_content.split(";", 1)
cookie_name, cookie_value = cookie_name_value.split("=", 1)
cookies[cookie_name] = cookie_value
## print "current cookies", cookies
# Set-Cookie: AWSELB=17A59...;PATH=/;MAX-AGE=3600
print "Downloading", repr(url), "to", repr(filepath)
# XXX Ignoring the url when naming the file will replicate images
# that are the same for all monsters (eg ancient vs. adult
# dragons), fix?
with open(filepath, "wb") as f_out:
f_out.write(f_in.read())
else:
print "Skipping error", f_in.getcode(), url
f_in.close()
else:
## print "Skipping already downloaded", url, "to", filepath
pass
def filename_from_monster_name(name):
return urllib2.quote(name.encode("utf-8"), "")
def download_monster_images(monster, force = False):
"""
https://www.dndbeyond.com/monsters/16925-hobgoblin
https://www.dndbeyond.com/avatars/thumbnails/30788/731/1000/1000/638062180460224402.png
https://www.dndbeyond.com/avatars/thumbnails/0/388/100/100/636252781431307548.jpeg
https://www.dndbeyond.com/monsters?filter-search=hobgoblin
https://www.dndbeyond.com/monsters?filter-search=hobgoblin&filter-source=1
It has a jpg avatar and a full png image
<div class="info" data-isopen="false" data-isloading="false" data-isloaded="false" data-type="monsters" data-slug="16925-hobgoblin">
<div class="row monster-icon">
<a href="https://www.dndbeyond.com/avatars/thumbnails/30788/731/1000/1000/638062180460224402.png" data-lightbox="16925-hobgoblin" data-title="<a target='_blank' href='https://www.dndbeyond.com/avatars/thumbnails/30788/731/1000/1000/638062180460224402.png' class='link link-full'>View Full Image</a>">
<div class="image" style="background-image: url('https://www.dndbeyond.com/avatars/thumbnails/0/388/100/100/636252781431307548.jpeg');"></div>
</a>
</div>
"""
##print "download_monster_images", repr(monster["name"])
name = monster["name"]
safe_name = filename_from_monster_name(name)
query_url = "https://www.dndbeyond.com/monsters?filter-search=%s&filter-source=1&_=%d" % (
urllib2.quote(name.encode("utf-8"), ""), random.randint(1, 999999))
# This can cause 403 forbidden and cause the local ip/user-agent to be
# blacklisted until using a browser to dndbeyond.com and click on I'm not a
# robot button
if ("link" not in monster) and force:
filepath = os.path.join(out_cache_dir, "%s.html" % safe_name)
http_get(query_url, filepath, throttle=True)
with open(filepath, "r") as f:
page = f.read()
# There can be multiple monsters returned by the query above and they
# are sorted by name so a straight search for the first thumb/image can
# return the wrong results (eg Ogre Zombie instead of Zombie).
# Split the page into each monster and search for the one that has the
# strict name, pick the first otherwise.
monster_info = page
infos = page.split('<div class="info"')
# The first split is the start of the page upto the first monster
# information exclusive, skip
if (len(infos) > 1):
for candidate_info in infos[1:]:
# <a class="link" href="/monsters/17077-zombie" >Zombie</a>
m = re.search(r'<a class="link" href="([^"]*)".*>%s<' % name, candidate_info, re.IGNORECASE)
if (m is not None):
monster_info = candidate_info
monster["link"] = "https://www.dndbeyond.com%s" % m.group(1)
break
m = re.search(r"url\('(https://www.dndbeyond.com/avatars/thumbnails[^']+)'\)", monster_info)
if (m is not None):
img_url = m.group(1)
monster["thumbnail"] = img_url
m = re.search(r"(https://www.dndbeyond.com/avatars/thumbnails[^\"]*)", monster_info)
if (m is not None):
img_url = m.group(1)
monster["image"] = img_url
# Images don't need to be throttled as they always return 200 OK even if the
# html returned 403 forbidden
if ("image" in monster):
img_url = monster["image"]
img_filepath = os.path.join(out_cache_dir, ("%s_img" % safe_name) + os.path.splitext(img_url)[1])
http_get(img_url, img_filepath, referrer=query_url)
if ("thumbnail" in monster):
img_url = monster["thumbnail"]
img_filepath = os.path.join(out_cache_dir, ("%s_thumb" % safe_name) + os.path.splitext(img_url)[1])
http_get(img_url, img_filepath, referrer=query_url)
def download_template_resources():
urls_dirnames = [
("https://www.dndbeyond.com/content/1-0-2552-0/skins/waterdeep/css/compiled.css", "css"),
("https://www.dndbeyond.com/content/1-0-2552-0/skins/waterdeep/images/expanded-listing-item-bottom-border.png", "images"),
("https://www.dndbeyond.com/content/1-0-2552-0/skins/waterdeep/images/background_texture.png", "images"),
("https://www.dndbeyond.com/content/1-0-2552-0/skins/waterdeep/images/mon-summary/stat-bar-book.png", "images/mon-summary"),
("https://www.dndbeyond.com/content/1-0-2552-0/skins/waterdeep/images/mon-summary/paper-texture.png", "images/mon-summary"),
("https://www.dndbeyond.com/content/1-0-2552-0/skins/waterdeep/images/mon-summary/stat-block-top-texture.png", "images/mon-summary"),
("https://www.dndbeyond.com/file-attachments/0/579/stat-block-header-bar.svg", "images"),
("https://www.dndbeyond.com/content/1-0-2552-0/skins/waterdeep/fonts/MrsEavesSmallCaps.ttf", "fonts"),
("https://www.dndbeyond.com/content/1-0-2552-0/skins/waterdeep/fonts/ScalaSansOffc-Ita.ttf", "fonts"),
("https://www.dndbeyond.com/content/1-0-2552-0/skins/waterdeep/fonts/ScalaSansOffc-Bold.ttf", "fonts"),
("https://www.dndbeyond.com/content/1-0-2552-0/skins/waterdeep/fonts/ScalaSansOffc.ttf", "fonts"),
("https://www.dndbeyond.com/content/1-0-2552-0/skins/waterdeep/fonts/ScalaSansOffc-BoldIta.ttf", "fonts"),
]
print "Downloading template resources"
for url, dirname in urls_dirnames:
dirpath = os.path.join(out_html_dir, dirname)
makedirs(dirpath)
http_get(url, os.path.join(dirpath, os.path.basename(url)))
# make google fonts reference absolute since trying to hit the local
# filesystem and failing causes stalls of seconds
css_filepath = os.path.join(out_html_dir, "css", "compiled.css")
with open(css_filepath, "r") as f:
data = f.read()
data = data.replace("//fonts.googleapis.com", "https://fonts.googleapis.com")
with open(css_filepath, "w") as f:
f.write(data)
def cleanup_text(text, strictly_necessary = True):
# Remove non-breaking space marker which renders incorrectly as a visible
# symbol char on the toc, leave spaces next to the non-breaking space marker
# since they separate words
# Additionally, the CC SRD "Legal Information" section is
# "Legal\xa0Information\xa0"
# where the non-breaking space doesn't have regular spaces around, so first
# replace entries with spaces around with a space and then replace any
# remaining entries (probably just Legal Information) without space with a
# space too
# Remove carriage return
# Remove tabs
text = text.replace(u" \u00a0", " ").replace(u"\u00a0", " ").replace("\r", "").replace("\t", "")
# Replace the sequence <hyphen minus, soft hyphen, hyphen minus> with just
# hyphen minus in eg
# "Half-\u00ad\u2010Red\t\r \u00a0Dragon\t\r \u00a0Veteran\t\r \u00a0",
# "Saber-\u00ad\u2010Toothed\t\r \xa0Tiger\t\r \xa0'
# Those render as single hyphen on the document's body but show as three
# hyphens on the toc and in HTML (not clear this is a bug in PyMuPDF not
# supporting tocs with those or SumatraPDF not showing those properly in the
# toc)
text = text.replace(u"-\u00ad\u2010", "-")
if (not strictly_necessary):
text = text.replace(u"\u2019","'")
# Left/right double quotation
text = text.replace(u"\u201c", '"').replace(u"\u201d", '"')
# Non breaking hyphen
text = text.replace(u"\u2011", "-")
text = text.replace(u"\u2212", "-")
# bullet
text = text.replace(u"\u2022", "-")
# m-dash
text = text.replace(u"\u2014", "-")
# Strip trailing chars left when removing non-break space at the end of
# line
text = text.strip()
return text
def generate_html_from_template(templatepath, data, filepath):
"""
Small template engine with
- single-pass parsing
- loops
- conditionals
- control flow nesting (conditionals, loops, mixed)
- struct-like expressions
<!--$ expr --> If expr is an iterator over a dict, return the value
<!--$ #expr --> If expr is an iterator over a dict, return the key
<!--$ %expr --> If expr is not an aggregate (list, dict) return None, otherwise return len(expr)
where expr can be a nested dict dereferencing expression eg, name.key1.key2.key3
<!--$ name.key1.key2 -> Equivalent to name[key1][key2] in python
<!--$ if lhs op rhs --> where
op one of ==, !=, <,<=,>,>?, startswith
lhs is expr
rhs is one of expr, number or string literal inside double quotation marks
<!--$ else -->
<!--$ endif -->
<!--$ for it:expr --> where
expr is a list or a dict
it can be used in the loop body to access the iterator value
#it can be used in the loop body the iterator key/index
<!--$ endfor -->
"""
def deref(s, locals):
if (s.startswith("#")):
quantifier = "#"
s = s[1:]
elif (s.startswith("%")):
quantifier = "%"
s = s[1:]
else:
quantifier = None
names = s.split(".")
ret = None
for local in reversed(locals):
if (names[0] not in local):
continue
ret = local
for name in names:
ret = ret.get(name, None)
if (ret is None):
break
elif (isinstance(ret, tuple) and (name is names[-1]) and (quantifier is None)):
# Return the item of iteritems
ret = ret[1]
break
if ((ret is not None) and (quantifier is not None)):
assert quantifier in ["#", "%"]
if (quantifier == "#"):
# Return the key of iteritems
ret = ret[0]
elif (quantifier == "%"):
if (isinstance(ret, tuple)):
# If it's an iteritems, return the number of elements of
# the item, but return None for eg strings
if (isinstance(ret[1], (list, dict))):
ret = len(ret[1])
else:
ret = None
else:
ret = len(ret)
return ret
def output(f, o, do_html_escaping=False):
# Both strings and numbers come through here, make sure they are strings
# as needed by functions below
s = unicode(o)
# XXX The template is producing one empty line due to the indentation of
# a directive that disables the output. If multiple of such
# directives follow each other, you can have gaps in the produced
# HTML
# Ideally those should be removed, but can't tell the difference
# between that kind of indentation and the separation necessary for
# layout between directives and html (ie can't remove the carriage
# return or space between a directive and text in the html or
# between directives).
# Another option is to collapse all whitespace into a single one but
# it's more trouble than it's worth
if (do_html_escaping):
s = escape_html(s)
# Assume output is utf-8
f.write(s)
with io.open(templatepath, "r", encoding="utf-8") as f:
template = f.read()
with io.open(filepath, "w", encoding="utf-8") as f:
# stack of scopes, first element is the fields of the data variable
# passed in, later elements store the loop iterator and loop information
# of different loop nesting levels
locals = [{ key: value for key, value in data.iteritems() }]
# Add a few beautified versions of existing fields
if ("xp" in locals[0]):
xp = unicode(locals[0]["xp"])[::-1]
locals[0]["xp"] = string.join([xp[i*3:i*3+3] for i in xrange((len(xp) + 2) / 3)], ",")[::-1]
if ("cr" in locals[0]):
cr = locals[0]["cr"]
locals[0]["cr"] = "1/%d" % int(1 / cr) if (0 < cr < 1) else int(cr)
locals[-1]["header"] = {
"author": os.path.basename(sys.argv[0]),
"date": time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime())
}
start = 0
t = template
# Counters for the current level and the last enabled level. This allows
# keeping track of whether output should be ignored because of
# traversing the false branch of an if/else. This is also used in order
# to ignore the output on the first iteration of a for loop over an
# empty list.
# A level is essentially the number of nested ifs at a given point in
# the execution of the template:
# - The current level is incremented on every if and decremented on
# every endif
# - The enabled level is incremented if:
# - an if is found and the current level is enabled and the if
# condition is true
# - an else is found and the if condition was false, this can be found
# because the delta between the current level and the last enabled
# level is 1 (ie the level was enabled before executing the if and
# This works for as many nesting levels as the range of Python numbers
# XXX Note this counter scheme doesn't support "elif" because when an
# "elif" is found, in the general case it cannot tell if there was a
# previous if/elif condition at this enable level whose condition
# was true (and the information needs to be preserved when nesting
# levels). In order to support elif:
# - a stack scheme could be used (so the information is preserved
# when nesting)
# - The number of elifs in a given level could be limited to N, so
# the counter would be incremented by N instead of 1 and, if the
# last enabled level is less than a distance of from the current,
# it means that there was an if/elif enabled in this if/elif/else
# block (essentially the current method is this method with N=1 or
# a single "elif" ie an else)
last_enabled_level = 0
current_level = 0
r = re.compile(r"""
<!--\$
\s*
(
# returns keys if iterating over a dict, index otherwise
# access the key/index with "#name", access the value with
# just "name"
(?P<for>for)\s+(?P<item>\w+)\s*:\s*(?P<list>\w+(\.\w+)?)
|
endfor
|
# No operation is equivalent to left_reference != None
(?P<if>if)\s+
(?P<left_reference>[#%]?\w+(\.\w+)*)
(\s*
(?P<operation>==|!=|<=|>=|<|>|startswith)\s*
(
(?P<right_string>\"[^"]*\")|
(?P<right_number>(\d+(\.\d+))*)|
(?P<right_reference>[#%]?\w+(\.\w+)*)
)
)?
|
else
|
endif
|
# name, name.field1.field2, #name (key), %name (length)
([#%]?\w+(\.\w+)*)
)
\s*
-->
""", re.VERBOSE)
while (True):
m = r.search(t)
if (m is None):
break
# Write whatever non-matching template text
if (last_enabled_level == current_level):
output(f, t[:m.start()])
# Skip over matched text
start += m.end()
if (m.group("for") is not None):
# Since it's a single pass parser, there's no way to jump to the
# end of a for loop if there are no elements in the list, create
# an enable level so lines can be ignored as they are read
current_level += 1
last_enabled_level += 1
if (last_enabled_level == current_level):
list_name = m.group("list")
l = deref(list_name, locals)
if (len(l) == 0):
last_enabled_level -= 1
else:
iterator_name = m.group("item")
iterator = l.iteritems()
# Note start has already been incremented by m.end()
# Isolate variables in this scope from the current scope
locals.append({})
for_info = { "start": start, "frame" : locals[-1], "iterator": iterator, "iterator_name": iterator_name }
locals[-1][iterator_name] = next(iterator)
# Using "for" to store the loop information is safe wrt
# variable name collisions since it could be regarded as a
# reserved word
locals[-1]["for"] = for_info
elif (m.group(1) == "endfor"):
if (last_enabled_level == current_level):
# Increment the iterator, jump to start of loop
for_info = deref("for", locals)
iterator_name = for_info["iterator_name"]
iterator_value = next(for_info["iterator"], None)
if (iterator_value is not None):
# Loop to the first instruction of the loop
for_info["frame"][iterator_name] = iterator_value
start = for_info["start"]
else:
# Done with the loop, undo scope and enable level
locals.pop()
last_enabled_level -= 1
current_level -= 1
elif (m.group("if") is not None):
# Don't deref if not enabled
enabled = (last_enabled_level == current_level)
current_level += 1
if (enabled):
left_reference = m.group("left_reference")
operation = m.group("operation")
left_value = deref(left_reference, locals)
if (operation is None):
condition = (left_value is not None)
else:
right_reference = m.group("right_reference")
right_number = m.group("right_number")
right_string = m.group("right_string")
if (right_reference is not None):
right_value = deref(right_value, locals)
elif (right_number is not None):
right_value = float(right_number)
elif (right_string is not None):
right_value = right_string[1:-1]
if (operation == "=="):
condition = (left_value == right_value)
elif (operation == "!="):
condition = (left_value != right_value)
elif (operation == ">"):
condition = (left_value > right_value)
elif (operation == "<"):
condition = (left_value < right_value)
elif (operation == ">="):
condition = (left_value >= right_value)
elif (operation == "<="):
condition = (left_value <= right_value)
elif (operation == "startswith"):
condition = left_value.startswith(right_value)
if (condition):
last_enabled_level += 1
elif (m.group(1) == "else"):
assert current_level > 0, "else without if"
if ((current_level - last_enabled_level) == 1):
last_enabled_level = current_level
elif (current_level == last_enabled_level):
last_enabled_level -= 1
elif (m.group(1) == "endif"):
assert current_level > 0, "endif without if"
current_level -= 1
last_enabled_level = min(current_level, last_enabled_level)
else:
# Output expression
if (last_enabled_level == current_level):
output(f, deref(m.group(1), locals), True)
# Refresh the template substring after processing in case start was
# updated eg by for loop
t = template[start:]
output(f, t)
def create_span_tokenizer(pages):
state = {}
state["next_token"] = next_span
state["pages"] = pages
state["page_index"] = state["block_index"] = state["line_index"] = state["span_index"] = 0
d = pages[0].getText("dict")
state["blocks"] = d["blocks"]
return state
def create_parser(tokenizer, grammar_filepath, process_token):
state = {}
# Tokenizing state
state["tokenizer"] = tokenizer
state["token"] = tokenizer["next_token"](tokenizer)
# Parsing state
state["process_token"] = process_token
prods = load_grammar(grammar_filepath)
state["prods"] = prods
# User data for process_token
state["data"] = { }
return state
def load_grammar(filepath):
"""
Grammar
# comment
prod :
| subrule10 subrule11
| subrule20 subrule21
| { text == "string1" }
| { text == "string2" }*
quantifiers: * + ?
terminal symbols: { conditions } or {} (matches any)
conditions: field == "string" or field == 1.0
operations: == != > < >= <= startswith endswith
Tips
- Do lists using the one or none quantifier "?"
list:
| item list?
- Since there's no tail recursion optimization / flattening, having lists
with thousands of may cause stack overflow since every new element is a
nested function call
- If two rules in the same production intersect, put the specific rule first
and the generic rule second (placing the specific second will cause to
never hit)
prod:
| { text == "abcdefgh" }
| { text startswith "abc" }
| {}
"abcdefgh" will trigger the first rule, while "abcdefghi" and "abcdefg" will
both trigger the second rule, "ab" will trigger the third
"""
prods = {}
with open(filepath, "r") as f:
def readline(f):
while (True):
l = f.readline()
ll = l.strip()
if ((l == "") or ((ll != "") and (not ll.startswith("#")))):
break
##print "empty", repr(ll)
##print "readline", repr(l)
return l, ll
l, ll = readline(f)
while (l != ""):
prod_name = ll
##print "read prod", repr(prod_name)
assert not prod_name.startswith("|")
assert prod_name.endswith(":")
prod_name = prod_name[:-1].strip()
assert prod_name not in prods, "Duplicated production name " + prod_name
l, ll = readline(f)
rule = None
rules = []
prods[prod_name] = rules
assert ll.startswith("|")
while (True):
if ((l == "") or (ll.endswith(":"))):
##print "read rule", rule
break
if (ll.startswith("|")):
if (rule is not None):
##print "read rule", rule
pass
rule = {}
rule["raw"] = ll[1:]
rules.append(rule)
else:
rule["raw"] += " " + ll
l, ll = readline(f)
for rule in rules:
##print "parsing rule" , rule
subrules = []
rule["subrules"] = subrules
# XXX Needs proper quotation mark, colon and brace escaping
# (replace all those with the unicode-escaping, xml or
# such?)
prev_subrule_end = 0
for m in re.finditer(r"""
(
\s*
(
({(?P<conditions>[^}]*)})|
(?P<prod>\w+)
)(?P<quant>\d+(-\d+)?|[*+?])?
)
""", rule["raw"], re.VERBOSE):
# Make sure there are no skips due to finditer skipping over
# an unmatched subrule
assert m.start() == prev_subrule_end, "Invalid subrule " + repr(rule["raw"][prev_subrule_end:m.start()])
prev_subrule_end = m.end()
subrule = {}
##print "parsing subrule", m.groupdict()
subrule["prod"] = m.group("prod")
# quant can be *+? or \d+ or \d+-\d+
quant = m.group("quant")
i = parse_int(quant)
# XXX Missing supporting ranges
if (i is not None):
quant = i
subrule["quant"] = quant
subrule["conditions"] = None
if (m.group("conditions") is not None):
conditions = []
# XXX Also allow value first and field second?
# XXX Allow operations between conditions
# XXX Allow parenthesis
# XXX Allow escaped double quotes
# XXX Allow bitwise & operation for flags
prev_condition_end = 0
all_conditions = m.group("conditions")
for m in re.finditer(r"""
\s*
(?P<field>\w+)
\s*
(?P<op>startswith|endswith|notendswith|==|!=|>|<|<=|>=)
\s*
(?P<value>"[^"]*"|[+-]?\d+(\.\d+)?)
\s*
""", all_conditions, re.VERBOSE):
# Make sure there are no skips due to finditer
# skipping over an unmatched condition
assert m.start() == prev_condition_end, "Invalid condition " + repr(all_conditions[prev_condition_end:m.start()])
prev_condition_end = m.end()
condition = m.groupdict()
value = condition["value"]
if (value.startswith('"')):
value = value[1:-1]
condition["value"] = unicode(value, "unicode-escape")
else:
condition["value"] = float(value)
conditions.append(condition)
assert prev_condition_end == len(all_conditions), "Invalid condition " + repr(all_conditions[prev_condition_end:])
subrule["conditions"] = conditions
##print "parsed subrule", subrule
subrules.append(subrule)
assert prev_subrule_end == len(rule["raw"]), "Invalid subrule " + repr(rule["raw"][prev_subrule_end:])
##print "parsed rule", rule
# Perform some sanity checks
for prod in prods.values():
##print "prod", prod
for rule in prod:
##print "rule", rule
for subrule in rule["subrules"]:
p = subrule.get("prod")
assert p is None or (p == "lambda") or p in prods, "Prod %s not in prods" % p
return prods
def next_span(state):
"""
Tokenizer frontend for the pdf's getText function, returns the next
available span in the document or None if no more available.
Takes care of moving to the next line, block or page to get to the next
span, skipping any "whitespace"
"""
pages = state["pages"]
page_index = state["page_index"]
page = pages[page_index]
block_index = state["block_index"]
line_index = state["line_index"]
span_index = state["span_index"]
skip_next_spans = 0
while (True):
# Consume whitespace spans and return the first nonwhitespace
# .blocks [ .lines [ .spans [ { .color, .text, .font, .size } ] ] ]
blocks = state["blocks"]
block = blocks[block_index]
lines = block["lines"]
line = lines[line_index]
spans = line["spans"]
if (span_index >= len(spans)):
span_index = 0
line_index += 1
if (line_index >= len(lines)):
line_index = 0
block_index += 1
if (block_index >= len(blocks)):
block_index = 0
page_index += 1
if (page_index >= len(pages)):
span = None
break
page = pages[page_index]
d = page.getText("dict")
state["blocks"] = d["blocks"]
state["page_index"] = page_index
state["block_index"] = block_index
state["line_index"] = line_index
span = state["blocks"][block_index]["lines"][line_index]["spans"][span_index]
if (span["text"] == u"System\t\r \u00a0Reference\t\r \u00a0Document\t\r \u00a05.1\t\r \u00a0"):
# Skip footer and page number, note the footer is one line and the
# page number and some whitespace in another, it's easier to skip
# the next two spans than fiddling with the indices here that can
# cause out of index access because it's at the end of the block for
# this page
# "color": 0, "flags": 4, "font": "LUFRKP+Calibri", "size": 10.800000190734863, "text": "System\t\r \u00a0Reference\t\r \u00a0Document\t\r \u00a05.1\t\r \u00a0"
# "color": 0, "flags": 20, "font": "DXJJCX+GillSans-SemiBold", "size": 10.800000190734863, "text": "3"
# "color": 0, "flags": 4, "font": "LUFRKP+Calibri", "size": 10.800000190734863, "text": "\t\r \u00a0"
skip_next_spans = 2
span_index += 1
continue
if (skip_next_spans > 0):
skip_next_spans -= 1
span_index += 1
continue
# Sometimes there's empty text like
# "font": "WWROEK+Calibri-Bold", "size": 9.84000015258789, "text": "\t\r \u00a0"
# ignore
if (span["text"].strip() == ""):
span_index += 1
continue
# Somne have garbage spaces or dot
# But keep it for Kraken, Mummy and Unicorn since they need the comma separator
# have garbage text with this font after the
# size, ignore
if ((span["font"] == "XPUSJH+ScalaSansOffc-BoldIta") and (span["text"] != ", ")):
span_index += 1
continue
# Place text in raw, cleanup the text in text
span["raw"] = span["text"]
span["text"] = cleanup_text(span["text"])
span["page"] = page_index + 1
span_index += 1
state["span_index"] = span_index
break
##print "next_span", repr(span)
return span
def token_matches(token, conditions):
if (token is None):
return False
match = True
for condition in conditions:
field, op, value = condition["field"], condition["op"], condition["value"]
token_value = token[field]
if (op == "=="):
match = match and (token_value == value)
elif (op == "!="):
match = match and (token_value != value)
elif (op == ">="):
match = match and (token_value >= value)
elif (op == ">"):
match = match and (token_value > value)
elif (op == "<="):
match = match and (token_value <= value)
elif (op == "<"):
match = match and (token_value < value)
elif (op == "startswith"):
match = match and (token_value.startswith(value))
elif (op == "endswith"):
match = match and (token_value.endswith(value))
elif (op == "notendswith"):
match = match and (not token_value.endswith(value))
# XXX Missing some inter condition operation (and, or, parenthesis)
# XXX Missing "not" unary operator so things like not endswith can
# be done
if (not match):
break
return match
def parse(state, prod_name):
"""
Given the grammar and the tokenizer, performs recursive descent parsing
"""
prods = state["prods"]
process_token = state["process_token"]
next_token = state["tokenizer"]["next_token"]
prod = prods[prod_name]
rules = prod
accepted = False
for rule in rules:
subrules = rule["subrules"]
for subrule in subrules:
new_prod_name = subrule.get("prod", None)
quant = subrule.get("quant", None)
accepted = True
accept_number = 0
while (accepted):
token = state["token"]
if (new_prod_name is None):
# Terminal symbol, try to match against token
conditions = subrule.get("conditions", None)
# Field None means {} which matches anything
match = token_matches(token, conditions)
accepted = ((token is not None) and match)
if ((token is not None) and (len(conditions) > 0) and match):
##print "real match", prod_name
process_token(prod_name, token, state["data"])
if (accepted):
state["token"] = next_token(state["tokenizer"])
accept_number += 1
elif (new_prod_name == 'lambda'):
# Accept with no token consumption, this is equivalent to
# using the "?" quantifier plus some non-accepting state, eg
# "{text != text}?"
# XXX Remove since it's redundant with the ? quantifier? but
# there's no trivial way of expressing a universal