示例#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."
        )
示例#2
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'))
示例#3
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
示例#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)
示例#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)
示例#7
0
文件: misc.py 项目: joseplj/GabberAPI
    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'])
示例#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)
示例#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
示例#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)
示例#11
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)
示例#12
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\""
示例#13
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
示例#14
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')
示例#15
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)

示例#16
0
 def __init__(self, api_key, app_name='quote-me-ai'):
     self.unsplash = PyUnsplash(api_key=api_key)
     self.app_name = app_name
示例#17
0
def get_unsplash_session():
    creds = settings.unsplash_auth()
    # instantiate PyUnsplash object
    api = PyUnsplash(api_key=creds["unsplash_access_key"])
    return api