c9f11e352f23ad75452c48240db0bb0fcb9b7e88
[books.alexwlchan.net] / scripts / render_html.py
1 #!/usr/bin/env python3
2
3 import datetime
4 import hashlib
5 import itertools
6 import os
7 import pathlib
8 import re
9 import subprocess
10 import sys
11
12 import attr
13 import frontmatter
14 from jinja2 import Environment, FileSystemLoader, select_autoescape
15 import markdown
16 from markdown.extensions.smarty import SmartyExtension
17 import smartypants
18
19 from generate_bookshelf import create_shelf_data_uri
20 from tint_colors import get_tint_colors, store_tint_color
21
22
23 def rsync(dir1, dir2):
24     subprocess.check_call(["rsync", "--recursive", "--delete", dir1, dir2])
25
26
27 @attr.s
28 class Book:
29     title = attr.ib()
30     author = attr.ib()
31     publication_year = attr.ib()
32     cover_image = attr.ib(default="")
33     cover_desc = attr.ib(default="")
34
35     isbn10 = attr.ib(default="")
36     isbn13 = attr.ib(default="")
37
38
39 @attr.s
40 class Review:
41     date_read = attr.ib()
42     text = attr.ib()
43     format = attr.ib(default=None)
44     rating = attr.ib(default=None)
45     did_not_finish = attr.ib(default=False)
46
47
48 @attr.s
49 class ReviewEntry:
50     path = attr.ib()
51     book = attr.ib()
52     review = attr.ib()
53
54     def out_path(self):
55         name = self.path.with_suffix("").name
56         return pathlib.Path(f"reviews/{name}")
57
58
59 def get_review_entry_from_path(path):
60     post = frontmatter.load(path)
61
62     kwargs = {}
63     for attr_name in Book.__attrs_attrs__:
64         try:
65             kwargs[attr_name.name] = post["book"][attr_name.name]
66         except KeyError:
67             pass
68
69     book = Book(**kwargs)
70
71     review = Review(**post["review"], text=post.content)
72
73     return ReviewEntry(path=path, book=book, review=review)
74
75
76 @attr.s
77 class CurrentlyReading:
78     text = attr.ib()
79
80
81 @attr.s
82 class CurrentlyReadingEntry:
83     path = attr.ib()
84     book = attr.ib()
85     reading = attr.ib()
86
87
88 def get_reading_entry_from_path(path):
89     post = frontmatter.load(path)
90
91     book = Book(**post["book"])
92     reading = CurrentlyReading(text=post.content)
93
94     return CurrentlyReadingEntry(path=path, book=book, reading=reading)
95
96
97 def _parse_date(value):
98     if isinstance(value, datetime.date):
99         return value
100     else:
101         return datetime.datetime.strptime(value, "%Y-%m-%d").date()
102
103
104 @attr.s
105 class Plan:
106     text = attr.ib()
107     date_added = attr.ib(converter=_parse_date)
108
109
110 @attr.s
111 class PlanEntry:
112     path = attr.ib()
113     book = attr.ib()
114     plan = attr.ib()
115
116
117 def get_plan_entry_from_path(path):
118     post = frontmatter.load(path)
119
120     book = Book(**post["book"])
121     plan = Plan(date_added=post["plan"]["date_added"], text=post.content)
122
123     return PlanEntry(path=path, book=book, plan=plan)
124
125
126 def get_entries(dirpath, constructor):
127     for dirpath, _, filenames in os.walk(dirpath):
128         for f in filenames:
129             if not f.endswith(".md"):
130                 continue
131
132             path = pathlib.Path(dirpath) / f
133
134             try:
135                 yield constructor(path)
136             except Exception:
137                 print(f"Error parsing {path}", file=sys.stderr)
138                 raise
139
140
141 def render_markdown(text):
142     return markdown.markdown(text, extensions=[SmartyExtension()])
143
144
145 def render_date(date_value):
146     if isinstance(date_value, datetime.date):
147         return date_value.strftime("%-d %B %Y")
148
149     date_match = re.match(
150         r"^(?P<year>\d{4})-(?P<month>\d{2})(?:-(?P<day>\d{2}))?$", date_value
151     )
152     assert date_match is not None, date_value
153
154     date_obj = datetime.datetime(
155         year=int(date_match.group("year")),
156         month=int(date_match.group("month")),
157         day=int(date_match.group("day") or "1"),
158     )
159
160     if date_match.group("day"):
161         return render_date(date_obj)
162     else:
163         return date_obj.strftime("%B %Y")
164
165
166 def render_individual_review(env, *, review_entry, **kwargs):
167     template = env.get_template("review.html")
168     html = template.render(
169         review_entry=review_entry,
170         title=f"My review of {review_entry.book.title}",
171         **kwargs
172     )
173
174     out_name = review_entry.out_path() / "index.html"
175     out_path = pathlib.Path("_html") / out_name
176     out_path.parent.mkdir(exist_ok=True, parents=True)
177     out_path.write_text(html)
178
179
180 def _create_new_thumbnail(src_path, dst_path):
181     dst_path.parent.mkdir(exist_ok=True, parents=True)
182
183     # Thumbnails are 240x240 max, then 2x for retina displays
184     subprocess.check_call([
185         "convert", src_path, "-resize", "480x480>", dst_path
186     ])
187
188
189 def thumbnail_1x(name):
190     pth = pathlib.Path(name)
191     return pth.stem + "_1x" + pth.suffix
192
193
194 def _create_new_square(src_path, square_path):
195     square_path.parent.mkdir(exist_ok=True, parents=True)
196
197     subprocess.check_call([
198         "convert",
199         src_path, "-resize", "240x240", "-gravity", "center", "-background", "white", "-extent", "240x240", square_path
200     ])
201
202
203 def create_thumbnails():
204     for image_name in os.listdir("src/covers"):
205         if image_name == ".DS_Store":
206             continue
207
208         src_path = pathlib.Path("src/covers") / image_name
209         dst_path = pathlib.Path("_html/thumbnails") / image_name
210
211         if not dst_path.exists():
212             _create_new_thumbnail(src_path, dst_path)
213         elif src_path.stat().st_mtime > dst_path.stat().st_mtime:
214             _create_new_thumbnail(src_path, dst_path)
215
216         square_path = pathlib.Path("_html/squares") / image_name
217
218         if not square_path.exists():
219             _create_new_square(src_path, square_path)
220         elif src_path.stat().st_mtime > square_path.stat().st_mtime:
221             _create_new_square(src_path, square_path)
222
223         store_tint_color(dst_path)
224
225
226 CSS_HASH = hashlib.md5(open('static/style.css', 'rb').read()).hexdigest()
227
228
229 def css_hash(_):
230     return f"md5:{CSS_HASH}"
231
232
233 def main():
234     env = Environment(
235         loader=FileSystemLoader("templates"),
236         autoescape=select_autoescape(["html", "xml"]),
237     )
238
239     env.filters["render_markdown"] = render_markdown
240     env.filters["render_date"] = render_date
241     env.filters["smartypants"] = smartypants.smartypants
242     env.filters["thumbnail_1x"] = thumbnail_1x
243     env.filters["css_hash"] = css_hash
244     env.filters["create_shelf_data_uri"] = create_shelf_data_uri
245
246     create_thumbnails()
247
248     tint_colors = get_tint_colors()
249
250     rsync("src/covers/", "_html/covers/")
251     rsync("static/", "_html/static/")
252
253     # Render the "all reviews page"
254
255     all_reviews = list(
256         get_entries(dirpath="src/reviews", constructor=get_review_entry_from_path)
257     )
258     all_reviews = sorted(
259         all_reviews, key=lambda rev: str(rev.review.date_read), reverse=True
260     )
261
262     for review_entry in all_reviews:
263         render_individual_review(
264             env,
265             review_entry=review_entry,
266             tint_colors=tint_colors
267         )
268
269     template = env.get_template("list_reviews.html")
270     html = template.render(
271         all_reviews=[
272             (year, list(reviews))
273             for (year, reviews) in itertools.groupby(
274                 all_reviews, key=lambda rev: str(rev.review.date_read)[:4]
275             )
276         ],
277         title="books i’ve read",
278         this_year=str(datetime.datetime.now().year),
279         tint_colors=tint_colors,
280     )
281
282     out_path = pathlib.Path("_html") / "reviews/index.html"
283     out_path.write_text(html)
284
285     # Render the "currently reading" page
286
287     all_reading = list(
288         get_entries(
289             dirpath="src/currently_reading", constructor=get_reading_entry_from_path
290         )
291     )
292
293     template = env.get_template("list_reading.html")
294     html = template.render(
295         all_reading=all_reading,
296         title="books i’m currently reading",
297         tint_colors=tint_colors
298     )
299
300     out_path = pathlib.Path("_html") / "reading/index.html"
301     out_path.parent.mkdir(exist_ok=True, parents=True)
302     out_path.write_text(html)
303
304     # Render the "want to read" page
305
306     all_plans = list(
307         get_entries(dirpath="src/plans", constructor=get_plan_entry_from_path)
308     )
309
310     all_plans = sorted(all_plans, key=lambda plan: plan.plan.date_added, reverse=True)
311
312     template = env.get_template("list_plans.html")
313     html = template.render(
314         all_plans=all_plans,
315         title="books i want to read",
316         tint_colors=tint_colors,
317     )
318
319     out_path = pathlib.Path("_html") / "to-read/index.html"
320     out_path.parent.mkdir(exist_ok=True, parents=True)
321     out_path.write_text(html)
322
323     # Render the "never going to read this page"
324
325     all_retired = list(
326         get_entries(dirpath="src/will_never_read", constructor=get_plan_entry_from_path)
327     )
328
329     all_retired = sorted(
330         all_retired, key=lambda plan: plan.plan.date_added, reverse=True
331     )
332
333     template = env.get_template("list_will_never_read.html")
334     html = template.render(
335         all_retired=all_retired,
336         title="books i&rsquo;m never going to read",
337         tint_colors=tint_colors
338     )
339
340     out_path = pathlib.Path("_html") / "will-never-read/index.html"
341     out_path.parent.mkdir(exist_ok=True, parents=True)
342     out_path.write_text(html)
343
344     # Render the front page
345
346     index_template = env.get_template("index.html")
347     html = index_template.render(
348         text=open("src/index.md").read(),
349         reviews=all_reviews[:5],
350         tint_colors=tint_colors
351     )
352
353     index_path = pathlib.Path("_html") / "index.html"
354     index_path.write_text(html)
355
356     print("✨ Rendered HTML files to _html ✨")
357
358
359 if __name__ == "__main__":
360     main()