Downsize images in the thumbnail view
[books.alexwlchan.net] / scripts / render_html.py
1 #!/usr/bin/env python
2
3 import datetime
4 import itertools
5 import os
6 import pathlib
7 import re
8 import subprocess
9 import sys
10
11 import attr
12 import frontmatter
13 from jinja2 import Environment, FileSystemLoader, select_autoescape
14 import markdown
15 from markdown.extensions.smarty import SmartyExtension
16 from PIL import Image
17 import smartypants
18
19
20 def rsync(dir1, dir2):
21     subprocess.check_call(["rsync", "--recursive", "--delete", dir1, dir2])
22
23
24 @attr.s
25 class Book:
26     title = attr.ib()
27     author = attr.ib()
28     publication_year = attr.ib()
29     cover_image = attr.ib()
30     cover_desc = attr.ib(default="")
31
32     isbn10 = attr.ib(default="")
33     isbn13 = attr.ib(default="")
34
35
36 @attr.s
37 class Review:
38     date_read = attr.ib()
39     text = attr.ib()
40     format = attr.ib(default=None)
41     rating = attr.ib(default=None)
42     did_not_finish = attr.ib(default=False)
43
44
45 @attr.s
46 class ReviewEntry:
47     path = attr.ib()
48     book = attr.ib()
49     review = attr.ib()
50
51     def out_path(self):
52         name = self.path.with_suffix("").name
53         return pathlib.Path(f"reviews/{name}")
54
55
56 def get_review_entry_from_path(path):
57     post = frontmatter.load(path)
58
59     book = Book(**post["book"])
60     review = Review(**post["review"], text=post.content)
61
62     return ReviewEntry(path=path, book=book, review=review)
63
64
65 @attr.s
66 class CurrentlyReading:
67     text = attr.ib()
68
69
70 @attr.s
71 class CurrentlyReadingEntry:
72     path = attr.ib()
73     book = attr.ib()
74     reading = attr.ib()
75
76
77 def get_reading_entry_from_path(path):
78     post = frontmatter.load(path)
79
80     book = Book(**post["book"])
81     reading = CurrentlyReading(text=post.content)
82
83     return CurrentlyReadingEntry(path=path, book=book, reading=reading)
84
85
86 def _parse_date(value):
87     if isinstance(value, datetime.date):
88         return value
89     else:
90         return datetime.datetime.strptime(value, "%Y-%m-%d").date()
91
92
93 @attr.s
94 class Plan:
95     text = attr.ib()
96     date_added = attr.ib(converter=_parse_date)
97
98
99 @attr.s
100 class PlanEntry:
101     path = attr.ib()
102     book = attr.ib()
103     plan = attr.ib()
104
105
106 def get_plan_entry_from_path(path):
107     post = frontmatter.load(path)
108
109     book = Book(**post["book"])
110     plan = Plan(**post["plan"], text=post.content)
111
112     return PlanEntry(path=path, book=book, plan=plan)
113
114
115 def get_entries(dirpath, constructor):
116     for dirpath, _, filenames in os.walk(dirpath):
117         for f in filenames:
118             if not f.endswith(".md"):
119                 continue
120
121             path = pathlib.Path(dirpath) / f
122
123             try:
124                 yield constructor(path)
125             except Exception:
126                 print(f"Error parsing {path}", file=sys.stderr)
127                 raise
128
129
130 def render_markdown(text):
131     return markdown.markdown(text, extensions=[SmartyExtension()])
132
133
134 def render_date(date_value):
135     if isinstance(date_value, datetime.date):
136         return date_value.strftime("%d %B %Y")
137
138     date_match = re.match(
139         r"^(?P<year>\d{4})-(?P<month>\d{2})(?:-(?P<day>\d{2}))?$", date_value
140     )
141     assert date_match is not None, date_value
142
143     date_obj = datetime.datetime(
144         year=int(date_match.group("year")),
145         month=int(date_match.group("month")),
146         day=int(date_match.group("day") or "1"),
147     )
148
149     if date_match.group("day"):
150         return date_obj.strftime("%-d %B %Y")
151     else:
152         return date_obj.strftime("%B %Y")
153
154
155 def render_individual_review(env, *, review_entry):
156     template = env.get_template("review.html")
157     html = template.render(
158         review_entry=review_entry, title=f"My review of {review_entry.book.title}"
159     )
160
161     out_name = review_entry.out_path() / "index.html"
162     out_path = pathlib.Path("_html") / out_name
163     out_path.parent.mkdir(exist_ok=True, parents=True)
164     out_path.write_text(html)
165
166
167 def _create_new_thumbnail(src_path, dst_path):
168     im = Image.open(src_path)
169     im.thumbnail((240, 240))
170     os.makedirs(os.path.dirname(dst_path), exist_ok=True)
171     im.save(dst_path)
172
173
174 def create_thumbnails():
175     for image_name in os.listdir("src/covers"):
176         if image_name == ".DS_Store":
177             continue
178
179         src_path = os.path.join("src/covers", image_name)
180         dst_path = os.path.join("_html/thumbnails", image_name)
181
182         if not os.path.exists(dst_path):
183             _create_new_thumbnail(src_path, dst_path)
184         elif os.stat(src_path).st_mtime > os.stat(dst_path).st_mtime:
185             _create_new_thumbnail(src_path, dst_path)
186
187
188 def main():
189     env = Environment(
190         loader=FileSystemLoader("templates"),
191         autoescape=select_autoescape(["html", "xml"]),
192     )
193
194     env.filters["render_markdown"] = render_markdown
195     env.filters["render_date"] = render_date
196     env.filters["smartypants"] = smartypants.smartypants
197
198     create_thumbnails()
199
200     rsync("src/covers/", "_html/covers/")
201     rsync("static/", "_html/static/")
202
203     # Render the "all reviews page"
204
205     all_reviews = list(
206         get_entries(dirpath="src/reviews", constructor=get_review_entry_from_path)
207     )
208     all_reviews = sorted(
209         all_reviews, key=lambda rev: str(rev.review.date_read), reverse=True
210     )
211
212     for review_entry in all_reviews:
213         render_individual_review(env, review_entry=review_entry)
214
215     template = env.get_template("list_reviews.html")
216     html = template.render(
217         all_reviews=[
218             (year, list(reviews))
219             for (year, reviews) in itertools.groupby(
220                 all_reviews, key=lambda rev: str(rev.review.date_read)[:4]
221             )
222         ],
223         title="books i’ve read",
224         this_year=str(datetime.datetime.now().year),
225     )
226
227     out_path = pathlib.Path("_html") / "reviews/index.html"
228     out_path.write_text(html)
229
230     # Render the "currently reading" page
231
232     all_reading = list(
233         get_entries(
234             dirpath="src/currently_reading", constructor=get_reading_entry_from_path
235         )
236     )
237
238     template = env.get_template("list_reading.html")
239     html = template.render(all_reading=all_reading, title="books i’m currently reading")
240
241     out_path = pathlib.Path("_html") / "reading/index.html"
242     out_path.parent.mkdir(exist_ok=True, parents=True)
243     out_path.write_text(html)
244
245     # Render the "want to read" page
246
247     all_plans = list(
248         get_entries(dirpath="src/plans", constructor=get_plan_entry_from_path)
249     )
250
251     all_plans = sorted(all_plans, key=lambda plan: plan.plan.date_added)
252
253     template = env.get_template("list_plans.html")
254     html = template.render(all_plans=all_plans, title="books i want to read")
255
256     out_path = pathlib.Path("_html") / "to-read/index.html"
257     out_path.parent.mkdir(exist_ok=True, parents=True)
258     out_path.write_text(html)
259
260     # Render the front page
261
262     index_template = env.get_template("index.html")
263     html = index_template.render(text=open("src/index.md").read())
264
265     index_path = pathlib.Path("_html") / "index.html"
266     index_path.write_text(html)
267
268     print("✨ Rendered HTML files to _html ✨")
269
270
271 if __name__ == "__main__":
272     main()