-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy patharchive.py
293 lines (264 loc) · 8.45 KB
/
archive.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
289
290
291
292
293
from urllib.request import urlopen
from urllib.error import URLError
from urllib.parse import urljoin
import os
from bs4 import BeautifulSoup as BS
import logging
import logging.config
from contextlib import contextmanager
import subprocess as sp
import datetime
import re
from uuid import uuid4
import base64
import shutil
from joblib import Memory
logging.config.dictConfig({
'version': 1,
'disable_existing_loggers': True,
'formatters': {
'detailed': {
'class': 'logging.Formatter',
'format': '%(asctime)s %(levelname)-8s %(message)s'
},
'simple': {
'class': 'logging.Formatter',
'format': '%(message)s'
}
},
'handlers': {
'console': {
'class': 'logging.StreamHandler',
'level': 'INFO',
'formatter': 'simple'
},
'file': {
'class': 'logging.FileHandler',
'level': 'DEBUG',
'filename': 'archive.log',
'mode': 'a',
'formatter': 'detailed'
}
},
'root': {
'level': 'DEBUG',
'handlers': ['console', 'file']
}
})
log = logging.getLogger(__name__)
memo = Memory('cache', verbose=0)
ROOT = os.path.abspath(os.path.dirname(__file__))
OUTPUT = 'archive'
class Bunch(object):
def __init__(self, **kargs):
self.__dict__.update(**kargs)
def load():
buf = []
with open('archive.txt', 'rb') as f:
for lineno, line in enumerate(f):
log.info('parse %dth line' % (lineno + 1))
line = line.decode('ascii').strip()
if line and not line.startswith('#'):
words = line.split()
if words[0] not in ('homework', 'lecture'):
try:
art = parse_homework(words)
except (KeyboardInterrupt, SystemExit):
raise
except:
log.info('parse failed: {}'.format(words))
else:
for i in range(len(buf)):
if buf[i].name == art.name and buf[i].dirname == art.dirname:
log.info('update %s in %s' % (art.name, art.dirname))
art.time = buf[i].time
buf[i] = art
break
else:
buf.append(art)
else:
buf.append(parse_mine(words))
return buf
def infopen(url):
while True:
try:
return urlopen(url).read()
except URLError as e:
if e.code in (400, 404):
log.info('open %s return %d, stop' % (url, e.code))
return None
else:
log.info('open %s return %d, reopen' % (url, e.code))
except Exception as e:
log.info('open %s failed, reopen' % url)
@memo.cache
def parse_homework(words):
n, gist, id, time = words
dirname = os.path.join(OUTPUT, 'homework', n)
name = id
url = 'http://nbviewer.ipython.org/%s' % gist
text = infopen(url)
if text is None:
url = 'http://gist.github.com/%s' % gist
text = infopen(url)
assert text is not None
soup = BS(text)
a = soup.find('a', title='View Raw')
assert a is not None
content = infopen(urljoin(url, a['href']))
assert content is not None
good = False
else:
soup = BS(text)
a = soup.find('a', text='Download Notebook')
if a is None:
content = text
good = False
else:
content = infopen(urljoin(url, a['href']))
assert content is not None
good = True
return Bunch(
dirname=dirname,
name=name,
content=content,
good=good,
time=time,
title='homework %s' % n,
author=id
)
def mdate(path):
t = os.path.getmtime(path)
t = datetime.datetime.fromtimestamp(t)
return t.strftime('%Y-%m-%d')
def parse_mine(words):
typename, n, path = words
n = int(n)
dirname = os.path.join(OUTPUT, 'lecture')
name = '%s.%02d' % (typename, n)
with open(path, 'rb') as f:
content = f.read()
good = True
time = mdate(path)
return Bunch(
dirname=dirname,
name=name,
content=content,
good=good,
time=time,
title='%s %d' % (typename, n),
author='[email protected]'
)
@contextmanager
def pushd(path):
old = os.getcwd()
os.chdir(path)
try:
yield old
finally:
os.chdir(old)
@contextmanager
def rmtmp(name, exts):
try:
yield None
finally:
for ext in exts:
path = name + ext if ext[0] == '.' else ext
if os.path.isdir(path):
shutil.rmtree(path)
elif os.path.exists(path):
os.unlink(path)
def dump(path, data):
if not os.path.exists('images'):
os.makedirs('images')
with open(path, 'wb') as f:
f.write(data)
return path.replace('\\', '/')
def compress_html(name):
with open('%s.html' % name, 'rb') as f:
soup = BS(f.read())
for img in soup.find_all('img'):
if img['src'].startswith('http://'):
log.info('download img in %s' % name)
data = infopen(img['src'])
ext = img['src'].split('.')[-1]
if ext not in ('jpg', 'png', 'gif'):
ext = 'jpg'
iname = uuid4()
ipath = os.path.join('images', '%s.%s' % (iname, ext))
img['src'] = dump(ipath, data)
else:
m = re.search(r"data:image/png;base64,b'(.*)'", img['src'])
if m:
log.info('compress img in %s' % name)
iname = uuid4()
ipath = os.path.join('images', '%s.png' % iname)
# remove '\n'
s = m.group(1).replace(r'\n', '')
img['src'] = dump(ipath, base64.b64decode(s.encode('ascii')))
with open('%s.html' % name, 'wb') as f:
f.write(soup.encode('utf-8'))
def convert(art):
log.info("convert %s's %s" % (art.author, art.title))
if not os.path.exists(art.dirname):
os.makedirs(art.dirname)
with pushd(art.dirname):
if not art.good:
log.info('not good, save to txt')
with open('%s.txt' % art.name, 'wb') as f:
f.write(art.content)
else:
log.info('good, convert to pdf')
with open('%s.ipynb' % art.name, 'wb') as f:
f.write(art.content)
with rmtmp(art.name, [
'.ipynb',
'.html',
'.tex',
'.log',
'.out',
'.aux',
'images'
]):
log.info('ipynb to html')
with open(os.path.join(ROOT, 'archive.tmp'), 'wb') as tmp:
if sp.call([
'ipython3',
'nbconvert',
'--to',
'html',
'%s.ipynb' % art.name
], stdout=tmp, stderr=tmp):
log.info('failed')
return
compress_html(art.name)
log.info('html to tex')
if sp.call([
'pandoc',
'--template',
os.path.join(ROOT, 'simple.tex'),
'%s.html' % art.name,
'-o',
'%s.tex' % art.name,
'-V',
'date:%s' % art.time,
'-V',
'title:%s' % art.title,
'-V',
'author:%s' % art.author,
'-N'
], stdout=tmp, stderr=tmp):
log.info('failed')
return
log.info('tex to pdf')
if sp.call([
'xelatex',
'-shell-escape',
'-interaction=nonstopmode',
'%s.tex' % art.name
], stdout=tmp, stderr=tmp):
log.info('failed or warning')
return
if __name__ == '__main__':
for art in load():
convert(art)