-
Notifications
You must be signed in to change notification settings - Fork 1
/
epubpager.py
2537 lines (2250 loc) · 97.5 KB
/
epubpager.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
import sys
import shutil
from subprocess import PIPE, run
import time
from pathlib import Path
import typing
import urllib.parse
import io
import zipfile
CR = "\n"
opf_dictkey = "package"
pglnk = "pagetb"
epubns = 'xmlns:epub="http://www.idpf.org/2007/ops"'
pg_xmlns = f'<nav {epubns} epub:type="page-list" id="page-list" hidden="hidden"><ol> \n'
comment_epubpager ="This epub was modified by epubpager https://github.com/tthkbw/epub_pager "
has_echk = True
try:
from epubcheck import EpubCheck
echk_message = "epubcheck module is present."
except ModuleNotFoundError:
echk_message = "epubcheck module was not found."
has_echk = False
class epub_paginator:
"""
Paginate an ePub3 using page-list navigation and/or inserting page
information pagelines and/or superscripts into the text.
pagelines appear as separately formatted lines in the text and may contain
current page, total pages in the book, and current chapter page and total
chapter pages. Pagelines are placed and the end of the paragraph where the
page break occurred.
Superscripts can contain the same information as pagelines, but the
information is presented at the exact location of the page break as a
superscript.
**Release Notes**
** Version 3.6**
1. Metadata added to opf file with words, pages, modified by epubpager notation.
2. Fixed a bug in logic that caused no pagination under circumstances where
pagination should have been done.
3. Added 'endp' as a format for pagelines. If selected, then no new
paragraph is created for the pageline, it is inserted at the end of the
paragraph in which the pagebreak occurs.
4. Fixed two problems where wrlog was called before logpath was setup and
caused fatal path errors.
TODO
**Version 3.5**
Done
1. Added a check to do nothing if the book has a plist and pagelines and
superscripts were not requested.
**Version 3.4**
1. Added quiet to the configuration. If set, nothing is echoed to stdout.
**Version 3.3**
1. prepare for release on GitHub.
**Version 3.2**
1. Added capability of not setting genplist, pageline or superscript and
epubpager will just convert, count words and count pages.
1. Refined how pagelinks and lines were inserted to be sure proper page
location worked. I think it did, but minor change made and operation
verified.
1. Generate an error if the original file removal fails.
**Version 3.1**
Finding bugs in 3.0
1. using the shell script to simplify cross-platform compatibility causes
problems with filenames with spaces. Copy the source_epub to a new filename
with spaces removed to fix this.
1. Oops! If the filename doesn't change when spaces are removed, then the
copy fails. Add '_orig' to the input epub filename.
1. By default, add xmlns locally to the added page-list element. Some files
do this locally and I find the naamespace and don't add my own. But since
the existing one is only local, my added pagelist is not recognized. Fixed
to scan only <html> element. this works for normal text files, i.e. files
with text for the book. For the nav file, we no longer use this scan and
add feature. Instead, just add locally to my page-list element.
**Version 3.0**
1. Shoot the engineer and ship the product.
1. Had the sense wrong on has_echk test. Now check self.epubcheck for
file.is_file rather than existence (which returns true if the string is
empty).
1. To facilitate compatibility across platforms, the epubcheck parameter
now points to an executable script that runs epubcheck and takes as input a
epub filename. Examples are included wit the distribution, epubcheck.sh for
unix and epubcheck.bat for Windows.
**Version 2.99**
1. Implement placing pagebreaks and supers at exact word position
with new scanning algorithm.
1. Fixed bug with enabling and disabling epubcheck. Must use "none" in the
config file for this to work properly.
1. Fixed bug with enabling and disabling epub convert. Without conversion,
epub2 books are now properly paginated.
1. Fixed a bug where some files in the manifest were url quoted. Used
urllib.parse.unquote() to fix this.
1. Append '_paged' to output file name so we don't inadvertently write over the input file.
1. Changed name of footer to pageline. Also, ft_ type variable names changed to 'pl'
1. Fixed a bug where the superscript, if colored, wasn't colored nor
a superscript. Left out a ';'
1. epubcheck is run with warnings disabled.
1. Fixed problems with reporting epubcheck results.
1. Fixed naming of logfile--appended _paged so it matches epub file name.
1. File names were changed to remove '_'.
1. Timing information added to rdict for epubcheck, epubconvert, and pagination times.
1. Fixed Windows error reading files. changed to read and write with
pathlib.read_text() and pathlib.write_text(). Although must be careful
since write_text() has no append mode. also verify that file paths ad opens
refer to Path objects
1. Changed from externally referenced epubcheck to the python module
epubcheck. If the module is not installed, disable checking and report in
log file.
1. Removed bkinfo dictionary and put all of the information in rdict.
1. Removed dependency on xmltodict. I parse all the xml myself.
1. Somewhere along the line, adding the pagelines with <div> . . . </div>
at the end of the paragraphs causes the next paragraph to not be indented.
This is caused by css that uses p+p, or paragraphs that follow paragraphs
get indentation, while those following headers, for example, do not.
Putting the pageline divs inside the paragraphs appears to display
properly, but generates epubcheck errors that they are misplaced. So, I now
just add '<p></p>' to the end of the pageline. This works, at least in
Sigil.
1. Tried various fixes for the problem of spacing after pagelines. The
obvious fix is now in. Just insert the pageline as a new paragraph with its
proper style, and margin of 0 0 0 0 specified. Removed the 'float' option in the
pageline format--too confusing and not worth it. Wasn't implemented in the
options anyway.
**Version 2.98**
1. Begin implmentation of new scanning algorithm. This algorithm
improves the scan by more than 5x. Same changes to scan_file,
count_words and scan_sections.
1. This version generates 750 paged ebooks from the library with no
fatal errors.
**Version 2.97**
1. Added chk_orig property to allow epubcheck to be run on original
file. Provide stats on errors for both original and paged epub file
results from epubcheck.
1. Added finding id="page-7" to searching for a page value in a
pagebreak element. A lot of books don't have a 'title' or
'aria-label' specification, or a displayable page number.
1. Changed epubcheck to not report warnings to simplify testing.
1. Made the page link id's more unique so we don't inadvertently get
duplicate ids of form id='page7' for example. I use pagetb as the
prefix now.
1. Added a fix for figuring out the relative href for page links
when opf_file and nav file are not at the same directory level.
1. Fixed books that have file names or paths that contain spaces,
commas, etc, which result in invalid URI in pagelists.
1. If a file in the spine contains 'toc' or 'contents', skip
counting words and inserting pagebreaks. This avoids lots of
epubcheck errors, even though those errors are benign.
1. Added chk_xmlns to fix namespace errors when we are adding a
page-list
**Version 2.96**
1. fixed a bug with calculating words per page when not matching and
total pages is provided.
**Version 2.95**
Fixing bugs and doing extensive testing with hundreds of epubs.
1. Fixed a problem with removing existing pagebreaks in a converted
epub2 book.
1. Parsed the epubcheck stdout to find Messages and report fatal and
other errors.
1. Fixed a problem where matching missed pages because it was
looking for a </span> afterthe epub:type="pagebreak" element.
Should look for '/>' instead.
1. Additional fixes that allow proper identification and handling of
epubs that use 'aria' features and don't have epub:type in
pagebreaks.
1. Major fix--we no longer scan and word count anything before
<body. Then, no pagelinks appear outside of <body and this makes
epubcheck happier.
1. When the epub:type page-list is added, also add the namespace
because it is not there sometimes and being repetitive doesn't
matter.
1. Fixed a bug where <span> was not removed correctly. Now checks
for /> as end of span rather than assuming </span> is the element
terminator.
**Version 2.94**
PEP8 compliant.
**Version 2.93**
1. Update Doc strings.
1. Refactor to eliminate globals--essentially move the class
statement to the top of the file and reference globals with self.
1. Fixed a bug that was looking for '/>' as the end of the pagebreak
element in scan and match routine. Should have been looking for
</span>.
**Version 2.92**
1. Can now match the superscript and pageline insertions to existing
page numbering. This is automatically done if a page-list exists
in the nav file.
**Version 2.91**
1. Lots of refactoring of code.
1. Added ebpub_info dictionary to consolidate data about the epub
file.
1. Added get_nav_pagecount() which determines the maximum page
number in an already paginated file.
**Version 2.9**
1. Add the role="doc-pagebreak" to the page links. This appears to
fix the bug that resulted in iBooks not showing all the page
numbers in the margin.
**Version 2.8**
1. Fixed a bug where the </span> was not removed when removing
existingn page links from a converted epub.
**Version 2.7**
1. Added rdict to return a set of data to the calling program,
including what used to go to stdout
**Version 2.6**
1. Fixed a bug in logic that removes pagebreak elements from
converted epub2 books.
**Version 2.5**
1. Implemented conversion of epub2 to epub3 using calibre
ebook-converter. epub_paginator contains command line switches
for all options to epub_pager.
**Version 2.4**
1. Implement configuration file.
**Version 2.3**
1. Add log file. Program produces minimal output, but puts data in
log file.
2. If running epubcheck, echo stdout to stdout, but echo stderr only
to the log file.
3. If DEBUG is False, remove the unzipped epub directory when done.
**Version 2.2**
1. Add epub_version exposed command to the class.
1. Fixed bug that mispositioned the pageline inside italic or other
textual html elements and caused epubcheck errors. pagelines are
now properly positioned apler the <div> or <p> active element
when the page limit is reached.
1. Refactored some of the code. Uses f strings for formatting;
cleaned up printing.
**Version 2.1**
1. Made a Github repository with a local copy.
1. Rewrote the scanning algorithm. Scans character by character
apler <body> element in spine files. Doesn't care about <p>
elements or anything else. Still places pagelines before paragraph
where the page ends. Other page numbering is at precise word
location.
1. Note that nested <div> elements are created by the placement of
pagelines and this creates errors in epubcheck. However, these
errors do not affect Calibre book reader, nor Apple Books.
**Version 2.0**
1. Includes Docstrings that are compatible with creating
documentation using pdoc.
1. Lot's of refactoring has been done.
1. Verifies epub3 version.
1. Verifies nav file exists.
1. Doesn't generate page-list if it already exists.
1. Adds chapter page numbering.
"""
version = "3.6"
curpg = 1 # current page number
tot_wcnt = 0 # count of total words in the book
pg_wcnt = 0 # word count per page
plist = "" # the page-list element for the nav file
bk_flist = [] # list of all files in the epub
logpath = Path() # path for the logfile
epub_file = "" # this will be the epub to paginate
rdict = {}
"""
rdict = { # data to return to calling program
"logfile": "", # logfile location and name a Path object
"bk_outfile": "", # modified epub file name and location a Path object
"unzip_path": "",
"title": "",
"nav_file": "None", # Path object pointing to navigation file in unzipped epub
"nav_item": "None",
"opf_file": "None", # path to opf file in zipfile, read with zipfile.read
"has_plist": False,
"spine_lst": [],
"words": 0,
"match": False,
"pgwords": 0,
"version": "no_version",
"converted": False, # if True, converted from epub2
"errors": [], # list of errors that occurred
"fatal": False, # Was there a fatal error?
"error": False, # epub_pager error
"warn": False, # epub_pager warning
"orig_fatal": 0, # epubcheck fatal error original file
"orig_error": 0, # epubcheck error original file
"orig_warn": 0, # epubcheck warning original file
"echk_fatal": 0, # epubcheck fatal error
"echk_error": 0, # epubcheck error
"convert_time": 0, # time to convert from epub2 to epub3
"paginate_time": 0, # time to paginate the epub
"epubchkpage_time": 0, # time to run epubcheck on paged epub
"epubchkorig_time": 0, # time to run epubcheck on original epub
"messages": "", # list of messages generated.
}
"""
def __init__(self):
# Instance Variables
"""
**Instance Variables**
**_outdir_**
full os path for placement of the paginated ePub file.
**_match_**
Boolean, if book is paginated, match super and pageline insertion
to existing page numbering. Default True
**_genplist_**
Create the page_list element in the navigation file.
**_pgwords_**
Number of words per page.
**_pages__**
Number of pages in the book.
**_pageline_**
Boolean, if True, insert the page pagelines, otherwise do not.
**_pl_align_**
lepl, right, or center, alignment of the page numbers in the
pageline.
**_pl_color_**
Optional color for the pageline--if not set, then no color is
used.
**_pl_bkt_**
Character (e.g. '<' or '(' ) used to bracket page numbers in
page pageline.
**_pl_fntsz_**
A percentage value for the relative font size used for the
pageline.
**_pl_pgtot_**
Present the book page number with a total (34/190) in the
pageline.
**_superscript_**
Insert a superscripted page entry
**_super_color_**
Optional color for the superscript--if not set, then no color is
used.
**_super_fntsz_**
A percentage value for the relative font size used for
superscript.
**_super_total_**
Present the book page number with a total (34/190) in
superscript.
**_chap_pgtot_**
Present the chapter page number and chapter page number total in
the pageline and/or superscript.
**_chap_bkt_**
Character (e.g. '<' or '(' ) used to bracket page numbers in
pageline and/or superscript.
**_ebookconvert_**
The OS path of the ebook conversion program. If present, epub2
books are converted to epub3 before pagination.
**_chk_orig_**
Run epubcheck on the file before pagination
**_chk_paged_**
Run epubcheck on the paged epub after pagination
**_quiet_**
Do not print anything to stdout.
**_DEBUG_**
Boolean. If True, print status and debug information to logile
while running.
"""
self.outdir = "/Users/tbrown/Documents/projects/" "BookTally/paged_epubs"
self.genplist = True
self.match = True
self.pgwords = 300
self.pages = 0
self.pageline = False
self.pl_align = "center"
self.pl_color = "red"
self.pl_bkt = "<"
self.pl_fntsz = "75%"
self.pl_pgtot = True
self.superscript = False
self.super_color = "red"
self.super_fntsz = "60%"
self.super_total = True
self.chap_pgtot = True
self.chap_bkt = "<"
self.ebookconvert = "none" # path to conversion executable
self.chk_orig = False
self.chk_paged = False
self.epubcheck = "none" # path to epubcheck executable
self.quiet = False
self.DEBUG = False
# the following two routines are modified from those on GitHub:
# https://github.com/MJAnand/epub/commit/8980928a74d2f761b2abdb8ef82a951be11b26d5
def ePubZip(self, epub_path, srcfiles_path, bk_flist):
"""
Zip files from a directory into an epub file
**Keyword arguments:**
**_epub_path_** -- os path for saving creating epub file
**_srcfiles_path_** -- path of the directory containing epub
files
**_bk_flist_** -- the list of files to zip into the epub file
"""
with zipfile.ZipFile(epub_path, "w") as myzip:
if "mimetype" in bk_flist:
mpath = srcfiles_path / "mimetype"
myzip.write(mpath, "mimetype")
# myzip.write(srcfiles_path + "/" + "mimetype", "mimetype")
bk_flist.remove("mimetype")
else:
self.wrlog(False, "Fatal error, no mimetype file was found.")
if self.DEBUG:
self.wrlog(False, "bk_flist: ")
self.wrlog(False, bk_flist)
sys.exit("Fatal error, no mimetype file was found.")
with zipfile.ZipFile(epub_path, "a", zipfile.ZIP_DEFLATED) as myzip:
for ifile in bk_flist:
myzip.write(f"{srcfiles_path}/{ifile}", ifile, zipfile.ZIP_DEFLATED)
def ePubUnZip(self, fileName, unzip_path):
"""
Unzip ePub file into a directory
**Keyword arguments:**
**_fileName_** -- the ePub file name
**_path_** -- path for the unzipped files.
"""
z = zipfile.ZipFile(fileName)
self.bk_flist = z.namelist()
z.extractall(unzip_path)
z.close()
def get_version(self):
"""
Return version of epub_pager.
"""
return self.version
def convert_epub(self):
"""
Called when epub is not version 3 and we have a convert program. Calls
convert. If successful points epub_file to the converted file. If
unsuccessful, throws a fatal error.
"""
ebconvert = Path(self.ebookconvert)
cnvrt_t1 = time.perf_counter()
self.wrlog(
True,
(f" Converting to epub3 using {ebconvert}"),
)
epub3_file = self.epub_file.replace(".epub", "_epub3.epub")
ebkcnvrt_cmd = [
ebconvert,
self.epub_file,
epub3_file,
"--epub-version",
"3",
]
result = run(
ebkcnvrt_cmd,
stdout=PIPE,
stderr=PIPE,
universal_newlines=True,
)
cnvrt_t2 = time.perf_counter()
self.rdict["convert_time"] = cnvrt_t2 - cnvrt_t1
self.wrlog(
True,
f" ebook-convert took {self.rdict['convert_time']:.2f} seconds.",
)
if result.returncode == 0:
self.wrlog(False, "Conversion log:")
self.wrlog(False, result.stdout)
self.epub_file = epub3_file
# now try again on version
v = self.get_epub_version(self.epub_file)
self.rdict["epub_version"] = v
if self.rdict["epub_version"] == "no_version":
estr = (
"Fatal error: After conversion, version was "
"not found in the ePub file."
)
self.wrlog(True, estr)
self.rdict["error_lst"].append(estr)
self.rdict["pager_error"] = True
return
lstr = f"Paginating epub3 file: {self.epub_file}"
self.wrlog(True, lstr)
self.plist = pg_xmlns
self.rdict["converted"] = True
else:
lstr = "Conversion to epub3 failed. Conversion reported:"
self.wrlog(False, lstr)
self.wrlog(False, result.stderr)
astr = "Fatal error: Conversion to epub3 failed."
self.rdict["error_lst"].append(astr)
self.rdict["pager_error"] = True
return
def initialize(self):
"""
Gather useful information about the epub file and put it in the
rdict dictionary.
**Instance Variables**
"""
# find the opf file using the META-INF/container.xml file
# operate from the unzipped epub
opf_file = self.find_opf(self.rdict["unzip_path"])
# Watch Out!!
self.rdict["opf_file"] = opf_file
if self.rdict["pager_error"]:
return
self.rdict["disk_path"] = ""
opf_path = opf_file.split("/")
if opf_path:
for index in range(0, len(opf_path) - 1):
self.rdict["disk_path"] += f"{opf_path[index]}/"
else:
self.rdict["pager_error"] = True
self.wrlog(False, "Fatal error: opf file not found")
return
opf_filep = Path(opf_file)
opfdata = opf_filep.read_text(encoding="utf-8")
self.parse_opf(opfdata)
def simple_epub_version(self) -> str:
# find the opf file using the META-INF/container.xml file
# operate from the unzipped epub
opf_file = self.find_opf(self.rdict["unzip_path"])
if self.rdict["pager_error"]:
return "no_version"
self.rdict["disk_path"] = ""
opf_path = opf_file.split("/")
if opf_path:
for index in range(0, len(opf_path) - 1):
self.rdict["disk_path"] += f"{opf_path[index]}/"
else:
self.rdict["pager_error"] = True
self.wrlog(False, "Fatal error: opf file not found")
return "no_version"
opf_filep = Path(opf_file)
opfdata = opf_filep.read_text(encoding="utf-8")
loc = opfdata.find("<package")
if loc != -1:
opfdata = opfdata[loc:]
vloc = opfdata.find("version")
if vloc != -1:
vlist = opfdata[vloc : vloc + 15].split('"')
eversion = vlist[1]
return eversion
else:
estr = "Fatal error: Did not find version string in opf file."
self.wrlog(False, estr)
self.rdict["error_lst"].append(estr)
self.rdict["pager_error"] = True
return "no version"
else:
estr = "Fatal error: Did not find package string in opf file."
self.rdict["error_lst"].append(estr)
self.rdict["pager_error"] = True
self.wrlog(False, estr)
return "no version"
def get_epub_version(self, epub_file):
"""
Return ePub version of ePub file
If ePub does not store the version information in the standard
location, return 'no version'
**Instance Variables**
**_epub_file_**
ePub file to return version of
"""
zfile = zipfile.ZipFile(epub_file)
# find the opf file, which contains the version information
contain_data = zfile.read("META-INF/container.xml")
contain_str = str(contain_data)
rloc = contain_str.find("<rootfiles>")
if rloc == -1:
self.wrlog(False, f"Did not find <rootfiles> in container.")
estr = "ABORTING: did not find <rootfiles> in container"
self.rdict["error_lst"].append(estr)
self.wrlog(False, estr)
self.wrlog(False, "Convert to ePub3 and try again.")
return "no_version"
contain_str = contain_str[rloc + 3 :]
rloc = contain_str.find("<rootfile")
if rloc == -1:
self.wrlog(False, f"Did not find <rootfile in container.")
estr = "ABORTING: did not find <rootfile in container"
self.rdict["error_lst"].append(estr)
self.wrlog(False, estr)
self.wrlog(False, "Convert to ePub3 and try again.")
return "no_version"
contain_str = contain_str[rloc + 3 :]
rloc = contain_str.find("full-path=")
if rloc == -1:
self.wrlog(False, f"Did not find full-path in container.")
estr = "ABORTING: did not find full-path in container"
self.rdict["error_lst"].append(estr)
self.wrlog(False, estr)
self.wrlog(False, "Convert to ePub3 and try again.")
return "no_version"
contain_str = contain_str[rloc + 3 :]
opflist = contain_str.split('"')
opf_file = opflist[1]
opf = zfile.read(opf_file)
opf_str = str(opf)
# first find the <package element
ploc = opf_str.find("<package")
if ploc == -1:
self.wrlog(
True, "get_epub_version: Did not find package string in opf file"
)
return "no version"
else:
# find the version= string
opf_str = opf_str[ploc:]
vloc = opf_str.find("version=")
if vloc == -1:
self.wrlog(
True, "get_epub_version: Did not find version string in opf file"
)
return "no version"
else:
vlist = opf_str[vloc : vloc + 15].split('"')
eversion = vlist[1]
return eversion
def get_nav_pagecount(self):
"""
Read the nav file and parse the page-list entries to find the
total pages in the book
**Instance Variables**
**_navfile_** -- ePub navigation file
"""
with self.rdict["nav_file"].open("r") as nav_r:
nav_data = nav_r.read()
loc = nav_data.find('epub:type="page-list"')
if loc == -1:
# this should never happen since we get here only after the entry
# was found
sys.exit(
(
"Error! oops, the page-list entry was not found "
"after having been initially found."
)
)
nav_data = nav_data[loc:]
not_done = True
max_page = 0
while not_done:
loc = nav_data.find("<a href")
if loc == -1:
not_done = False
continue
nav_data = nav_data[loc:]
loc = nav_data.find('">')
if loc == -1:
self.wrlog(False, "Unclosed '<a href' element in nav file.")
self.wrlog(False, "Does this file pass epubcheck?")
self.rdict["pager_error"] = True
return 0
loc += 2
nav_data = nav_data[loc:]
loc2 = nav_data.find("</a>")
if loc2 == -1:
self.wrlog(False, "'</a>' element not found in nav file.")
self.wrlog(False, "Does this file pass epubcheck?")
self.rdict["pager_error"] = True
return 0
if nav_data[:loc2].isdigit():
if int(nav_data[:loc2]) > max_page:
max_page = int(nav_data[:loc2])
self.wrlog(False, f"Nav pagelist page count is: {max_page}")
return max_page
def wrlog(self, stdout, message):
"""
Write a message to the log file.
**Instance Variables**
**_stdout_**
If True, then echo the message to stdout.
**_message_**
The message to print
"""
if stdout and not self.quiet:
print(message)
self.rdict["messages"] += "\n" + message
with self.logpath.open("a") as logfile:
logfile.write(message + "\n")
def update_opffile(self):
"""
add metadata to the opf file if the pagination was successful
# Add custom metadata to opf file
# <meta name="tlbepubpager:words" content="57000"/>
# <meta name="tlbepubpager:pages" content="197"/>
# <meta name="tlbepubpager:modified" content="True"/>
"""
with Path(self.rdict["opf_file"]).open("r") as opf_file_read:
opf_data = opf_file_read.read()
mloc = opf_data.find("</metadata>")
if mloc != -1:
self.wrlog(True,f"Found end of metadata: {opf_data[mloc-20:mloc+20]}")
new_opf = opf_data[:mloc]
new_opf += f'''<meta name="tlbepubpager:words" content="{self.rdict['words']}"/>'''
new_opf += CR
new_opf += f'''<meta name="tlbepubpager:pages" content="{self.rdict['pages']}"/>'''
new_opf += CR
new_opf += f'''<meta name="tlbepubpager:modified" content="True"/>'''
new_opf += CR
new_opf += opf_data[mloc:]
with Path(self.rdict["opf_file"]).open("w") as opf_file_write:
opf_file_write.write(new_opf)
else:
self.wrlog(True,f"Did not find end of metadata")
def update_navfile(self):
"""
Add generated page-list element to the ePub navigation file
Verify that nav file has proper xmlns. If not fix it.
"""
with self.rdict["nav_file"].open("r") as nav_file_read:
nav_data = nav_file_read.read()
pagelist_loc = nav_data.find("</body>")
new_nav_data = nav_data[:pagelist_loc]
new_nav_data += self.plist
with self.rdict["nav_file"].open("w") as nav_file_write:
nav_file_write.write(new_nav_data)
nav_file_write.write(nav_data[pagelist_loc:])
def add_plist_target(self, curpg, href):
"""
Generate page-list entry and page pageline and add them to a
string that accumulates them for placement in the navigation
file.
**Keyword arguments:**
**_curpg_**
The page number in the book.
**_href_**
The filename and path for the internal page link in the book.
"""
self.plist += f' <li><a href="{href}#{pglnk}{curpg}">{curpg}</a></li>'
self.plist += CR
return
def bld_pageline(self, curpg, sct_pg, sct_pgcnt):
"""
Format and return page pageline.
**Keyword arguments:**
**_curpg_**
The current page number of the book.
**_sct_pg_**
The current section page number.
**_sct_pgcnt_**
The pagecount of the section.
"""
# construct the page pageline based on formatting selections
# brackets
# hack_p = '<p style="margin: 0 0 0 0"></p>'
if self.pl_bkt == "<":
flb = "<"
frb = ">"
elif self.pl_bkt == "-":
flb = "-"
frb = "-"
else:
flb = ""
frb = ""
if self.chap_bkt == "<":
clb = "<"
crb = ">"
elif self.chap_bkt == "-":
clb = "-"
crb = "-"
else:
clb = ""
crb = ""
# book pages format
if self.pl_pgtot:
pagestr_bookpages = f"{flb}{curpg}/{self.rdict['pages']}{frb}"
else:
pagestr_bookpages = f"{flb}{curpg}{frb}"
# chapter pages format
if self.chap_pgtot:
pagestr_chapterpages = f" {clb}{sct_pg}/{sct_pgcnt}{crb}"
else:
pagestr_chapterpages = ""
pagestr = pagestr_bookpages + pagestr_chapterpages
if self.pl_color == "none":
if self.pl_align == 'endp':
# endp means put the page information at the end of the current
# paragraph, so no text-align and no ending or starting <p> and
# use a <div> instead
pageline = (
f'<span style="font-size:{self.pl_fntsz}; '
f'margin: 0 0 0 0">'
f" {pagestr}</span>"
)
else:
pageline = (
f'<p style="font-size:{self.pl_fntsz}; '
f'text-align: self.pl_align; margin: 0 0 0 0">'
f"{pagestr}</p>"
)
else:
if self.pl_align == 'endp':
pageline = (
f'<span style="font-size:{self.pl_fntsz}; '
f'color: {self.pl_color}; margin: 0 0 0 0">'
f" {pagestr}</span>"
)
else:
pageline = (
f'<p style="font-size:{self.pl_fntsz}; '
f"text-align:{self.pl_align}; "
f'color: {self.pl_color}; margin: 0 0 0 0">'
f"{pagestr}</p>"
)
return pageline
def new_super(self, curpg, sct_pg, sct_pgcnt):
"""
Format and return a <span> element for superscripted page
numbering.
**Keyword arguments:**
**_curpg_**
The current page number of the book.
**_sct_pg_**
The current section page number.
**_sct_pgcnt_**
The pagecount of the section.
"""
# construct the page pageline based on formatting selections
# brackets
if self.pl_bkt == "<":
flb = "<"
frb = ">"
elif self.pl_bkt == "-":
flb = "-"
frb = "-"
else:
flb = ""
frb = ""
if self.chap_bkt == "<":
clb = "<"
crb = ">"
elif self.chap_bkt == "-":
clb = "-"
crb = "-"
else:
clb = ""
crb = ""
# book pages format
if self.super_total:
pagestr_bookpages = f"{flb}{curpg}/{self.rdict['pages']}{frb}"
else:
pagestr_bookpages = f"{flb}{curpg}{frb}"
# chapter pages format
if self.chap_pgtot:
pagestr_chapterpages = f" {clb}{sct_pg}/{sct_pgcnt}{crb}"
else:
pagestr_chapterpages = ""
pagestr = pagestr_bookpages + pagestr_chapterpages
if self.super_color == "none":