forked from standardebooks/web
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinject-chapter-navigation-footer
executable file
·57 lines (41 loc) · 2.41 KB
/
inject-chapter-navigation-footer
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
#!/usr/bin/env python3
import argparse
import html
import os
import se
import se.easy_xml
import se.se_epub
# Require arguments
parser = argparse.ArgumentParser(description="A script to inject the navigation footer with links in the web version of a Standard Ebook")
parser.add_argument("ebook_dir", type=str, help="Path to the main directory of the ebook") # No trailing "/" on this path
parser.add_argument("book_url", type=str, help="The ebook URL") # No trailing "/" on this link
args = parser.parse_args()
ebook_dir = args.ebook_dir
book_url = args.book_url
# Make an instance of the SeEpub class so we can use helper functions to easily get spine
se_epub = se.se_epub.SeEpub(ebook_dir)
# Get spine paths
spine_paths = se_epub.spine_file_paths
# Make sure spine paths are of the form "text/chapter-1.xhtml", with no leading "/"
rel_spine_paths = ["/".join(str(path).split("/")[str(path).split("/").index("text"):]).lstrip("/") for path in spine_paths]
# Get titles from spine
spine_titles = [se.easy_xml.EasyXmlTree(open(file_path).read()).xpath("//head/title/text()", True) for file_path in spine_paths]
# Make list of dicts containing title and relative path for each file
chapter_links = [{"title": title, "path": path} for title, path in zip(spine_titles, rel_spine_paths)]
# Create helper function for getting filename without extension
def get_filename_without_extension(dict_with_path):
return os.path.splitext(dict_with_path["path"])[0] if dict_with_path else ""
# Create footers
for i, chapter_link in enumerate(chapter_links):
previous_dict = chapter_links[i - 1] if i > 0 else None
next_dict = chapter_links[i + 1] if i < len(chapter_links) - 1 else None
file_path = os.path.join(ebook_dir, "src/epub", chapter_link["path"])
previous_link_filename, next_link_filename = [get_filename_without_extension(chapter_dict) for chapter_dict in [previous_dict, next_dict]]
with open(file_path, "r") as file:
chapter = file.read()
previous_link = f"""<a href="{book_url}/{previous_link_filename}" rel="prev"><i>Previous:</i> {html.escape(previous_dict["title"])}</a>""" if previous_dict else ""
next_link = f"""<a href="{book_url}/{next_link_filename}" rel="next"><i>Next:</i> {html.escape(next_dict["title"])}</a>""" if next_dict else ""
footer = f"<footer><ul><li>{previous_link}</li><li>{next_link}</li></ul></footer>"
chapter = chapter.replace("</body>", f"{footer}</body>")
with open(file_path, "w") as file:
file.write(chapter)