-
Notifications
You must be signed in to change notification settings - Fork 6
/
build.py
99 lines (79 loc) · 3.08 KB
/
build.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
# thanks: http://eosrei.net/articles/2015/11/latex-templates-python-and-jinja2-generate-pdfs
# thanks: http://flask.pocoo.org/snippets/55/
import sys
from pathlib import Path
import io
import argparse
import re
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf8')
import docutils.core
import jinja2
from markupsafe import Markup
import gwadoc
#gwadoc.set_preferred_language('en')
DIR = Path(__file__).parent.resolve()
def rst_renderer(fmt):
"""Create a function to render ReStructuredText to *fmt*."""
@jinja2.pass_eval_context
def render_rst(eval_ctx, s):
s = docutils.core.publish_parts(str(s), writer_name=fmt)['body']
s = s.strip()
# remove (hopefully) unnecessary <p>...</p>
if s[:3] == '<p>' and s[-4:] == '</p>':
s = s[3:-4]
# replace ILIURL with the actual URL
s = s.replace('ILIURL', 'https://lr.soh.ntu.edu.sg/omw/omw/concepts/ili')
# make sure Jinja2 doesn't try to escape the HTML markup
if eval_ctx.autoescape:
s = Markup(s)
return s
return render_rst
def build(args):
gwadoc.set_preferred_language(args.lang)
loader = jinja2.FileSystemLoader(DIR / 'templates')
if args.format == 'html':
env = jinja2.Environment(
loader=loader,
autoescape=jinja2.select_autoescape(['html', 'xml']))
env.filters['render_rst'] = rst_renderer('html')
template = env.get_template(f'{args.object}.{args.format}')
elif args.format == 'latex':
LATEX_SUBS = (
(re.compile(r'\\'), r'\\textbackslash'),
(re.compile(r'([{}_#%&$])'), r'\\\1'),
(re.compile(r'~'), r'\~{}'),
(re.compile(r'\^'), r'\^{}'),
(re.compile(r'"'), r"''"),
(re.compile(r'\.\.\.+'), r'\\ldots'),
)
def escape_tex(value):
newval = value
for pattern, replacement in LATEX_SUBS:
newval = pattern.sub(replacement, newval)
return newval
env = jinja2.Environment(
block_start_string=r'\BLOCK{',
block_end_string='}',
variable_start_string=r'\VAR{',
variable_end_string='}',
comment_start_string=r'\%{',
comment_end_string=r'}',
line_statement_prefix=r'\STMT',
line_comment_prefix=r'\CMNT',
trim_blocks=True,
autoescape=False,
loader=loader)
env.filters['render_rst'] = rst_renderer
env.filters['escape_tex'] = escape_tex
template = env.get_template('index.tex')
else:
raise ValueError('invalid format: {}'.format(args.format))
print(template.render(gwadoc=gwadoc,
lang=args.lang))
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('format', choices=('html', 'latex'), default='html')
parser.add_argument('--object', choices=('index', 'summary'), default='index')
parser.add_argument("--lang", help="language to make the docs in", default="en")
args = parser.parse_args()
build(args)