-
Notifications
You must be signed in to change notification settings - Fork 0
/
xkcd_reader.py
executable file
·127 lines (111 loc) · 3.66 KB
/
xkcd_reader.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
import easygui as gui
from bs4 import BeautifulSoup
import requests
from requests.exceptions import ConnectionError
from urllib.parse import urljoin
import pickle
import os
import time
URL = 'https://www.xkcd.com'
def get_image(count=1):
img_url = urljoin(URL, str(count))
while True:
try:
req = requests.get(img_url)
except ConnectionError:
print('Error occurred. Trying again in 30s.')
time.sleep(30)
continue
break
if req.status_code == 404:
print('No More Comics')
return False
soup = BeautifulSoup(req.text, 'lxml')
comic_titile = soup.find(attrs={'id': 'ctitle'})
comic = soup.find(attrs={'id': 'comic'})
image = {
'number': count,
'title': comic_titile.text,
'content': comic.img.get('title'),
'link': urljoin('https:', comic.img.get('src')),
'format': comic.img.get('src').split('.')[-1]
}
req = requests.get(image['link'], stream=True)
filename = 'temp.' + image['format']
with open(filename, 'wb') as temp:
for chunk in req.iter_content(chunk_size=1024 * 256):
temp.write(chunk)
return image
def show_image(image_data):
file = 'temp.' + image_data['format']
options = ['Favorite', 'Next', 'Close']
title = '{}: {}'.format(
image_data['number'], image_data['title'])
message = image_data['content']
select = gui.buttonbox(
title=title, choices=options,
image=file, msg=message)
if select is None:
select = 'Close'
return select
def save_image(image, data):
count = image['number']
if count - 1 in data['FavoriteComics']:
msg = 'This image is already in your favorites.'
title = 'File Exists.'
gui.msgbox(msg=msg, title=title)
else:
from_file = 'temp.' + image['format']
to_file = image['title'].strip('.') + '.' + image['format']
path = os.path.expanduser('~')
path = os.path.join(path, 'Pictures', 'xkcd')
to_file = os.path.join(path, to_file)
if not os.path.isdir(path):
os.makedirs(path)
os.rename(from_file, to_file)
data['FavoriteComics'].add(count - 1)
def main():
if os.path.isfile('metadata.pkl'):
with open('metadata.pkl', 'rb') as meta:
data = pickle.load(meta)
else:
data = {
'LastComicPage': 0,
'FavoriteComics': set(),
'SharedComics': set(),
'ComicLimit': 1863,
}
count = data['LastComicPage'] + 1
while True:
image = get_image(count)
if not image:
data['ComicLimit'] = count
data['LastComicPage']
msg = 'No More Comics at the moment.\n'
msg += 'Do you want to start from first comic.'
title = 'Sorry'
options = ['Yes', 'No', 'Close']
select = gui.buttonbox(
msg=msg, title=title, choices=options, cancel_choice='Close')
if select == 'Close':
quit()
elif select == 'Yes':
data['LastComicPage'] = count = 1
image = get_image(count)
elif select == 'No':
msg = 'Nothing else i can do.'
title = 'Sorry'
gui.msgbox(msg=msg, title=title)
quit()
opt = show_image(image)
count += 1
if opt == 'Close':
break
elif opt == 'Favorite':
save_image(image, data)
elif opt == 'Next':
continue
data['LastComicPage'] = count - 1
with open('metadata.pkl', 'wb') as meta:
pickle.dump(data, meta)
main()