def __init__(self, keyword):
     client_id = "e1f37996871427d8a491cda804e65e9fde2e1ae55c7e6996a34bb1216ea25471"
     client_secret = "810ea5b466bd7b5cd6a93103cf71430e38ca423e000b00b2446d857b2547875a"
     redirect_uri = "urn:ietf:wg:oauth:2.0:oob"
     auth = Auth(client_id, client_secret, redirect_uri)
     self.api = Api(auth)
     self.photos_urls = self.get_photos_urls_by_keyword(keyword)
Beispiel #2
0
def search_images_unsplash(request):
    """Search image from unsplash"""
    if request.method == 'GET':
        form = ImageSearchForm()
        return render(request, 'core/search_img.html', {'form': form})
    if request.method == 'POST':
        tag = request.POST['tags']
        auth = Auth(client_id, client_secret, redirect_uri, code=code)
        api = Api(auth)
        images = api.search.photos(tag)
        results = images.get('results')

        paginator = Paginator(results, 3)
        page_request_var = 'page'
        page = request.GET.get(page_request_var)
        try:
            paginated_queryset = paginator.page(page)
        except PageNotAnInteger:
            paginated_queryset = paginator.page(1)
        except EmptyPage:
            paginated_queryset = paginator.page(paginator.num_pages)

        context = {
            'images': paginated_queryset,
            'page_request_var': page_request_var
        }
        return render(request, 'core/list_img_unsplash.html', context=context)
def get_img():
    auth = Auth(access_key, secret_key, redirect_uri)
    api = Api(auth)
    photo = api.photo.random(query="Wallpaper", orientation="landscape")[0]

    #finding the format of the image from the download link
    link = photo.urls.full
    n = link.find('fm=')
    m = n + link[n:].find('&')
    forma = link[n + 3:m]

    if saveImg:
        try:
            name = photo.alt_description.replace(" ", "_") + '.' + forma
        except:
            name = str(datetime.now()) + forma
    else:
        #find the img format to delete it
        name = 'background.' + forma
        files = os.listdir()
        for i in range(len(files)):
            if files[i].startswith("background."):
                #remove old image
                try:
                    os.remove(files[i])
                except:
                    raise Warning("background file not found, not removing")

    download(link, name)
    return name
Beispiel #4
0
def auth_unsplash():
    auth = Auth(UNSPLASH_CLIENT_ID,
                UNSPLASH_CLIENT_SECRET,
                UNSPLASH_REDIRECT_URI,
                code=UNSPLASH_CODE)
    api = Api(auth)
    print('Logged in into unsplash')
    return api
Beispiel #5
0
 def setUp(self):
     if self.token:
         self.auth = Auth(client_id,
                          client_secret,
                          redirect_uri,
                          scope=scope,
                          token=token)
         self.is_authenticated = True
     elif self.code:
         self.auth = Auth(client_id,
                          client_secret,
                          redirect_uri,
                          scope=scope,
                          code=code)
         self.is_authenticated = True
     else:
         self.auth = Auth(client_id,
                          client_secret,
                          redirect_uri,
                          scope=scope)
     self.api = Api(self.auth)
    def __init__(self):

        # load credentials for image APIs
        load_dotenv()

        # set credentials
        client_id = os.getenv("CLIENT_ID")
        client_secret = os.getenv("SECRET_KEY")
        redirect_uri = os.getenv('REDIRECT_URI')

        # create api object
        auth = Auth(client_id, client_secret, redirect_uri)
        self.api = Api(auth)
Beispiel #7
0
def index():
    # Authentication and access to the API of Tweepy
    auth = OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)

    # Search for the tag "DFIR" and get last_tweet 100 tweets in 01 page
    tweepy_api = tw_API(auth)
    tweets_search_4tag = tweepy_api.search("#DFIR",
                                           lang='en',
                                           rpp=100,
                                           tweet_mode="extended")

    # cursor on the search
    tweets_5 = []
    for status in tweepy.Cursor(tweepy_api.search,
                                q="#DFIR",
                                lang='en',
                                rpp=100,
                                tweet_mode="extended").items(5):
        tweets_5.append(status.full_text)

    # get last tweet
    last_tweet = tweets_search_4tag[0]
    tweet_text = last_tweet.full_text

    client_id = os.environ['access_key_unsplash']
    client_secret = os.environ['secret_key_unsplash']
    redirect_uri = os.environ['redirect_uri_unsplash']
    code = os.environ['code_unsplash']

    # Authentication and api instanciation
    auth = Auth(client_id, "", "", "")
    unsplash_api = us_API(auth)

    # Get a random photo object using the api
    bg_photo = unsplash_api.photo.random()

    # Get URLs  of the random photo to be set
    bg_photo_urls = bg_photo[0].urls
    bg_photo_custom_url = bg_photo_urls.raw + "&fit=clamp&h=300&w=350&auto=compress"

    return render_template("base.html",
                           tweet=tweet_text,
                           tweets=tweets_5,
                           bg_photo_url=bg_photo_custom_url)
Beispiel #8
0
RED = "🍎"
YELLOW = "🌼"
BLUE = "🦋"
PURPLE = "☂️"
BLACK = "♣️"

with open("secret.json") as f:
    keys = json.load(f)

client_id = keys["client_id"]
client_secret = keys["client_secret"]
redirect_uri = keys["redirect_uri"]
code = keys["code"]

auth = Auth(client_id, client_secret, redirect_uri, code=code)
api = Api(auth)


class UnsplashPhoto:
    def __init__(self, url, photo_id):
        self.url = url
        self.photo_id = photo_id


def download_image(url, filename):
    response = requests.get(url)
    file = open("images/" + filename, "wb")
    file.write(response.content)
    file.close()
    return file
import urllib.request
import random
from unsplash.api import Api
from unsplash.auth import Auth

client_id = "unsplashed_api_id"
client_secret = "unsplashed_secret_key"
redirect_uri = "localhost"

auth = Auth(client_id, client_secret, redirect_uri)
api = Api(auth)
for x in range(4):
    photo = api.photo.get(
        api.photo.random(query='mountains', w=3840, count=1)[random.randint(
            0,
            len(api.photo.random(query='mountains', w=3840, count=1)) - 1)].id)

    def downloader(image_url):
        full_file_name = 'wallpaper' + str(x) + '.jpg'
        urllib.request.urlretrieve(image_url, full_file_name)

    downloader('https://unsplash.com/photos/' + photo.id + '/download')
Beispiel #10
0
import os
import time
import requests
import ctypes
import urllib.request
import config
from unsplash.api import Api
from unsplash.auth import Auth

auth = Auth(config.client_id, config.client_secret, config.redirect_uri, code=config.code)
api = Api(auth)


def get_wallpaper():
    query = "kitten"
    photo = api.photo.random(query=query)
    photo_id = photo[0].id
    url = "https://api.unsplash.com/photos/%s/download?client_id=%s" % (photo_id, config.client_id)
    res = requests.get(url)
    if res.status_code == 200:
        photo = res.json()
        link = photo["url"]
        print(link)
        with open("img.jpg", "wb") as f:
            f.write(urllib.request.urlopen(link).read())
    else:
        print("unable to make request")


def set_wallpaper():
    get_wallpaper()
 def authentication(self):
     auth = Auth(self.client_id,
                 self.client_secret,
                 self.redirect_uri,
                 code=self.code)
     api = Api(auth)
Beispiel #12
0
    i = 0
    if (len(sys.argv) > 1):
        n = int(sys.argv[1])
    else:
        n = 999
    while i < n:
        print("Iteration number " + str(i) + "...")
        data = getQuote()
        createImg(data)
        postQuote(data)
        time.sleep(config['timeout'])
        i = i + 1
    print("End program\n")


####

config = load_config()
InstagramApi = InstagramAPI(config['ig_username'], config['ig_password'])
print("\nLogin on Instagram:")
print "IG Username:", config['ig_username']
InstagramApi.login()  # login

auth = Auth(config['client_id'],
            config['client_secret'],
            config['redirect_uri'],
            code=config['code'])
api = Api(auth)

main()
def recommend(orig_photo_url, text):
    """
    Handles the image recommending.
    :param orig_photo_url: the url where the
    :param text: the context text to look at to rank the tags
    :return:
    """
    # get a file so we can write results into it
    results_file = open('Everest_WierdD_0_01.output', 'w')

    #get unsplash API stuff
    client_id = os.environ.get('UNSPLASH_ID', None)
    client_secret = os.environ.get('UNSPLASH_SECRET', None)
    redirect_uri = ""
    code = ""
    auth = Auth(client_id, client_secret, redirect_uri, code=code)
    api = Api(auth)
    photo_worker = Photo(api=api)

    # get env variable Azure API key
    azure_key = os.environ.get('AZURE_KEY', None)

    # do Azure analysis on the original photo that we want recommendations for, and write the retrieved into to a file
    orig_tags, orig_captions = azureAnalysis(orig_photo_url, azure_key)
    write_picture_info(results_file, 'Original Photo:', orig_photo_url, orig_tags, orig_captions)

    # use those tags and the text provided to get a re-ranking of the importance of tags/search terms
    search_terms = keyworder.get_search_terms(orig_tags, text, results_file)

    tagged_photos = {} # a dict which maps the url where we can find a photo to the tags of that photo

    # iterate through the top 3 search terms and search each one
    for term in search_terms[:5]:
        photo_urls = unsplashRequest(term, api, photo_worker)

        # analyze each of the photos returned
        for i, url in enumerate(photo_urls):
            try:
                # the following line will throw an KeyError if Azure can't use the photo url, which happens often
                tags, captions = azureAnalysis(url, azure_key)
                tagged_photos[url] = tags

                # write information about this photo to a file
                heading = 'Search term: %s\tResult #%d' %(term, i)
                write_picture_info(results_file, heading, url, tags, captions)
            except KeyError:
                print('KeyError with image. Image is probably "not accessible." Moving on to next one.')

    scores = {} # this dict will map photo urls to a similarity score, so that we can find the most similar photo
    for url, tags in tagged_photos.items():
        scores[url] = jaccard(orig_tags, tags)

    # the image we want to recommend is the photo with the highest similarity score
    best_url = max(scores, key=scores.get)
    # save the photo to disk so we can look at it.
    urllib.request.urlretrieve(best_url, 'BEST.jpeg')

    # write information about the best photo to the file.
    best_tags = tagged_photos[best_url]
    write_picture_info(results_file, 'BEST PHOTO:', best_url, best_tags, None)

    results_file.close()
Beispiel #14
0
from wagtail_unsplash.settings import wagtail_unsplash_settings

from unsplash.api import Api
from unsplash.auth import Auth

api = Api(
    Auth(
        wagtail_unsplash_settings.CLIENT_ID,
        wagtail_unsplash_settings.CLIENT_SECRET,
        wagtail_unsplash_settings.REDIRECT_URI,
        code=wagtail_unsplash_settings.CODE,
    ))
Beispiel #15
0
import os
from PIL import Image, ImageDraw, ImageFont, ImageFilter, ImageEnhance
import requests
from unsplash.api import Api
from unsplash.auth import Auth

import config

unsplash_auth = Auth(config.UNSPLASH_ACCESS_KEY,
                     config.UNSPLASH_SECRET_KEY,
                     '',
                     code='')
unsplash_api = Api(unsplash_auth)


def get_random_photo():
    """Gets a random photo URL from Unsplash"""
    photo = unsplash_api.photo.random(orientation='landscape',
                                      collections='1093525')
    if photo:
        return {
            'url': photo[0].urls.regular,
            'name': photo[0].user.name,
            'user': photo[0].user.username
        }
    return None


def get_photo(quote, author, filename):
    """"""
    photo = get_random_photo()
Beispiel #16
0
def get_auth(client_id, client_secret, redirect_uri, code):
    auth = Auth(client_id, client_secret, redirect_uri, code=code)
    return Api(auth)
Beispiel #17
0
from unsplash.api import Api
from unsplash.auth import Auth
import json, os, glob, random, time

credentials = json.loads(open("credentials.json").read())

unsplashAuth = Auth(credentials['unsplashID'], credentials['unsplashSecret'],
                    credentials['callbackURL'])

unsplashApi = Api(unsplashAuth)

randId = unsplashApi.photo.random(featured=True)[0]

print(randId)
Beispiel #18
0
 def _authenticate(self):
     with open(UNSPLASH_CREDENTIALS_FILE_PATH) as file:
         cred = json.load(file)
     return Api(Auth(**cred))