-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathGUIepubpager.py
executable file
·2361 lines (2139 loc) · 83.7 KB
/
GUIepubpager.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
# from ctypes import string_at
# import sys
import os
# import datetime
import time
from pathlib import Path
import shutil
import zipfile
import io
import copy
import PySimpleGUI as sg
import json
import base64
import textwrap
from html2text import html2text
from PIL import Image
# from subprocess import PIPE, run
# from dateutil import parser
# these are my modules
# from packages.pst import PrettySimpleTable
from epubpager import epub_paginator
Version = "0.3"
"""
new stuff
GUIepubpager.py based on CalibrePaginator.py
Version = "0.3"
Version = "0.2"
1. Add epub version to metadata from the epub and display.
2. Determine if file is already paginated by epubpager (requires enhancement to
epubpager).
3. Add ability to paginate all books in the list. Select Find files becomes the
means to paginate selected books.
4. Hide the epubpage metadata if there is none in the epub file.
5. Implemented a method to perform_long_operation method of running pagination
in a thread and allowing canceling of a long list at any point.
TODO
Version = '0.1'
Basics work:
1. Open a directory, read all epubs.
2. Open files with multifile capability.
3. Opened files are scannned to get metadata and covers.
4. Epub information displayed.
5. Pagination of single selected epub works.
6. Find works to filter books in the list.
When Find is active (list is filtered), Find button becomes "ShowAll"
and clicking it returns to unfiltered list.
7.
"""
# the minimal database for generic epubs to paginate.
"""
"title": string
"author": string
"blurb":
"cover":
"formats":
"identifiers":
"pubdate":
"publisher":
"
"""
# string constants for formatting stuff
CR = "\n"
INDENT = " "
BREAK = "-------------------" + CR
MainWindowSize = (1024, 920)
termcolumns = 148
termrows = 20
help_length = termrows + 5
output_width = 80
output_height = 32
debug_width = 56
bookdata_textwidth = 24
booklist_width = 68
indent = 3
wrap_width = output_width - 8
recent_table_length = 28 # how many lines in each section of recent books table
# Render Markdown Styles and PrettyTable rendering styles for Multiline
defaultfont = "Menlo"
defaultfontsize = "12"
nocolor = "black"
codefont = "Hack"
codefontsize = "10"
head1size = "20"
head2size = "16"
head3size = "14"
none = defaultfont + " " + defaultfontsize
noformat = none
bold = defaultfont + " " + defaultfontsize + " bold"
italic = defaultfont + " " + defaultfontsize + " italic"
bolditalic = defaultfont + " " + defaultfontsize + " bold italic"
head1none = defaultfont + " " + head1size + " bold"
head1italic = defaultfont + " " + head1size + " bold italic"
head2none = defaultfont + " " + head2size + " bold"
head2italic = defaultfont + " " + head2size + " bold italic"
head3none = defaultfont + " " + head3size + " bold"
head3italic = defaultfont + " " + head3size + " bold italic"
code = codefont + " " + codefontsize
# unicode box drawing characters
hline = "\u2501"
vbar = "\u2503"
cross = "\u254b"
top_left_corner = "\u250f"
top_right_corner = "\u2513"
bottom_left_corner = "\u2517"
bottom_right_corner = "\u251b"
top_tee = "\u2533"
bottom_tee = "\u253b"
left_tee = "\u2523"
right_tee = "\u252b"
cross = "\u254b"
bullet = "\u2022"
# hline = '\u23af'
# vbar = '\u2758'
current_book = {} # The current book, this is the json dictionary for the book
format_list = []
booklist = [] # List of books in Booklist item. Current books, or result of search
findlist = [] # books found from the 'find' button
cb_cover = ""
nocover = "./NoBookCover.png"
findlist_active = False
cancel_pagination = False
paginate_list = []
paginate_count = 0
config = {
"srcdir": "/Users/tbrown/data_store/epubs",
"outdir": "./paged_epubs",
"match": True,
"genplist": True,
"pgwords": 275,
"pages": 0,
"pageline": True,
"pl_align": "center",
"pl_color": "red",
"pl_bkt": "<",
"pl_fntsz": "75%",
"pl_pgtot": True,
"superscript": False,
"super_color": "red",
"super_fntsz": "60%",
"super_total": True,
"chap_pgtot": True,
"chap_bkt": "",
"ebookconvert": "/Applications/calibre.app/Contents/MacOS/ebook-convert",
"epubcheck": "/Users/tbrown/bin/epubcheck.sh",
"chk_orig": True,
"chk_paged": True,
"quiet": True,
"DEBUG": False,
}
# chars to remove from titles
badchars = [",", "(", ")", "&", "*", "/", "."]
CalibredbCmd = "/Applications/calibre.app/Contents/MacOS/calibredb"
month_str = [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
]
# import tkinter
# root = tkinter.Tk()
# width = root.winfo_screenwidth()
# height = root.winfo_screenheight()
# print(f"The screen resolution is {width} x {height}")
# the print for the help MLINE element
def cprint(*args, **kwargs):
window["-config_help-" + sg.WRITE_ONLY_KEY].print(*args, **kwargs)
def hprint(*args, **kwargs):
window["-DEBUG-" + sg.WRITE_ONLY_KEY].print(*args, **kwargs)
# this function and assignment redefines print so it prints to the multiline field
def mprint(*args, **kwargs):
window["-MLINE-" + sg.WRITE_ONLY_KEY].print(*args, **kwargs)
lprint = mprint
# functions
def LogWarning(message):
window["-DEBUG-" + sg.WRITE_ONLY_KEY].print(message, font="Menlo 12 bold", t="red")
def LogEvent(message):
window["-DEBUG-" + sg.WRITE_ONLY_KEY].print(message)
def IsNumber(s):
"""Returns True if string is a number."""
try:
float(s)
return True
except ValueError:
return False
config_file = ""
# the config file may be local, which has precedence, or in the ~/.config/BookTally directory
def read_config():
if os.path.exists("./GUIepubpager.cfg"):
config_file = "./GUIepubpager.cfg"
elif os.path.exists("/Users/tbrown/.config/GUIepubpager/GUIepubpager.cfg"):
config_file = "/Users/tbrown/.config/GUIepubpager/GUIepubpager.cfg"
else:
# print("No config file found!")
return config
with open(config_file, "r") as cfg:
return json.loads(cfg.read())
def update_config(values):
"""
Called from main event loop, updates config dictionary with values set in Configuration Frame.
"""
global window
config["srcdir"] = window["-cfgsrcdir-"].get()
config["outdir"] = values["-outdir-"]
config["match"] = values["-match-"]
config["genplist"] = values["-genplist-"]
config["pgwords"] = int(values["-pgwords-"])
config["pages"] = int(values["-pages-"])
config["pageline"] = values["-pageline-"]
if values["-align_left-"]:
config["pl_align"] = "left"
elif values["-align_center-"]:
config["pl_align"] = "center"
else:
config["pl_align"] = "right"
if values["-pl_color_red-"]:
config["pl_color"] = "red"
elif values["-pl_color_green-"]:
config["pl_color"] = "green"
else:
config["pl_color"] = "none"
if values["-pl_bkt_angle-"]:
config["pl_bkt"] = "<"
elif values["-pl_bkt_paren-"]:
config["pl_bkt"] = "("
else:
config["pl_bkt"] = ""
config["pl_fntsz"] = values["-pl_fntsz-"]
config["pl_pgtot"] = values["-pl_pgtot-"]
config["superscript"] = values["-superscript-"]
if values["-super_color_red-"]:
config["super_color"] = "red"
elif values["-super_color_green-"]:
config["super_color"] = "green"
else:
config["super_color"] = "none"
config["super_fntsz"] = values["-super_fntsz-"]
config["super_total"] = values["-super_total-"]
config["chap_pgtot"] = values["-chap_pgtot-"]
# config['chap_bkt'] = values['-chap_bkt-']
if values["-chap_bkt_angle-"]:
config["chap_bkt"] = "<"
elif values["-chap_bkt_paren-"]:
config["chap_bkt"] = "("
else:
config["chap_bkt"] = ""
config["ebookconvert"] = values["-ebookconvert-"]
config["epubcheck"] = values["-epubcheck-"]
config["chk_orig"] = values["-chk_orig-"]
config["chk_paged"] = values["-chk_paged-"]
config["quiet"] = values["-quiet-"]
config["DEBUG"] = values["-DEBUG-"]
# this is a wait function to read debug output.
def waitinput(message): # {{{
dummy = sg.popup_get_text(message, "Check debug statement.") # }}}
# field definitions for the table
# item: 4 - allows for digits up to 9999
# title: 2+ variable 35/20 ratio with author
# author: 2+ variable 35/20 ratio with title
# pages: 6 for comma formatted number, 2 in front, rjust6 number up to 9,999
# words: 8 for comma formatted number, 2 in front, rjust8 number up to 999,999
# rating: 4 rjust2 number 1-10
# def browse_booklist(browselist):# {{{
# titlelength = int(35/80 * termcolumns) - 5
# authorlength = int(20/80 * termcolumns) - 2
# titleheadlen = titlelength - 5
# authorheadlen = authorlength - 6
# pagelength = 6
# wordlength = 8
# ratinglength = 4
# outputlist = []
# outputlist.append(' ID | Title' + ' '*titleheadlen + '| Author' + ' '*authorheadlen + '| Pages | Words | Rating ')
# outputlist.append(' |-' + '-'*titlelength + '+-' + '-'*authorlength + '|-------|---------|-------|')
# for book in browselist:
# tstring = book['title']
# bookid = book['id']
# if len(tstring) >= titlelength:
# tstring = tstring[0:titlelength-1]
# else:
# tstring = tstring.ljust(titlelength-1,' ')
# astring = book['author']
# if len(astring) >= authorlength:
# astring = astring[0:authorlength-1]
# else:
# astring = astring.ljust(authorlength-1,' ')
# pages = "{:,}".format(book['Pages'])
# words = "{:,}".format(book['Words'])
# rating = "{:,}".format(book['Rating'])
# outputlist.append(str(bookid).rjust(3,' ') + '| ' + tstring + ' | ' + astring + ' | ' + pages.rjust(pagelength-1,' ') + ' | ' + words.rjust(wordlength-1,' ') + ' |' + rating.rjust(ratinglength-1,' ') + ' |')
# return outputlist# }}}
# Format a string with a color, size, and font. Add CR or not
# Format types:
# header1 - Menlo 18 bold
# header2 - Menlo 16 bold
# titlestr = Menlo 16 bold italic, t='red', end=''
# authorstr = Menlo 16 bold, t='green', end=''
def print_title(fstr):
window["-MLINE-" + sg.WRITE_ONLY_KEY].print(
fstr, font="Menlo 16 italic", t="red", end=""
)
def print_author(fstr):
window["-MLINE-" + sg.WRITE_ONLY_KEY].print(
fstr, font="Menlo 16 bold", t="green", end=""
)
def print_header1(fstr):
window["-MLINE-" + sg.WRITE_ONLY_KEY].print(fstr, font="Menlo 20 bold")
def print_header2(fstr):
window["-MLINE-" + sg.WRITE_ONLY_KEY].print(fstr, font="Menlo 18 bold")
def print_nocr(fstr):
window["-MLINE-" + sg.WRITE_ONLY_KEY].print(fstr, font="Menlo 12", end="")
def print_color_nocr(fstr, thecolor):
window["-MLINE-" + sg.WRITE_ONLY_KEY].print(
fstr, font="Menlo 12", t=thecolor, end=""
)
def print_bold(fstr):
window["-MLINE-" + sg.WRITE_ONLY_KEY].print(fstr, font="Menlo 12 bold")
def print_color(fstr, thecolor):
window["-MLINE-" + sg.WRITE_ONLY_KEY].print(fstr, font="Menlo 12", t=thecolor)
def print_line(fstr):
window["-MLINE-" + sg.WRITE_ONLY_KEY].print(fstr, font="Menlo 12")
def print_hline():
window["-MLINE-" + sg.WRITE_ONLY_KEY].print(
"".join([char * 80 for char in hline]), font="Menlo 12", t="blue"
)
def print_bluechar(char):
window["-MLINE-" + sg.WRITE_ONLY_KEY].print(char, font="Menlo 12", t="blue", end="")
# render markdown in the -MLINE- multiline window
# currently only support for three levels of header and bold and italic
def next_style(current_style, new_style): # {{{
styleitalic = {
none: italic,
bold: bolditalic,
italic: none,
bolditalic: bold,
head1none: head1italic,
head1italic: head1none,
head2none: head2italic,
head2italic: head2none,
head3none: head3italic,
head3italic: head3none,
}
stylebold = {
none: bold,
bold: none,
italic: bolditalic,
bolditalic: italic,
head1none: head1none,
head1italic: head1italic,
head2none: head2none,
head2italic: head2italic,
head3none: head3none,
head3italic: head3italic,
}
if new_style == italic:
return styleitalic.get(current_style, none)
if new_style == bold:
return stylebold.get(current_style, none) # }}}
def wraplines(source): # {{{
prelines = source.splitlines()
# pre-process the source with TextWrapper to properly wrap blockquotes
wrapper = textwrap.TextWrapper()
wrapper.width = wrap_width
wrapper.initial_indent = "> "
wrapper.subsequent_indent = "> "
lines = ""
for preline in prelines:
if len(preline) > 0:
if preline[0] == ">":
lines = lines + wrapper.fill(preline[2 : len(preline)]) + CR
else:
lines = lines + preline + CR
else:
lines = lines + preline + CR
return lines # }}}
def render_markdown(lprint, source): # {{{
# preprocess in case there are block quotes
lines = wraplines(source).splitlines()
# the stylelist is a list of tuples (style, location)
# The style is applied beginning at the location until the next location.
listnum = 1
codeblock = False
for line in lines:
stylelist = []
words = line.split()
if len(words) > 0:
# set up the initial style as a header or none
if words[0] == "#":
listnum = 1
stylelist.append((head1none, 0))
if line[1] == " ":
line = line[2 : len(line)]
else:
line = line[1 : len(line)]
elif words[0] == "##":
listnum = 1
stylelist.append((head2none, 0))
if line[2] == " ":
line = line[3 : len(line)]
else:
line = line[2 : len(line)]
elif words[0] == "###":
listnum = 1
stylelist.append((head3none, 0))
if line[3] == " ":
line = line[4 : len(line)]
else:
line = line[3 : len(line)]
# this is an unordered list
elif words[0] == "+":
listnum = 1
line = " " + bullet + " " + line[2 : len(line)]
stylelist.append((none, 0))
# this is an ordered list
elif words[0][0] in ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]:
line = (
" "
+ "{:3d}".format(listnum)
+ ". "
+ line[len(words[0]) + 1 : len(line)]
)
listnum += 1
stylelist.append((none, 0))
# This is a horizontal line
elif words[0] == "***" or words[0] == "---":
line = hline * (wrap_width - 1)
stylelist.append((none, 0))
# this is a blockquote--just indent
elif words[0] == ">":
line = " " * (indent) + vbar + " " + line[2 : len(line)]
stylelist.append((none, 0))
# this is a code block, either start or end
elif words[0] == "```":
if codeblock:
codeblock = False
else:
codeblock = True
lprint(hline * (wrap_width - 1))
continue
else:
listnum = 1
stylelist.append((none, 0))
else:
# this is a blank line
lprint("")
continue
# if we have a code block, just print with code style
if codeblock:
lprint(line, font=code)
continue
# now scan the line by character and add character styles as appropriate
renderline = ""
current_style = stylelist[0][0]
j = 0
skip = False
nocharstyle = False
for i in range(0, len(line)):
if skip:
skip = False
continue
char = line[i]
# handle escaping character styles
# skip the escape char and mark to ignore style
if char == '\\':
nocharstyle = True
continue
if i < len(line) - 2:
nextchar = line[i + 1]
else:
# this is a dummy, just to not be '*'
nextchar = "a"
# this is italic
if (char == "*" and nextchar != "*") or char == "_" and not nocharstyle:
thenextstyle = next_style(current_style, italic)
stylelist.append((thenextstyle, j))
current_style = thenextstyle
# and this is bold
elif char == "*" and nextchar == "*" and not nocharstyle:
thenextstyle = next_style(current_style, bold)
stylelist.append((thenextstyle, j))
current_style = thenextstyle
skip = True
else:
nocharstyle = False
renderline += char
j += 1
start = 0
# print(f"Before printing: {stylelist}")
# print(f"renderline: {renderline}")
if len(stylelist) == 1:
style = stylelist[0][0]
lprint(renderline, font=style, t="black")
# In this case, we reset the stylelist for the next line, it's all used up.
stylelist = []
else:
bound = len(stylelist)
for i in range(1, len(stylelist)):
# style and start location are previous entry in stylelist
style = stylelist[i - 1][0]
start = stylelist[i - 1][1]
# end location is where the next style starts, current entry in stylelist
end = stylelist[i][1]
lprint(renderline[start:end], font=style, end="")
# this is the last of the line
lprint(renderline[end : len(line)], font=stylelist[len(stylelist) - 1][0])
# }}}
def present_book(): # {{{
global lprint
# clear the window
window["-MLINE-" + sg.WRITE_ONLY_KEY].update("")
print_hline()
# present formatted information about the book, partly based on its status
# first the title, author and publication date
# clear the window
window["-MLINE-" + sg.WRITE_ONLY_KEY].update("")
print_title(current_book["title"])
print_nocr(" by ")
print_author(current_book["author"])
mprint()
print_bold("Published " + current_book["pubdate"])
print_hline()
s = fix_amp(current_book["blurb"])
s = html2text(s)
render_markdown(mprint, s)
print_hline()
return # }}}
def place_value(number): # {{{
return "{:,}".format(number) # }}}
def update_view(current_book): # {{{
present_book()
load_cover(current_book)
update_BookDataFrame()
# }}}
def create_bookname(title, author):# {{{
"""
Create a book name of the form title-author. Remove odd characters for
file system simplicity.
"""
for c in badchars:
title = title.replace(c, "-")
author = author.replace(c, "-")
title = title.replace(" ", "_")
author = author.replace(" ", "_")
return f"{title}-{author}"# }}}
def print_dict(idict):# {{{
print("{")
for key in idict.keys():
print(f''' "{key}": {idict[key]}"''')
print("}")# }}}
def show_dict(idict):# {{{
LogEvent("{")
for key in idict.keys():
LogEvent(f''' "{key}": {idict[key]}"''')
LogEvent("}")# }}}
def read_opf(epub_file):# {{{
"Read the opf file data from the epub zipfile and return the opf_path and opf_data."
opf_data = "No opf data"
opf_path = "No opf path"
# find the opf file
with zipfile.ZipFile(epub_file) as zfile:
with zfile.open(f"META-INF/container.xml") as c:
c_data = c.read()
cs = str(c_data)
rloc = cs.find("<rootfiles>")
if rloc == -1:
print("Error: did not find <rootfiles> in container")
return (opf_path, opf_data)
cs = cs[rloc + 3 :]
rloc = cs.find("<rootfile")
if rloc == -1:
print("Error: did not find <rootfile in container")
return (opf_path, opf_data)
cs = cs[rloc + 3 :]
rloc = cs.find("full-path=")
if rloc == -1:
print("Error: did not find full-path in container")
return (opf_path, opf_data)
cs = cs[rloc + 3 :]
opflist = cs.split('"')
opf_path = f"{opflist[1]}" # d/d/d/fname
# print(f"opf_path: {opf_path}")
if opf_path == "":
print(
"Error: apparently opf file was not found. Return value was blank."
)
return (opf_path, opf_data)
# print(opf_path)
opf = opf_path.split("/")
# print(f"opf.split: {opf}; opf len: {len(opf)}")
opf_file = opf[len(opf) - 1]
opf = opf[: len(opf) - 1]
opf_path = ""
for d in opf:
opf_path += f"{d}/"
# print(f"{opf_path} - {opf_file}; cat: {opf_path}/{opf_file}")
# with zfile.open(f"{opf_path}{opf_file}") as o:
with io.TextIOWrapper(
zfile.open(f"{opf_path}{opf_file}"), encoding="utf-8"
) as o:
opf_data = o.read()
# opf_data = str(opf_b)
return (opf_path, opf_data)# }}}
def get_cover(epubfile, coverpath, bname, opf_path, opf_data):# {{{
"Get the cover file from epubfile and return it as coverpath/ename.jpg in path coverpath."
"""
TODO
in epub 2 files, we might find the cover in this type of xml
<reference href="Text/Octavia E Butler - Parable of the Sower.html" title="Cover" type="cover" />
"""
# print(f"get_cover {bname}")
with zipfile.ZipFile(epubfile) as z:
# opf_tuple = read_opf(z) # d/d/d/fname
# opf_path = opf_tuple[0]
# opf_data = opf_tuple[1]
v1 = 'properties="cover-image"'
v2 = 'id="cover-image"'
v3 = 'id="coverimage"'
v4 = 'id="cover"'
if opf_data.find(v1) != -1:
ss = v1
elif opf_data.find(v2) != -1:
ss = v2
elif opf_data.find(v3) != -1:
ss = v3
elif opf_data.find(v4) != -1:
ss = v4
else:
LogWarning("Warning: No property or id for cover-image found")
return "nocover"
# print(f"ss found is: {ss}")
cloc = opf_data.find(ss)
# since the item may be ordered randomly, we need to find the bounding
# element < all the stuff >, then search for href.
lftang = opf_data[:cloc].rfind("<")
if lftang != -1:
# print(f"found lftang: {opf_data[lftang:lftang+50]}")
opf_data = opf_data[lftang:]
# print(f"new opf1: {opf_data[:20]}")
hloc = opf_data.find("href=")
if hloc != -1:
# print(f"found href: {opf_data[hloc:hloc+20]}")
# end location of the href
# we add 6 for 'href="'
opf_data = opf_data[hloc+6:]
# print(f"new opf2: {opf_data[:20]}")
eloc = opf_data.find('"')
if eloc != -1:
cpath = opf_data[:eloc]
# print(f"cpath is: {opf_path}{cpath}")
ftype = Path(cpath).suffix
# print(f"ftype: {ftype}")
z.extract(f"{opf_path}{cpath}", "./")
shutil.copyfile(f"{opf_path}{cpath}", f"{coverpath}/{bname}{ftype}")
rmlink = f"{opf_path}{cpath}"
if Path(rmlink).is_file():
Path(rmlink).unlink
if Path(rmlink).is_dir():
shutil.rmtree(Path(rmlink).parts[0])
return f"{coverpath}/{bname}.jpg"
else:
LogWarning("get_cover Error: Did not find href")
return "nocover"
else:
LogWarning("get_cover Error: Did not find href")
return "nocover"
else:
LogWarning("get_cover Error: Did not find href")
return "nocover"# }}}
def get_tlbmeta(opf_data, loc):
'''
given opf_data and location of a name:tlbepubpager metadata, find the value of the item
form of xml lines:
<meta name="tlbepubpager:words" content="32772"/>
'''
loc1 = opf_data[loc:].find(">")
mlist = opf_data[loc:loc + loc1].split('"')
# print(mlist)
return (mlist[3])
def get_metaprop(opf_data, loc):
'''
given opf_data and location of a dc:item, find the value of the item
form of xml lines:
<meta property="dcterms:modified">2021-11-12T15:12:06Z</meta>
Location is pinting to the property location, so we find '>' and then '<'
then return the information between the two.
'''
loc1 = opf_data[loc:].find(">")
loce= opf_data[loc + loc1 :].find("<")
return (opf_data[loc + loc1 + 1 : loc + loc1 + loce])
def fetch_tlb(opf_data):# {{{
"""
parse opf file and grab data from:
dc:title
dc:creator
dc:date
cd:description
"""
rdict = {}
rdict["title"] = "none"
rdict["author"] = "none"
rdict["epub_version"] = 0
rdict["pubdate"] = "none"
rdict["publisher"] = "none"
rdict["blurb"] = "none"
rdict["cover"] = "none"
rdict["identifiers"] = []
rdict["pages"] = 0
rdict["words"] = 0
rdict["modified"] = False
# get the epub version
# find the <package element
ploc = opf_data.find("<package")
if ploc == -1:
LogEvent(
"get_epub_version: Did not find package string in opf file"
)
else:
# find the version= string
# print(f"package: {opf_data[ploc:ploc+50]}")
opf_str = opf_data[ploc:]
vloc = opf_str.find("version=")
if vloc == -1:
LogEvent(
"get_epub_version: Did not find version string in opf file"
)
else:
# print(f"epub_version: {opf_data[vloc : vloc + 15]}")
vlist = opf_str[vloc : vloc + 15].split('"')
rdict['epub_version'] = vlist[1]
# title
lt = opf_data.find("dcterms:title")
if lt == -1:
# print("Looking for dc:title")
# look for <dc:title
lt = opf_data.find("<dc:title")
if lt == -1:
print("Error: Title meta data not found in opf file.")
return rdict
if lt != -1:
rdict['title'] = get_metaprop(opf_data, lt)
# author
lc = opf_data.find("<dcterms:creator")
if lc == -1:
# print("Looking for dc:creator")
# look for <dc:creator
lc = opf_data.find("<dc:creator")
if lc == -1:
LogWarning("Error: Author meta data not found in opf file.")
return rdict
if lc != -1:
rdict['author'] = get_metaprop(opf_data, lc)
# check to see if the creator name is of the form "last, first", and if so fix it.
if "," in rdict["author"]:
rdict["author"] = rdict["author"].replace(",", "")
asplit = rdict["author"].split()
au = ""
for item in asplit[1:]:
au += item + " "
au += asplit[0]
rdict["author"] = au
hprint("-----")
hprint(f"Fetch metadata from {rdict['title']} by {rdict['author']}")
# pubdate
ld = opf_data.find("dcterms:modified")
if ld == -1:
ld = opf_data.find("<dc:date")
if ld == -1:
LogWarning("Publication date not found in opf file.")
if ld != -1:
rdict['pubdate'] = get_metaprop(opf_data, ld)
if rdict["pubdate"] != "none":
pd = rdict["pubdate"]
pds = pd.split("-")
year = pds[0]
if len(pds) > 1:
if int(pds[1]) > 0 and int(pds[1]) < 13:
month = month_str[int(pds[1]) - 1]
else:
print("month was not found.")
month = "Jan"
else:
month = "Jan"
rdict["pubdate"] = f"{month} {year}"
# publisher
lp = opf_data.find("dcterms:publisher")
if lp == -1:
lp = opf_data.find("<dc:publisher")
if lp == -1:
LogWarning("Warning: publisher meta data not found in opf file.")
if lp != -1:
rdict['publisher'] = get_metaprop(opf_data, lp)
# Blurb
lb = opf_data.find("dcterms:description")
if lb == -1:
lb = opf_data.find("<dc:description")
if lb == -1:
lb = opf_data.find("<description")
if lb == -1:
LogWarning("Warning: Blurb meta data not found in opf file.")
if lb != -1:
rdict['blurb'] = get_metaprop(opf_data, lb)
# identifiers
li = opf_data.find("dcterms:identifier")
if li == -1:
li = opf_data.find("<dc:identifier")
if li != -1:
lid = get_metaprop(opf_data, li)
if len(lid) == 13 and (lid[0:3] == "978" or lid[0:3] == "979"):
lid = "ISBN-13: " + lid
rdict['identifiers'].append(lid)
# epubpager meta data
lew = opf_data.find('<meta name="tlbepubpager:words"')
if lew != -1:
rdict['words'] = int(get_tlbmeta(opf_data, lew))
lep = opf_data.find('<meta name="tlbepubpager:pages"')
if lep != -1:
rdict['pages'] = int(get_tlbmeta(opf_data, lep))
lem = opf_data.find('<meta name="tlbepubpager:modified"')
if lem != -1:
v = get_tlbmeta(opf_data, lem)
if v == "True":
rdict['modified'] = True
else:
rdict['modified'] = False
return rdict# }}}
def load_files(directory, flist):# {{{
global epub_database
global bnamelist
t1 = time.perf_counter()
count = 0
idx = 1
epub_database = []
bnamelist = []
for f in flist:
count += 1
fp = f"{directory}/{f}"
ot = read_opf(fp)
opf_path = ot[0]
opf_data = ot[1]
nbook = fetch_tlb(opf_data)
nbook["formats"] = []
# this loads the actual path of the format to formats
nbook["formats"].append(fp)
# show_dict(nbook)
if nbook["title"] == "none" or nbook["author"] == "none":
LogWarning(
f"Fatal Error: Either title or author not found in epub metadata."
)
else:
bname = create_bookname(nbook["title"], nbook["author"])
# print(f"bname: {bname}")
# this gets the cover from the original book
nbook["cover"] = get_cover(fp, config["outdir"], bname, opf_path, opf_data)
# print(f"cover: {cover}")
epub_database.append(nbook)
if idx < 10:
bnamelist.append(f" {idx}. {nbook['title']} by {nbook['author']}")
else:
bnamelist.append(f"{idx}. {nbook['title']} by {nbook['author']}")
idx += 1
# if count == 10:
# break
t2 = time.perf_counter()
tt = t2 - t1
tbook = tt / idx
LogEvent('')
LogEvent(
f"Load and scan epubs took {t2-t1:.3f} seconds; {tbook:.3f} seconds per book."
)# }}}
def get_dirpath(book):# {{{
"""
return the path of the directory containing the formats and cover for the book
"""
epub_path = ""
coverpath = ""
for fmt in book["formats"]:
# LogEvent(f"fmt: {fmt}")