summaryrefslogtreecommitdiff
path: root/build-concerts.py
blob: 9c8176af123cb61d5d49d52e6610b366479e5c0a (plain)
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
#!/usr/bin/env python3

from contextlib import contextmanager
from dataclasses import dataclass
from datetime import datetime
import locale
from operator import attrgetter
from pathlib import Path
import re
from sys import argv
from typing import Iterator, Optional

from helpers import relative_path


# TODO: change some jargon:
# - event => concert
# - canceled => warning


LICENSE_URLS = {
    'CC0': 'https://creativecommons.org/publicdomain/zero',
    'CC BY': 'https://creativecommons.org/licenses/by',
    'CC BY-SA': 'https://creativecommons.org/licenses/by-sa',
}

LICENSE_RE = re.compile(
    '('+'|'.join(LICENSE_URLS.keys())+')' + ' ([0-9.]+)'
)


@dataclass
class LicenseInfo:
    tag: str
    version: str

    @classmethod
    def deserialize(cls, info):
        if info is None:
            return None
        return cls(*LICENSE_RE.fullmatch(info).groups())

    def format(self):
        url = f'{LICENSE_URLS[self.tag]}/{self.version}/'

        return f'<a href="{url}" target="_blank">{self.tag}</a>'


@dataclass
class Illustration:
    file: str
    alt_text: str
    source_name: str
    source_link: Optional[str]
    license_info: Optional[LicenseInfo]

    @classmethod
    def deserialize(cls, d):
        return cls(d['pic_file'],
                   d['pic_alt'],
                   d['pic_src'],
                   d['pic_link'],
                   LicenseInfo.deserialize(d['pic_license']))


@dataclass
class Concert:
    time: datetime
    place: str
    address: str
    pieces: Iterator[str]
    instructions: str
    illustration: Illustration
    warning: Optional[str]

    @classmethod
    def deserialize(cls, d):
        return cls(
            time=datetime.strptime(d['time'], '%d/%m/%Y %Hh%M'),
            place=d['place'],
            address=d['address'],
            pieces=d['pieces'],
            instructions=d['instructions'],
            illustration=Illustration.deserialize(d),
            warning=d['warning']
        )


def optional(line):
    return f'(?:{line})?'


CONCERT_LINES = (
    r'QUAND : (?P<time>[^\n]+)\n',
    r'O[UÙ] : (?P<place>[^\n]+)\n',
    'ADRESSE :\n',
    '(?P<address>.+?)\n',
    'PROGRAMME :\n',
    '(?P<pieces>.+?)\n',
    'INSTRUCTIONS :\n',
    '(?P<instructions>.+?)\n',
    'ILLUSTRATION :\n',
    r'fichier : (?P<pic_file>[^\n]+)\n',
    r'légende : (?P<pic_alt>[^\n]+)\n',
    r'source : (?P<pic_src>[^\n]+)\n',
    optional(r'lien : (?P<pic_link>[^\n]+)\n'),
    optional(r'licence : (?P<pic_license>[^\n]+)\n'),
    optional(r'AVERTISSEMENT : (?P<warning>[^\n]+)\n'),
)

CONCERT_RE = re.compile(''.join(CONCERT_LINES), flags=re.DOTALL)


def guess_language(filename):
    parent = str(Path(filename).parent)
    if parent == '.':
        return 'fr'
    return parent


def read_concerts(filename):
    with open(filename) as f:
        concerts = (
            Concert.deserialize(match)
            for match in re.finditer(CONCERT_RE, f.read())
        )
        return tuple(sorted(concerts, key=attrgetter('time')))


def split_concerts(concerts, threshold):
    for i, c in enumerate(concerts):
        if c.time > threshold:
            return concerts[:i], concerts[i:]

    return concerts, ()


LOCALIZED_TEXT = {
    'en': {
        'past': 'Past concerts',
        'next': 'Next concerts',
        'alt': 'Illustration:',
        'hint': 'Click on a concert to obtain more information.',
    },
    'fr': {
        'past': 'Concerts passés',
        'next': 'Prochains concerts',
        'alt': 'Illustration :',
        'hint': "Cliquez sur un concert pour obtenir plus d'informations.",
    }
}

THUMBNAILS_TEMPLATE = '''\
  <h1>{heading}</h1>
  <div class="events {time}">
{thumbnails}
  </div>\
'''

THUMBNAIL_TEMPLATE = '''\
    <div class="{eventclasses}">
      <a class="thumbnail" href="#{eventid}">
        <img src="{pic_file}" alt="{pic_alt}">
        <p class="summary">
          {summary}
        </p>
      </a>
      <div class="credits">
        <span>
          {credits}
        </span>
      </div>
    </div>\
'''


@contextmanager
def tmplocale(lang):
    old_lang, encoding = locale.getlocale()
    try:
        locale.setlocale(locale.LC_TIME, (lang, encoding))
        yield
    finally:
        locale.setlocale(locale.LC_TIME, (old_lang, encoding))


def format_credits(illustration):
    credits = illustration.source_name

    if illustration.source_link is not None:
        credits = (f'<a href="{illustration.source_link}" target="_blank">'
                   f'{illustration.source_name}'
                   '</a>')

    if illustration.license_info is not None:
        credits += ' / ' + illustration.license_info.format()

    return credits


def format_thumbnail(concert, imgdir, lang):
    eventclasses = ('event',)
    with tmplocale(lang):
        day = f'{concert.time.day} {concert.time.strftime("%B %Y")}'
    summary = f'{concert.place}<br>{day}'

    if concert.warning is not None:
        eventclasses += ('canceled',)
        summary = (f'<span class="canceled">{concert.warning}</span>\n'
                   f'          {summary}')

    alt_prefix = LOCALIZED_TEXT[lang]['alt']

    return THUMBNAIL_TEMPLATE.format_map({
        'eventclasses': ' '.join(eventclasses),
        'eventid': f'concert-{concert.time.strftime("%F")}',
        'pic_file': Path(imgdir, 'concerts', concert.illustration.file),
        'pic_alt': f'{alt_prefix} {concert.illustration.alt_text}',
        'summary': summary,
        'credits': format_credits(concert.illustration)
    })


def print_thumbnails_section(concerts, imgdir, section, lang):
    if not concerts:
        return

    thumbnails = '\n'.join(
        format_thumbnail(c, imgdir, lang) for c in concerts
    )

    print(THUMBNAILS_TEMPLATE.format(heading=LOCALIZED_TEXT[lang][section],
                                     time=section,
                                     thumbnails=thumbnails))


def print_thumbnails(concerts, imgdir, lang):
    today = datetime.fromordinal(
        datetime.today().date().toordinal()
    )
    past_concerts, next_concerts = split_concerts(concerts, today)

    print('<div id="event-list">')
    print_thumbnails_section(next_concerts, imgdir, 'next', lang)
    print_thumbnails_section(past_concerts, imgdir, 'past', lang)
    print('</div>')


DETAILS_TEMPLATE = '''\
  <div class="{concertclasses}" id="{concertid}">
{details}
  </div>\
'''


DATE_FORMATTERS = {
    'en': {
        'date': lambda d: d.strftime('%A %B %-d, %Y'),
        'time': lambda d: d.strftime('%I:%M %P'),
    },
    'fr': {
        'date': lambda d: d.strftime('%A %-d %B %Y').capitalize(),
        'time': lambda d: d.strftime('%Hh%M'),
    },
}


def detail_block(tag, classes, content):
    opener = f'<{tag} class="{" ".join(classes)}">'
    closer = f'</{tag}>'

    if isinstance(content, str):
        return f'    {opener}{content}{closer}'

    return '\n'.join((
        '    '+opener,
        *('      '+line for line in content),
        '    '+closer,
    ))


def break_lines(lines):
    return tuple(line+'<br>' for line in lines[:-1]) + (lines[-1],)


TOUCHUPS = (
    (re.compile('([0-9])(st|nd|rd|th|er|ère|nde|ème)'), r'\1<sup>\2</sup>'),
    (re.compile('(https://[^ ]+)'), r'<a href="\1" target="_blank">\1</a>'),
    (re.compile('([^ ]+@[^ ]+)'), r'<a href="mailto:\1">\1</a>'),
)


def touchup_plaintext(plaintext):
    text = plaintext
    for regexp, repl in TOUCHUPS:
        text = regexp.sub(repl, text)
    return text


def print_concert_details(concert, lang):
    concert_id = f'concert-{concert.time.strftime("%F")}'
    classes = ('details',)
    blocks = []

    if concert.warning is not None:
        classes += ('canceled',)
        blocks.append(
            detail_block('p', ('canceled',), concert.warning)
        )

    with tmplocale(lang):
        day = DATE_FORMATTERS[lang]['date'](concert.time)
    hour = DATE_FORMATTERS[lang]['time'](concert.time)

    address_lines = break_lines(concert.address.splitlines())
    piece_list = tuple(
        f'<li>{touchup_plaintext(line)}</li>'
        for line in concert.pieces.splitlines()
    )

    blocks.extend((
        detail_block('p', ('detail', 'date'), day),
        detail_block('p', ('detail', 'time'), hour),
        detail_block('p', ('detail', 'place'), address_lines),
        detail_block('ol', ('detail', 'program'), piece_list),
    ))

    instructions = [
        f'    <p>{touchup_plaintext(line)}</p>'
        for line in concert.instructions.splitlines()
    ]

    print(f'  <div class="{" ".join(classes)}" id="{concert_id}">')
    print('\n'.join(blocks+instructions))
    print('  </div>')


def print_details(concerts, lang):
    print('<div id="event-details">')
    print(f'  <p class="hint">{LOCALIZED_TEXT[lang]["hint"]}</p>')

    for c in concerts:
        print_concert_details(c, lang)

    print('</div>')


def main(concerts_src):
    imgdir = relative_path(to='images', ref=concerts_src)
    lang = guess_language(concerts_src)

    concerts = read_concerts(concerts_src)
    print_thumbnails(concerts, imgdir, lang)
    print_details(concerts, lang)


if __name__ == '__main__':
    main(argv[1])