|
import flickrapi |
|
import urllib.request |
|
import os.path |
|
import json |
|
|
|
# Make it work for Python 2+3 and with Unicode |
|
import io |
|
try: |
|
to_unicode = unicode |
|
except NameError: |
|
to_unicode = str |
|
|
|
api_key = u'API_KEY' # CHANGE THIS |
|
api_secret = u'API_SECRET' # AND THIS |
|
directory = './photos' # change if you need |
|
|
|
flickr = flickrapi.FlickrAPI(api_key, api_secret, format='parsed-json') |
|
flickr.authenticate_via_browser(perms='read') |
|
|
|
def downloadPhoto(p, file_name): |
|
if 'url_o' in p: |
|
url = p['url_o'] |
|
else: |
|
url = "https://farm{farm}.staticflickr.com/{server}/{id}_{secret}_b.jpg".format(**p) # use large size |
|
print("using fallback url {url}".format(url=url)) |
|
|
|
try: |
|
urllib.request.urlretrieve(url, file_name) |
|
return True |
|
except Exception as inst: |
|
print(type(inst)) |
|
print(inst) |
|
return False |
|
|
|
|
|
# TODO - favorite getList pagination |
|
favs = flickr.favorites.getList(per_page=500,extras="url_o") |
|
|
|
photosInfo = {} |
|
counter = 0 |
|
|
|
# ensure photos directory exists |
|
if not os.path.exists(directory): |
|
os.makedirs(directory) |
|
|
|
for p in favs['photos']['photo']: |
|
counter = counter + 1 |
|
# print(p) |
|
file_name = "{directory}/{title}.jpg".format(directory=directory, title=p['title']) |
|
|
|
if not os.path.exists(file_name): |
|
print("{counter} - attempting to download {title}".format(counter=counter, title=p['title'])) |
|
downloadSuccessful = downloadPhoto(p, file_name) |
|
info = flickr.photos.getInfo(photo_id=p['id'], secret=p['secret']) |
|
|
|
if downloadSuccessful: |
|
photosInfo[file_name] = info['photo'] |
|
else: |
|
print("unable to download image {id}".format(id=p['id'])) |
|
|
|
break |
|
|
|
# Write JSON file |
|
with io.open('photoData.json', 'w', encoding='utf8') as outfile: |
|
str_ = json.dumps(photosInfo, |
|
indent=4, sort_keys=True, |
|
separators=(',', ': '), ensure_ascii=False) |
|
outfile.write(to_unicode(str_)) |