-
Notifications
You must be signed in to change notification settings - Fork 3
/
__main__.py
212 lines (179 loc) · 8.55 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
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
from collections import namedtuple
from csv import DictWriter
from csv import excel_tab
from glob import glob
from itertools import product
from os import getenv
from os import makedirs
from os.path import isfile
from os.path import join
from sys import stderr
from sys import stdout
from benchmarks.compression import get_all as compressors
from benchmarks.encryption import get_all as encryptors
from benchmarks.serialization import get_all as serializers
from benchmarks.utils import Timer
from benchmarks.utils import download_sample_emails
from benchmarks.utils import filesize_kb
from benchmarks.utils import load_sample_email
from benchmarks.utils import pretty_extension
from benchmarks.utils import remove_if_exists
Benchmark = namedtuple('Benchmark', (
'Compressor',
'Serializer',
'Encryptor',
'FilesizeKb',
'WriteTimeSeconds',
'ReadTimeSeconds',
))
class BenchmarkError:
def __init__(self, ex):
self.ex = ex
def __str__(self):
return 'ERROR'
def load_samples(zip_url, inputs_dir, exclude_attachments):
download_sample_emails(zip_url, inputs_dir)
sample_emails = []
for path in glob(join(inputs_dir, '*')):
sample_email = load_sample_email(path)
if exclude_attachments:
sample_email.pop('attachments', None)
sample_emails.append(sample_email)
return sample_emails
def print_progress(compressor, serializer, encryptor, i, total):
print('Running {}+{}+{} ({}/{})'.format(
pretty_extension(compressor.extension),
pretty_extension(serializer.extension),
pretty_extension(encryptor.extension),
i + 1,
total,
), file=stderr)
def print_error(stage, compressor, serializer, encryptor, ex):
print('Error during {}-phase in {}+{}+{}: {}'.format(
stage,
pretty_extension(compressor.extension),
pretty_extension(serializer.extension),
pretty_extension(encryptor.extension),
ex,
), file=stderr)
def run_benchmarks(emails, results_dir, incremental):
makedirs(results_dir, exist_ok=True)
jobs = list(product(compressors(), serializers(), encryptors()))
num_jobs = len(jobs)
for i, (compressor, serializer, encryptor) in enumerate(jobs):
outpath = join(results_dir, 'emails{}{}{}'.format(
serializer.extension, compressor.extension, encryptor.extension))
if incremental and isfile(outpath):
continue
print_progress(compressor, serializer, encryptor, i, num_jobs)
try:
with Timer.timeit() as write_timer:
with open(outpath, 'wb') as raw:
with encryptor.encrypt(raw) as enc:
with compressor.compress(enc) as comp:
serializer.serialize(iter(emails), comp)
except Exception as ex:
print_error('write', compressor, serializer, encryptor, ex)
write_time = BenchmarkError(ex)
filesize = BenchmarkError(ex)
else:
write_time = write_timer.seconds()
filesize = '{:.2f}'.format(filesize_kb(outpath))
try:
with Timer.timeit() as read_timer:
with open(outpath, 'rb') as raw:
with encryptor.deserialize(raw) as denc:
with compressor.decompress(denc) as decomp:
actuals = serializer.deserialize(decomp)
for i, (actual, expected) in enumerate(zip(actuals, emails)):
for key in actual.keys() | expected.keys():
actual_value = actual.get(key)
expected_value = expected.get(key)
assert \
(actual_value == expected_value) or \
(not actual_value and not expected_value), \
'i={},key={},actual={},expected={}'.format(
i, key, actual_value, expected_value)
except Exception as ex:
print_error('read', compressor, serializer, encryptor, ex)
read_time = BenchmarkError(ex)
else:
read_time = read_timer.seconds()
yield Benchmark(
Compressor=pretty_extension(compressor.extension),
Serializer=pretty_extension(serializer.extension),
Encryptor=pretty_extension(encryptor.extension),
FilesizeKb=filesize,
WriteTimeSeconds=write_time,
ReadTimeSeconds=read_time,
)
if not incremental:
remove_if_exists(outpath)
def display_benchmarks(results, display_format, buffer=stdout):
if display_format == 'csv':
writer = DictWriter(buffer, Benchmark._fields, dialect=excel_tab)
writer.writeheader()
for result in results:
writer.writerow(result._asdict())
elif display_format == 'html':
buffer.write('<!doctype html>\n')
buffer.write('<html>\n')
buffer.write(' <head>\n')
buffer.write(' <meta charset="utf-8">\n')
buffer.write(' <meta name="viewport" content="width=device-width, initial-scale=1">\n') # noqa: E501
buffer.write(' <title>Ascoderu compression benchmark results</title>\n') # noqa: E501
buffer.write(' <link rel="stylesheet" href="https://unpkg.com/[email protected]/build/base-min.css">\n') # noqa: E501
buffer.write(' <link rel="stylesheet" href="https://unpkg.com/[email protected]/build/pure-min.css">\n') # noqa: E501
buffer.write(' <link rel="stylesheet" href="https://unpkg.com/[email protected]/tablesort.css">\n') # noqa: E501
buffer.write(' <style>\n')
buffer.write(' td { text-align: center; }\n')
buffer.write(' table { margin-bottom: 1em; }\n')
buffer.write(' .error { color: #FF4136; }\n')
buffer.write(' </style>\n')
buffer.write(' </head>\n')
buffer.write(' <body>\n')
buffer.write(' <table id="benchmarks" class="pure-table pure-table-horizontal pure-table-striped">\n') # noqa: E501
buffer.write(' <thead>\n')
buffer.write(' <tr>\n')
for field in Benchmark._fields:
buffer.write(' <th>{}</th>\n'.format(field))
buffer.write(' </tr>\n')
buffer.write(' </thead>\n')
buffer.write(' <tbody>\n')
for result in results:
buffer.write(' <tr>\n')
for value in result:
tdclass = ''
if isinstance(value, BenchmarkError):
tdclass = ' class="error" title="{}" data-sort="999999999"'.format(value.ex) # noqa: E501
buffer.write(' <td{}>{}</td>\n'.format(tdclass, value))
buffer.write(' </tr>\n')
buffer.write(' </tbody>\n')
buffer.write(' </table>\n')
buffer.write(' <script src="https://unpkg.com/[email protected]/dist/tablesort.min.js"></script>\n') # noqa: E501
buffer.write(' <script src="https://unpkg.com/[email protected]/dist/sorts/tablesort.number.min.js"></script>\n') # noqa: E501
buffer.write(' <script>new Tablesort(document.getElementById("benchmarks"))</script>\n') # noqa: E501
if getenv('GITHUB_SHA') and getenv('GITHUB_REPOSITORY'):
buffer.write(' <a class="pure-button" href="https://github.com/{}/tree/{}">View code</a>\n'.format(getenv('GITHUB_REPOSITORY'), getenv('GITHUB_SHA'))) # noqa: E501
if getenv('GITHUB_RUN_ID') and getenv('GITHUB_REPOSITORY'):
buffer.write(' <a class="pure-button" href="https://github.com/{}/actions/runs/{}">View build</a>\n'.format(getenv('GITHUB_REPOSITORY'), getenv('GITHUB_RUN_ID'))) # noqa: E501
buffer.write(' </body>\n')
buffer.write('</html>\n')
else:
raise NotImplementedError(display_format)
def cli():
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument('emails_zip_url')
parser.add_argument('--results_dir', default='results')
parser.add_argument('--inputs_dir', default='sample-emails')
parser.add_argument('--exclude_attachments', action='store_true')
parser.add_argument('--incremental', action='store_true')
parser.add_argument('--display_format', default='csv')
args = parser.parse_args()
emails = load_samples(args.emails_zip_url, args.inputs_dir,
args.exclude_attachments)
results = run_benchmarks(emails, args.results_dir, args.incremental)
display_benchmarks(results, args.display_format)
if __name__ == '__main__':
cli()