-
Notifications
You must be signed in to change notification settings - Fork 0
/
upload.py
executable file
·217 lines (177 loc) · 7.81 KB
/
upload.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
#!/usr/bin/python
# -*- coding: utf-8 -*-
from argparse import ArgumentParser
from lib.index import Index
from lib.smugmug import API, SmugmugException
from lib.logging_utils import setup_logging
from lib.decorators import memoize
from lib.fs_utils import read_exif
from ConfigParser import ConfigParser
from os import path
import logging
import codecs
import locale
import sys
import re
setup_logging('upload.log')
# Wrap sys.stdout into a StreamWriter to allow writing unicode.
sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout)
def is_ascii(path):
return all(ord(ch) < 128 for ch in path)
def get_parser():
parser = ArgumentParser()
parser.add_argument('archive_dir', help='Home directory.')
parser.add_argument('--config', help='Path to config file.', default='config.ini')
parser.add_argument('--skip-unicode-filenames', default=False,
action='store_true')
parser.add_argument('--move', default=False, action='store_true',
help='Check already-uploaded files and move to correct '
'album if required.')
return parser
ALBUM_NAME_REGEXP = re.compile(r'\d{4}-\d{2}-\d{2}')
def get_subcategory_album_name(path):
chunks = path.split('/')
year_month = chunks[0]
album_name = chunks[1][:10]
if not ALBUM_NAME_REGEXP.match(album_name):
album_name = 'Uncategorized'
return year_month, album_name
def get_required_albums(index):
'Returns a list of ("subcategory name", "album name")'
albums = set()
for date in index.get_distinct('date'):
if date is None:
albums.add(('Uncategorized', 'Uncategorized'))
else:
albums.add((date[:7], date))
return sorted(albums)
def create_required_albums(api, category, required_albums):
categories = api.get_categories()
if category not in categories:
raise Exception('Cannot find category %s', category)
cid = categories[category]
subcategories = api.get_subcategories(cid)
existing_albums = {(album['Category']['id'],
album['SubCategory']['id'],
album['Title']): {'id': album['id'],
'Key': album['Key']}
for album in api.get_albums()
if 'SubCategory' in album}
for subcategory, album in required_albums:
if subcategory not in subcategories:
logging.info('Creating subcategory %s ..', subcategory)
sid = api.create_subcategory(cid, subcategory)
subcategories[subcategory] = sid
else:
sid = subcategories[subcategory]
if (cid, sid, album) not in existing_albums:
logging.info('Creating album %s/%s/%s ..' % (category,
subcategory,
album))
key, id = api.create_album(album.encode('utf-8'), cid,
{'Public': False,
'SmugSearchable': False,
'SubCategoryID': sid})
existing_albums[(cid, sid, album)] = {'Key': key,
'id': id}
subcategory_reverse_map = {v: k for k, v in subcategories.items()}
return {(subcategory_reverse_map[sid], album): val
for (cat_id, sid, album), val in existing_albums.items()
if cid == cat_id}
def retry(job, times):
for i in xrange(times):
try:
return job()
except KeyboardInterrupt:
raise
except Exception as e:
pass
raise e
def has_non_standard_colorspace(path):
""" Returns if colorspace is not sRGB:
Smugmug converts all uploaded photos to sRGB. Therefore these photos should not
be checked using MD5 checksum."""
if not path.lower().endswith('.jpg'): return False
exif = read_exif(path)
return 'sRGB' not in exif.get('Profile Description', 'sRGB')
def upload_file(api, path, filesize, md5, album_id):
ret = api.upload(path, album_id, filesize, md5, hidden=True)
if ret['stat'] != 'ok':
logging.info('FAILED to upload %s: result JSON %s',
path, str(ret))
return False
info = api.get_image_info(ret['Image']['id'], ret['Image']['Key'])
if info['Image']['MD5Sum'] != md5:
logging.info('Uploaded file is corrupt! Expected md5: %s Got md5: %s',
md5, info['Image']['MD5Sum'])
logging.info('Path: %s', path)
if not has_non_standard_colorspace(path):
api.delete_image(ret['Image']['id'])
return False
logging.info('However, original picture has non-sRGB colorspace; carrying on.')
return ret['Image']
def upload_file_retry(api, path, filesize, md5, album_id, tries=3):
logging.info('Uploading file %s to album %d..', path, album_id)
exception = None
ret = None
while tries > 0:
tries -= 1
try:
ret = upload_file(api, path, filesize, md5, album_id)
if ret: return ret
except Exception as e:
exception = e
logging.warning('Exception raised: %s', str(e))
if exception: raise exception
return False
def upload(home, index, api, to_upload, albums):
total_size = sum(img['filesize'] for img in to_upload)
logging.info('%d files will be uploaded.' % len(to_upload))
for idx, img in enumerate(to_upload):
subcategory, album = get_subcategory_album_name(img['path'])
album_info = albums[(subcategory, album)]
logging.info('Uploading %s (%dkb).. (#%d/%d)', img['path'],
img['filesize'] / 1024,
idx+1,
len(to_upload))
image_info = upload_file_retry(api, path.join(home, img['path']),
img['filesize'], img['md5'], album_info['id'])
if image_info:
logging.info('Uploaded %s to image id: %d image key: %s',
img['path'], image_info['id'], image_info['Key'])
index.set(img['rowid'],
smugmug_id=image_info['id'],
smugmug_key=image_info['Key'],
smugmug_album_id=album_info['id'],
smugmug_album_key=album_info['Key'])
else:
logging.info('failed to upload image %s after repeated tries.',
img['path'])
index.set(img['rowid'], smugmug_error='Failed to upload')
def main():
args = get_parser().parse_args()
cp = ConfigParser()
cp.readfp(open(args.config))
home = args.archive_dir
default_category = cp.get('Smugmug', 'DEFAULT_CATEGORY')
api = API(cp.get('Smugmug', 'APIKEY'), cp.get('Smugmug', 'USERID'), cp.get('Smugmug', 'PASSWORD'))
logging.info('Logging in..')
api.login()
try:
with Index(path.join(home, 'pictures.db')) as index:
logging.info('Creating required albums ..')
required_albums = get_required_albums(index)
albums = create_required_albums(api, default_category, required_albums)
images = index.get(smugmug_id=None)
images.sort(key=lambda img: img['date'])
images.reverse()
images = [img for img in images if img['smugmug_error'] is None]
if args.skip_unicode_filenames:
images = [img for img in images if is_ascii(img['path'])]
# skip everything over 1gb for now... hmm...
images = [img for img in images if img['filesize'] < 1024*1024*1024]
upload(home, index, api, images, albums)
except SmugmugException as e:
logging.critical('SmugmugException: %s', str(e.response))
if __name__ == '__main__':
main()