-
Notifications
You must be signed in to change notification settings - Fork 0
/
build-book.py
executable file
·288 lines (244 loc) · 8.08 KB
/
build-book.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
#!/usr/bin/python
# TODO
# cover image
# start page?
# magazine format?
#
# worst page ever:
# Washington's I.T. Guy | The American Prospect
# <!******************** -->
kindlegen = 'kindlegen'
ebook_convert = 'ebook-convert'
from time import strftime
import subprocess
import feedparser
import os
import sys
import urllib.request, urllib.error, urllib.parse
import ez_epub
import re
import csv
import unicodedata
import optparse
from BeautifulSoup import BeautifulSoup, Comment
from optparse import OptionParser
import xml.parsers.expat
def everything_between(content,begin,end):
idx1=content.find(begin)
idx2=content.find(end,idx1)
return content[idx1+len(begin):idx2].strip()
def unescape(s):
want_unicode = False
if isinstance(s, str):
s = s.encode('utf-8')
want_unicode = True
# the rest of this assumes that `s` is UTF-8
list = []
# create and initialize a parser object
p = xml.parsers.expat.ParserCreate('utf-8')
p.buffer_text = True
p.returns_unicode = want_unicode
p.CharacterDataHandler = list.append
# parse the data wrapped in a dummy element
# (needed so the 'document' is well-formed)
p.Parse('<e>', 0)
p.Parse(s, 0)
p.Parse('</e>', 1)
# join the extracted strings and return
es = ''
if want_unicode:
es = ''
return es.join(list)
files = []
count = 1
def get_title(url):
data = urllib.request.urlopen(url).read()
title = everything_between(data,'<title>','</title>')
return unescape(title)
def get_data(url):
if use_boilerpipe:
url = 'http://boilerpipe-web.appspot.com/extract?url=' + url
print(url)
data = urllib.request.urlopen(url).read()
return data
import urllib.parse
import os.path
def entry_date(e):
try:
return e.published_parsed
except:
try:
return e.updated_parsed
except:
return e.created_parsed
def entry_date_str(e):
return strftime('%a, %d %b %Y %H:%M:%S', entry_date(e))
def entry_get(x, key):
if key in x:
return x.get(key)
return ''
def get_all_entries(url, entries):
global book_title
global author
d = feedparser.parse(url)
if 'title' in d.feed and not book_title:
book_title = d.feed.title
title = d.feed.title + '<br>' + d.feed.subtitle
if not author:
author = entry_get(d.feed, 'author')
entries += d['entries']
print('entries size: %d' % len(entries))
next_links = [l for l in d.feed.links if l.rel == 'next']
if len(next_links):
print('getting next links')
get_all_entries(next_links[0].href, entries)
def process_feed(file):
entries = []
get_all_entries(file, entries)
for entry in reversed(entries):
print('adding: %s' % entry.title)
if full_content:
content = entry_get(entry, 'content')[0].value
if not content:
content = entry_get(entry, 'summary')
add_article(entry_get(entry, 'title'),
'<html><body><h1>%s</h1><h3>%s</h3>%s</body></html>' % (
entry_get(entry, 'title'),
entry_date_str(entry),
content))
else:
print(entry.link)
data = get_data(entry.link)
add_article(entry_get(entry, 'title'), data)
def process(row):
url = row[0]
title = None
if len(row) == 2:
if 'http' in row[0]:
url, title = row
if 'http' in row[1]:
title, url = row
if not title:
title = get_title(url)
data = get_data(url)
add_article(title, data)
def add_article(title, data):
global count
# fix_images
soup = BeautifulSoup(data)
comments = soup.findAll(text=lambda text:isinstance(text, Comment))
[comment.extract() for comment in comments]
[script.extract() for script in soup.findAll('script')]
[script.extract() for script in soup.findAll('noscript')]
for a in soup.findAll('a'):
for attr in a.attrs:
if ':' in attr[1]:
del a[attr[0]]
if download_images:
for img in soup.findAll('img'):
try:
print('img src: ' + img['src'])
img_url = img['src']
if 'http' not in img_url:
img_url = urllib.parse.urljoin(url, img_url)
img_data = urllib.request.urlopen(img_url).read()
path = urllib.parse.urlsplit(img['src']).path
print('img path: ' + path)
img_filename = os.path.split(path)[1]
output_path = os.path.join(output_tmp, img_filename)
open(output_path, 'w').write(img_data)
img['src'] = img_filename
book.impl.addImage(output_path, img_filename)
except:
pass
print('title: ' + title)
section = ez_epub.Section()
section.title = '%d: %s' % (count, title.decode('utf-8').encode('ascii', 'ignore'))
count += 1
#section.title = unicodedata.normalize('NFKD', title.encode('utf-8')).encode('ascii','ignore')
section.html = True
section.text = soup.prettify()
sections.append(section)
usage = """
usage %prog [options] input_file
input file can be one of the following
- a text file containing URLs to parse
- a CSV file of the form title,url or url, title
- a downloaded rss or atom file
- a URL of an rss or atom feed """
parser = OptionParser(usage=usage)
parser.add_option('-f', '--full', action='store_true', dest='full_content', default=False,
help='Use content from RSS/Atom feed, rather than fetching links')
parser.add_option('-s', '--strip', action='store_true', dest='use_boilerpipe', default=True,
help='Attempt to strip boilerplate from web content using https://boilerpipe-web.appspot.com/')
parser.add_option('-t', '--title', dest='title',
help='Book Title')
parser.add_option('-a', '--author', dest='author',
help='Book Author')
parser.add_option('-o', '--output', dest='output',
help='Base name of output file & directory')
parser.add_option('-e', '--epub', action='store_true', dest='generate_epub', default=True,
help='Generate an epub file')
parser.add_option('-k', '--kindle', action='store_true', dest='use_kindlegen', default=True,
help='Generate a mobi (kindle) file using kindlegen')
parser.add_option('-c', '--calibre', action='store_true', dest='use_calibre', default=False,
help='Generate a mobi (kindle) file using ebook-convert from calibre')
parser.add_option('-n', '--no_images', action='store_false', dest='download_images', default=True,
help='Don\'t download images in web pages')
(options, args) = parser.parse_args()
if len(args) < 1:
print('Must specify an input source')
parser.print_help()
sys.exit(1)
file = args[0]
if not options.output:
output = os.path.splitext(os.path.split(file)[1])[0]
author = options.author
book_title = options.title
download_images = options.download_images
print('Download images? ', 'Yes' if download_images else 'No')
use_boilerpipe = options.use_boilerpipe
print('Using boilerpipe? ', 'Yes' if use_boilerpipe else 'No')
full_content = options.full_content
print('Full content feed? ', 'Yes' if full_content else 'No')
output_tmp = '/tmp/' + os.path.basename(output) + '_tmp'
try:
os.mkdir(output_tmp)
except:
pass
book = ez_epub.Book()
sections = []
if not options.output and book_title:
output = book_title
print("Processing: " + file)
print('Output: %s' % output)
if 'rss' in file or 'http' in file or 'atom' in file or 'xml' in file:
print("Processing as feed")
process_feed(file)
else:
print("Processing as csv/text input")
f = open(file)
csv_reader = csv.reader(f)
for row in csv_reader:
process(row)
if not options.output:
output = book_title
print('Title: %s' % book_title)
print('Author: %s' % author)
book.title = book_title
book.authors = [author]
book.sections = sections
generate_epub = options.generate_epub or options.use_calibre
print('Generating epub? ', 'Yes' if generate_epub else 'No')
book.make(output, generate_epub)
if options.use_kindlegen:
kindle_cmd = '%s "%s/OEBPS/content.opf" -o "%s.mobi"' % (kindlegen, output, output)
print(kindle_cmd)
os.system(kindle_cmd)
mv_cmd = 'mv "%s/OEBPS/%s.mobi" "%s.mobi"' % (output, output, output)
print (mv_cmd)
os.system(mv_cmd)
if options.use_calibre:
calibre_cmd = '%s "%s.epub" -o "%s.mobi"' % (ebook_convert, output, output)
print(calibre_cmd)
os.system(calibre_cmd)