Exemplo n.º 1
0
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."
        )
Exemplo n.º 2
0
    def test_collections_curated(self):
        type = 'curated'
        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)
        collections = pu_obj.collections(type_=type)
        assert collections.body is not None
        assert collections.header is not None
        assert collections.status_code == 200
        for collection in collections.entries:
            print(collection.id, collection.title, collection.description,
                  collection.user, collection.link_photos,
                  collection.link_related)
        assert collections.link_next is not None
        assert collections.link_previous is not None
        assert collections.link_first is not None
        assert collections.link_last is not None
Exemplo n.º 3
0
    def test_user_stats(self):
        username = '******'

        # Add the user api response
        type = 'salvoventura'
        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')
        )

        # Add the user statistics api response
        type = 'salvoventura_statistics'
        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)
        this_user = pu_obj.user(source=username)  # create a User object
        this_user_stats = this_user.statistics()  # fetch a UserStatistics object
        print(this_user_stats.downloads.get('total'), this_user_stats.views.get('total'), this_user_stats.likes.get('total'))
Exemplo n.º 4
0
    def test_photos_curated(self):
        type = 'curated'
        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)
        photos = pu_obj.photos(type_=type)
        assert photos.body is not None
        assert photos.header is not None
        assert photos.status_code == 200
        for photo in photos.entries:
            # if any of the fields breaks, then it's a problem
            print(photo.id, photo.link_html, photo.link_download,
                  photo.link_download_location
                  )  # , photo.stats  # TODO: include stats in unit test
 def get_link(self):
     pu = PyUnsplash(self.api_key)
     photos = pu.photos(type_='random',
                        order_by='popular',
                        orientaion='landscape',
                        count=3)
     link = []
     for photo in photos.entries:
         photo.refresh()
         data = {'Photo Id': photo.id, 'Url': photo.link_download}
         link.append(data)
         #print(data['Url'])
     print(link)
Exemplo n.º 6
0
 def test_stats_total(self):
     type = 'salvoventura'
     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)
     this_user = pu_obj.user(source=type)
     print(this_user.id, this_user.link_html, this_user.link_portfolio, this_user.link_following, this_user.link_followers, this_user.link_photos)
Exemplo n.º 7
0
    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'])
Exemplo n.º 8
0
 def test_stats_total(self):
     type = 'total'
     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)
     stats = pu_obj.stats()
     # TODO: implement after successful stats download
     print(stats.total)
Exemplo n.º 9
0
 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
Exemplo n.º 10
0
 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)
Exemplo n.º 11
0
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)
Exemplo n.º 12
0
 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)
Exemplo n.º 13
0
#             if searchFont in row:
#                 targetFont.append(row)
#         except TypeError:
#             pass
#     font = ImageFont.truetype(targetFont[0], 16)
#
#     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\""
Exemplo n.º 14
0
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)

# Get a page from the collections api
# Parameters:
#   'type' : 'generic', 'curated', 'featured'
#            default: 'generic'
#   'page' : <int>, which page to retrieve
#   'per_page': <int>, how many collections to include in each page
#
collections_page = py_un.collections(type_='generic', per_page=3)

# iterate through all the collections retrieved in the collections_page, two ways
# 1) iterating through 'body' returns just a dictionary, no additional API call
for collection in collections_page.body:
    print('Collection as dictionary', collection.get('id'), collection.get('title'))
Exemplo n.º 15
0
import logging
from pyunsplash import PyUnsplash
api_key = '#######################'

# instantiate PyUnsplash object
py_un = 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
#
collections = py_un.collections(per_page=20)
while collections.has_next:
    for collection in collections.entries:
        photos = collection.photos()
        for photo in photos.entries:
            print(photo.link_download)

    # no need to specify per_page: will take from original object
    collections = collections.get_next_page()
Exemplo n.º 16
0
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
Exemplo n.º 17
0
 def __init__(self, api_key, app_name='quote-me-ai'):
     self.unsplash = PyUnsplash(api_key=api_key)
     self.app_name = app_name
Exemplo n.º 18
0
#    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()
Exemplo n.º 19
0

def first_one(img_search):
    for photo in img_search.entries:
        return (photo.link_download)


def polari_check(search):
    search = TextBlob(search)
    try:
        return search.sentiment.polarity
    except ValueError:
        return "cant find polarity"


img_yes = PyUnsplash(api_key=os.getenv('PU'))


def find_ety(search):
    search = ety.origins(search)
    word_origin_list = ""
    for word in search:
        word_origin_list += str(word)
    return word_origin_list


def syn_find(search):
    dictionary = PyDictionary()
    return dictionary.synonym(search)

Exemplo n.º 20
0
def get_unsplash_session():
    creds = settings.unsplash_auth()
    # instantiate PyUnsplash object
    api = PyUnsplash(api_key=creds["unsplash_access_key"])
    return api
Exemplo n.º 21
0
def getImages(client_id):
    py_un = PyUnsplash(api_key=client_id)
    logging.getLogger("pyunsplash").setLevel(logging.DEBUG)
    # retrieve 4 random photos, which are featured, and tagged as "dog"
    return py_un.photos(type_='random', count=1, query='noir')
Exemplo n.º 22
0
#    Author: Salvatore Ventura <*****@*****.**>
#      Date: 5/9/2020
#   Purpose: Example file for SinglePhoto
#
#  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)

# Get a single photo from a known ID
photo = py_un.photos(type_="single", photo_id='l0_kVknpO2g')
print(photo.entries.get_attribution(format='txt'))
print(photo.entries.get_attribution(format='html'))
Exemplo n.º 23
0
        f.write(args.api_key)
    api_key = args.api_key
else:
    with open(API_KEY_FILE, 'r') as f:
        api_key = f.read()

# Initialize app logging
logger = logging.getLogger()
logging.basicConfig(filename='app.log',
                    format='%(asctime)s %(levelname)s:%(message)s',
                    level=args.verbose,
                    datefmt='%m/%d/%Y %I:%M:%S %p')
logging.getLogger(PyUnsplash.logger_name).setLevel(args.verbose)

# instantiate PyUnsplash object
py_un = PyUnsplash(api_key=api_key)

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))