-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
165 lines (134 loc) · 6.73 KB
/
main.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
import re, os, sys, shutil, subprocess
import problemparser, colors
import traceback
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--upload', '-u', help = 'upload to /trains', action = 'store_true')
args = parser.parse_args()
def verify_structure(script_path):
if not os.path.isdir(os.path.join(script_path, 'temp')):
os.mkdir(os.path.join(script_path, 'temp'))
if not os.path.isdir(os.path.join(script_path, 'temp', 'problems')):
os.mkdir(os.path.join(script_path, 'temp', 'problems'))
for file in ['statement.tex', 'colors.tex', 'olymp.sty']:
if not os.path.isfile(os.path.join(script_path, 'src', file)):
raise FileNotFoundError('No file called {} in {}.'.format(
file, os.path.join(script_path, 'src')))
def get_contest_name_and_date():
contest_cfg = os.path.join(os.getcwd(), 'contest.cfg')
if not os.path.isfile(contest_cfg):
raise FileNotFoundError("There's no contest.cfg in {}.".format(os.getcwd()))
date = '.'.join(re.findall('(\d{2})', re.split(r'[\\\/]', os.getcwd())[-1])[:3][::-1])
with open(contest_cfg, 'r', encoding = '866') as f:
for line in map(lambda x: x.strip(), f):
if line.startswith('#'):
continue
regex_result = re.findall('^ContestName\s*:=\s*(.*)$', line.split('#')[0])
if regex_result:
return regex_result[0].strip(), date
raise NameError("Unable to locate contest name in {}.".format(contest_cfg))
def get_problemset():
problemset_cfg = os.path.join(os.getcwd(), 'problemset.cfg')
if not os.path.isfile(problemset_cfg):
raise FileNotFoundError("There's no problemset.cfg in {}.".format(os.getcwd()))
problemset = []
section = colors.Section.default_section()
with open(problemset_cfg, 'r', encoding = '866') as f:
for line in map(lambda x: x.strip(), f):
if colors.Section.is_section(line):
section = colors.Section(line)
problem_type = problemparser.ProblemType.get_problem_type(line)
if problem_type is None:
continue
problemset.append(problemparser.ProblemParser.create(line, problem_type, section))
return problemset
def create_contest_info(script_path):
contest_info = os.path.join(script_path, 'temp', 'contest_info.tex')
with open(contest_info, 'w', encoding = 'utf8') as w:
contest_name, contest_date = get_contest_name_and_date()
print('\def\\ID{{}}', file = w)
print('\def\\NAME{{{}}}%'.format(contest_name), file = w)
print('\def\\WHERE{Санкт-Петербургский Государственный Университет}%', file = w)
print('\def\\DATE{{{}}}%'.format(contest_date), file = w)
def alter_graphics(id, file_path):
def replacer(match):
# We don't support pictures that are generated on the fly.
pic = os.path.join(os.path.split(file_path)[0], match.group(2))
if not any(match.group(2).endswith(x) for x in ['.jpg', '.jpeg', '.png']) \
and not any(os.path.isfile(pic + x) for x in ['.jpg', '.jpeg', '.png']):
return ''
# <1>{<2>}
return '{}{{{}}}'.format(
match.group(1),
# os.path.join produces backslashes (\) which are incorrectly treated by pdflatex.
# So we force forward slashes (/) here.
'./problems/{}/{}'.format(id, os.path.split(match.group(2))[1])
)
with open(file_path, 'r', encoding = 'utf8') as f:
data = f.read()
with open(file_path, 'w', encoding = 'utf8') as w:
print(re.sub(r'(\\includegraphics.*?){\s*(.+?)\s*}', replacer, data), file = w)
def create_problemset_info(script_path):
colors.Section.init_palette(script_path)
problemset_info = os.path.join(script_path, 'temp', 'problemset_info.tex')
with open(problemset_info, 'w', encoding = 'utf8') as w:
problemset = get_problemset()
if not problemset:
raise AssertionError('No problems found?')
print(problemset[0].section().latex(), file = w)
print(problemset[0].latex(), file = w)
for i in range(1, len(problemset)):
if problemset[i - 1].section() != problemset[i].section():
print(problemset[i].section().latex(), file = w)
print(problemset[i].latex(), file = w)
for problem in problemset:
dest_folder = os.path.join(script_path, 'temp', 'problems', problem.id())
os.mkdir(dest_folder)
dest_statement = os.path.join(dest_folder, '{}.tex'.format(problem.name()))
shutil.copy(problem.statements(), dest_statement)
for picture in problem.graphics():
shutil.copy(picture, os.path.join(dest_folder, os.path.split(picture)[1]))
alter_graphics(problem.id(), dest_statement)
def copy_sources(script_path):
for file in ['statement.tex', 'colors.tex', 'olymp.sty']:
shutil.copy(os.path.join(script_path, 'src', file),
os.path.join(script_path, 'temp', file))
def create_pdf(script_path):
source_dir = os.path.join(script_path, 'temp')
subprocess.run("cd {} && echo 'X' | pdflatex statement.tex > nul".format(source_dir),
shell = True)
subprocess.run("cd {} && echo 'X' | pdflatex statement.tex | grep 'Output written'".format(source_dir),
shell = True)
if not os.path.isfile(os.path.join(script_path, 'temp', 'statement.pdf')):
shutil.move(os.path.join(script_path, 'temp', 'statement.log'),
os.path.join(os.getcwd(), 'statement.log'))
raise FileNotFoundError('Unable to create statement.pdf from sources.')
shutil.move(os.path.join(script_path, 'temp', 'statement.pdf'),
os.path.join(os.getcwd(), 'statement.pdf'))
def clear_temp(script_path):
temp_dir = os.path.join(script_path, 'temp')
shutil.rmtree(temp_dir)
def upload_pdf():
pdf_src = os.path.join(os.getcwd(), 'statement.pdf')
date = re.split(r'[\\\/]', os.getcwd())[-1]
pdf_target = '/var/www/acm/trains/{}.pdf'.format(date)
print('Uploading {} to {}'.format(pdf_src, pdf_target), file = sys.stderr)
subprocess.run('pscp -P 220 {} {}@acm.math.spbu.ru:{}'.format(
pdf_src, os.getlogin(), pdf_target
), shell = True)
def main():
script_path = os.path.dirname(os.path.realpath(sys.argv[0]))
try:
verify_structure(script_path)
copy_sources(script_path)
create_contest_info(script_path)
create_problemset_info(script_path)
create_pdf(script_path)
if args.upload:
upload_pdf()
except Exception as e:
traceback.print_exc()
finally:
clear_temp(script_path)
if __name__ == '__main__':
main()