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