-
Notifications
You must be signed in to change notification settings - Fork 2
/
pretalx2tex.py
executable file
·176 lines (157 loc) · 5.71 KB
/
pretalx2tex.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
#! /usr/bin/env python3
import argparse
import datetime
import html
import jinja2
import json
import os
import re
import sys
import textwrap
latex_substitutions = [
(re.compile("([a-z])\*(innen|r|n)"), "\\1(\\2)"),
(re.compile("„"), "\""),
(re.compile("“"), "\""),
(re.compile(r'\\'), r'\\textbackslash'),
(re.compile(r'([{}_#%&$])'), r'\\\1'),
(re.compile(r'~'), r'\~{}'),
(re.compile(r'\^'), r'\^{}'),
(re.compile(r' "'), " \"`"),
(re.compile(r'"([ .,;:])'), "\"'\\1"),
(re.compile(r'^"'), "\"`"),
(re.compile(r'"$'), "\"'"),
(re.compile("([^ ]) (–|-) "), "\\1~-- ")
]
commands = {
"HS Rundbau": {
"name": "HS Rundbau",
"command": "\\abstractHSRundbau"
},
"HS Anatomie": {
"name": "Z211",
"command": "\\abstractHSAnatomie"
},
"HS Weismannhaus": {
"name": "Z254",
"command": "\\abstractWeismannhaus"
},
"Mensa": {
"name": "Z208",
"command": "\\abstractMensa"
},
}
default_cmd = {"name": "???", "command": "\\abstractOther"}
DATE_FORMAT = "%Y-%m-%dT%H:%M:%S%z"
RE_SINGLE_NEWLINE = re.compile("[^\\n]\\n", re.MULTILINE)
RE_VALID_WORD = re.compile("^[-A-ZÄÖÜäöüa-z]{2,}$")
def datetimeformat(value, format="%H:%M"):
return value.strftime(format)
def escape_latex(source):
result = source
for pair in latex_substitutions:
result = pair[0].sub(pair[1], result)
return result
def get_wordlist(text):
words = text.replace("\r", "")
words = words.replace("\n", " ")
result = []
for word in words.split(" "):
if word is None or len(word) < 2:
continue
# remove punctuation characters at beginning and end
if word[0] in ("\"", "'", ".", ",", ";", ":", "[", "]", "(", ")", "-", "*"):
word = word[1:]
if word[-1] in ("\"", "'", ".", ",", ";", ":", "[", "]", "(", ")", "-", "*"):
word = word[:-1]
if RE_VALID_WORD.match(word) is None:
continue
result.append(word)
return result
def break_long_lines(source):
# split source by newlines to preserve them
splitted = source.replace("\r\n", "\n")
splitted = RE_SINGLE_NEWLINE.sub("\\n\\n", splitted).split("\n")
result = []
for paragraph in splitted:
if paragraph != "":
result += textwrap.wrap(paragraph, 98, break_on_hyphens=False)
else:
# empty lines
result.append("")
# add two spaces at the beginning of each line
for i in range(0, len(result)):
if result[i] != "":
result[i] = " {}".format(result[i])
result = "\n".join(result)
return result
def talk2tex(template, item, last_timeslot):
return template.render(command=commands.get(item["room"], default_cmd).get("command"), last_timeslot=last_timeslot, default_cmd=default_cmd, **item)
parser = argparse.ArgumentParser(description="convert Pretalx exports to LaTeX, output will be written to STDOUT")
parser.add_argument("-f", "--format", help="output format, either 'tex', 'txt' or 'wordlist'", type=str)
parser.add_argument("-w", "--workshops", help="workshops only", action="store_true")
parser.add_argument("-d", "--day", help="day, format: YYYY-MM-DD")
parser.add_argument("template", help="template to render")
parser.add_argument("frab_export", help="Frab-compatible JSON export of Pretalx", type=argparse.FileType("r"))
args = parser.parse_args()
# read JSON
schedule = json.load(args.frab_export)["schedule"]
talks = []
for day in schedule["conference"]["days"]:
if args.day and day["date"] != args.day:
continue
for room, sessions in day["rooms"].items():
for talk in sessions:
if args.workshops and talk["type"] != "Workshop":
continue
elif not args.workshops and talk["type"] == "Workshop":
continue
speakers = []
for person in talk["persons"]:
speakers.append(person["public_name"])
speakers = ", ".join(speakers)
abstract = break_long_lines(html.unescape(talk["abstract"]))
talks.append({
"date": datetime.datetime.strptime(talk["date"], DATE_FORMAT),
"title": talk["title"],
"room": talk["room"],
"abstract": abstract,
"speakers": speakers,
"slug": talk["slug"],
"type": talk["type"]
})
# sort talks by start, then by room
talks.sort(key=lambda t : (t["date"], t["room"]))
# load template
template_dir = os.path.abspath(os.path.dirname(args.template))
jinja2_env = jinja2.Environment(
loader=jinja2.FileSystemLoader(template_dir),
block_start_string='((%',
block_end_string='%))',
variable_start_string='(((',
variable_end_string=')))',
comment_start_string='((#',
comment_end_string='#))',
undefined=jinja2.StrictUndefined
)
jinja2_env.filters["e"] = escape_latex
jinja2_env.filters["datetimeformat"] = datetimeformat
template = jinja2_env.get_template(os.path.basename(args.template)) if args.format == "tex" else None
# render talks as LaTeX and write to file
last_timeslot = ""
wordlist = []
for t in talks:
if args.format == "txt":
out = "{} {}\n".format(t["title"], t["abstract"])
sys.stdout.write(out)
elif args.format == "tex":
out = talk2tex(template, t, last_timeslot)
sys.stdout.write(out)
elif args.format == "wordlist":
out = "{} {}\n".format(t["title"], t["abstract"])
wordlist += get_wordlist(out)
else:
raise Exception("Output format {} is not supported.".format(args.format))
last_timeslot = t["date"]
if args.format == "wordlist":
wordlist.sort()
sys.stdout.write("\n".join(wordlist))