-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrender.py
270 lines (225 loc) · 7.79 KB
/
render.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
#-*-coding:utf-8-*-
import logging
import itertools
import envoy
import pystache as mustache
logger = logging.getLogger(__name__)
templates = {
'head': u'''
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
body {
}
p {
text-indent: 2em;
line-height: 1.3em;
}
.p_indent {
text-indent: 2em;
}
.t_indent {
text-indent: 2em;
}
.p_align_left {
text-align: left;
}
.p_align_center,
.p_center {
text-align: center;
}
.p_align_right {
text-align: right;
}
.p_bold {
font-weight: bold;
}
.p_quote {
}
</style>
</head>
<body>
''',
'footer': u'''
</body>
</html>
''',
'title': u'''
<a href="#{{toc_anchor}}"></a>
<h2 id="{{toc_anchor}}">{{title}}</h2>
<h4>
{{author}}
{{#translator}} | {{translator}} 译{{/translator}}
</h4>
<br>
''',
'headline': u'''
<a href="#{{toc_anchor}}"></a>
<h3 id="{{toc_anchor}}" class="{{classes}}">{{text}}</h3>
''',
'paragraph': u'''
<p class="{{classes}}">{{text}}</p>
''',
'illus': u'''
<p class="p_align_center">
<img class="{{classes}}" src="{{image}}" />
</p>
''',
'code': u'''
<code class="{{classes}}">{{text}}</code>
''',
'breaker': u'''
<mbp:pagebreak/>
''',
'toc.ncx': u'''
<?xml version="1.0" encoding="UTF-8"?>
<ncx xmlns="http://www.daisy.org/z3986/2005/ncx/" version="2005-1" xml:lang="zh-CN">
<head>
<meta name="dtb:depth" content="4" />
<meta name="dtb:totalPageCount" content="0" />
<meta name="dtb:maxPageNumber" content="0" />
</head>
<docTitle><text>{{ title }}</text></docTitle>
<docAuthor><text></text></docAuthor>
<navMap>
{{#contents}}
<navPoint class="chapter" id="{{ anchor }}" playOrder="{{ anchor }}">
<navLabel><text>{{ title }}</text></navLabel>
<content src="content.html#{{ anchor }}" />
</navPoint>
{{/contents}}
</navMap>
</ncx>
''',
'opf': u'''
<?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://www.idpf.org/2007/opf" version="2.0" unique-identifier="uid">
<metadata>
<dc-metadata xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:opf="http://www.idpf.org/2007/opf">
<dc:title>{{ title }}</dc:title>
<dc:language>zh-CN</dc:language>
<dc:creator>豆瓣阅读</dc:creator>
<dc:publisher>豆瓣阅读</dc:publisher>
<dc:subject>{{ title }}</dc:subject>
<dc:date>2013-04-05T06:07:08</dc:date>
<dc:description></dc:description>
</dc-metadata>
</metadata>
<manifest>
<item id="content" media-type="application/xhtml+xml" href="content.html"></item>
<item id="toc" media-type="application/x-dtbncx+xml" href="toc.ncx"></item>
</manifest>
<spine toc="toc">
<itemref idref="content"/>
</spine>
</package>
'''
}
def render(template_name, data):
try:
return mustache.render(templates.get(template_name, 'paragraph'), data)
except:
# TODO more specific
return ''
table_of_contents = []
book_index = 0
def add_to_table_of_contens(title):
if len(table_of_contents) <= book_index:
table_of_contents.append([])
anchor = 'toc_%s_%s' % (len(table_of_contents), len(table_of_contents[-1])+1)
table_of_contents[-1].append({
'title': title,
'anchor': anchor
})
return anchor
# ------------
def generate_book(book_id, book_title, content_json_data):
logger.info('going to render content.html')
content_html = render_html(content_json_data)
logger.info('content.html rendered')
with open('data/%s/content.html' % book_id, 'w') as fp:
fp.write(content_html.encode('utf-8'))
toc_xml = render_toc(book_title)
with open('data/%s/toc.ncx' % book_id, 'w') as fp:
fp.write(toc_xml.encode('utf-8'))
opf_xml = render_opf(book_title)
with open('data/%s/book.opf' % book_id, 'w') as fp:
fp.write(opf_xml.encode('utf-8'))
logger.info('book files prepared for %s', book_id)
# kindlegen
logger.info('before run kindlegen for %s', book_id)
r = envoy.run('kindlegen -o %s.mobi data/%s/book.opf' % (book_id, book_id))
if r.status_code != 1:
logging.error('generate book error: %s', r.std_out, exc_info=True)
raise RuntimeError(r)
logger.info('mobi file generated to data/%s/%s.mobi', book_id, book_id)
return 'data/%s/%s.mobi' % (book_id, book_id)
def render_opf(book_title):
return render('opf', {'title': book_title})
def render_toc(book_title):
toc_length = len(table_of_contents)
if toc_length == 1:
toc_s = table_of_contents
elif toc_length == 2:
toc_s = table_of_contents[1]
else:
toc_s = list(itertools.chain.from_iterable(table_of_contents))
return render('toc.ncx', {
'title': book_title,
'contents': toc_s
})
# generate html from json data
def render_html(data):
body = '<mbp:pagebreak/>'.join(map(render_post, data['posts']))
return templates['head'] + body + templates['footer']
# a post is an article
def render_post(post):
html = ''
html += render_title(post)
html += ''.join(map(render_content, post['contents']))
return html
def render_title(post):
toc_anchor = add_to_table_of_contens(post['title'])
global book_index
book_index += 1
return render('title', {
'title': post['title'],
'author': post['orig_author'],
'translator': post['translator'],
'toc_anchor': toc_anchor
})
# 一个段落等
def render_content(content):
classes = []
content_type, data = content['type'], content['data']
text_format = data.get('format')
if text_format:
for class_name in ['p_indent', 'p_center', 'p_quote', 'p_bold']:
if text_format.get(class_name):
classes.append(class_name)
text_align = text_format.get('p_align')
if text_align in ['left', 'right', 'center']:
classes.append('p_align_' + text_align)
text = data.get('text')
render_data = {
'text': text,
'classes': ' '.join(classes)
}
# image
if content_type == 'illus':
render_data['image'] = data['size']['orig']['src']
if content_type == 'headline':
render_data['toc_anchor'] = add_to_table_of_contens(text)
return render(content_type, render_data)
if __name__ == '__main__':
import json
from decrypt import decrypt
book_id = 'e140964'
with open('data/' + book_id + '/data.txt') as fp:
file_content = fp.read()
_, title, content = file_content.split(':')[:3]
json_str = decrypt(content)
data = json.loads(json_str)
generate_book(book_id, title.decode('utf-8'), data)