forked from mattzzw/kindle-gphotos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_photo.py
executable file
·153 lines (122 loc) · 4.82 KB
/
get_photo.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
#!/usr/bin/env python3
# coding: utf8
import random
import json
import logging
from pathlib import Path
from random import randrange
import flickrapi
import requests
from PIL import Image, ImageOps
from gphotos.authorize import Authorize
from gphotos.restclient import RestClient
log = logging.getLogger()
logging.basicConfig(level=logging.WARNING)
# log.setLevel(logging.NOTSET)
class KindlePhotos:
def __init__(self):
self.auth: Authorize = None
self.provider = "flickr"
def setup(self):
if self.provider == "google":
credentials_file = Path(".gphotos.token")
secret_file = Path("client_secret.json")
scope = [
"https://www.googleapis.com/auth/photoslibrary.readonly",
"https://www.googleapis.com/auth/photoslibrary.sharing",
]
photos_api_url = (
"https://photoslibrary.googleapis.com/$discovery" "/rest?version=v1"
)
self.album_title = 'Kindle'
self.auth = Authorize(
scope, credentials_file, secret_file, 3)
self.auth.authorize()
self.google_photos_client = RestClient(
photos_api_url, self.auth.session)
elif self.provider == "flickr":
flickr_json = json.load(open("flickr.json"))
self.flickr = flickrapi.FlickrAPI(
flickr_json['key'], flickr_json['secret'], format='parsed-json')
def start(self):
log.debug("Starting up...")
if self.provider == "google":
# Get album list
mylist = self.google_photos_client.sharedAlbums.list.execute(
pageSize=50).json()
# Get album ID
items_count = 0
for album in mylist['sharedAlbums']:
if 'title' in album.keys():
log.debug('"'+album['title']+'"')
if album['title'] == self.album_title:
print(album['title'], album['mediaItemsCount'])
items_count = int(album['mediaItemsCount'])
album_id = album['id']
if not items_count:
quit()
# Get list of images
body = {
"pageSize": 50,
"albumId": album_id,
# "filters": {
# "mediaTypeFilter": {"mediaTypes": ["PHOTO"]},
# },
}
photo_list = self.google_photos_client.mediaItems.search.execute(
body).json()
notfound = 1
while (notfound):
idx = randrange(items_count)
log.debug(idx)
if photo_list['mediaItems'][idx]['mimeType'] in ["image/jpeg", "image/png"]:
notfound = 0
media_item = photo_list['mediaItems'][idx]
# Download photo
url = str(media_item['baseUrl'])+'=w2048-h1024'
elif self.provider == "flickr":
extras = 'url_c, tags, description' # Medium sized url
flickr_json = json.load(open("flickr.json"))
user_id = flickr_json['user_id']
tags = (', ').join(flickr_json['tags'])
bad_tags = flickr_json['bad_tags']
good_tags = False
while not good_tags:
random.seed()
rand_page = random.randrange(1, 258, 1)
print('Random page:', rand_page)
# Get random photo of flower
photos = self.flickr.photos.search(
user_id=user_id, page=rand_page, per_page=25,
tag_mode='any', orientation='portrait',
tags=tags, extras=extras)
photos = photos['photos']
print('Number of pages:', photos['pages'])
# Check for photos
photo_list = photos['photo']
if len(photo_list) == 0:
continue
# Iterate through page and check tags
for photo in random.shuffle(photo_list):
photo_tags = photo['tags'].split(' ')
if any(p in photo_tags for p in bad_tags):
continue
good_tags = True
break
photo = random.choice(photo_list)
# Get medium sized image
url = photo['url_c']
else:
url = "https://source.unsplash.com/random/600x800"
print(url)
# Image processing
open('photo.jpg', 'wb').write(requests.get(url).content)
img = Image.open('photo.jpg')
img = ImageOps.grayscale(img)
img = ImageOps.autocontrast(img)
img.save('photo.jpg')
def main(self):
self.setup()
self.start()
if __name__ == '__main__':
KindlePhotos().main()