-
Notifications
You must be signed in to change notification settings - Fork 2
/
printing.py
627 lines (439 loc) · 16.5 KB
/
printing.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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
#!/usr/bin/env python3
"""
Game of Thrones chapters vs episodes chart generator
Copyright (c) 2013-2018, Joel Geddert
This script generates an HTML file of the table.
Software License:
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
A note from the author:
The original chart generated by this code, as well as all remaining applicable
source & asset files (except where noted), are licensed under a Creative Commons
BY-SA 4.0 license <http://creativecommons.org/licenses/by-sa/4.0/>. If you are
going to use any of this code to create a derivative work, please respect this
CC license.
"""
from utils import *
from book_show_types import *
from typing import Iterable, Optional
import os.path
# Darken every n cells
_n_stripe = 5
_table_line = '<!--table-->'
_top_left_box = '<img src="imgs/cornerbox.png">'
_use_img_headers = True
_curr_season = 5
_latest_episode = 50
# If chapter name is longer than this many characters, it will be abbreviated
# Based on number of utils.display_string_len_approx() returns
_max_chap_name_length = 15
_use_roman_numerals_for_season_nums = True
class FileWriter:
# HTML indentation character - ASCII tab "\t", several spaces, or nothing.
tab = "\t"
# Windows EOL
eol = "\r\n"
def __init__(self, *files):
self.files = files
def op(self, text: str, indent=0):
for file in self.files:
indentation = self.tab * indent
file.write(indentation + text)
def opl(self, text: str, indent=0):
self.op(text + self.eol, indent=indent)
def is_chap_name_empty(chap_name: str):
x = ''.join(ch for ch in chap_name if ch.isalnum())
return x == ''
def print_html_header(writer: FileWriter, in_file):
line = ''
while _table_line not in line:
line = in_file.readline()
if not line.endswith('\n'):
raise ValueError('Error: line %s not found' % _table_line)
writer.op(line)
def print_html_footer(writer: FileWriter, in_file):
while True:
line = in_file.readline()
if not line.endswith('\n'):
break
writer.op(line)
def is_striped(
episode: Optional[Episode]=None,
chapter: Optional[Chapter]=None,
book: Optional[Book]=None):
if episode is not None and (episode.number_in_season % _n_stripe == 1):
return True
if chapter is not None:
if book is not None:
return book.chapters.index(chapter) % _n_stripe == 0
else:
return chapter.number_in_book % _n_stripe == 1
else:
return False
def print_book_title_cells(writer: FileWriter, book: Book):
book_name = htmlize_string(book.name)
# Column that summarizes book (for when column set is collapsed)
classes = 'booktitle b%ititle b%ic' % (book.number, book.number)
if _use_img_headers:
cell_contents = '<img src="imgs/b%icoll.png" alt="%s">' % (book.number, book_name)
else:
cell_contents = \
'<div class="booktitleabbrevrotate"><div class="booktitleabbrevinside">%s</div></div>' % book.abbreviation
writer.opl(
'<th rowspan="2" class="%s" onclick="expandbook(%i)">%s</th>' % (
classes, book.number, cell_contents),
indent=1)
# Main book title column
classes = 'booktitle b%ititle b%i' % (book.number, book.number)
if _use_img_headers:
cell_contents = '<img src="imgs/b%ititle.png" alt="%s">' % (book.number, book_name)
else:
cell_contents = book_name
writer.opl(
'<th colspan="%i" class="%s" onclick="collapsebook(%i)">%s</th>' % (
len(book.chapters), classes, book.number, cell_contents),
indent=1)
def print_all_book_title_cells(writer: FileWriter, books: Iterable[Book]):
for book in books:
print_book_title_cells(writer, book)
def print_chapter_title_cell(writer: FileWriter, book: Book, chapter: Chapter):
"""
:param writer:
:param book: Note that this may not match chapter.book for combined books
:param chapter:
"""
if not book.is_combined() and book is not chapter.book:
warn('Book does not match chapter.book for non-combined book!')
# For "?" chapters after TWOW preview chaps
chap_name_isnt_real = is_chap_name_empty(chapter.name)
# if name longer than ~15 characters, abbreviate
# If we're in combined section, prepend book number to chapter
# Want real book number, not fake combined book number, so use chapter.book.number rather than book.number
chap_name_to_display = abbrev_string(
chapter.name,
_max_chap_name_length,
prefix=str(chapter.book.number) if book.is_combined() else None)
if book.is_combined():
classes = ["cn", "b%i" % book.number, "b%ico" % chapter.book.number, "bb"]
else:
classes = ["cn", "b%i" % chapter.book.number, "bb"]
if chapter is book.chapters[0]:
classes.append("lb")
if chapter is book.chapters[-1]:
classes.append("rb")
if is_striped(chapter=chapter, book=book):
classes.append("s")
if chap_name_isnt_real:
writer.opl('<th class="%s"><div class="cni nonrotate">?</div></th>' % (' '.join(classes)), indent=1)
else:
classes_inner = "cni"
if not chapter.occurred:
classes_inner += " ho"
writer.opl('<th class="%s" title="%s"><div class="cnr"><div class="%s">%s</div></div></th>' % (
' '.join(classes), chapter.name, classes_inner, chap_name_to_display), indent=1)
def print_all_chapter_title_cells(writer: FileWriter, books: Iterable[Book]):
for book in books:
for chapter in book.chapters:
print_chapter_title_cell(writer, book, chapter)
def print_connection(
writer: FileWriter,
is_strong_connection: bool,
notes: Optional[str]=None,
pov: Optional[str]=None):
classes = ["c"]
if pov is not None:
classes.append("pov%s" % pov.lower())
if is_strong_connection:
classes.append("sc")
else:
classes.append("wc")
classes = ' '.join(classes)
if notes:
writer.op('<div class="%s" title="%s"></div>' % (classes, htmlize_string(notes)))
else:
writer.op('<div class="%s"></div>' % classes)
def print_book_summary_cell_for_episode(
writer: FileWriter,
episode: Episode,
book: Book,
connections: Iterable[Connection]):
classes = ["b%ic" % book.number, "lb", "rb"]
if episode.number_in_season == 1:
classes.append("tb")
if episode.number_in_season == len(episode.season.episodes):
classes.append("bb")
if is_striped(episode=episode):
classes.append("s")
writer.op('<td class="%s">' % ' '.join(classes), indent=1)
if book.is_combined():
ep_book_connections = [
item for item in connections
if (item.episode.number == episode.number) and (item.chapter.book in book.combined_books)
]
else:
ep_book_connections = [
item for item in connections
if (item.episode.number == episode.number) and (item.chapter.book is book)
]
if ep_book_connections:
print_connection(writer, is_strong_connection=any([item.strength for item in ep_book_connections]))
writer.opl("</td>")
def print_episode_chapter_cell(
writer: FileWriter,
episode: Episode,
book: Book,
chapter: Chapter,
debug_print_this_line=False):
"""
:param writer:
:param episode:
:param book: Note that this may not match chapter.book for combined books
:param chapter:
:param debug_print_this_line:
"""
if not book.is_combined() and book is not chapter.book:
warn('Book does not match chapter.book for non-combined book!')
if debug_print_this_line:
debug_print("Book %i, Chapter %i" % (chapter.book.number, chapter.number_in_book))
if not book.is_combined():
classes = ["b%i" % chapter.book.number]
else:
classes = ["b%i" % book.number, "b%ico" % chapter.book.number]
if episode.number_in_season == 1:
classes.append("tb")
if episode.number_in_season == len(episode.season.episodes):
classes.append("bb")
if chapter is book.chapters[0]:
classes.append("lb")
if chapter is book.chapters[-1]:
classes.append("rb")
if is_striped(episode=episode, chapter=chapter, book=book):
classes.append("s")
if debug_print_this_line:
if 'lb' in classes:
debug_print('left border')
if 'rb' in classes:
debug_print('right border')
writer.op('<td class="%s">' % ' '.join(classes))
matching_connections = [item for item in episode.book_connections if item.chapter.number == chapter.number]
if matching_connections:
if len(matching_connections) > 1:
print('Multiple connections found for episode %i & chapter %i:' % (episode.number, chapter.number))
for conn in matching_connections:
print('\t' + repr(conn))
notes = '; '.join([c.notes for c in matching_connections if c.notes])
print_connection(writer, max([c.strength for c in matching_connections]), notes, pov=chapter.pov)
writer.op('</td>')
def print_episode_body_cells(
writer: FileWriter,
episode: Episode,
books: Iterable[Book],
debug_print_this_line=False):
debug_print("episode %i, %i connections: %s" % (
episode.number,
len(episode.book_connections),
repr([item.chapter.number for item in episode.book_connections])))
debug_print(repr(episode.book_connections))
for book in books:
if debug_print_this_line:
debug_print('')
debug_print('Book %i start' % book.number)
print_book_summary_cell_for_episode(writer, episode, book, episode.book_connections)
for chapter in book.chapters:
print_episode_chapter_cell(writer, episode, book, chapter, debug_print_this_line=debug_print_this_line)
def print_episode_title_cells(
writer: FileWriter,
episode: Episode,
hide_on_float: bool,
mirror: bool):
"""
:param writer:
:param episode:
:param hide_on_float: if True, will add "hideonfloat" class
:param mirror: if True, episode and season cells will be swapped (i.e. for print version right floating table)
"""
opl = writer.opl
first_of_season = episode is episode.season.episodes[0]
last_of_season = episode is episode.season.episodes[-1]
episode_classes = [] # Classes for both episode number and episode title
season_title_classes = ['seas%ititle' % episode.season.number]
if is_striped(episode=episode):
episode_classes.append('s')
if first_of_season:
episode_classes.append("tb")
if last_of_season:
episode_classes.append("bb")
if hide_on_float:
episode_classes.append('hideonfloat')
season_title_classes.append('hideonfloat')
ep_num_classes = ['epnum'] + episode_classes
if mirror:
ep_num_classes.append('rb')
ep_title_classes = ['eptitle', 'lb' if mirror else 'rb'] + episode_classes
season_title_classes = ' '.join(season_title_classes)
ep_num_classes = ' '.join(ep_num_classes)
ep_title_classes = ' '.join(ep_title_classes)
if mirror:
opl('<th class="%s"><div class="eptitleinside">%s</div></th>' % (ep_title_classes, episode.name), indent=1)
opl('<th class="%s">%i</th>' % (ep_num_classes, episode.number_in_season), indent=1)
if first_of_season:
opl('<th rowspan="%i" class="seasontitle %s">' % (len(episode.season.episodes), season_title_classes), indent=1)
if _use_img_headers:
opl('<img src="imgs/s%ititle.png" alt="Season %i">' % (episode.season.number, episode.season.number))
else:
if _use_roman_numerals_for_season_nums:
season_num_str = to_roman_numeral(episode.season.number)
else:
season_num_str = str(episode.season.number)
opl('<div class="seasonnamerotate">', indent=2)
opl('<div class="seasonnameinside">Season %s</div>' % season_num_str, indent=3)
opl("</div>", indent=2)
opl("</th>", indent=1)
if not mirror:
opl('<th class="%s">%i</th>' % (ep_num_classes, episode.number_in_season), indent=1)
opl('<th class="%s"><div class="eptitleinside">%s</div></th>' % (ep_title_classes, episode.name), indent=1)
def print_episode_row(
writer: FileWriter,
episode: Episode,
books: Optional[Iterable[Book]],
is_body_section: bool,
is_end_section: bool):
"""
:param writer:
:param episode:
:param books: must be given if print_body_cells
:param is_body_section:
:param is_end_section:
"""
if is_body_section and is_end_section:
raise ValueError('Cannot be both body section and end section!')
if is_body_section and not books:
warn('is_body_section given but books empty!')
# <tr>
ep_row_classes = ['eprow']
if episode is episode.season.episodes[0]:
ep_row_classes.append('epkeyrow')
season_class = "seas%i" % episode.season.number
if episode.season.number == _curr_season:
if episode.number <= _latest_episode:
season_class += "aired"
else:
season_class += "unaired"
ep_row_classes.append(season_class)
writer.opl('<tr class="%s">' % ' '.join(ep_row_classes))
# Season & episode title cells
print_episode_title_cells(writer, episode, hide_on_float=is_body_section, mirror=is_end_section)
# Body cells
if is_body_section:
print_episode_body_cells(writer, episode, books, debug_print_this_line=(episode.number == 1))
# </tr>
writer.opl("</tr>")
def print_all_episode_rows(
writer: FileWriter,
seasons: Iterable[Season],
books: Iterable[Book]):
for season in seasons:
for episode in season.episodes:
print_episode_row(
writer, episode, books,
is_body_section=True,
is_end_section=False)
def print_floating_episode_list(writer: FileWriter, seasons: Iterable[Season]):
for season in seasons:
for episode in season.episodes:
print_episode_row(
writer, episode,
books=None,
is_body_section=False,
is_end_section=False)
def print_right_episode_list(writer: FileWriter, seasons: Iterable[Season]):
for season in seasons:
for episode in season.episodes:
print_episode_row(
writer, episode,
books=None,
is_body_section=False,
is_end_section=True)
def print_floating_table(w: FileWriter, db: DB):
w.opl('<table id="floatingtable">')
w.opl('<thead>')
w.opl('<tr class="booktitlerow">')
w.opl('<th colspan="3" rowspan="2" class="cornerbox rb"><div class="cornerboxdiv">%s</div></th>' %
_top_left_box, indent=1)
w.opl('</tr>')
w.opl('<tr></tr>')
w.opl('</thead>')
print_floating_episode_list(w, db.seasons)
w.opl("</table>")
def print_right_floating_table(w: FileWriter, db: DB):
w.opl('<table id="floatingtable">')
w.opl('<thead>')
w.opl('<tr class="booktitlerow">')
w.opl('<th colspan="3" rowspan="2" class="cornerbox lb"><div class="cornerboxdiv"> </div></th>', indent=1)
w.opl("</tr>")
w.opl("<tr></tr>")
w.opl("</thead>")
print_right_episode_list(w, db.seasons)
w.opl("</table>")
def print_main_table(w: FileWriter, db: DB):
w.opl('<table id="maintable">')
# thead
w.opl('<thead>')
w.opl('<tr class="booktitlerow">')
w.opl('<th colspan="3" rowspan="2" class="cornerbox hideonfloat"><div class="cornerboxdiv">%s</div></th>' %
_top_left_box, indent=1)
print("Writing table chapter headers")
print_all_book_title_cells(w, db.books)
w.opl('</tr>')
w.opl('<tr>')
print_all_chapter_title_cells(w, db.books)
w.opl('</tr>')
w.opl('</thead>')
# tbody
print('')
print('***** Writing table body *****')
print('')
w.opl('<tbody>')
print_all_episode_rows(w, db.seasons, db.books)
w.opl('</tbody>')
print('')
print('***** Table body complete *****')
print('')
# End of table
w.opl('</table>')
def do_printing(db: DB, input_dir='input', output_dir='output', output_print_dir='output-print'):
html_template_filename_inter = os.path.join(input_dir, 'template.html')
html_template_filename_print = os.path.join(input_dir, 'template-print.html')
output_filename_inter = os.path.join(output_dir, 'bookshow.html')
output_filename_print = os.path.join(output_print_dir, 'bookshow_print.html')
print('Opening files')
with \
open(html_template_filename_inter, 'r') as in_file_interactive, \
open(html_template_filename_print, 'r') as in_file_print, \
open(output_filename_inter, 'w') as out_file_interactive, \
open(output_filename_print, 'w') as out_file_print:
writer_interactive = FileWriter(out_file_interactive)
writer_print_version = FileWriter(out_file_print)
writer_both = FileWriter(out_file_print, out_file_interactive)
print('Writing HTML Header')
print_html_header(writer_interactive, in_file_interactive)
print_html_header(writer_print_version, in_file_print)
writer_both.opl('<div id="tablediv" class="cpov spoiler_b0">')
print('Writing floating table')
print_floating_table(writer_interactive, db)
writer_both.opl('<div id="maintablediv">')
print_main_table(writer_both, db)
writer_both.opl('</div> <!-- /maintablediv -->')
print_right_floating_table(writer_print_version, db)
writer_both.opl('</div> <!-- /tablediv -->')
print('Writing HTML footer')
print_html_footer(writer_interactive, in_file_interactive)
print_html_footer(writer_print_version, in_file_print)