Render titles with smartypants
[books.alexwlchan.net] / scripts / add_book.py
1 #!/usr/bin/env python
2
3 import datetime
4 import os
5 import re
6 import subprocess
7 from urllib.request import urlretrieve
8
9 import frontmatter
10 import hyperlink
11 import inquirer
12 from unidecode import unidecode
13
14
15 def slugify(u):
16     """Convert Unicode string into blog slug."""
17     # https://leancrew.com/all-this/2014/10/asciifying/
18     u = re.sub("[–—/:;,.]", "-", u)  # replace separating punctuation
19     a = unidecode(u).lower()  # best ASCII substitutions, lowercased
20     a = re.sub(r"[^a-z0-9 -]", "", a)  # delete any other characters
21     a = a.replace(" ", "-")  # spaces to hyphens
22     a = re.sub(r"-+", "-", a)  # condense repeated hyphens
23     return a
24
25
26 def get_book_info():
27     questions = [
28         inquirer.List(
29             "entry_type",
30             message="What type of book is this?",
31             choices=[
32                 "one I’ve read",
33                 "one I’m currently reading",
34                 "one I want to read",
35             ],
36         ),
37         inquirer.Text("title", message="What’s the title of the book?"),
38         inquirer.Text("author", message="Who’s the author?"),
39         inquirer.Text("publication_year", message="When was it published?"),
40         inquirer.Text("cover_image_url", message="What’s the cover URL?"),
41         inquirer.Text("cover_desc", message="What’s the cover?"),
42         inquirer.Text("isbn10", message="Do you know the ISBN-10?"),
43         inquirer.Text("isbn13", message="Do you know the ISBN-13?"),
44     ]
45
46     answers = inquirer.prompt(questions)
47
48     answers["entry_type"] = {
49         "one I’ve read": "reviews",
50         "one I’m currently reading": "currently_reading",
51         "one I want to read": "plans",
52     }[answers["entry_type"]]
53
54     return answers
55
56
57 def get_review_info():
58     date_read_question1 = [
59         inquirer.List(
60             "date_read",
61             message="When did you finish reading it?",
62             choices=["today", "yesterday", "another day"],
63         )
64     ]
65
66     date_read = inquirer.prompt(date_read_question1)["date_read"]
67
68     today = datetime.datetime.now()
69
70     if date_read == "today":
71         date_read = today.strftime("%Y-%m-%d")
72     elif date_read == "yesterday":
73         yesterday = today - datetime.timedelta(days=1)
74         date_read = yesterday.strftime("%Y-%m-%d")
75     else:
76         date_read_question2 = [
77             inquirer.Text("date_read", message="When did you finish reading it?")
78         ]
79
80         date_read = inquirer.prompt(date_read_question2)["date_read"]
81
82     other_questions = [
83         inquirer.List(
84             "rating",
85             message="When’s your rating?",
86             choices=["★★★★★", "★★★★☆", "★★★☆☆", "★★☆☆☆", "★☆☆☆☆"],
87         ),
88         inquirer.Text("format", message="What format did you read it in?"),
89     ]
90
91     answers = inquirer.prompt(other_questions)
92     format = answers["format"]
93
94     rating = int(answers["rating"].count("★"))
95     assert 1 <= rating <= 5
96
97     if rating > 3:
98         did_not_finish = False
99     else:
100         questions = [
101             inquirer.List(
102                 "did_you_finish",
103                 message="Did you finish the book?",
104                 choices=["yes", "no"],
105             ),
106         ]
107
108         answers["did_you_finish"] = inquirer.prompt(questions)["did_you_finish"] == "no"
109
110     return {
111         "date_read": date_read,
112         "rating": rating,
113         "format": format,
114         "did_not_finish": did_not_finish,
115     }
116
117
118 def save_cover(slug, cover_image_url):
119     filename, _ = urlretrieve(cover_image_url)
120
121     url_path = hyperlink.URL.from_text(cover_image_url).path
122     extension = os.path.splitext(url_path[-1])[-1]
123     cover_name = f"{slug}{extension}"
124     os.rename(filename, f"src/covers/{cover_name}")
125
126     return cover_name
127
128
129 if __name__ == "__main__":
130     book_info = get_book_info()
131
132     slug = slugify(book_info["title"])
133
134     cover_name = save_cover(slug=slug, cover_image_url=book_info["cover_image_url"])
135
136     new_entry = {
137         "book": {
138             "title": book_info["title"],
139             "author": book_info["author"],
140             "publication_year": book_info["publication_year"],
141             "cover_image": cover_name,
142         }
143     }
144
145     for key in ("cover_desc", "isbn10", "isbn13"):
146         if book_info[key]:
147             new_entry["book"][key] = book_info[key]
148
149     if book_info["entry_type"] == "reviews":
150         review_info = get_review_info()
151
152         new_entry["review"] = {
153             "date_read": review_info["date_read"],
154             "rating": review_info["rating"],
155             "format": review_info["format"],
156         }
157
158         if review_info["did_not_finish"]:
159             new_entry["review"]["did_not_finish"] = True
160
161         year = review_info["date_read"][:4]
162         out_dir = f"reviews/{year}"
163     else:
164         out_dir = book_info["entry_type"]
165
166     out_path = os.path.join("src", out_dir, f"{slug}.md")
167     os.makedirs(os.path.dirname(out_path), exist_ok=True)
168
169     with open(out_path, "wb") as out_file:
170         frontmatter.dump(frontmatter.Post(content="", **new_entry), out_file)
171         out_file.write(b"\n")
172
173     subprocess.check_call(["open", out_path])