def unsplash_parse_resp(subject): """ From Unsplash API, collect the top 4 images from results. :param subject: The subject to be used for the image search or type(None). If None, random photos are fetched. :rtype images: A list containing data on the fetched images. :except AttributeErrror: Occurs when resp fails to fetch images and enumerate cannot parse resp. """ py_un = PyUnsplash(api_key=UNSPLASH_CLIENT_ID) images = [] if subject is not None: resp = py_un.search("photos", query=subject, per_page=4) else: resp = py_un.photos(type_="random", count=4) # Gather data from resp object. try: for num, item in enumerate(resp.entries, 1): image_info = { "author_name": item.body["user"]["name"], "full_image": item.body["urls"]["full"], "image_id": item.id, "author_profile": f"{item.body['user']['links']['html']}?utm_source=Wallie&utm_medium=referral", "download_location": item.link_download_location, } images.append(image_info) return images except AttributeError as err: handle_err( f"Failed to parse unsplash resp object: {err}\nCheck that your API_KEYs are setup correctly." )
class Unsplash: def __init__(self, api_key, app_name='quote-me-ai'): self.unsplash = PyUnsplash(api_key=api_key) self.app_name = app_name def get_photos(self, query, num): photos = [] search = self.unsplash.search(type_='photos', query=query, per_page=30) for entry in search.entries: if len(photos) >= num: break description = entry.body.get('description', None) photo_url = entry.body.get('urls', None) if photo_url: photo_url = photo_url.get('regular', None) if entry.link_download_location and description and photo_url: photographer_text = '''Photo by %s?utm_source=%s&utm_medium=referral %s on https://unsplash.com/?utm_source=%s&utm_medium=referral''' % ( entry.body['user']['links']['html'], self.app_name, entry.body['user']['name'], self.app_name) photos.append( ('%s?client_id=%s' % (entry.link_download_location, config.UNSPLASH_API_KEY), photo_url, description, photographer_text)) return photos @staticmethod def trigger_download(url): response = requests.get(url=url)
def get(self): """ Retrieves a list of thumbnails """ from flask import current_app as app query = request.args.get('query', None) if query: pu = PyUnsplash(api_key=app.config['PHOTOS_API_KEY']) search = pu.search(type_='photos', query=query) thumbnails = [ photo.body['urls']['thumb'] for photo in list(search.entries) ] return custom_response(200, data={'thumbnails': thumbnails}) return custom_response(500, errors=['general.NO_PHOTOS'])
def test_search_users(self): type = 'users' resource_filepath = self.store_mapping[type] stored_response = json.loads(open(resource_filepath).read()) responses.add( responses.GET, '{}{}'.format(API_ROOT, stored_response.get('url').split('?')[0]), # cheating on the url, because the class always inits without query params json=stored_response.get('body'), status=stored_response.get('status_code'), content_type='application/json', adding_headers=stored_response.get('headers') ) pu_obj = PyUnsplash(api_key=api_key) search = pu_obj.search(type, query='tree') for user in search.entries: print(user.id, user.link_html, user.link_portfolio, user.link_following, user.link_followers, user.link_photos)
def test_search_photos(self): type = 'photos' resource_filepath = self.store_mapping[type] stored_response = json.loads(open(resource_filepath).read()) responses.add( responses.GET, '{}{}'.format(API_ROOT, stored_response.get('url').split('?')[0]), # cheating on the url, because the class always inits without query params json=stored_response.get('body'), status=stored_response.get('status_code'), content_type='application/json', adding_headers=stored_response.get('headers') ) pu_obj = PyUnsplash(api_key=api_key) search = pu_obj.search(type, query='tree') for photo in search.entries: print(photo.id, photo.link_html, photo.link_download, photo.link_download_location) # , photo.stats # TODO: include stats in unit test
def test_search_collections(self): type = 'collections' resource_filepath = self.store_mapping[type] stored_response = json.loads(open(resource_filepath).read()) responses.add( responses.GET, '{}{}'.format(API_ROOT, stored_response.get('url').split('?')[0]), # cheating on the url, because the class always inits without query params json=stored_response.get('body'), status=stored_response.get('status_code'), content_type='application/json', adding_headers=stored_response.get('headers') ) pu_obj = PyUnsplash(api_key=api_key) search = pu_obj.search(type, query='tree') for collection in search.entries: print(collection.id, collection.title, collection.description, collection.user, collection.link_photos, collection.link_related)
# margin = offset = 40 # for line in textwrap.wrap(str_qtd[0], width=60): # draw.text((margin, offset), line, font=font) # offset += font.getsize(line)[1] # wrapper = textwrap.TextWrapper(width=50) # image.save('test.png') # elif display_option == 4: api_key = '4d567a0f2dea38fb54e06c03a3efa0e8df73cdec5de06bc5c62653033357b90c' py_un = PyUnsplash(api_key=api_key) randNumb1 = randint(1, 5) pageLength = 30 randNumb2 = randint(0, pageLength - 1) listPhoto = py_un.search(type_='photos', query='white', per_page=pageLength, page=randNumb1) i = 1 for photo in listPhoto.entries: # print(photo.link_download) i = i + 1 if i >= randNumb2: cmd = "wget " + photo.link_download + " --output-document=\"" + "unsplash.jpeg\"" cp = subprocess.run([cmd], shell=True, stdout=subprocess.PIPE) break cp = subprocess.run([ "convert unsplash.jpeg -resize 640x384! -type GrayScale -depth 8 -rotate \"180\" black1.bmp" ], shell=True,
import logging from pyunsplash import PyUnsplash # instantiate PyUnsplash object pu = PyUnsplash(api_key=api_key) # pyunsplash logger defaults to level logging.ERROR # If you need to change that, use getLogger/setLevel # on the module logger, like this: logging.getLogger("pyunsplash").setLevel(logging.DEBUG) # Start with the generic collection, maximize number of items # note: this will run until all photos of all collections have # been visited, unless a connection error occurs. # Typically the API hourly limit gets hit during this images = [] search = pu.search(type_='photos', query='refugee camps') for entry in search.entries: linkAndAuthor = {} linkAndAuthor['link'] = entry.link_download linkAndAuthor['author'] = entry.get_attribution() images.append(linkAndAuthor) print(images) # no need to specify per_page: will take from original object # no need to specify per_page: will take from original object
# Author: Salvatore Ventura <*****@*****.**> # Date: 6/1/2020 # Purpose: Example file for Search # # Revision: 1 # Comment: What's new in revision 1 # ############################################################################### import logging import os from pyunsplash import PyUnsplash api_key = os.environ.get('APPLICATION_ID', None) or 'DUMMY_APPLICATION_ID' # Initialize app logging logger = logging.getLogger() logging.basicConfig(filename='app.log', level=logging.DEBUG) # pyunsplash logger defaults to level logging.ERROR # If you need to change that, use getLogger/setLevel # on the module logger, like this: logging.getLogger(PyUnsplash.logger_name).setLevel(logging.DEBUG) # instantiate PyUnsplash object py_un = PyUnsplash(api_key=api_key) search = py_un.search(type_="photos", query="bear") while search.has_next: print(search.link_next, search.link_last) search = search.get_next_page()
now = datetime.now().strftime("slideshow-%d_%m_%Y-%H:%M:%S") outDir = join(getcwd(), now) mkdir(outDir) if args.count > MAX_PER_PAGE: pages = (args.count + (MAX_PER_PAGE - 1)) // MAX_PER_PAGE per_page = MAX_PER_PAGE else: pages = 1 per_page = args.count for q in args.query: count = 0 print("Collecting {:s} query".format(q)) search = py_un.search(type_='photos', page=pages, per_page=per_page, query=str(q)) while search and search.has_next: #print(collections_page) for photo in search.entries: urls = photo.body.get('urls', None)['raw'] url = "{:s}&fit=crop&crop=focalpoint&w={:d}&h={:d}&fm=jpg".format( urls, args.width, args.height) outFile = join( outDir, '{:s}-{:d}x{:d}.jpg'.format(photo.id, args.width, args.height)) wget.download(url, out=outFile) count = count + 1 if (count >= args.count): search = None break