-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathelection_observer.py
executable file
·542 lines (425 loc) · 17.7 KB
/
election_observer.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
#!/usr/bin/env python3
import csv
import lzma
import bz2
import gzip
import json
import logging
import math
import os
import sys
import time
import pygal
import scraping
logger = logging.getLogger(__name__)
class ElectionData(object):
def __init__(self, host, constituent_badges, caucus_badges):
self.host = host
if caucus_badges:
reason_html = caucus_badges[0].reason_html
else:
reason_html = constituent_badges[0].reason_html
for badge in constituent_badges:
assert reason_html == badge.reason_html
for badge in caucus_badges:
assert reason_html == badge.reason_html
self.id = int(
reason_html
.partition('/election/')[2]
.partition('"')[0])
self.constituent_badges = constituent_badges
self.caucus_badges = caucus_badges
if caucus_badges:
self.start_timestamp = self.caucus_badges[0].timestamp
else:
self.start_timestamp = self.constituent_badges[0].timestamp
if constituent_badges:
self.election_timestamp = self.constituent_badges[0].timestamp
else:
self.election_timestamp = self.caucus_badges[-1].timestamp
# We can't just look at the data, because there are some
# badges awarded later than makes sense. Hope this doesn't
# change.
self.end_timestamp = self.start_timestamp + 15 * 24 * 60 * 60
self._prepare_data()
def _prepare_data(self):
logger.info(
"Generating graphs for election {}.".format(self.id))
self.hour_duration = 60 * 60
self.election_hours = int(
1 + math.floor(self.end_timestamp - self.start_timestamp) /
self.hour_duration)
self.constituents_by_hour = [0 for _ in range(self.election_hours)]
self.first_constituent_index = len(self.constituents_by_hour)
for badge in self.constituent_badges:
index = int(math.floor(
(badge.timestamp - self.start_timestamp) /
self.hour_duration))
if index < self.first_constituent_index:
self.first_constituent_index = index
try:
self.constituents_by_hour[index] += 1
except IndexError:
logger.debug("ignoring weird {!r}".format(badge))
self.caucus_by_hour = [0 for _ in range(self.election_hours)]
for badge in self.caucus_badges:
try:
self.caucus_by_hour[
int(math.floor(
(badge.timestamp - self.start_timestamp) /
self.hour_duration))] += 1
except IndexError:
logger.debug("ignoring weird {!r}".format(badge))
def hello_graphs(self):
name = self.host + '-' + str(self.id)
filename = 'images/election-{}-both-per-hour.svg'.format(name)
logger.info("Generating {}.".format(filename))
chart = pygal.Line(
title="Election {} Participation Per Hour".format(name),
y_title="Users",
show_dots=False,
width=1024,
height=768,
range=(0, 1000),
value_formatter=lambda n: str(int(n)),
legend_at_bottom=True)
chart.add('constituents', self.constituents_by_hour)
chart.add('caucus', self.caucus_by_hour)
chart.render_to_file(filename)
logger.info("Wrote {}.".format(filename))
filename = 'images/election-{}-constituents-per-hour.svg'.format(name)
logger.info("Generating {}.".format(filename))
chart = pygal.Line(
title="Election {} Constituents Per Hour".format(name),
y_title="Users",
show_dots=False,
width=1024,
height=768,
range=(0, 1000),
value_formatter=lambda n: str(int(n)),
legend_at_bottom=True)
chart.add(
'constituents', self.constituents_by_hour[
self.first_constituent_index:])
chart.render_to_file(filename)
logger.info("Wrote {}.".format(filename))
filename = 'images/election-{}-both-cumulative.svg'.format(name)
logger.info("Generating {}.".format(filename))
chart = pygal.Line(
title="Election {} Participation".format(self.id),
y_title="Users",
show_dots=False,
width=1024,
height=768,
value_formatter=lambda n: str(int(n)),
legend_at_bottom=True)
chart.add('constituents', list(cumulative(self.constituents_by_hour)))
chart.add('caucus', list(cumulative(self.caucus_by_hour)))
chart.render_to_file(filename)
logger.info("Wrote {}.".format(filename))
def main(*args):
flags = set(args)
assert not flags - {
'-n', '--no-update', '-e', '--forever', '-m', '--no-write' }
os.makedirs('data', exist_ok=True)
os.makedirs('images', exist_ok=True)
logging.basicConfig(
level=logging.INFO,
format='\n'
' ' + '_' * 76 + '\n'
' | %(asctime)23s %(pathname)44s:%(lineno)-4s \n'
'____| %(levelname)-10s %(name)51s \n'
'\n'
'%(message)s')
so_sheriffs, write_sherrifs = get_badge_data_and_write_function(
host='stackoverflow.com', badge_id=3109, filename='sheriff')
so_constituents, write_constituents = get_badge_data_and_write_function(
host='stackoverflow.com', badge_id=1974, filename='constituent')
so_great_answers, write_great_answers = get_badge_data_and_write_function(
host='stackoverflow.com', badge_id=25, filename='great-answers')
so_caucus, write_caucus = get_badge_data_and_write_function(
host='stackoverflow.com', badge_id=1973, filename='caucus')
math_constituents, write_math_constituents = get_badge_data_and_write_function(
host='math.stackexchange.com', badge_id=208, filename='constituent')
math_caucus, write_math_caucus = get_badge_data_and_write_function(
host='math.stackexchange.com', badge_id=207, filename='caucus')
while True:
if not flags.intersection(['-n', '--no-update']):
so_sheriffs.update()
so_great_answers.update()
so_constituents.update()
so_caucus.update()
math_constituents.update()
math_caucus.update()
logger.info("Grouping constituents by election.")
constituents_by_reason = so_constituents.by_reason()
logger.info("Grouping caucuses by election.")
caucus_by_reason = so_caucus.by_reason()
elections = {}
for reason in set(caucus_by_reason.keys()) | set(constituents_by_reason.keys()):
election = ElectionData(
host='stackoverflow.com',
constituent_badges=constituents_by_reason.get(reason, []),
caucus_badges=caucus_by_reason.get(reason, []))
assert elections.get(election.id) is None
elections[election.id] = election
election.hello_graphs()
# ELECTION 5 AND 6 AND 7 CAUCUS COMPARISON
filename = 'images/election-5-6-7-cumulative-caucus.svg'
logger.info("Generating {}.".format(filename))
chart = pygal.Line(
title="Election 5 and 6 and 7 Caucus",
y_title="Users",
show_dots=False,
width=1024,
height=768,
value_formatter=lambda n: str(int(n)),
legend_at_bottom=True)
chart.add(
'5 caucus', list(cumulative(elections[5].caucus_by_hour)))
chart.add(
'6 caucus', list(cumulative(elections[6].caucus_by_hour)))
chart.add(
'7 caucus', list(cumulative(elections[7].caucus_by_hour)))
chart.render_to_file(filename)
logger.info("Wrote {}.".format(filename))
# ELECTION 5 AND 6 COMPARISON
filename = 'images/election-5-6-7-both-cumulative.svg'
logger.info("Generating {}.".format(filename))
chart = pygal.Line(
title="Election 5 and 6 and 7 Participation",
y_title="Users",
show_dots=False,
width=1024,
height=768,
value_formatter=lambda n: str(int(n)),
legend_at_bottom=True)
chart.add(
'5 constituents', list(cumulative(elections[5].constituents_by_hour)))
chart.add(
'5 caucus', list(cumulative(elections[5].caucus_by_hour)))
chart.add(
'6 constituents', list(cumulative(elections[6].constituents_by_hour)))
chart.add(
'6 caucus', list(cumulative(elections[6].caucus_by_hour)))
chart.add(
'7 constituents', list(cumulative(elections[7].constituents_by_hour)))
chart.add(
'7 caucus', list(cumulative(elections[7].caucus_by_hour)))
chart.render_to_file(filename)
logger.info("Wrote {}.".format(filename))
# ELECTION 8 AND 9 AND 10 CAUCUS COMPARISON
filename = 'images/election-8-9-10-cumulative-caucus.svg'
logger.info("Generating {}.".format(filename))
chart = pygal.Line(
title="Election 8 and 9 and 10 Caucus",
y_title="Users",
show_dots=False,
width=1024,
height=768,
value_formatter=lambda n: str(int(n)),
legend_at_bottom=True)
chart.add(
'8 caucus', list(cumulative(elections[8].caucus_by_hour)))
chart.add(
'9 caucus', list(cumulative(elections[9].caucus_by_hour)))
chart.add(
'10 caucus', list(cumulative(elections[10].caucus_by_hour)))
chart.render_to_file(filename)
logger.info("Wrote {}.".format(filename))
# constituent
# All Election Constituents
filename = 'images/elections-cumulative-all.svg'
logger.info("Generating {}.".format(filename))
chart = pygal.Line(
title="Cumulative Election Participation",
y_title="Users",
x_title="Hours",
show_dots=False,
width=1024,
height=768,
value_formatter=lambda n: str(int(n)),
legend_at_bottom=True)
hours = 0
chart.show_x_labels = True
for election_id, election in sorted(elections.items())[4:]:
hours = max([hours, len(election.caucus_by_hour), len(election.constituents_by_hour)])
chart.add(
'{} caucus'.format(election_id), list(cumulative(election.caucus_by_hour)))
chart.add(
'{} constituents'.format(election_id), list(cumulative(election.constituents_by_hour)))
chart.x_labels = [
str(hour)
for hour in range(hours)
]
chart.truncate_legend = -1
chart.truncate_label = -1
chart.x_labels_major_every = 24
chart.show_minor_x_labels = False
chart.render_to_file(filename)
logger.info("Wrote {}.".format(filename))
# Hourly Election Constituents
filename = 'images/elections-hourly-all.svg'
logger.info("Generating {}.".format(filename))
chart = pygal.Line(
title="Hourly Election Participation",
y_title="Users",
x_title="Hour",
show_dots=False,
width=1024,
height=768,
value_formatter=lambda n: str(int(n)),
legend_at_bottom=True)
hours = 0
chart.show_x_labels = True
for election_id, election in sorted(elections.items())[4:]:
hours = max([hours, len(election.caucus_by_hour), len(election.constituents_by_hour)])
chart.add(
'{} caucus'.format(election_id), list((election.caucus_by_hour)))
chart.add(
'{} constituents'.format(election_id), list((election.constituents_by_hour)))
chart.x_labels = [
str(hour)
for hour in range(hours)
]
chart.truncate_legend = -1
chart.truncate_label = -1
chart.x_labels_major_every = 24
chart.show_minor_x_labels = False
chart.render_to_file(filename)
logger.info("Wrote {}.".format(filename))
# Hourly Election Constituents
from pygal.style import Style
filename = 'images/elections-hourly-all-log.svg'
logger.info("Generating {}.".format(filename))
chart = pygal.Line(
title="Hourly Election Participation",
y_title="Users",
show_dots=False,
width=1400,
height=750,
value_formatter=lambda n: str(int(n)),
legend_at_bottom=True,
style=Style(
font_family="arial",
colors=list(reversed(['#DD22DD44', '#DD222244', '#DDDD2244', '#22DD2244', '#22DDDD44', '#6666DD44'] +
['#DD22DD', '#DD2222', '#DDDD22', '#22DD22', '#22DDDD', '#6666DD']))))
hours = 0
chart.show_x_labels = True
for election_id, election in sorted(elections.items())[4:]:
hours = max([hours, len(election.caucus_by_hour), len(election.constituents_by_hour)])
chart.add(
'election {} (eligible viewers)'.format(election_id), [max(x, 10) for x in election.caucus_by_hour]
)
for election_id, election in sorted(elections.items())[4:]:
hours = max([hours, len(election.caucus_by_hour), len(election.constituents_by_hour)])
chart.add(
'election {} (actual voters)'.format(election_id), [max(x, 10) for x in election.constituents_by_hour])
chart.logarithmic = True
def label(h):
if h % 24 != 0:
return ""
elif h == 0:
return "Nomination"
elif h < 168:
return "Day {}".format(h // 24 + 1)
elif h == 168:
return "Primary"
elif h < 264:
return "Day {}".format((h - 168) // 24 + 1)
elif h == 264:
return "Election"
elif h < 360:
return "Day {}".format((h - 264) // 24 + 1)
else:
return "End"
chart.x_labels = [
label(hour) for hour in range(hours)
]
chart.truncate_legend = -1
chart.truncate_label = -1
chart.x_labels_major_every = 24
chart.show_minor_x_labels = False
chart.render_to_file(filename)
logger.info("Wrote {}.".format(filename))
# MATH ELECTION COMPARISON
logger.info("Grouping math constituents by election.")
constituents_by_reason = math_constituents.by_reason()
logger.info("Grouping math caucuses by election.")
caucus_by_reason = math_caucus.by_reason()
math_elections = {}
for reason in list(sorted(constituents_by_reason))[-3:]:
election = ElectionData(
host='math.stackexchange.com',
constituent_badges=constituents_by_reason[reason],
caucus_badges=caucus_by_reason[reason])
assert math_elections.get(election.id) is None
math_elections[election.id] = election
election.hello_graphs()
filename = 'images/math-comparison-both-cumulative.svg'
logger.info("Generating {}.".format(filename))
chart = pygal.Line(
title="SO 6 and Math.SE 5 Participation",
y_title="Users",
show_dots=False,
width=1024,
height=768,
value_formatter=lambda n: str(int(n)),
legend_at_bottom=True)
chart.add(
'Math.SE 5 Constituents',
list(cumulative(math_elections[5].constituents_by_hour)))
chart.add(
'Math.SE 5 Caucus',
list(cumulative(math_elections[5].caucus_by_hour)))
chart.add(
'SO 6 Constituents', list(cumulative(elections[6].constituents_by_hour)))
chart.add(
'SO 6 Caucus', list(cumulative(elections[6].caucus_by_hour)))
chart.render_to_file(filename)
logger.info("Wrote {}.".format(filename))
if not flags.intersection(['-n', '--no-update', '-m', '--no-write']):
write_constituents()
write_caucus()
write_math_constituents()
write_math_caucus()
write_sherrifs()
write_great_answers()
if not flags.intersection(['-e', '--forever']):
break
logger.info("Sleeping for a while")
time.sleep(60 * 5)
def cumulative(xs):
n = 0
for x in xs:
n += x
yield n
def get_badge_data_and_write_function(
host, badge_id, filename, require_file=False
):
filename = host + '-' + filename
logger.info("Loading {} badges...".format(filename))
try:
f = lzma.open('data/' + filename + '.json.xz', 'rt')
except FileNotFoundError:
try:
f = open('data/' + filename + '.json', 'rt')
except FileNotFoundError:
if not require_file:
f = None
else:
raise
if f:
with f:
badge_data = scraping.BadgeData.from_json(json.load(f))
else:
badge_data = scraping.BadgeData(host=host, badge_id=badge_id)
logger.info("...{} {} badges loaded.".format(len(badge_data), filename))
def write():
logger.info("Writing {} {} badges...".format(len(badge_data), filename))
with lzma.open('data/' + filename + '.json.xz', 'wt') as f:
json.dump(badge_data.to_json(), f)
logger.info("...wrote {} {} badges.".format(len(badge_data), filename))
return badge_data, write
if __name__ == '__main__':
sys.exit(main(*sys.argv[1:]))