/
se_epub.py
1011 lines (774 loc) · 34.1 KB
/
se_epub.py
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Defines the SeEpub class, the master class for representing and operating on
Standard Ebooks epub3 files.
"""
import os
import html
import tempfile
import shutil
import fnmatch
import datetime
from pathlib import Path
import concurrent.futures
import base64
import subprocess
import regex
import git
from bs4 import Tag, BeautifulSoup
import se
import se.formatting
import se.easy_xml
import se.images
def _process_endnotes_in_file(filename: str, root: Path, note_range: range, step: int) -> None:
"""
Helper function for reordering endnotes.
This has to be outside of the class to be able to be called by `executor`.
"""
with open(root / filename, "r+", encoding="utf-8") as file:
xhtml = file.read()
processed_xhtml = xhtml
processed_xhtml_is_modified = False
for endnote_number in note_range:
# If we’ve already changed some notes and can’t find the next then we don’t need to continue searching
if not "id=\"noteref-{}\"".format(endnote_number) in processed_xhtml and processed_xhtml_is_modified:
break
processed_xhtml = processed_xhtml.replace("id=\"noteref-{}\"".format(endnote_number), "id=\"noteref-{}\"".format(endnote_number + step), 1)
processed_xhtml = processed_xhtml.replace("#note-{}\"".format(endnote_number), "#note-{}\"".format(endnote_number + step), 1)
processed_xhtml = processed_xhtml.replace(">{}</a>".format(endnote_number), ">{}</a>".format(endnote_number + step), 1)
processed_xhtml_is_modified = processed_xhtml_is_modified or (processed_xhtml != xhtml)
if processed_xhtml_is_modified:
file.seek(0)
file.write(processed_xhtml)
file.truncate()
class GitCommit:
"""
Object used to represent the last Git commit.
"""
short_sha = ""
timestamp = None
def __init__(self, short_sha: str, timestamp: datetime.datetime):
self.short_sha = short_sha
self.timestamp = timestamp
class Endnote:
"""
Class to hold information on endnotes
"""
number = 0
anchor = ""
contents = [] # The strings and tags inside an <li> element
back_link = ""
source_file = ""
matched = False
class SeEpub:
"""
An object representing an SE epub file.
An SE epub can have various operations performed on it, including recomposing and linting.
"""
path = ""
metadata_file_path = None
metadata_xhtml = None
__metadata_tree = None
_generated_identifier = None
_generated_github_repo_url = None
_last_commit = None # GitCommit object
__endnotes_soup = None # bs4 soup object of the endnotes.xhtml file
_endnotes = None # List of Endnote objects
def __init__(self, epub_root_directory: str):
try:
self.path = Path(epub_root_directory).resolve()
if not self.path.is_dir():
raise se.InvalidSeEbookException("Not a directory: {}".format(self.path))
with open(self.path / "src" / "META-INF" / "container.xml", "r", encoding="utf-8") as file:
container_tree = se.easy_xml.EasyXmlTree(file.read())
self.metadata_file_path = self.path / "src" / container_tree.xpath("//container:container/container:rootfiles/container:rootfile[@media-type=\"application/oebps-package+xml\"]/@full-path")[0]
with open(self.metadata_file_path, "r", encoding="utf-8") as file:
self.metadata_xhtml = file.read()
if "<dc:identifier id=\"uid\">url:https://standardebooks.org/ebooks/" not in self.metadata_xhtml:
raise se.InvalidSeEbookException
except:
raise se.InvalidSeEbookException("Not a Standard Ebooks source directory: {}".format(self.path))
@property
def last_commit(self) -> GitCommit:
"""
Accessor
"""
if not self._last_commit:
# We use git command instead of using gitpython's commit object because we want the short hash
try:
# We have to clear this environmental variable or else GitPython will think the repo is "." instead
# of the dir we actually pass, if we're called from a git hook (like post-receive).
# See https://stackoverflow.com/questions/42328426/gitpython-not-working-from-git-hook
if 'GIT_DIR' in os.environ:
del os.environ['GIT_DIR']
git_command = git.cmd.Git(self.path)
output = git_command.show("-s", "--format=%h %ct", "HEAD").split()
self._last_commit = GitCommit(output[0], datetime.datetime.fromtimestamp(int(output[1]), datetime.timezone.utc))
except Exception:
self._last_commit = None
return self._last_commit
@property
def generated_identifier(self) -> str:
"""
Accessor
Generate an SE identifer based on the metadata in the metadata file.
"""
if not self._generated_identifier:
# Add authors
identifier = "url:https://standardebooks.org/ebooks/"
authors = []
for author in self._metadata_tree.xpath("//dc:creator"):
authors.append(author.inner_html())
identifier += se.formatting.make_url_safe(author.inner_html()) + "_"
identifier = identifier.strip("_") + "/"
# Add title
for title in self._metadata_tree.xpath("//dc:title[@id=\"title\"]"):
identifier += se.formatting.make_url_safe(title.inner_html()) + "/"
# For contributors, we add both translators and illustrators.
# However, we may not include specific translators or illustrators in certain cases, namely
# if *some* contributors have a `display-seq` property, and others do not.
# According to the epub spec, if that is the case, we should only add those that *do* have the attribute.
# By SE convention, any contributor with `display-seq == 0` will be excluded from the identifier string.
translators = []
illustrators = []
translators_have_display_seq = False
illustrators_have_display_seq = False
for role in self._metadata_tree.xpath("//opf:meta[@property=\"role\"]"):
contributor_id = role.attribute("refines").lstrip("#")
contributor_element = self._metadata_tree.xpath("//dc:contributor[@id=\"" + contributor_id + "\"]")
if contributor_element:
contributor = {"name": contributor_element[0].inner_html(), "include": True, "display_seq": None}
display_seq = self._metadata_tree.xpath("//opf:meta[@property=\"display-seq\"][@refines=\"#" + contributor_id + "\"]")
if display_seq and int(display_seq[0].inner_html()) == 0:
contributor["include"] = False
display_seq = None
if role.inner_html() == "trl":
if display_seq:
contributor["display_seq"] = display_seq[0]
translators_have_display_seq = True
translators.append(contributor)
if role.inner_html() == "ill":
if display_seq:
contributor["display_seq"] = display_seq[0]
illustrators_have_display_seq = True
illustrators.append(contributor)
for translator in translators:
if (not translators_have_display_seq and translator["include"]) or translator["display_seq"]:
identifier += se.formatting.make_url_safe(translator["name"]) + "_"
if translators:
identifier = identifier.strip("_") + "/"
for illustrator in illustrators:
if (not illustrators_have_display_seq and illustrator["include"]) or illustrator["display_seq"]:
identifier += se.formatting.make_url_safe(illustrator["name"]) + "_"
identifier = identifier.strip("_/")
self._generated_identifier = identifier
return self._generated_identifier
@property
def generated_github_repo_url(self) -> str:
"""
Accessor
Generate a GitHub repository URL based on the *generated* SE identifier,
*not* the SE identifier in the metadata file.
INPUTS
None
OUTPUTS
A string representing the GitHub repository URL (capped at maximum 100 characters).
"""
if not self._generated_github_repo_url:
self._generated_github_repo_url = "https://github.com/standardebooks/" + self.generated_identifier.replace("url:https://standardebooks.org/ebooks/", "").replace("/", "_")[0:100]
return self._generated_github_repo_url
@property
def _endnotes_soup(self) -> BeautifulSoup:
"""
Accessor
Return a BeautifulSoup object representing the endnotes.xhtml file for this ebook.
INPUTS
None
OUTPUTS
A BeautifulSoup object representing the endnotes.xhtml file for this ebook.
"""
if not self.__endnotes_soup:
try:
with open(self.path / "src" / "epub" / "text" / "endnotes.xhtml") as file:
self.__endnotes_soup = BeautifulSoup(file.read(), "html.parser")
except:
raise se.InvalidFileException("Could't open file: {}".format(str(self.path / "src" / "epub" / "text" / "endnotes.xhtml")))
return self.__endnotes_soup
@property
def endnotes(self) -> list:
"""
Accessor
Return a list of Endnote objects representing the endnotes.xhtml file for this ebook.
INPUTS
None
OUTPUTS
A list of Endnote objects representing the endnotes.xhtml file for this ebook.
"""
if not self._endnotes:
self._endnotes = []
ol_tag: BeautifulSoup = self._endnotes_soup.find("ol")
items = ol_tag.find_all("li")
for item in items:
note = Endnote()
note.contents = []
for content in item.contents:
note.contents.append(content)
if isinstance(content, Tag):
links = content.find_all("a")
for link in links:
epub_type = link.get("epub:type") or ""
if epub_type == "backlink":
href = link.get("href") or ""
if href:
note.back_link = href
note.anchor = item.get("id") or ""
self._endnotes.append(note)
return self._endnotes
@property
def _metadata_tree(self) -> se.easy_xml.EasyXmlTree:
"""
Accessor
"""
if self.__metadata_tree is None:
try:
self.__metadata_tree = se.easy_xml.EasyXmlTree(self.metadata_xhtml)
except Exception as ex:
raise se.InvalidSeEbookException("Couldn’t parse {}: {}".format(self.metadata_file_path, ex))
return self.__metadata_tree
@staticmethod
def _new_bs4_tag(section: Tag, output_soup: BeautifulSoup) -> Tag:
"""
Helper function used in self._recompose_xhtml()
Create a new BS4 tag given the current section.
INPUTS
section: A BS4 tag
output_soup: A BS4 object representing the entire soup
OUTPUTS
A new BS4 tag.
"""
tag = output_soup.new_tag(section.name)
for name, value in section.attrs.items():
tag.attrs[name] = value
return tag
def _recompose_xhtml(self, section: Tag, output_soup: BeautifulSoup) -> None:
"""
Helper function used in self.recompose()
Recursive function for recomposing a series of XHTML files into a single XHTML file.
INPUTS
section: A BS4 tag to inspect
output_soup: A BS4 object representing the entire soup
OUTPUTS
None
"""
# Quick sanity check before we begin
if "id" not in section.attrs or (section.parent.name.lower() != "body" and "id" not in section.parent.attrs):
raise se.InvalidXhtmlException("Section without ID attribute.")
# Try to find our parent tag in the output, by ID.
# If it's not in the output, then append it to the tag's closest parent by ID (or <body>), then iterate over its children and do the same.
existing_section = output_soup.select("#" + section["id"])
if not existing_section:
if section.parent.name.lower() == "body":
output_soup.body.append(self._new_bs4_tag(section, output_soup))
else:
output_soup.select("#" + section.parent["id"])[0].append(self._new_bs4_tag(section, output_soup))
existing_section = output_soup.select("#" + section["id"])
for child in section.children:
if not isinstance(child, str):
tag_name = child.name.lower()
if tag_name in ("section", "article"):
self._recompose_xhtml(child, output_soup)
else:
existing_section[0].append(child)
def recompose(self) -> str:
"""
Iterate over the XHTML files in this epub and "recompose" them into a single HTML5 string representing this ebook.
INPUTS
None
OUTPUTS
A string of HTML5 representing the entire recomposed ebook.
"""
# Get the ordered list of spine items
with open(self.metadata_file_path, "r", encoding="utf-8") as file:
metadata_soup = BeautifulSoup(file.read(), "lxml")
# Get some header data: title, core and local css
title = html.escape(metadata_soup.find("dc:title").contents[0])
css = ""
with open(self.path / "src" / "epub" / "css" / "core.css", "r", encoding="utf-8") as file:
css = regex.sub(r"@.+?;", "", file.read()).strip()
with open(self.path / "src" / "epub" / "css" / "local.css", "r", encoding="utf-8") as file:
css = css + "\n\n\n/* local.css */" + regex.sub(r"@.+?;", "", file.read())
css = "\t\t\t".join(css.splitlines(True))
output_xhtml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:epub=\"http://www.idpf.org/2007/ops\" epub:prefix=\"z3998: http://www.daisy.org/z3998/2012/vocab/structure/, se: https://standardebooks.org/vocab/1.0\"><head><meta charset=\"utf-8\"/><title>" + title + "</title><style/></head><body></body></html>"
output_soup = BeautifulSoup(output_xhtml, "lxml")
# Iterate over spine items in order and recompose them into our output
for element in metadata_soup.select("spine itemref"):
filename = metadata_soup.select("item[id=\"{}\"]".format(element["idref"]))[0]["href"]
with open(self.path / "src" / "epub" / filename, "r", encoding="utf-8") as file:
xhtml_soup = BeautifulSoup(file.read(), "lxml")
for child in xhtml_soup.select("body > *"):
self._recompose_xhtml(child, output_soup)
# Add the ToC after the titlepage
with open(self.path / "src" / "epub" / "toc.xhtml", "r", encoding="utf-8") as file:
toc_soup = BeautifulSoup(file.read(), "lxml")
output_soup.select("#titlepage")[0].insert_after(toc_soup.find("nav"))
# Get the output XHTML as a string
output_xhtml = str(output_soup)
output_xhtml = regex.sub(r"\"(\.\./)?text/(.+?)\.xhtml\"", "\"#\\2\"", output_xhtml)
output_xhtml = regex.sub(r"\"(\.\./)?text/.+?\.xhtml#(.+?)\"", "\"#\\2\"", output_xhtml)
# Replace SVG images hrefs with inline SVG
for match in regex.findall(r"src=\"../images/(.+?)\.svg\"", output_xhtml):
with open(self.path / "src" / "epub" / "images" / (match + ".svg"), "r", encoding="utf-8") as file:
svg = file.read()
# Remove XML declaration
svg = regex.sub(r"<\?xml.+?\?>", "", svg)
output_xhtml = regex.sub(r"<img.+?src=\"\.\./images/{}\.svg\".*?/>".format(match), svg, output_xhtml)
with tempfile.NamedTemporaryFile(mode="w+", delete=False) as file:
file.write(output_xhtml)
file_name = Path(file.name)
file_name_xhtml = Path(str(file_name) + ".xhtml")
file_name.rename(file_name_xhtml)
# All done, clean the output
se.formatting.format_xhtml_file(file_name_xhtml, False, False, file_name_xhtml.name == "endnotes.xhtml", file_name_xhtml.name == "colophon.xhtml")
with open(file_name_xhtml, "r", encoding="utf-8") as file:
xhtml = file.read()
# Remove xml declaration and re-add the doctype
xhtml = regex.sub(r"<\?xml.+?\?>", "<!doctype html>", xhtml)
xhtml = regex.sub(r" epub:prefix=\".+?\"", "", xhtml)
# Insert our CSS. We do this after `clean` because `clean` will escape > in the CSS
xhtml = regex.sub(r"<style/>", "<style>\n\t\t\t" + css + "\t\t</style>", xhtml)
# Make some replacements for HTML5 compatibility
xhtml = xhtml.replace("epub:type", "data-epub-type")
xhtml = xhtml.replace("epub|type", "data-epub-type")
xhtml = xhtml.replace("xml:lang", "lang")
xhtml = xhtml.replace("<html", "<html lang=\"{}\"".format(metadata_soup.find("dc:language").string))
xhtml = regex.sub(" xmlns.+?=\".+?\"", "", xhtml)
file_name_xhtml.unlink()
return xhtml
def generate_titlepage_svg(self) -> None:
"""
Generate a distributable titlepage SVG in ./src/epub/images/ based on the titlepage file in ./images/
INPUTS
None
OUTPUTS
None.
"""
try:
inkscape_path = Path(shutil.which("inkscape"))
except Exception:
raise se.MissingDependencyException("Couldn’t locate Inkscape. Is it installed?")
source_images_directory = self.path / "images"
source_titlepage_svg_filename = source_images_directory / "titlepage.svg"
dest_images_directory = self.path / "src" / "epub" / "images"
dest_titlepage_svg_filename = dest_images_directory / "titlepage.svg"
if source_titlepage_svg_filename.is_file():
# Convert text to paths
# inkscape adds a ton of crap to the SVG and we clean that crap a little later.
# Path arguments must be cast to string for Windows compatibility.
subprocess.run([str(inkscape_path), str(source_titlepage_svg_filename), "--without-gui", "--export-text-to-path", "--export-plain-svg", str(dest_titlepage_svg_filename)])
se.images.format_inkscape_svg(dest_titlepage_svg_filename)
# For the titlepage we want to remove all styles, since they are not used anymore
with open(dest_titlepage_svg_filename, "r+", encoding="utf-8") as file:
svg = regex.sub(r"<style.+?</style>[\n\t]+", "", file.read(), flags=regex.DOTALL)
file.seek(0)
file.write(svg)
file.truncate()
def generate_cover_svg(self) -> None:
"""
Generate a distributable cover SVG in ./src/epub/images/ based on the cover file in ./images/
INPUTS
None
OUTPUTS
None.
"""
inkscape_path = shutil.which("inkscape")
if inkscape_path is None:
raise se.MissingDependencyException("Couldn’t locate Inkscape. Is it installed?")
source_images_directory = self.path / "images"
source_cover_jpg_filename = source_images_directory / "cover.jpg"
source_cover_svg_filename = source_images_directory / "cover.svg"
dest_images_directory = self.path / "src" / "epub" / "images"
dest_cover_svg_filename = dest_images_directory / "cover.svg"
# Create output directory if it doesn't exist
dest_images_directory.mkdir(parents=True, exist_ok=True)
# Remove useless metadata from cover source files
for root, _, filenames in os.walk(source_images_directory):
for filename in fnmatch.filter(filenames, "cover.source.*"):
se.images.remove_image_metadata(Path(root) / filename)
if source_cover_jpg_filename.is_file():
se.images.remove_image_metadata(source_cover_jpg_filename)
if source_cover_svg_filename.is_file():
# base64 encode cover.jpg
with open(source_cover_jpg_filename, "rb") as file:
source_cover_jpg_base64 = base64.b64encode(file.read()).decode()
# Convert text to paths
# Inkscape adds a ton of crap to the SVG and we clean that crap a little later
subprocess.run([str(inkscape_path), str(source_cover_svg_filename), "--without-gui", "--export-text-to-path", "--export-plain-svg", str(dest_cover_svg_filename)])
# Embed cover.jpg
with open(dest_cover_svg_filename, "r+", encoding="utf-8") as file:
svg = regex.sub(r"xlink:href=\".*?cover\.jpg", "xlink:href=\"data:image/jpeg;base64," + source_cover_jpg_base64, file.read(), flags=regex.DOTALL)
file.seek(0)
file.write(svg)
file.truncate()
se.images.format_inkscape_svg(dest_cover_svg_filename)
# For the cover we want to keep the path.title-box style, and add an additional
# style to color our new paths white
with open(dest_cover_svg_filename, "r+", encoding="utf-8") as file:
svg = regex.sub(r"<style.+?</style>", "<style type=\"text/css\">\n\t\tpath{\n\t\t\tfill: #fff;\n\t\t}\n\n\t\t.title-box{\n\t\t\tfill: #000;\n\t\t\tfill-opacity: .75;\n\t\t}\n\t</style>", file.read(), flags=regex.DOTALL)
file.seek(0)
file.write(svg)
file.truncate()
def reorder_endnotes(self, target_endnote_number: int, step: int = 1) -> None:
"""
Reorder endnotes starting at target_endnote_number.
INPUTS:
target_endnote_number: The endnote to start reordering at
step: 1 to increment or -1 to decrement
OUTPUTS:
None.
"""
increment = step == 1
endnote_count = 0
source_directory = self.path / "src"
try:
endnotes_filename = source_directory / "epub" / "text" / "endnotes.xhtml"
with open(endnotes_filename, "r+", encoding="utf-8") as file:
xhtml = file.read()
soup = BeautifulSoup(xhtml, "lxml")
endnote_count = len(soup.select("li[id^=note-]"))
if increment:
note_range = range(endnote_count, target_endnote_number - 1, -1)
else:
note_range = range(target_endnote_number, endnote_count + 1, 1)
for endnote_number in note_range:
xhtml = xhtml.replace("id=\"note-{}\"".format(endnote_number), "id=\"note-{}\"".format(endnote_number + step), 1)
xhtml = xhtml.replace("#noteref-{}\"".format(endnote_number), "#noteref-{}\"".format(endnote_number + step), 1)
# There may be some links within the notes that refer to other endnotes.
# These potentially need incrementing / decrementing too. This code assumes
# a link that looks something like <a href="#note-1">note 1</a>.
endnote_links = regex.findall(r"href=\"#note-(\d+)\"(.*?) (\d+)</a>", xhtml)
for link in endnote_links:
link_number = int(link[0])
if (link_number < target_endnote_number and increment) or (link_number > target_endnote_number and not increment):
continue
xhtml = xhtml.replace("href=\"#note-{0}\"{1} {0}</a>".format(link[0], link[1]), "href=\"#note-{0}\"{1} {0}</a>".format(link_number + step, link[1]))
file.seek(0)
file.write(xhtml)
file.truncate()
except Exception:
raise se.InvalidSeEbookException("Couldn’t open endnotes file: {}".format(endnotes_filename))
with concurrent.futures.ProcessPoolExecutor() as executor:
for root, _, filenames in os.walk(source_directory):
for filename in fnmatch.filter(filenames, "*.xhtml"):
# Skip endnotes.xhtml since we already processed it
if filename == "endnotes.xhtml":
continue
executor.submit(_process_endnotes_in_file, filename, Path(root), note_range, step)
def set_release_timestamp(self) -> None:
"""
If this ebook has not yet been released, set the first release timestamp in the metadata file.
"""
if "<dc:date>1900-01-01T00:00:00Z</dc:date>" in self.metadata_xhtml:
now = datetime.datetime.utcnow()
now_iso = regex.sub(r"\.[0-9]+$", "", now.isoformat()) + "Z"
now_iso = regex.sub(r"\+.+?Z$", "Z", now_iso)
now_friendly = "{0:%B %e, %Y, %l:%M <abbr class=\"time eoc\">%p</abbr>}".format(now)
now_friendly = regex.sub(r"\s+", " ", now_friendly).replace("AM", "a.m.").replace("PM", "p.m.").replace(" <abbr", " <abbr")
self.metadata_xhtml = regex.sub(r"<dc:date>[^<]+?</dc:date>", "<dc:date>{}</dc:date>".format(now_iso), self.metadata_xhtml)
self.metadata_xhtml = regex.sub(r"<meta property=\"dcterms:modified\">[^<]+?</meta>", "<meta property=\"dcterms:modified\">{}</meta>".format(now_iso), self.metadata_xhtml)
with open(self.metadata_file_path, "w", encoding="utf-8") as file:
file.seek(0)
file.write(self.metadata_xhtml)
file.truncate()
self.__metadata_tree = None
with open(self.path / "src" / "epub" / "text" / "colophon.xhtml", "r+", encoding="utf-8") as file:
xhtml = file.read()
xhtml = xhtml.replace("<b>January 1, 1900, 12:00 <abbr class=\"time eoc\">a.m.</abbr></b>", "<b>{}</b>".format(now_friendly))
file.seek(0)
file.write(xhtml)
file.truncate()
def update_flesch_reading_ease(self) -> None:
"""
Calculate a new reading ease for this ebook and update the metadata file.
Ignores SE boilerplate files like the imprint.
INPUTS
None
OUTPUTS
None.
"""
text = ""
for filename in se.get_target_filenames([self.path], (".xhtml")):
with open(filename, "r", encoding="utf-8") as file:
text += " " + file.read()
self.metadata_xhtml = regex.sub(r"<meta property=\"se:reading-ease\.flesch\">[^<]*</meta>", "<meta property=\"se:reading-ease.flesch\">{}</meta>".format(se.formatting.get_flesch_reading_ease(text)), self.metadata_xhtml)
with open(self.metadata_file_path, "w", encoding="utf-8") as file:
file.seek(0)
file.write(self.metadata_xhtml)
file.truncate()
def update_word_count(self) -> None:
"""
Calculate a new word count for this ebook and update the metadata file.
Ignores SE boilerplate files like the imprint, as well as any endnotes.
INPUTS
None
OUTPUTS
None.
"""
word_count = 0
for filename in se.get_target_filenames([self.path], (".xhtml")):
if filename.name == "endnotes.xhtml":
continue
with open(filename, "r", encoding="utf-8") as file:
word_count += se.formatting.get_word_count(file.read())
self.metadata_xhtml = regex.sub(r"<meta property=\"se:word-count\">[^<]*</meta>", "<meta property=\"se:word-count\">{}</meta>".format(word_count), self.metadata_xhtml)
with open(self.metadata_file_path, "r+", encoding="utf-8") as file:
file.seek(0)
file.write(self.metadata_xhtml)
file.truncate()
def generate_manifest(self) -> str:
"""
Return the <manifest> element for this ebook as an XML string.
INPUTS
None
OUTPUTS
An XML fragment string representing the manifest.
"""
manifest = []
# Add CSS
for _, _, filenames in os.walk(self.path / "src" / "epub" / "css"):
for filename in filenames:
manifest.append("<item href=\"css/{0}\" id=\"{0}\" media-type=\"text/css\"/>".format(filename))
# Add images
for _, _, filenames in os.walk(self.path / "src" / "epub" / "images"):
for filename in filenames:
media_type = "image/jpeg"
properties = ""
if filename.endswith(".svg"):
media_type = "image/svg+xml"
if filename.endswith(".png"):
media_type = "image/png"
if filename == "cover.svg":
properties = " properties=\"cover-image\""
manifest.append("<item href=\"images/{0}\" id=\"{0}\" media-type=\"{1}\"{2}/>".format(filename, media_type, properties))
# Add XHTML files
for root, _, filenames in os.walk(self.path / "src" / "epub" / "text"):
for filename in filenames:
# Skip dotfiles, because .DS_Store might be binary and then we'd crash when we try to read it below
if filename.startswith("."):
continue
properties = "properties=\""
with open(Path(root) / filename, "r", encoding="utf-8") as file:
file_contents = file.read()
if "http://www.w3.org/1998/Math/MathML" in file_contents:
properties += "mathml "
if ".svg" in file_contents:
properties += "svg "
properties = " " + properties.strip() + "\""
if properties == " properties=\"\"":
properties = ""
manifest.append("<item href=\"text/{0}\" id=\"{0}\" media-type=\"application/xhtml+xml\"{1}/>".format(filename, properties))
manifest = se.natural_sort(manifest)
manifest_xhtml = "<manifest>\n\t<item href=\"toc.xhtml\" id=\"toc.xhtml\" media-type=\"application/xhtml+xml\" properties=\"nav\"/>\n"
for line in manifest:
manifest_xhtml = manifest_xhtml + "\t" + line + "\n"
manifest_xhtml = manifest_xhtml + "</manifest>"
return manifest_xhtml
def generate_spine(self) -> str:
"""
Return the <spine> element of this ebook as an XML string, with a best guess as to the correct order. Manual review is required.
INPUTS
None
OUTPUTS
An XML fragment string representing the spine.
"""
excluded_files = se.IGNORED_FILENAMES + ["dedication.xhtml", "introduction.xhtml", "foreword.xhtml", "preface.xhtml", "epigraph.xhtml", "endnotes.xhtml"]
spine = ["<itemref idref=\"titlepage.xhtml\"/>", "<itemref idref=\"imprint.xhtml\"/>"]
filenames = se.natural_sort(os.listdir(self.path / "src" / "epub" / "text"))
if "dedication.xhtml" in filenames:
spine.append("<itemref idref=\"dedication.xhtml\"/>")
if "introduction.xhtml" in filenames:
spine.append("<itemref idref=\"introduction.xhtml\"/>")
if "foreword.xhtml" in filenames:
spine.append("<itemref idref=\"foreword.xhtml\"/>")
if "preface.xhtml" in filenames:
spine.append("<itemref idref=\"preface.xhtml\"/>")
if "epigraph.xhtml" in filenames:
spine.append("<itemref idref=\"epigraph.xhtml\"/>")
if "halftitle.xhtml" in filenames:
spine.append("<itemref idref=\"halftitle.xhtml\"/>")
for filename in filenames:
if filename not in excluded_files:
spine.append("<itemref idref=\"{}\"/>".format(filename))
if "endnotes.xhtml" in filenames:
spine.append("<itemref idref=\"endnotes.xhtml\"/>")
if "loi.xhtml" in filenames:
spine.append("<itemref idref=\"loi.xhtml\"/>")
spine.append("<itemref idref=\"colophon.xhtml\"/>")
spine.append("<itemref idref=\"uncopyright.xhtml\"/>")
spine_xhtml = "<spine>\n"
for line in spine:
spine_xhtml = spine_xhtml + "\t" + line + "\n"
spine_xhtml = spine_xhtml + "</spine>"
return spine_xhtml
def get_content_files(self) -> list:
"""
Reads the spine from content.opf to obtain a list of content files, in the order wanted for the ToC.
It assumes this has already been manually ordered by the producer.
INPUTS:
None
OUTPUTS:
list of content files in the order given in the spine in content.opf
"""
return regex.findall(r"<itemref idref=\"(.*?)\"/>", self.metadata_xhtml)
def get_work_type(self) -> str:
"""
Returns either "fiction" or "non-fiction", based on analysis of se:subjects in content.opf
INPUTS:
None
OUTPUTS:
The fiction or non-fiction type
"""
worktype = "fiction" # default
subjects = regex.findall(r"<meta property=\"se:subject\">([^<]+?)</meta>", self.metadata_xhtml)
if not subjects:
return worktype
# Unfortunately, some works are tagged "Philosophy" but are nevertheless fiction, so we have to double-check
if "Nonfiction" in subjects:
return "non-fiction"
nonfiction_types = ["Adventure", "Autobiography", "Memoir", "Philosophy", "Spirituality", "Travel"]
for nonfiction_type in nonfiction_types:
if nonfiction_type in subjects:
worktype = "non-fiction"
fiction_types = ["Fantasy", "Fiction", "Horror", "Mystery", "Science Fiction"]
for fiction_type in fiction_types:
if fiction_type in subjects:
worktype = "fiction"
return worktype
def get_work_title(self) -> str:
"""
Returns the title of the book from content.opf, which we assume has already been correctly completed.
INPUTS:
None
OUTPUTS:
Either the title of the book or the default WORKING_TITLE
"""
match = regex.search(r"<dc:title(?:.*?)>(.*?)</dc:title>", self.metadata_xhtml)
if match:
dc_title = match.group(1)
else:
dc_title = "WORK_TITLE" # default
return dc_title
def lint(self) -> list:
"""
The lint() function is very big so for readability and maintainability
it's broken out to a separate file. Strictly speaking that file can be inlined
into this class.
"""
from se.se_epub_lint import lint
return lint(self, self.metadata_xhtml)
def build(self, run_epubcheck: bool, build_kobo: bool, build_kindle: bool, output_directory: Path, proof: bool, build_covers: bool, verbose: bool):
"""
The build() function is very big so for readability and maintainability
it's broken out to a separate file. Strictly speaking that file can be inlined
into this class.
"""
from se.se_epub_build import build
build(self, self.metadata_xhtml, self._metadata_tree, run_epubcheck, build_kobo, build_kindle, output_directory, proof, build_covers, verbose)
def generate_toc(self) -> str:
"""
The generate_toc() function is very big so for readability and maintainability
it's broken out to a separate file. Strictly speaking that file can be inlined
into this class.
"""
from se.se_epub_generate_toc import generate_toc
return generate_toc(self)
def generate_endnotes(self) -> str:
"""
Read the epub spine to regenerate all endnotes in order of appearance, starting from 1.
Changes are written to disk.
"""
processed = 0
report = ""
current_note_number = 1
notes_changed = 0
change_list = []
for file_name in self.get_content_files():
if file_name in ["titlepage.xhtml", "colophon.xhtml", "uncopyright.xhtml", "imprint.xhtml", "halftitle.xhtml", "endnotes.xhtml"]:
continue
processed += 1
file_path = self.path / "src" / "epub" / "text" / file_name
try:
with open(file_path) as file:
soup = BeautifulSoup(file.read(), "lxml")
except:
raise se.InvalidFileException("Could't open file: {}".format(str(file_path)))
links = soup.find_all("a")
needs_rewrite = False
for link in links:
epub_type = link.get("epub:type") or ""
if epub_type == "noteref":
old_anchor = ""
href = link.get("href") or ""
if href:
# Extract just the anchor from a URL (ie, what follows a hash symbol)
old_anchor = ""
hash_position = href.find("#") + 1 # we want the characters AFTER the hash
if hash_position > 0:
old_anchor = href[hash_position:]
new_anchor = "note-{:d}".format(current_note_number)
if new_anchor != old_anchor:
change_list.append("Changed " + old_anchor + " to " + new_anchor + " in " + file_name)
notes_changed += 1
# Update the link in the soup object
link["href"] = 'endnotes.xhtml#' + new_anchor
link["id"] = 'noteref-{:d}'.format(current_note_number)
link.string = str(current_note_number)
needs_rewrite = True
# Now try to find this in endnotes
matches = list(filter(lambda x, old=old_anchor: x.anchor == old, self.endnotes))
if not matches:
raise se.InvalidInputException("Couldn't find endnote with anchor " + old_anchor)
if len(matches) > 1:
raise se.InvalidInputException("Duplicate anchors in endnotes file for anchor " + old_anchor)
# Found a single match, which is what we want
endnote = matches[0]
endnote.number = current_note_number
endnote.matched = True
# We don't change the anchor or the back ref just yet
endnote.source_file = file_name
current_note_number += 1
# If we need to write back the body text file
if needs_rewrite:
new_file = open(file_path, "w")
new_file.write(se.formatting.format_xhtml(str(soup)))
new_file.close()
if processed == 0:
report += "No files processed. Did you update the manifest and order the spine?" + "\n"
else:
report += "Found {:d} endnotes.".format(current_note_number - 1) + "\n"
if notes_changed > 0:
# Now we need to recreate the endnotes file
ol_tag = self._endnotes_soup.ol
ol_tag.clear()
self.endnotes.sort(key=lambda endnote: endnote.number)
for endnote in self.endnotes:
if endnote.matched:
li_tag = self._endnotes_soup.new_tag("li")
li_tag["id"] = "note-" + str(endnote.number)
li_tag["epub:type"] = "endnote"
for content in endnote.contents:
if isinstance(content, Tag):
links = content.find_all("a")
for link in links:
epub_type = link.get("epub:type") or ""
if epub_type == "backlink":
href = link.get("href") or ""
if href:
link["href"] = endnote.source_file + "#noteref-" + str(endnote.number)