def image_trending(subscription_key):
    """ImageTrending.

    This will search for trending images then verify categories and tiles.
    """
    client = ImageSearchAPI(CognitiveServicesCredentials(subscription_key))

    try:
        trending_result = client.images.trending()
        print("Search trending images")

        # Categorires
        if trending_result.categories:
            first_category = trending_result.categories[0]
            print("Category count: {}".format(len(trending_result.categories)))
            print("First category title: {}".format(first_category.title))
            if first_category.tiles:
                first_tile = first_category.tiles[0]
                print("Subcategory tile count: {}".format(len(first_category.tiles)))
                print("First tile text: {}".format(first_tile.query.text))
                print("First tile url: {}".format(first_tile.query.web_search_url))
            else:
                print("Couldn't find subcategory tiles!")
        else:
            print("Couldn't find categories!")

    except Exception as err:
        print("Encountered exception. {}".format(err))
示例#2
0
def main():
    # load the counts and hashes of the current images
    print('Loading current data...')
    class_counts, hashes = load_current_data()
    print(f'Loaded {len(hashes)} hashes\n')
    print(f'Class counts: {pprint.pformat(class_counts)}\n')

    # load the query information
    print('Loading queries...')
    queries = load_queries()
    print(f'Queries: {pprint.pformat(queries)}\n')

    # initialize the search client
    client = ImageSearchAPI(CognitiveServicesCredentials(API_KEY))

    # iterate over the different classes and retrieve the images
    for class_name, class_queries in queries.items():
        print('Downloading {class_name} images')
        # first just do the plaintext query with "yoga pose" appended

        all_queries = [class_queries['plaintext_name'] + " yoga pose"
                       ] + class_queries['other_queries']
        for q in all_queries:
            print(f'Running query "{q}"')
            count = download_images_from_query_text(client, class_name, q,
                                                    hashes,
                                                    class_counts[class_name])

            class_counts[class_name] += count

    print(f'Done! Class Counts: {pprint.pformat(class_counts)}')
示例#3
0
def download_data(vehicleType):
    azure_subscription_key = "19670b769b814ebb8ecfb8a1781fffd2"
    azure_client = ImageSearchAPI( CognitiveServicesCredentials( azure_subscription_key ) )

    bikeDataAPIURL = "https://www.zigwheels.com/feedsV2/feed.php?sortdirection=popularity&country_code=in&appVersionCode=75&pageSize=1000&devicePlatform=android&cityName=delhi&api_key=z48ig11523wh02ee46849522820l246s&_v=5&pageNo=1&business_unit=bike&lang_code=en&appVersion=3.0.9&connecto_id=a3138959-5a3d-404a-9ba6-3e1ba6d4763b&_format=json&page=vehicleSearch"
    carDataAPIURL = "https://www.zigwheels.com/feedsV2/feed.php?sortdirection=popularity&country_code=in&appVersionCode=75&pageSize=1000&devicePlatform=android&cityName=delhi&api_key=z48ig11523wh02ee46849522820l246s&_v=5&pageNo=1&business_unit=car&lang_code=en&appVersion=3.0.9&connecto_id=a3138959-5a3d-404a-9ba6-3e1ba6d4763b&_format=json&page=vehicleSearch"
    if vehicleType == 'cars':
        api_url = carDataAPIURL
    elif vehicleType == 'bikes':
        api_url = bikeDataAPIURL
    else:
        raise Exception( 'value of vehicle type should be car or bike.' )
    carDataResponse = requests.get( api_url )

    carJson = carDataResponse.json()

    for vehicle in carJson['data']['items']:
        get_vehicle_details( vehicle, vehicleType, azure_client )


    threads = list()
    for vehicle in carJson['data']['items']:
        x = threading.Thread( target=get_vehicle_details, args=(vehicle, vehicleType, azure_client,) )
        threads.append( x )
        x.start()

    for index, thread in enumerate( threads ):
        logging.info( "Main    : before joining thread %d.", index )
        thread.join()
        logging.info( "Main    : thread %d done", index )
def image_search_with_filters(subscription_key):
    """ImageSearchWithFilters.

    This will search images for (studio ghibli), filtered for animated gifs and wide aspect, then verify number of results and print out insightsToken, thumbnail url and web url of first result.
    """
    client = ImageSearchAPI(CognitiveServicesCredentials(subscription_key))

    try:
        image_results = client.images.search(
            query="studio ghibli",
            image_type=ImageType.animated_gif, # Could be the str "AnimatedGif"
            aspect=ImageAspect.wide # Could be the str "Wide"
        )
        print("Search images for \"studio ghibli\" results that are animated gifs and wide aspect")

        if image_results.value:
            first_image_result = image_results.value[0]
            print("Image result count: {}".format(len(image_results.value)))
            print("First image insights token: {}".format(first_image_result.image_insights_token))
            print("First image thumbnail url: {}".format(first_image_result.thumbnail_url))
            print("First image web search url: {}".format(first_image_result.web_search_url))
        else:
            print("Couldn't find image results!")

    except Exception as err:
        print("Encountered exception. {}".format(err))
示例#5
0
def grab_images(query, file_name):
    load_dotenv()
    api_key = os.getenv("AZURE_API_KEY_IMAGE")
    url = 'https://api.cognitive.microsoft.com/bing/v7.0/images/search'
    EXCEPTIONS = set([
        IOError, FileNotFoundError, requests.exceptions.RequestException,
        requests.exceptions.HTTPError, requests.exceptions.ConnectionError,
        requests.exceptions.Timeout
    ])
    client = ImageSearchAPI(CognitiveServicesCredentials(api_key))
    image_results = client.images.search(query=query,
                                         imageType='Photo',
                                         license='Any')
    try:
        first_image_result = image_results.value[0]
        r = requests.get(first_image_result.content_url)
        ext = first_image_result.content_url[first_image_result.content_url.
                                             rfind("."):]
        #file_name = query.split("logo", 1)[0].rstrip() + ext
        file_name = file_name + ext
        p = os.path.join("./images2/", file_name)
        # Write file to disk
        f = open(p, "wb")
        f.write(r.content)
        f.close()

    except Exception as e:
        if type(e) in EXCEPTIONS:
            print("No image results returned for:", query)
示例#6
0
def get_image(query):
    client = ImageSearchAPI(CognitiveServicesCredentials(subscription_key))
    image_results = client.images.search(query=query, safe_search=safe_search)
    if not image_results.value:
        return None
    result = random.choice(image_results.value[:search_depth])
    link = result.content_url
    return link
def retrieve_images(search,key):
  client = ImageSearchAPI(CognitiveServicesCredentials(key))
 
  try:
    image_results = client.images.search(query=search)
    
    print("Search images for query " + search)
    return image_results
  except Exception as err:
    print("Encountered exception. {}".format(err))
    return null
示例#8
0
def findImages (subscription_key, search_term):

    client = ImageSearchAPI(CognitiveServicesCredentials(subscription_key)) 
    image_results = client.images.search(query=search_term,count=100,ImageContent=face) 

    if image_results.value:
        first_image_result = random.choice(image_results.value)  
        return(first_image_result.content_url); 

    else:
        print("No image results returned!") 
示例#9
0
def photo_from_place(search_place, restaurant_info):
    api_key = return_bing_image_api_key()
    credentials = ImageSearchAPI(CognitiveServicesCredentials(api_key))
    search_place = search_place + " Iasi Romania"
    image_results = credentials.images.search(query=search_place)
    total_number_of_results = len(image_results.value)
    random_image = random.randint(0, total_number_of_results)

    if image_results.value:
        image_result = image_results.value[0]
        restaurant_info["url"] = image_result.content_url
    else:
        restaurant_info["url"] = "No image results returned!"
示例#10
0
def getImgUrl(result):
    search_term = '주역 ' + result.split(' ')[0] + '괘'
    
    subscription_key = "ee6cdff6d00440ba84a5040435d90d6b"

    client = ImageSearchAPI(CognitiveServicesCredentials(subscription_key))
    image_results = client.images.search(query=search_term)

    if image_results.value:
        first_image_result = image_results.value[0]
        return first_image_result.content_url
    else:
        return 'http://cfile208.uf.daum.net/image/18630D3950C82953265E8A'
def image_search(subscription_key):
    """ImageSearch.

    This will search images for (canadian rockies) then verify number of results and print out first image result, pivot suggestion, and query expansion.
    """
    client = ImageSearchAPI(CognitiveServicesCredentials(subscription_key))

    try:
        image_results = client.images.search(query="canadian rockies")
        print("Search images for query \"canadian rockies\"")

        # Image results
        if image_results.value:
            first_image_result = image_results.value[0]
            print("Image result count: {}".format(len(image_results.value)))
            print("First image insights token: {}".format(first_image_result.image_insights_token))
            print("First image thumbnail url: {}".format(first_image_result.thumbnail_url))
            print("First image content url: {}".format(first_image_result.content_url))
        else:
            print("Couldn't find image results!")

        print("Image result total estimated matches: {}".format(image_results.total_estimated_matches))
        print("Image result next offset: {}".format(image_results.next_offset))

        # Pivot suggestions
        if image_results.pivot_suggestions:
            first_pivot = image_results.pivot_suggestions[0]
            print("Pivot suggestion count: {}".format(len(image_results.pivot_suggestions)))
            print("First pivot: {}".format(first_pivot.pivot))

            if first_pivot.suggestions:
                first_suggestion = first_pivot.suggestions[0]
                print("Suggestion count: {}".format(len(first_pivot.suggestions)))
                print("First suggestion text: {}".format(first_suggestion.text))
                print("First suggestion web search url: {}".format(first_suggestion.web_search_url))
            else:
                print("Couldn't find suggestions!")
        else:
            print("Couldn't find pivot suggestions!")

        # Query expansions
        if image_results.query_expansions:
            first_query_expansion = image_results.query_expansions[0]
            print("Query expansion count: {}".format(len(image_results.query_expansions)))
            print("First query expansion text: {}".format(first_query_expansion.text))
            print("First query expansion search link: {}".format(first_query_expansion.search_link))
        else:
            print("Couldn't find image results!")

    except Exception as err:
        print("Encountered exception. {}".format(err))
示例#12
0
def get_image_urls(query):
    subscription_key = app.config['AZURE_SECRET_KEY']

    client = ImageSearchAPI(CognitiveServicesCredentials(subscription_key))

    image_results = client.images.search(query=query)

    if image_results.value:
        num_urls = len(image_results.value)
        return num_urls, [(value.thumbnail_url, value.content_url)
                          for value in image_results.value]
    else:
        # TODO dude, figure something better than this out you n00b
        return 0, []
示例#13
0
def get_image(word, api_key, endpoint):
    client = ImageSearchAPI(
        CognitiveServicesCredentials(api_key),
        base_url=endpoint,
    )
    data = client.images.search(query=word, safe_search=SafeSearch.strict)
    if data.value:
        first_image = data.value[0]
        logging.info("got image url {}".format(first_image.content_url))
        img = requests.get(first_image.content_url).content
        if not img:
            logging.warn("couldn't download image")
            raise ValueError("couldn't download image")
        return img
    else:
        logging.warn("couldn't find image")
        raise ValueError("couldn't find image")
def FetchImage(search_term):

    client = ImageSearchAPI(CognitiveServicesCredentials(subscription_key))

    image_results = client.images.search(query=search_term)
    if image_results.value:
        first_image_result = image_results.value[0]
        #print("Total number of images returned: {}".format(len(image_results.value)))
        #print("First image thumbnail url: 				{}".format(first_image_result.thumbnail_url))
        #print("First image content url: {}".format(first_image_result.content_url))

        return {
            'image_url': first_image_result.content_url,
            'search_word': search_term
        }

    else:
        print("No image results returned!")
示例#15
0
def get_pics():
    name = request.args.get('name')
    res_list = []
    player = Highscore.query.filter_by(name=name).first()
    if player is None:
        error = {'error': 'that player is not in the database'}
        return jsonify(error)
    else:
        client2 = ImageSearchAPI(
            CognitiveServicesCredentials(subscription_key))
        image_results = client2.images.search(query=name)
        image_list = image_results.value
        for image in image_list:
            res_list.append(image.content_url)
        res = Object()
        res.pics = res_list
        payload = res.toJSON()
        return jsonify(payload)
def getImageUrls(search_q="スーツ", get_once_images=10, max_images=30):
    '''
    max_imagesの数だけ、search_qで見つけたURLを取得してreturnする
    返り値:
    image_results["画像のサムネイルURL"]["画像のフルURL"]
    np.arrayで帰ってくる。
    '''
    # Azure のAPIを登録。
    from azure.cognitiveservices.search.imagesearch import ImageSearchAPI
    from msrest.authentication import CognitiveServicesCredentials
    # 環境設定
    apikey_file = "apikey.txt"
    with open(apikey_file) as f:
        key = f.readlines()
    subscription_key = key[0].strip()

    # 検索クエリ
    search_term = search_q
    # パラメータ
    img_count = get_once_images
    # API Client
    client = ImageSearchAPI(CognitiveServicesCredentials(subscription_key))

    # max_imagesの数だけ画像を取得。
    # img_countごとに取得するが、端数は切り捨て。
    image_results = []
    file_num = 0
    for i in range(0, max_images // img_count):
        tmp_results = client.images.search(query=search_term,
                                           count=img_count,
                                           offset=(i * img_count))
        for tmp_img in tmp_results.value:
            image_results.append([
                str(file_num).zfill(5), tmp_img.thumbnail_url,
                tmp_img.content_url
            ])
            file_num += 1
        sleep(1)

    # listをnp.arrayに変換してreturn
    return np.array(image_results)
def download_top_images(searchterm, n=4):
    assert (n > 1)
    # Download the top n images for an image search on some search provider.
    # Returns a list of image urls

    # clean up search string (no special chars etc)
    searchterm = ''.join(c for c in searchterm if c.isalnum() or c == " ")
    try:
        client = ImageSearchAPI(CognitiveServicesCredentials(subscription_key))
        image_results = client.images.search(query=searchterm)
    except Exception as e:
        print("unknown Error retrieving {}".format(seachterm))
        print(e)
        return []
    if image_results.value:
        my_results = image_results.value[:n]
        res = []
        for r in my_results:
            res.append(r.content_url)
        return res
    else:
        print("No images found for {}".format(searchterm))
        return []
示例#18
0
def search(query,key,count):
    client = ImageSearchAPI(CognitiveServicesCredentials(key))
    image_results = client.images.search(query=query, count=count)
    urls = []

    for i in range(len(image_results.value)):
        image = image_results.value[i]
        urls.append(image.content_url)
    
    for link in urls:
        link = link.strip()
        name = link.rsplit('/', 1)[-1]
        filename = os.path.join(DOWNLOADS_DIR, name)
        #print(link)
        if not os.path.exists(DOWNLOADS_DIR):
            os.makedirs(DOWNLOADS_DIR)
        if not os.path.isfile(filename):
            print('Downloading: ' + filename)
            try:
                urllib.request.urlretrieve(link, filename)
            except Exception as inst:
                print(inst)
                print('  Encountered unknown error. Continuing.')
示例#19
0
def openImage(search_term, time_span=2000):
    subscription_key = "768fb70aaef144a4bbdcd344c8b80c8a"

    # Search using Azure Bing Image Search
    client = ImageSearchAPI(CognitiveServicesCredentials(subscription_key))
    image_results = client.images.search(query=search_term)

    if image_results.value:  # Check if result found
        first_image_result = image_results.value[0]

        # Display using Pillow
        response = requests.get(first_image_result.thumbnail_url)
        img = Image.open(BytesIO(response.content))

        # Open Image using tkinter
        root = tk.Tk()
        tkimage = ImageTk.PhotoImage(img)
        tk.Label(root, image=tkimage).pack()
        root.after(
            time_span,
            lambda: root.destroy())  # Destroy the widget after time_span ms
        root.mainloop()
    else:
        print("No image results returned!")
示例#20
0
def home(request):

    # if this is a POST request we need to process the form data
    form = {}
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = QueryForm(request.POST)

        # check whether it's valid:
        if form.is_valid():

            dirty_text = form.cleaned_data['query_text']
            query_format = form.cleaned_data['text_format']
            service = NaturalLanguageUnderstandingV1(
                version='2018-03-16',
                ## url is optional, and defaults to the URL below. Use the correct URL for your region.
                # url='https://gateway.watsonplatform.net/natural-language-understanding/api',
                username='******',
                password='******')
            if query_format == "Plaintext":
                form = service.analyze(
                    text=dirty_text,
                    features=Features(keywords=KeywordsOptions(limit=3),
                                      concepts=ConceptsOptions(limit=3),
                                      entities=EntitiesOptions(limit=3),
                                      emotion=EmotionOptions())).get_result()
            else:
                form = service.analyze(
                    url=dirty_text,
                    features=Features(keywords=KeywordsOptions(limit=3),
                                      concepts=ConceptsOptions(limit=3),
                                      entities=EntitiesOptions(limit=3),
                                      emotion=EmotionOptions())).get_result()
                #with urlopen(dirty_text) as dirty_text:
                #   dirty_text = dirty_text.decode("UTF-8").readlines()
            #print(type(dirty_text))
            #print(dirty_text)
            par = []
            first_sent = []
            str1 = ""
            char_counter = 0
            if query_format == "Plaintext":
                for c in dirty_text:
                    char_counter = char_counter + 1

                    if c != '\n' and char_counter != len(dirty_text):
                        str1 = str1 + c
                    else:
                        par.append(str1)
                        str1 = ""
                for p in par:
                    str2 = ""
                    for c in p:
                        if c == '.' or c == '?' or c == '!':
                            first_sent.append(str2)
                            break
                        else:
                            str2 = str2 + c

            lang = form["language"]
            expanded_lang = ISO639_2[lang]
            keywords = form["keywords"]
            emotions = form["emotion"]["document"]["emotion"]
            for k, v in emotions.items():
                if emotions[k] >= 0.10:
                    emotions[k] = str(v * 100)[0:2] + "%"
                else:
                    emotions[k] = str(v * 100)[0:1] + "%"
            words = {}
            count = 0
            for keyword in keywords:
                words[count] = keyword["text"]
                count = count + 1
            concepts = form["concepts"]
            concept_links = {}
            for c in concepts:
                concept_links[c["text"]] = c["dbpedia_resource"]
            entities = form["entities"]
            people = []
            places = []
            org = []
            for e in entities:
                if e["type"] == "Location":
                    places.append(e["text"])
                if e["type"] == "Person":
                    people.append(e["text"])
                if e["type"] == "Organization":
                    org.append(e["text"])
            subscription_key = "380c79b8a61d4f97a08c2cb48993c569"
            search_term = words[0]
            client = ImageSearchAPI(
                CognitiveServicesCredentials(subscription_key))
            image_results = client.images.search(query=search_term)

            image_url = []
            if image_results.value:
                first_image_result = image_results.value[0]
                image_url.append(first_image_result.content_url)
            else:
                image_url.append("")

            height = []
            width = []
            image = Image.open(urllib.request.urlopen(image_url[0]))
            w, h = image.size
            height.append(400 * h / w)

            final_form = {
                "language": expanded_lang,
                "keywords": words,
                "concepts": concept_links,
                "first_sentences": first_sent,
                "image_url": image_url,
                "emotions": emotions,
                "people": people,
                "places": places,
                "orgs": org,
                "height": height
            }
            # process the data in form.cleaned_data as required
            # ...
            # redirect to a new URL:
    else:
        form = QueryForm()
        final_form = {'form': form}
        # if a GET (or any other method) we'll create a blank form

    return render(request, 'blog/results.html', final_form)
示例#21
0
from datetime import datetime
from datetime import timezone
from datetime import timedelta

# Declare constants
TIME_WINDOW = 5

# Set up Twython
t = Twython(
        settings.twitter_app_key,
        settings.twitter_app_secret,
        settings.twitter_oauth_token,
        settings.twitter_oauth_token_secret)

# Set up Bing API
b = ImageSearchAPI(CognitiveServicesCredentials(settings.bing_key_one))

# Search recent tweets for spooky content
def witchHunt():
    # Get user's timeline
    tl =  t.get_user_timeline(
            screen_name='realDonaldTrump',
            include_rts='true',
            count='50',
            tweet_mode='extended')

    # HUNT FOR WITCHES
    for tweet in tl:
        # If it is a retweet, use the original untruncated text
        if 'retweeted_status' in tweet.keys():
            tweet["full_text"] = tweet["retweeted_status"]["full_text"]
示例#22
0
# Import required modules.
from azure.cognitiveservices.search.websearch import WebSearchAPI
from azure.cognitiveservices.search.websearch.models import SafeSearch
# from msrest.authentication import CognitiveServicesCredentials
from azure.cognitiveservices.search.imagesearch import ImageSearchAPI
from msrest.authentication import CognitiveServicesCredentials

# Just variables in the accounts.py files that is gitignored
from accounts import subscription_key, endpoint

# Instantiate the client and replace with your endpoint.
client = WebSearchAPI(CognitiveServicesCredentials(subscription_key), base_url = endpoint)

# Images
image_client = ImageSearchAPI(CognitiveServicesCredentials(subscription_key), base_url=endpoint)

# Not used
def get_web_pages(query):
    web_data = client.web.search(query=query)
    return web_data.web_pages

def image_detail(subscription_key):
    """ImageDetail.

    This will search images for (degas) and then search for image details of the first image.
    """
    client = ImageSearchAPI(CognitiveServicesCredentials(subscription_key))

    try:
        image_results = client.images.search(query="degas")
        print("Search images for \"degas\"")

        first_image = image_results.value[0]

        image_detail = client.images.details(
            query="degas",
            insights_token=first_image.image_insights_token,
            modules=[
                ImageInsightModule.all # Could be the str "all"
            ],

        )
        print("Search detail for image insights token: {}".format(first_image.image_insights_token))
        print("Expected image insights token: {}".format(image_detail.image_insights_token))

        # Best representative query
        if image_detail.best_representative_query:
            print("Best representative query text: {}".format(image_detail.best_representative_query.text))
            print("Best representative query web search url: {}".format(image_detail.best_representative_query.web_search_url))
        else:
            print("Couldn't find best representative query!")

        # Caption
        if image_detail.image_caption:
            print("Image caption: {}".format(image_detail.image_caption.caption))
            print("Image caption data source url: {}".format(image_detail.image_caption.data_source_url))
        else:
            print("Couldn't find image caption!")

        # Pages including the image
        if image_detail.pages_including.value:
            first_page = image_detail.pages_including.value[0]
            print("Pages including cound: {}".format(len(image_detail.pages_including.value)))
            print("First page content url: {}".format(first_page.content_url))
            print("First page name: {}".format(first_page.name))
            print("First page date published: {}".format(first_page.date_published))
        else:
            print("Couldn't find any pages including this image!")

        # Related searched
        if image_detail.related_searches.value:
            first_related_search = image_detail.related_searches.value[0]
            print("Related searches count: {}".format(len(image_detail.related_searches.value)))
            print("First related search text: {}".format(first_related_search.text))
            print("First related search web search url: {}".format(first_related_search.web_search_url))
        else:
            print("Couldn't find any related searches!")
        
        # Visually similar images
        if image_detail.visually_similar_images.value:
            first_visually_similar_images = image_detail.visually_similar_images.value[0]
            print("Visually similar images count: {}".format(len(image_detail.visually_similar_images.value)))
            print("First visually similar image name: {}".format(first_visually_similar_images.name))
            print("First visually similar image content url: {}".format(first_visually_similar_images.content_url))
            print("First visually similar image content size: {}".format(first_visually_similar_images.content_size))
        else:
            print("Couldn't find any visually similar images!")

        # Image tags:
        if image_detail.image_tags.value:
            first_image_tag = image_detail.image_tags.value[0]
            print("Image tags count: {}".format(len(image_detail.image_tags.value)))
            print("First tag name: {}".format(first_image_tag.name))
        else:
            print("Couldn't find any image tags!")

    except Exception as err:
        print("Encountered exception. {}".format(err))
示例#24
0
 def __init__(self, key):
     super(BingImageEngine, self).__init__()
     self.key = key
     self.client = ImageSearchAPI(CognitiveServicesCredentials(self.key))
示例#25
0
def init_bing_image_search_api():
    with open('./.azure/config.json') as f:
        data = json.load(f)
        subscription_key = data['bing_image_search_key']
    return ImageSearchAPI(CognitiveServicesCredentials(subscription_key))
示例#26
0
# -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
"""

from azure.cognitiveservices.search.imagesearch import ImageSearchAPI
from msrest.authentication import CognitiveServicesCredentials

subscription_key = "76003022336e40e58c6b33f57506396c"
search_term = "canadian rockies"

client = ImageSearchAPI(CognitiveServicesCredentials(subscription_key))
image_results = client.images.search(query=search_term)

if image_results.value:
    first_image_result = image_results.value[0]
    print("Total number of images returned: {}".format(len(image_results.value)))
    print("First image thumbnail url: {}".format(
        first_image_result.thumbnail_url))
    print("First image content url: {}".format(first_image_result.content_url))
else:
    print("No image results returned!")
示例#27
0
from apixu.client import ApixuClient
import logging
from azure.cognitiveservices.search.imagesearch import ImageSearchAPI
from msrest.authentication import CognitiveServicesCredentials
from newsapi import NewsApiClient

logging.basicConfig(filename='main.log',
                    format='%(asctime)s %(levelname)s %(name)s %(message)s',
                    level=logging.DEBUG)

newsapi = NewsApiClient(api_key=keys.news_api)
app = apiai.ApiAI(keys.apiai)
yandex = yandex_search.Yandex(api_key=keys.yandex_key,
                              api_user=keys.yandex_user)
client = ApixuClient(keys.apixu)
image_search = ImageSearchAPI(
    credentials=CognitiveServicesCredentials(keys.visual_search_key))

session_storage = {}
err = " Если у вас постоянно возникает ошибка с поиском, поиском по изображению или новостями," \
      " то рекомендую вам перезапустить меня командой /start ."


def get_toponym_delta(toponym):
    toponym_bounded_lower = tuple(
        toponym["boundedBy"]["Envelope"]["lowerCorner"].split(" "))
    toponym_bounded_upper = tuple(
        toponym["boundedBy"]["Envelope"]["upperCorner"].split(" "))
    return str(abs(float(toponym_bounded_lower[0]) -
                   float(toponym_bounded_upper[0]))), \
           str(abs(float(toponym_bounded_lower[1]) -
                   float(toponym_bounded_upper[1])))
示例#28
0
api = twitter.Api(c_key, c_secret, a_token_key, a_token_secret)

conn = psycopg2.connect(os.environ["DATABASE_URL"], sslmode='require')
cur = conn.cursor()

cur.execute("SELECT * FROM index;")
image_index = cur.fetchone()[0]

cur.execute("SELECT COUNT(*) FROM images;")
url_count = cur.fetchone()[0]

if (url_count == 0 or url_count < image_index):

    print("FETCHING NEW URLS")
    client = ImageSearchAPI(
        CognitiveServicesCredentials(os.environ["BING_KEY"]))

    image_results = []
    image_results.extend(client.images.search(query="cute dog").value)
    image_results.extend(client.images.search(query="puppies").value)

    for image in image_results:
        cur.execute("INSERT INTO images(url) VALUES(%s)", [image.content_url])

    conn.commit()

tweeted = False

while not tweeted:
    try:
        cur.execute("SELECT url FROM images WHERE id=%s;", [image_index])
示例#29
0
from msrest.authentication import CognitiveServicesCredentials
from azure.cognitiveservices.vision.face import FaceClient
from azure.cognitiveservices.search.imagesearch import ImageSearchAPI

from .utils import settings

FACE_KEY = settings("azure", "face", "key")
FACE_ENDPOINT = settings("azure", "face", "endpoint")

BING_KEY = settings("azure", "bing", "key")
BING_ENDPOINT = settings("azure", "bing", "endpoint")

face_client = FaceClient(FACE_ENDPOINT, CognitiveServicesCredentials(FACE_KEY))
bing_client = ImageSearchAPI(CognitiveServicesCredentials(BING_KEY),
                             base_url=BING_ENDPOINT)