forked from standardebooks/tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathextract-ebook
executable file
·59 lines (45 loc) · 1.72 KB
/
extract-ebook
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
#!/usr/bin/env python3
import argparse
import os
import sys
import zipfile
from io import TextIOWrapper, BytesIO
import magic
from se.kindleunpack import kindleunpack # GPLv3: https://www.mobileread.com/forums/showthread.php?t=61986
import se
def main():
parser = argparse.ArgumentParser(description="Extract an EPUB, MOBI, or AZW3 ebook into ./FILENAME.extracted/ or a target directory.")
parser.add_argument("-v", "--verbose", action="store_true", help="increase output verbosity")
parser.add_argument("-d", "--destination", type=str, help="a target directory to extract into")
parser.add_argument("targets", metavar="TARGET", nargs="+", help="an EPUB, MOBI, or AZW3 file")
args = parser.parse_args()
for target in args.targets:
target = os.path.abspath(target)
if args.verbose:
print("Processing {} ...".format(target), end="", flush=True)
if args.destination is None:
extracted_path = os.path.basename(target) + ".extracted"
else:
extracted_path = args.destination
if os.path.exists(extracted_path):
se.print_error("Directory already exists: {}".format(extracted_path))
exit(1)
mime_type = magic.from_file(target)
if "Mobipocket E-book" in mime_type:
# kindleunpack uses print() so just capture that output here
old_stdout = sys.stdout
sys.stdout = TextIOWrapper(BytesIO(), sys.stdout.encoding)
kindleunpack.unpackBook(target, extracted_path)
# Restore stdout
sys.stdout.close()
sys.stdout = old_stdout
elif "EPUB document" in mime_type:
with zipfile.ZipFile(target, "r") as file:
file.extractall(extracted_path)
else:
se.print_error("Couldn't understand file type: {}".format(mime_type))
exit(1)
if args.verbose:
print(" OK")
if __name__ == "__main__":
main()