コード例 #1
0
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
コード例 #2
0
ファイル: views.py プロジェクト: ad54/bs-test
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)
コード例 #3
0
 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)
コード例 #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
コード例 #5
0
    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)
コード例 #6
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)
コード例 #7
0
ファイル: app.py プロジェクト: carteralbrecht/macsplash
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
コード例 #8
0
ファイル: commands.py プロジェクト: eiskrenkov/SplanderBot
import telegram
from unsplash.api import Api
from unsplash.auth import Auth

from config import *

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

def start(bot, update):
    bot.send_message(chat_id = update.message.chat_id, text = "I'm a bot, please talk to me!")

def random_unsplash_photo(bot, update):
	random_photo = unsplash_api.photo.random(w=900,h=1600)
	photo_id = random_photo[0].id
	bot.send_photo(chat_id = update.message.chat_id, photo = 'unsplash.com/photos/{}'.format(photo_id))

def photo_by_request(bot, update, args):
	required_photo = unsplash_api.search.photos(args[0])['results'][0]
	photo_id = required_photo.id
	bot.send_photo(chat_id = update.message.chat_id, photo = 'unsplash.com/photos/{}'.format(photo_id))

def help(bot, update):
	bot.send_message(chat_id = update.message.chat_id, text = "Команды на данный момент:\n\n/random - Получить случайную фотку\n/search - Получить фото по запросу(Пример: \search stars))")

def many_photos(bot, update, args):
	ListOfPhotos = []
	if int(args[0]) > 5:
		args[0] = 5
	for i in range(int(args[0])):
		random_photo = unsplash_api.photo.random()
コード例 #9
0
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()
コード例 #10
0
ファイル: api.py プロジェクト: lleviy/silk_bookmark
from unsplash.api import Api
from unsplash.auth import Auth
import os.path
import json
from django.core.exceptions import ImproperlyConfigured

def get_secret(setting):
    """Возвращает значение setting из файла unsplash_api.json"""
    if os.path.exists('unsplash_api.json'):
        BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        key = os.path.join(BASE_DIR, "unsplash_api.json")
        with open(key) as f:
            secrets = json.loads(f.read())
        try:
            return secrets[setting]
        except KeyError:
            error_msg = "Set the {} environment variable".format(setting)
            raise ImproperlyConfigured(error_msg)
    else:
        return os.environ[setting]

#API Unsplash settings
client_id = get_secret("client_id")
client_secret = get_secret("client_secret")
redirect_uri = get_secret("redirect_uri")
code = ""

unsplash_auth = Auth(client_id, client_secret, redirect_uri, code=code)
unsplash_api = Api(unsplash_auth)
コード例 #11
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,
    ))
コード例 #12
0
def get_auth(client_id, client_secret, redirect_uri, code):
    auth = Auth(client_id, client_secret, redirect_uri, code=code)
    return Api(auth)
コード例 #13
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)
コード例 #14
0
 def _authenticate(self):
     with open(UNSPLASH_CREDENTIALS_FILE_PATH) as file:
         cred = json.load(file)
     return Api(Auth(**cred))
コード例 #15
0
 def authentication(self):
     auth = Auth(self.client_id,
                 self.client_secret,
                 self.redirect_uri,
                 code=self.code)
     api = Api(auth)