def get_image_url(self, use_google=False):
        """Return a URL for an image of this recipe.
        It will try to return the OpenRecipes scraped image if it exists,
        else it will do a Google image search, else it will return a default
        placeholder image.

        Args:
            use_google: If true, will make an API call to Google images for missing
                images, else it will skip this step (for API quota purposes).

        Returns:
            A string URL which can be GET requested to obtain an image
        """
        # First try the OpenRecipes image
        try:
            response = requests.head(self.image, allow_redirects=True)

            if response.status_code == 200:
                return self.image
        except Exception:
            # e.g. timeout
            pass

        # Then try the first Google Image search result
        if use_google:
            try:
                google_image_search = GoogleImagesSearch(None, None)

                google_image_search.search(
                    search_params={
                        "q": self.name,
                        "num": 1,
                    }
                )

                return google_image_search.results()[0].url
            except Exception:
                # e.g. API quota limit reached
                pass

        # Else return our default image
        return url_for("static", filename="images/default_recipe_image.jpg")
Esempio n. 2
0
async def google_img(message: Message):
    if (GCS_API_KEY and GCS_IMAGE_E_ID) is None:
        await message.edit(REQ_ERR, disable_web_page_preview=True)
        return
    if os.path.exists(PATH):
        shutil.rmtree(PATH, ignore_errors=True)

    fetcher = GIS(GCS_API_KEY, GCS_IMAGE_E_ID)
    query = message.input_str
    search = {
        "q": query,
        "num": 5,
        "safe": "off",
        "fileType": "jpg",
        "imgType": "photo",
        "imgSize": "MEDIUM",
    }
    await message.edit("`Processing...`")
    fetcher.search(search_params=search)
    for image in fetcher.results():
        image.download(PATH)
    if not os.path.exists(PATH):
        await message.edit("Oops, No Results Found")
        return
    ss = []
    for img in os.listdir(PATH):
        imgs = PATH + img
        image = Image.open(imgs)
        if not (image.height <= 1280 and image.width <= 1280):
            image.thumbnail((1280, 1280), Image.ANTIALIAS)
            a_dex = image.mode.find("A")
            if a_dex != -1:
                new_im = Image.new("RGB", image.size, (255, 255, 255))
                new_im.paste(image, mask=image.split()[a_dex])
                new_im.save(imgs, "JPEG")
        ss.append(InputMediaPhoto(str(imgs)))
        if len(ss) == 5:
            break
    await message.reply_chat_action("upload_photo")
    await message.reply_media_group(ss, True)
    shutil.rmtree(PATH, ignore_errors=True)
    await message.delete()
Esempio n. 3
0
    def get(self, request):
        search = request.GET.get('key')
        # you can provide API key and CX using arguments,
        # or you can set environment variables: GCS_DEVELOPER_KEY, GCS_CX
        gis = GoogleImagesSearch(settings.API_KEY, settings.SEARCH_ENGINE_ID)
        # define search params:
        _search_params = {
            'q': search,
            'num': 1
        }

        ## this will only search for images:
        gis.search(search_params=_search_params)


        # search first, then download and resize afterwards:
        gis.search(search_params=_search_params)
        for image in gis.results():
            url = image.url

        return JsonResponse({'image': url}, safe=False)
Esempio n. 4
0
    def imagem(update: Update, context: CallbackContext):
        global CONTEXTO_BUSCA_IMG
        global CHAT_OQ_IMG
        global CHAT_INT_IMG
        if context.args != [] and update.message.text[0:4].lower() == '/img':
            CONTEXTO_BUSCA_IMG = context.args[0:]
            CHAT_OQ_IMG[update.effective_chat.id] = CONTEXTO_BUSCA_IMG
            CHAT_INT_IMG[update.effective_chat.id] = 0
        elif context.args == [] and update.message.text[0:4].lower() == '/img':
            context.bot.send_message(
                chat_id=update.effective_user.id,
                text='Digite /img e o que deseja pesquisar.')
            return
        elif context.args != [] and update.message.text[0:5].lower(
        ) == '/next':
            context.bot.send_message(chat_id=update.effective_user.id,
                                     text='Não é assim que funciona o /next.')
            return
        elif context.args == [] and update.message.text[0:5].lower(
        ) == '/next':
            CHAT_INT_IMG[update.effective_chat.id] += 1

        parametros_busca = {
            'q': CHAT_OQ_IMG.get(update.effective_chat.id),
            'num': 10,
            'safe': 'off',
        }
        gis = GoogleImagesSearch(DEVELOPER_KEY, CX)

        imagens = []

        gis.search(search_params=parametros_busca)
        for image in gis.results():
            imagens.append(image.url)

        if CHAT_INT_IMG[update.effective_chat.id] == 9:
            CHAT_INT_IMG[update.effective_chat.id] = 0
        imagem = imagens[CHAT_INT_IMG.get(update.effective_chat.id)]

        context.bot.send_photo(chat_id=update.effective_chat.id, photo=imagem)
Esempio n. 5
0
def search_pic(aphorism):
    if not aphorism:
        return None
    if aphorism in PICS_CACHE:
        img_bytes = PICS_CACHE[aphorism]
        img_bytes.seek(0)
        return img_bytes
    try:
        words = aphorism
        for sep in '.,!?:;-/\\@#$%^&*()\'"':
            words = words.replace(sep, ' ')
        words = words.split(' ')
        # убираем лишние пробелы
        words = list(filter(lambda w: len(w) > 0, words))
        search_words = (' '.join(words))
        # ограничиваем длину строки для поиска
        while len(search_words) > 80:
            search_words = search_words.rsplit(' ', 1)[0]

        while len(search_words) > 10:
            print('searching pic by query:', search_words)
            gis = GoogleImagesSearch(settings.GOOGLE_DEVELOPER_KEY,
                                     settings.GOOGLE_CX_CODE)
            gis.search({'q': search_words, 'num': 1})
            gis_result = gis.results()
            print('results len:', len(gis_result))
            if gis_result:
                if isinstance(gis_result, list):
                    image = gis_result[0]
                else:
                    image = gis_result
                img_bytes = BytesIO()
                image.copy_to(img_bytes, image.get_raw_data())
                img_bytes.seek(0)
                PICS_CACHE[aphorism] = img_bytes
                return img_bytes
            search_words = search_words[:2 * len(search_words) / 3]
    except Exception as ex:
        logger.error("Exception on receiving image: %s" % (str(ex)))
    return None
Esempio n. 6
0
    def fishImage(query, API_KEY, PROJECT_KEY):
        #QUERY SEARCH
        gis = GoogleImagesSearch(API_KEY, PROJECT_KEY)
        query = query + " peixe"
        _search_params = {
            'q':
            query,
            'num':
            1,
            'searchType':
            'image',
            'safe':
            'off',
            'imgType':
            'photo',
            'fileType':
            'jpg',
            'orTerms':
            'peixe|fish|pesca|pescaria|rio|isca|nadando|nadar|água|mar|anzol'
        }

        #limit google API request in 5
        i = 0
        images = []
        gis.search(search_params=_search_params, path_to_dir=path)
        while gis.results() == [] and i < 5:
            try:
                gis.next_page()
            except:
                print('page ' + i + ' nothing found')
            i = i + 1

        if os.path.exists(path):
            filename = os.listdir(path)
            os.rename(path + filename[0], path + 'post.jpg')

        if os.path.exists(path + 'post.jpg'):
            images.append(path + 'post.jpg')

        return images
Esempio n. 7
0
 def google_image_search(self, search_text):
     """
     Searches for an image with the given search text and downloads it into a io.BytesIO object
     :param search_text: The text you would like to search for in Google images
     :return: Returns a io.BytesIO with the given image
     """
     output = io.BytesIO()
     gis = GoogleImagesSearch(self.config['GIS_DEV_API_KEY'],
                              self.config['GIS_PROJECT_CX'])
     _search_params = {
         'q': search_text,
         'num': 1,
         'safe': 'off',
         'imgSize': 'SMALL'
     }
     gis.search(_search_params)
     image = gis.results()[0]
     output.seek(0)  # Tell the BytesIO object to go back to address 0
     image.copy_to(output)
     output.seek(
         0
     )  # Go back to address 0 again so PIL can read it from start to finish
     return output
Esempio n. 8
0
async def google_img(message: Message):
    if GCS_API_KEY and GCS_IMAGE_E_ID is None:
        await message.edit(REQ_ERR)
        return
    fetcher = GIS(GCS_API_KEY, GCS_IMAGE_E_ID)
    query = message.input_str
    search = {
        'q': query,
        'num': 9,
        'safe': "off",
        'fileType': "jpg",
        'imgType': "photo",
        'imgSize': "HUGE"
    }
    await message.edit("`Processing...`")
    fetcher.search(search_params=search)
    for image in fetcher.results():
        image.download(PATH)
    for img in os.listdir(PATH):
        imgs = PATH + img
        await userge.send_photo(chat_id=message.chat.id, photo=imgs)
    shutil.rmtree(PATH, ignore_errors=True)
    await message.delete()
Esempio n. 9
0
def getImage(word, desired_width=225, desired_height=300, return_found=False):
    gis = GoogleImagesSearch(apikey, cx)

    # set search parameters
    # maximum results num is 10
    _search_params = {
        'q': word,
        'num': 10,
        'safe': 'off',
        'fileType': 'jpg',
        'imgType': 'photo',
        'imgSize': 'large',
    }

    # do search
    gis.search(search_params=_search_params)

    # randomly select 1 image from results
    results = random.sample(gis.results(), 1)
    result = results[0]

    img = getImageFromGoogleSearchImage(result)
    del gis

    width, height = img.size
    resize_ratio = max(desired_width / width, desired_height / height)
    img = img.resize(
        (round(resize_ratio * width), round(resize_ratio * height)))
    # 4-tuple defining the left, upper, right, and lower pixel coordinate
    img = img.crop((0, 0, desired_width, desired_height))

    # print("going into evolution")
    polygons = run_evolve(img, desired_width, desired_height)

    if return_found:
        return polygons, img
    return polygons
Esempio n. 10
0
    async def google_image(self, ctx, *, search_param: str = 'cat'):
        """Returns first result of Google Image Search."""
        gis = GoogleImagesSearch(os.getenv("API"), os.getenv("CSE"))

        safe = 'off' if ctx.message.guild is not None and ctx.channel.is_nsfw(
        ) else 'high'

        _search_params = {
            'q': search_param,
            'num': 1,
            'searchType': 'image',
            'safe': safe
        }

        try:
            gis.search(_search_params)
        except:
            return await ctx.send(
                'Google Error: Please try again or use another search term.\n'
                'If this error persists, it means my daily search limit has been reached and cannot '
                'search anymore due to Google\'s restrictions... \n'
                'Sorry, please try again tomorrow. \U0001f626')

        if gis.results():
            image_url = gis.results()[0].url
        else:
            return await ctx.send(
                f'Error: Image search for `{search_param}` failed.')

        e = discord.Embed(colour=discord.Colour.green())
        e.set_image(url=image_url)
        e.set_footer(
            text=
            f'Google Image Search for: {search_param} — Safe Search: {safe}')

        await ctx.send(embed=e)
Esempio n. 11
0
class GoogleInterface:
    def __init__(self,keyword,total_images=25):
        self.inputFormat = {"Records":[]}
        self.gis = GoogleImagesSearch('AIzaSyB07WusV1J5ncbUBCCyRWnmWTPSWLb6K5U','de1bc6f11f40840c2')

        # define search params:
        self._search_params = {
            'q': keyword,
            'num': total_images,
        }

        self.totalimages = total_images

    def setKeywords(self,keyword,total_images=10):
        self._search_params = {
            'q': keyword,
            'num':total_images,
        }

    def gettingUrls(self):
        self.gis.search(search_params=self._search_params)
        result = self.gis.results()
        index = random.randrange(0,len(result))
        return result[index].url
Esempio n. 12
0
def imageFinder(nameLooker):
    gis = GoogleImagesSearch('AIzaSyALNghCvPMwTXWwrXorvOUvy9ydUCdlcvU',
                             'aa5bd644ce5a37202')
    name = nameLooker

    response = requests.get(
        'https://www.behindthename.com/api/lookup.json?name=' + name +
        '&key=er829146479').json()

    try:
        usage = response[0]['usages'][0]['usage_full']

        if usage == 'English':
            usage = 'UK'

        if usage == 'Italian':
            usage = 'Italy'

        searchTerm = usage + ' Flag'
    except KeyError:
        searchTerm = 'IDK'

    gis.search({
        'q': searchTerm,
        'num': 1,
        'fileType': 'png'
    },
               custom_image_name=name)

    for image in gis.results():
        path = 'static/img/'
        image.download(path)
        #output = image

    namePath = 'static/img/' + name + '.jpg'
    return namePath
Esempio n. 13
0
def google_search(query_text, num=5, again=False):
    gis = \
        GoogleImagesSearch(DEV_API_KEY, PROJECT_CX) if not again else GoogleImagesSearch(DEV_API_KEY2, PROJECT_CX2)
    gis.search({'q': '{query} meme'.format(query=query_text), 'num': num})
    return [img._url for img in gis.results()]
Esempio n. 14
0
#define search params:
_search_params = {
    'q': '...',
    'num': 1 - 50,
    'safe': 'high|medium|off',
    'fileType': 'jpg|gif|png',
    'imgType': 'clipart|face|lineart|news|photo',
    'imgSize': 'huge|icon|large|medium|small|xlarge|xxlarge',
    'searchType': 'image',
    'imgDominantColor':
    'black|blue|brown|gray|green|pink|purple|teal|white|yellow'
}

# this will only search for images:
gis.search(_search_params=_search_params)

# this will search and download:
gis.search(_search_params=_search_params, path_to_dir='/path/')

# this will search, download and resize:
gis.search(_search_params=_search_params,
           path_to_dir='/path/',
           width=500,
           height=500)

# search first, then download and resize afterwards
gis.search(_search_params=_search_params)
for image in gis.results():
    image.download('/path/')
    image.resize(500, 500)
Esempio n. 15
0
from google_images_search import GoogleImagesSearch
import os

cse_id = os.environ.get("cse_id", None)
api_key = os.environ.get("api_key", None)

gis = GoogleImagesSearch("api_key", "cse_id")

_search_params = {
    'q': '...',
    'num': 1 - 50,
    'safe': 'high|medium|off',
    'fileType': 'jpg|gif|png',
    'imgType': 'clipart|face|lineart|news|photo',
    'imgSize': 'huge|icon|large|medium|small|xlarge|xxlarge',
    'searchType': 'image',
    'imgDominantColor':
    'black|blue|brown|gray|green|pink|purple|teal|white|yellow'
}

gis.search({'q': 'puppies', 'num': 3})
Esempio n. 16
0
    # Iterate over Cards adding pictures
    for s in c.fetchall():
        # Fetch fields
        id = s[0]
        (flds_first, flds_second) = s[1].split(SEP)
        sfld = s[2]

        #Check if image is already present
        if '.jpg' in s[1] or '.png' in s[1]:
            s = c.fetchone()
            continue

        # Get image from google images
        _search_params['q'] = flds_second
        gis = GoogleImagesSearch(GCS_DEVELOPER_KEY, GCS_CX)
        gis.search(search_params=_search_params, path_to_dir=DECKPATH)
        (image,) = gis.results()

        # Rename picture
        os.rename(image.path, DECKPATH + str(curr_pic_num))
        picname = flds_second + ".jpg"

        # Push image to database
        t = (flds_first + '\x1f' + flds_second + '<div><img src=\"' + picname + '\"><br></div>', id,)
        c.execute('UPDATE notes SET flds = ? WHERE id = ?', t)

        # Update JSON
        picnames[str(curr_pic_num)] = picname

        # Increment counter
        curr_pic_num += 1
Esempio n. 17
0
    def handle(self, *args, **options):

        wikipedia.set_lang("it")

        if options.get("delete"):
            print("delete everything!")
            ArtworkQueryTextResult.objects.all().delete()
            ArtworkQueryImageResult.objects.all().delete()

        for artwork in Artwork.objects.all():
            print("- Processing artwork {}".format(artwork.title))
            if not options.get("only_images"):
                try:
                    page = wikipedia.page(artwork.title)
                    if not check_existing(page.url, artwork, ArtworkQueryTextResult):
                        website = create_website_for_url(page.url)
                        query_result = ArtworkQueryTextResult(
                            url=page.url,
                            body=page.summary,
                            title=page.title,
                            website=website,
                            artwork=artwork
                        )
                        query_result.save()
                        print("\t Wikipedia page saved correctly")
                    else:
                        print("\t Wikipedia page already in db")
                except wikipedia.exceptions.PageError:
                    print("no wikipedia pages found with the artwork title!")

                if ArtworkQueryTextResult.objects.filter(artwork=artwork).count() > 10:
                    continue

                for url in search(artwork.get_query(), stop=20, lang='it'):
                    if '.pdf' in url:
                        continue
                    try:
                        print("\t- url: {}".format(url))

                        if check_existing(url, artwork, ArtworkQueryTextResult):
                            print("\t\t skip! [already in db]")
                            continue

                        page = requests.get(url)
                        if page.status_code != 200:
                            print("\t\t skip! [status code {}]".format(page.status_code))
                            continue
                    except requests.exceptions.ContentDecodingError:
                        continue
                    except requests.exceptions.ConnectionError:
                        continue

                    website = create_website_for_url(url)

                    soup = BeautifulSoup(page.text, 'html.parser')
                    try:
                        title = soup.find("title").text
                        abstract = soup.find("title").text
                    except AttributeError:
                        continue

                    try:
                        abstract = soup.find("meta", {"name": "description"}).attrs['content']
                    except Exception:
                        pass
                    try:
                        abstract += sorted([p.text for p in soup.find_all("p")], key=lambda p: len(p), reverse=True)[0]
                    except IndexError:
                        continue

                    query_result = ArtworkQueryTextResult(
                        url=base_url(page.url),
                        body=abstract,
                        title=title,
                        website=website,
                        artwork=artwork
                    )
                    query_result.save()

            print("\n\t search for images")
            gis = GoogleImagesSearch(
                settings.GOOGLE_CUSTOMSEARCH_DEVELOPER_API_KEY,
                settings.GOOGLE_CUSTOMSEARCH_ENGINE_ID
            )
            search_params = {
                'q': artwork.get_query(),
                'num': 10,
                'safe': 'off',
                # 'imgSize': 'large'
            }
            gis.search(search_params=search_params)

            for google_image in gis.results():
                print("\t processing image {}".format(google_image.url))
                if google_image.url.split(".")[-1].lower() not in IMAGE_EXTENSIONS:
                    continue

                if check_existing(google_image.url, artwork, model=ArtworkQueryImageResult):
                    print("\t skip [already in db]")
                    continue

                website = create_website_for_url(google_image.url)
                query_image = ArtworkQueryImageResult(
                    url=base_url(google_image.url),
                    website=website,
                    artwork=artwork
                )
                extension = os.path.split(urlsplit(query_image.url).path)[-1].split(".")[-1]
                ok = save_image_from_url(query_image, "image", google_image.url, "{}.{}".format(uuid.uuid4(), extension))
                if ok:
                    query_image.save()
                    print("\t image saved")
                else:
                    print("\t skip [cannot save image]")
Esempio n. 18
0
    'imgType': 'clipart'
}

pixel_dim = 2  # based on thickness of pen on screen

USELINES = True  # draw lines instead of pixels - faster

n = 100  # image width (maintains aspect ratio)

shortcut = 'alt+x'  # hotkey to start drawing

###########################################################

gis = GoogleImagesSearch(key, cx)

gis.search(search_params=_search_params, path_to_dir=path)

downloaded = gis.results()[0]._path

image = Image.open(downloaded).convert('RGB')
image = image.resize(size=(n + 1, int(n * image.size[1] / image.size[0])))
image = PIL.ImageOps.mirror(image)

try:
    original = np.asarray(image)[:, :, 0]
except IndexError:
    original = np.asarray(image)

data = original.copy()
data = np.rot90(data)
Esempio n. 19
0
# Initialise google image search (uses API)
gis = GoogleImagesSearch(os.environ['GCS_DEVELOPER_KEY'], os.environ['GCS_CX'])

# Run the search, protecting against failures crashing the script
failed = True
# Keep count of the failures, many probably means an actual issue rather than
# one dodgy image
fail_count = 0
while failed:
    try:
        # Search for user input, 10 images at a time
        # Looking for letters, so want white background
        gis.search({
            'q': 'engineer cover letter',
            'num': 10,
            'start': 1,
            'safe': 'high',
            'fileType': 'jpg',
            'imgDominantColor': 'white'
        })
        failed = False
    except Exception as e:
        failed = True
        fail_count += 1
        if fail_count > 10:
            raise RuntimeError(e)

# Big loop to keep getting images until daily API quota reached
for i in range(0, 2000):
    # Loop over the image search results
    for ind, image in enumerate(gis.results()):
        # Protect against errors crashing the script
Esempio n. 20
0
class ImageSearch:
    """Allow for easy use of both Giphy and Google Image searches

    Args:
      gis_api_key (str): Google Image Search API key (None)
      gis_project_cx (str): Google Image Search project CX (None)
      gis_search_phrases (list): Pool of GIS search phrases (empty)
      giphy_api_key (str): Giphy API key
      giphy_search_phrases (list): Pool of Giphy search phrases (empty)
    """
    giphy = None
    giphy_api_key = None
    giphy_search_phrases = None
    gis = None
    gis_search_phrases = None

    def __init__(self,
                 gis_api_key=None,
                 gis_project_cx=None,
                 gis_search_phrases=[],
                 giphy_api_key=None,
                 giphy_search_phrases=[]):
        # GIS API key and project CX were given
        if gis_api_key and gis_project_cx:
            self.gis = GoogleImagesSearch(gis_api_key, gis_project_cx)
            # ENABLE GOOGLE IMAGE SEARCH "START" PARAMETER
            self.gis._google_custom_search._search_params_keys['start'] = 0

        self.gis_search_phrases = gis_search_phrases

        # Giphy API key was provided
        if giphy_api_key:
            self.giphy = giphy_client.DefaultApi()
            self.giphy_api_key = giphy_api_key

        self.giphy_search_phrases = giphy_search_phrases

    def can_use_gis(self):
        """Indicates whether Google Image Search
        is available"""
        return bool(self.gis and self.gis_search_phrases)

    def can_use_giphy(self):
        """Indicates whether Giphy is available"""
        return bool(self.giphy and self.giphy_search_phrases)

    def is_ready(self):
        """Indicates as bool whether values required for Image Search
        to work were properly set"""
        return (self.can_use_gis() or self.can_use_giphy())

    # This is the actual method used for performing requests  to
    # seach online for an image
    def get_random_url(self, gis_giphy_chance=None):
        """Get random image URL

        Args:
          gis_giphy_chance (float):
            Chance of either using Google Image Search or Giphy for
            getting an image (defaults to random choice)
            The closer the number is to 0, the higher the chance for GIS gets
            The closer the number is to 1, the higher the chance for Giphy will be
            Example: 0 = 100% GIS/0% Giphy; 0.2 = 80% GIS/20% Giphy

        Returns:
            url (str): An image URL
        """
        # Use random bit if no specific chance for either Giphy or
        # GIS was given
        if gis_giphy_chance is None:
            gis_giphy_chance = random.getrandbits(1)

        image_url = None

        # Choose either Giphy or GIS based off chance
        image_engine = hydra_image_engines.GIPHY
        if random.uniform(0, 1) < 1 - gis_giphy_chance:
            image_engine = hydra_image_engines.GIS
        if (image_engine is hydra_image_engines.GIS
                and not self.can_use_gis()):
            image_engine = hydra_image_engines.GIPHY

            print(tcolors.FAIL +
                  'GIS wasn\'t properly configured, therefore ' +
                  'switching to Giphy now...' + tcolors.ENDC)
        elif (image_engine is hydra_image_engines.GIPHY
              and not self.can_use_giphy()):
            image_engine = hydra_image_engines.GIS

            print(tcolors.FAIL +
                  'Giphy wasn\'t properly configured, therefore ' +
                  'switching to GIS now...' + tcolors.ENDC)

        # Select random search query
        search_query_used = None

        # Perform image search
        while image_url is None:
            if image_engine is hydra_image_engines.GIPHY:
                try:
                    search_phrases = self.giphy_search_phrases
                    search_query_used = random.choice(search_phrases)

                    # Search Endpoint
                    giphy_response = self.giphy.gifs_search_get(
                        self.giphy_api_key,
                        search_query_used,
                        limit=100,
                        offset=random.randint(0, 100),
                    )

                    # No images could be retrieved, therefore skip to
                    # next iteration
                    if not len(giphy_response.data):
                        continue

                    # Choose random image based of response
                    found_giphy = random.choice(giphy_response.data)
                    # Set image URL to downsized version
                    image_url = found_giphy.images.downsized.url

                # Continue to next iteration if Giphy ApiException occured
                except giphy_client.rest.ApiException:
                    continue
            else:
                try:
                    search_phrases = self.gis_search_phrases
                    search_query_used = random.choice(search_phrases)

                    self.gis.search(
                        search_params={
                            'q': search_query_used,
                            'num': 10,
                            'start': random.randint(0, 90)
                        })

                    search_results = self.gis.results()

                    # No image could be found
                    if not len(search_results):
                        continue

                    # Set image URL randomly based on results
                    image_url = random.choice(search_results).url

                # Continue to next iteration if common request exceptions
                # occured
                except (requests.exceptions.ReadTimeout,
                        requests.exceptions.ConnectionError):
                    continue

                # GIS HttpError exception normally indicated reaching of
                # maximum search queries per day
                except googleapiclient.errors.HttpError:
                    # Switch to Giphy instead
                    image_engine = hydra_image_engines.GIPHY

                    print(tcolors.FAIL +
                          'GIS returned HTTP error, probably because ' +
                          'daily request limit has been reached. ' +
                          'Therefore switching to Giphy now...' + tcolors.ENDC)

        # Get image engine name as string
        # TODO: Improve model logic to provide for this there instead
        image_engine_name = 'Giphy'
        if image_engine is hydra_image_engines.GIS:
            image_engine_name = 'Google Image Search'

        # Return tuple of found URL, plus useful information
        return image_url, search_query_used, image_engine_name
Esempio n. 21
0

common_word_list = [
    'je', 'tu', 'il', 'elle', 'on', 'nous', 'vous', 'ils', 'elles', 'me', 'te',
    'le', 'lui', 'la', 'les', 'leur', 'eux', 'moi', 'toi', 'celui', 'celle',
    'ceux', 'celles', 'ceci', 'cela', 'ce', 'ça', 'celui-ci', 'qui', 'que',
    'quoi', 'dont', 'où', 'aussi', 'le', 'la', 'un', 'une', 'du', 'de',
    'de la', 'des', 'les', 'ce', 'cet', 'cette', 'mon', 'ton', 'son', 'notre',
    'votre', 'leur', 'mes', 'ses', 'tes'
]

txt_l = text_to_keyword(newText)
txt_l_len = len(txt_l)

ran_i = random.randrange(0, txt_l_len - 1)

gis = GoogleImagesSearch('AIzaSyAUQgZTiWpy0YXdE0IJwkVCNrEdmSiNpiU',
                         '175c210d3316ae770')

_search_params = {
    'q': txt_l[ran_i],
    'num': 1,
    'safe': 'off',
    'fileType': 'jpg',
}

gis.search(search_params=_search_params, custom_image_name='image')

for image in gis.results():
    image.download(imageUrl)
    image.resize(500, 500)
Esempio n. 22
0
        'rights': 'off'
    }

    _search_params_opponent = {
        'q': opponent.lower(),
        'num': 1,
        'safe': 'off',
        'fileType': 'jpeg',
        'imgType': 'imgTypeUndefined',
        'imgSize': 'imgSizeUndefined',
        'imgDominantColor': 'imgDominantColorUndefined',
        'rights': 'off'
    }
    
    # Download image for player and opponent
    gis.search(search_params=_search_params_player, path_to_dir='Images', 
               custom_image_name=player.lower())
    gis.search(search_params=_search_params_opponent, path_to_dir='Images', 
               custom_image_name=opponent.lower())
    
    # result = [0]
    if result[0] == 1:
        st.write("The winner will be: ", player)
        image_file = './Images/' + player.lower()+'.jpg'
        image_object = Image.open(image_file)
        st.image(image_object, caption='WINNEEEEEERR')
        y_pred_prob = clf.predict_proba(X_interview)[:, 1]
        st.write("Probability of winning", y_pred_prob[0])
    else:
        st.write("The winner will be: ", opponent)
        image_file = './Images/' + opponent.lower()+'.jpg'
        image_object = Image.open(image_file)
client = boto3.client(
    'dynamodb',
    region_name='eu-west-3',
    aws_access_key_id='AKIAJUT7RTNWU5DRJXVQ',
    aws_secret_access_key='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')

tmp = 'https://sun1-24.userapi.com/impg/c853628/v853628852/1f9990/STE1qgZYLF8.jpg?size=1200x1600&quality=96&proxy=1&sign=27ec6271c29d8d5a319e4ac924ac1828'
gis = GoogleImagesSearch('AIzaSyCJCs7A4UrfS5Bc7NwvI91JYT71-JxZKPc',
                         '017576662512468239146')
f = open('count.txt', 'r')

for category in f.readlines():
    _search_params = {'q': category, 'num': 200, 'safe': 'off'}
    gis.search(search_params=_search_params,
               path_to_dir='/download/',
               width=224,
               height=224)

f.close()

# try:
#     response = client.put_item(
#         TableName=table_name,
#         Item={
#             'url': {'S': f'{tmp}'},
#             'category': {'S': 'пиздец'}
#         }
#     )
# except ClientError as err:
#     print(err)
Esempio n. 24
0
from google_images_search import GoogleImagesSearch

# you can provide API key and CX using arguments,
# or you can set environment variables: GCS_DEVELOPER_KEY, GCS_CX
API_KEY = ' '
CX = ' '

gis = GoogleImagesSearch(API_KEY, CX)

#Define download destination:
Download_destination = 'D:\Pictures'

# Define search params:
_search_params = {
    'q': 'cute puppy',  # Search Query
    'num': 150,  # Amount of pics to download
    'safe': 'high',  # Safe search level
    'fileType': 'jpg',  # File type
}

# this will search, download and resize:
gis.search(search_params=_search_params, path_to_dir=Download_destination)
    for n, noun in enumerate(nouns):

        #replace nouns in question with numbers
        data_ob["question"] = data_ob["question"].replace(
            noun, '[{:02d}]'.format(n), 1)

        #searches google and saves enumerated images to an enumerated folder
        search_params = {
            'q': noun,
            'num': 1,
            'safe': 'high',
            'fileType': 'png',
        }
        gis.search(search_params=search_params,
                   path_to_dir="./img/{:04d}/".format(i),
                   custom_image_name='{:02d}'.format(n))

        # picture = "./img/{:04d}/".format(i) + '{:02d}'.format(n) + ".png"

        # #open image as a background
        # with Image.open('{:02d}'.format(n) + ".png") as image:
        #     draw = ImageDraw.Draw(image)

        #     #set up message
        #     font = ImageFont.truetype("Roboto-Bold.ttf", size = 30)
        #     (x, y) = (50, 50)
        #     message = "some number"
        #     color = "rgb(0, 0, 0)"

        #     draw.text((x, y), message, fill=color, font=font)
Esempio n. 26
0
    async def gs(self,
                 ctx,
                 start: typing.Optional[int] = 1,
                 num: typing.Optional[int] = 1,
                 *,
                 arg,
                 skip_cache=False,
                 delete=False):
        '''Searches the phrase given on google'''

        if not (start >= 1 and start <= 200 and num >= 1 and num <= 10):
            await ctx.send('Numbers not in bound')
            return

        # sanitization
        searchTerm = ''
        for i in arg:
            if i.isalnum or i in "'+.:":
                searchTerm += i
        searchTerm = ''.join(searchTerm)

        gis = GoogleImagesSearch(secret_api_key, secret_cx_code)

        _search_params = {
            'q': searchTerm,
            'start': start,
            'num': num,
            'safe': 'high',
        }

        webhook = await get_web_hook(ctx.channel)

        with DBConnection('meme_cache.db') as db_conn:
            cur = db_conn.conn.cursor()

            if (not skip_cache) or (num != 1):
                for row in cur.execute(db_conn.select_query %
                                       (searchTerm, start)):
                    url = row[0]
                    if url:
                        embed = discord.Embed()
                        embed.set_image(url=url)
                        if not delete:
                            await webhook.send(
                                content=ctx.message.content,
                                embed=embed,
                                username=ctx.message.author.nick,
                                avatar_url=ctx.message.author.avatar_url)
                        else:
                            await webhook.send(
                                embed=embed,
                                username=ctx.message.author.nick,
                                avatar_url=ctx.message.author.avatar_url)
                        await ctx.message.delete()
                    else:
                        await ctx.send('Couldn\'t find the searched image.')
                    return

            gis.search(search_params=_search_params)
            embeds = []
            for i, img in enumerate(gis.results()):
                if img.url:
                    embed_data = {
                        'type': 'image',
                        'image': {
                            'url': img.url,
                        },
                    }
                    embeds.append(discord.Embed.from_dict(embed_data))

                try:
                    cur.execute(db_conn.insert_query %
                                (searchTerm, start + i, img.url))
                    db_conn.conn.commit()
                except sqlite3.IntegrityError:
                    cur.execute(db_conn.update_query %
                                (img.url, start + i, searchTerm))

        if not delete:
            cont = ctx.message.content
            await webhook.send(content=cont,
                               embeds=embeds,
                               username=ctx.message.author.display_name,
                               avatar_url=ctx.message.author.avatar_url)
        else:
            await webhook.send(embeds=embeds,
                               username=ctx.message.author.display_name,
                               avatar_url=ctx.message.author.avatar_url)
        await ctx.message.delete()
Esempio n. 27
0
#file to fetch pictures
import argparse
import subprocess
from google_images_search import GoogleImagesSearch
parser = argparse.ArgumentParser()
parser.add_argument("-m","--mode",type=str)
parser.add_argument("-t","--titolo",type=str)
parser.add_argument("-n","--name",type=str)
args = parser.parse_args()

gis = GoogleImagesSearch('API-KEY', 'SEARCH-ENGINE-ID')
_search_params = {
        'q': args.titolo,
        'num': 1,
        'safe': 'high',
        'fileType': 'jpg'
}

if args.mode == "NSFW":
    _search_params = {
        'q': args.titolo,
        'num': 1,
        'safe': 'off',
        'fileType': 'jpg'
    }
gis.search(search_params=_search_params, path_to_dir='.', custom_image_name=args.name)
Esempio n. 28
0
def create_blog_post(self, results, src, title, search):
    supported_images = [".gif", ".png", ".jpg", ".jpeg"]
    path = "media/"
    image = False
    # Google image search has limits
    google_search_images = False
    # We need a valid big image
    page_images = False
    # Manual search
    manual_search = True

    # First attempted not really working
    if page_images:
        for url in src.split(","):
            if url.find("http") != -1:
                name = url.split("/")[-1]

                try:
                    urllib.request.urlretrieve(url, path + name)
                    im = Image.open(path + name)
                except:
                    os.system("rm {}".format(path + name))
                    continue

                width, height = im.size
                if width > 850 and height > 400:
                    with open(path + name, "rb") as f:

                        file_obj = File(f, name=name)
                        image = FilerImage.objects.create(owner=User.objects.get(id=1),
                                                          original_filename=path + name,
                                                          file=file_obj)
                        os.system("rm {}".format(path + name))
                        break

                else:
                    os.system("rm {}".format(path + name))


    # Not in use limited requests
    if google_search_images:

        api_key = "AIzaSyBr5FSmPl_RffFM_X_bLQXGFOBm8DborDY"
        from google_images_search import GoogleImagesSearch

        # you can provide API key and CX using arguments,
        # or you can set environment variables: GCS_DEVELOPER_KEY, GCS_CX
        gis = GoogleImagesSearch(api_key, "ff9add50d98a394d6")

        # define search params:
        _search_params = {
            'q': title,
            'num': 1,
            # 'safe': 'off', #high|medium|off
            # 'fileType': 'png', #jpg|gif|png
            # 'imgType': 'photo', #clipart|face|lineart|news|photo
            'imgSize': 'XXLARGE',  # huge|icon|large|medium|small|xlarge|xxlarge
            # 'imgDominantColor': 'white', #black|blue|brown|gray|green|pink|purple|teal|white|yellow
            # 'rights': '' #cc_publicdomain|cc_attribute|cc_sharealike|cc_noncommercial|cc_nonderived
        }

        gis.search(search_params=_search_params)
        for image in gis.results():
            try:
                image.download('media/')
                with open(image.path, "rb") as f:

                    file_obj = File(f, name=image.path.split('/')[1])
                    image = FilerImage.objects.create(owner=User.objects.get(id=1),
                                                      original_filename=image.path,
                                                      file=file_obj)
                break
            except:
                pass
                image = False
Esempio n. 29
0
    with sr.Microphone() as source:
        print("Speak:")
        audio = r.listen(source, phrase_time_limit=2)
    try:
        words = r.recognize_google(audio)
        print(words)
        # define search params:
        _search_params = {
            'q': words,
            'num': 10,
            'safe': 'high',
            'fileType': 'png',
            'imgType': 'photo',
            'imgSize': 'LARGE'
        }

        # search first, then download and resize afterwards:
        gis.search(search_params=_search_params)
        gis.results()[0].download('images/')
        lst = os.listdir('images/')
        img = Image.open('images/' + str(lst[0]))
        img.show()
        time.sleep(1)
        img.close()
        os.remove('images/' + str(lst[0]))

    except sr.UnknownValueError:
        print("Could not understand audio")
    except sr.RequestError as e:
        print("Could not request results; {0}".format(e))
Esempio n. 30
0
def say_hello(**payload):
    data = payload['data']
    global speak_after
    channel = data['channel']

    after_ts = datetime.min

    if channel in speak_after:
        after_ts = speak_after[channel]

    try:
        if datetime.today() < after_ts:
            raise Exception("The track last announced is still playing...")

        if 'song' in data['text'].lower() or 'sonos' in data['text'].lower(
        ) or 'music' in data['text'].lower():
            thread_ts = data['ts']
            # user = data['user']

            text = "I couldn't find anything playing currently."

            coordinator = Empty

            for zone in soco.discover():
                if zone.is_coordinator and zone.get_current_transport_info()['current_transport_state'] == "PLAYING" \
                        and len(zone.get_current_track_info()['title']) > 0:
                    coordinator = zone
                    break

            track = coordinator.get_current_track_info()
            attachment = []

            if len(track['title']) > 0:
                text = zone.player_name.strip() + " is playing " + track[
                    'artist'].strip() + " with " + track['title'].strip(
                    ) + " from the album " + track['album'].strip()

                gis = GoogleImagesSearch(os.environ["GOOGLE_API_TOKEN"],
                                         os.environ["GOOGLE_CX_TOKEN"])

                _search_params = {
                    'q':
                    "album cover " + track['artist'].strip() + " " +
                    track['album'].strip(),
                    'num':
                    1
                }

                gis.search(search_params=_search_params, cache_discovery=False)
                image_url = gis.results().pop().url
                attachment.append({
                    "image_url":
                    image_url,
                    "fallback":
                    track['artist'].strip() + " - " + track['title'].strip(),
                    "title":
                    track['artist'].strip() + " - " + track['title'].strip(),
                    "text":
                    track['album'].strip(),
                    "color":
                    "#212121"
                })

            webclient = payload['web_client']
            webclient.chat_postMessage(
                channel=channel,
                text=text,
                thread_ts=thread_ts,
                as_user=False,
                icon_url=
                "https://images-na.ssl-images-amazon.com/images/I/41838a7kfqL.png",
                username="******",
                attachments=attachment)

            duration = datetime.strptime(track['duration'], '%H:%M:%S')
            position = datetime.strptime(track['position'], '%H:%M:%S')
            remaining_time = duration - position
            speak_after[channel] = datetime.today() + remaining_time
    except:
        buffer = datetime.today() + timedelta(0, 5)
        speak_after[channel] = speak_after[
            channel] if speak_after[channel] > buffer else buffer
        pass