This repository has been archived by the owner on Mar 15, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 13
/
epub.py
128 lines (104 loc) · 5.5 KB
/
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
# -*- coding: utf-8 -*-
import os
import html
import uuid
from lxml import etree
from modules.utils import transliterate
from modules.myhyphen import MyHyphen
def save_html(string):
if string:
return html.escape(string, quote=False)
else:
return ''
class EpubProc:
def __init__(self, opffile, config):
self.buff = []
self.book_title = '' # Название книги
self.book_author = '' # Автор
self.book_series = '' # Книжная серия
self.book_series_num = '' # Номер в книжной серии
self.book_lang = 'ru'
self.hyphenate = config.current_profile['hyphens']
if self.hyphenate:
self.replaceNBSP = config.current_profile['hyphensReplaceNBSP']
self.hyphenator = MyHyphen(self.book_lang)
self.opffile = opffile
self.path = os.path.dirname(opffile)
self.log = config.log
self.bookseriestitle = config.current_profile['bookTitleFormat']
self.transliterate_author_and_title = config.transliterate_author_and_title
self.book_uuid = uuid.uuid4()
self.tree = etree.parse(opffile, parser=etree.XMLParser(recover=True))
self.root = self.tree.getroot()
def insert_hyphenation(self, s):
if not s:
return ''
return html.unescape(s) if not self.hyphenator or not self.hyphenate else self.hyphenator.hyphenate_text(html.unescape(s), self.replaceNBSP)
def process(self):
# get uuid if any
for node in self.root.iter('{*}identifier'):
try:
self.book_uuid = uuid.UUID(node.text)
except:
pass
break
# Lookup series/sequences data if any
for node in self.root.iter('{*}meta'):
attributes = node.attrib
if 'name' in attributes:
if attributes['name'].endswith('series_index'):
self.book_series_num = attributes['content']
elif attributes['name'].endswith('series'):
self.book_series = attributes['content']
# And reformat book title accordingly
if self.book_series != '':
for node in self.root.iter('{*}title'):
self.book_title = node.text
abbr = ''.join(word[0] for word in self.book_series.split())
title = self.bookseriestitle
title = title.replace('#series', '' if not self.book_series else self.book_series.strip())
title = title.replace('#number', '' if not self.book_series_num else self.book_series_num.strip())
title = title.replace('#padnumber', '' if not self.book_series_num else self.book_series_num.strip().zfill(2))
title = title.replace('#title', '' if not self.book_title else self.book_title.strip())
title = title.replace('#abbrseries', '' if not abbr else abbr.lower())
if self.transliterate_author_and_title:
title = transliterate(title)
node.text = title
for node in self.root.iter('{*}language'):
self.book_lang = node.text if len(node.text) > 2 else node.text.lower()
if self.book_lang in ('rus'):
self.book_lang = 'ru'
if self.hyphenate and self.hyphenator:
try:
self.hyphenator.set_language(self.book_lang.replace("-", "_"))
except:
self.log.warning('Unable to set hyphenation dictionary for language code "{}" - turning hyphenation off'.format(self.book_lang))
self.hyphenate = False
self.tree.write(self.opffile, encoding='utf-8', method='xml', xml_declaration=True, pretty_print=True)
# See if we have items to correct and process
for node in self.root.iter('{*}item'):
attributes = node.attrib
if 'href' in attributes and 'media-type' in attributes:
if attributes['media-type'] == 'application/xhtml+xml':
filename = os.path.join(self.path, attributes['href'])
self.log.debug('Processing {}'.format(filename))
# Proper XML encoding needed by kndlegen
xhtml = etree.parse(filename, parser=etree.XMLParser(recover=True))
if self.hyphenate:
# Do hyphenation if desiried
for body in xhtml.getroot().iter('{*}body'):
for elem in body.iter('{*}p', '{*}div'):
if elem.text:
elem.text = save_html(self.insert_hyphenation(elem.text))
if elem.tail:
elem.tail = save_html(self.insert_hyphenation(elem.tail))
for child in elem.iterchildren(tag=etree.Element):
if not child.tag.endswith('pre'):
if child.text:
child.text = save_html(self.insert_hyphenation(child.text))
if child.tail:
child.tail = save_html(self.insert_hyphenation(child.tail))
xhtml.write(filename, encoding='utf-8', method='xml', xml_declaration=True)
# TODO: Do we need profile per file extension?
# TODO: Replace stylesheets?
# TODO: book_author = transliterate(book_author)