forked from akkana/scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkoboize.py
More file actions
executable file
·76 lines (60 loc) · 2.01 KB
/
koboize.py
File metadata and controls
executable file
·76 lines (60 loc) · 2.01 KB
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
#!/usr/bin/env python
# Convert regular epubs to kobo kepub.
# HTML manipulations from koboish,
# http://dsandrei.blogspot.fr/2012/07/koboish-ebooks.html
import sys, os
from bs4 import BeautifulSoup
import zipfile
import re
import epubtag
def convert_file(filename, destdir):
if not filename.lower().endswith(".epub"):
print("%s Doesn't end with .epub" % filename)
return
if destdir:
outbookname = os.path.join(destdir,
os.path.basename(filename[:-5])
+ ".kepub.epub")
else:
outbookname = filename[:-5] + ".kepub.epub"
book = epubtag.EpubBook()
book.open(filename)
ozf = zipfile.ZipFile(outbookname, 'w')
namelist = book.namelist()
for name in namelist:
# print("name: %s" % name)
if name.endswith('.html') or name.endswith('.xhtml'):
# print("Converting %s" % name)
fp = book.zip.open(name)
soup = BeautifulSoup(fp, "lxml")
altertags(soup)
fp.close()
ozf.writestr(name, str(soup))
else:
ozf.writestr(name, book.zip.read(name))
book.close()
ozf.close()
print("Converted %s to %s" % (filename, outbookname))
return outbookname
def altertags(soup):
counter = 1
for tag in soup.body.find_all(re.compile("^(p|h[1-6])")):
new_tag = soup.new_tag("span", id="kobo.%d.1" % counter)
counter = counter + 1
tag.wrap(new_tag)
tag.unwrap()
new_tag.wrap(tag)
if __name__ == '__main__':
if len(sys.argv) <= 1:
print("Usage: %s a.epub [b.epub c.epub ...] [destdir]" % \
os.path.basename(sys.argv[0]))
sys.exit(1)
files = sys.argv[1:]
destdir = None
# Is the last argument a directory?
if os.path.isdir(files[-1]):
destdir = files[-1]
files = files[:-1]
print("Koboizing to directory %s" % destdir)
for arg in files:
convert_file(arg, destdir)