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 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) if not os.path.exists(PATH): await message.edit("Oops, No Results Found") return 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()
def find_image(search_param, username): search_param_fill = "{} reaction meme".format(search_param) gis = GoogleImagesSearch(GOOGL_DEV_API_KEY, CX_API_KEY) # define search params: _search_params = { 'q': '{}'.format(search_param_fill), 'num': 10, } gis.search(search_params=_search_params) images = gis.results() image_index = random.randint(0, images.__len__() - 1) image = images[image_index] dl_location = os.path.join(os.getcwd(), "images\\{}".format(username)) print(dl_location) if os.path.isdir(dl_location) == False: os.mkdir(dl_location) image.download(dl_location) onlyfiles = [f for f in listdir(dl_location) if isfile(join(dl_location, f))] if onlyfiles.__len__() > 1: print("There should be only one file, but there are {}".format(onlyfiles.__len__())) filename = join(dl_location, onlyfiles[0]) return filename
async def execute(self, args, msg): query = ' '.join(args) suffix = globals.conf.get(globals.conf.keys.IMAGINE_SUFFIX) if suffix: query = f'{query} {suffix}' search_params = { 'q': query, 'safe': 'off' if msg.channel.is_nsfw() else 'medium', 'num': 10 } async with msg.channel.typing(): coll = globals.bot.db['imagine'] results = coll.find_one({'query': search_params['q'], 'safe': search_params['safe']}) if results is None or results['date'] + datetime.timedelta(days=7) < datetime.datetime.utcnow(): image_api_key = globals.conf.get(globals.conf.keys.IMAGE_API_KEY, bypass_protected=True) image_search_cx = globals.conf.get(globals.conf.keys.IMAGE_SEARCH_CX, bypass_protected=True) if image_api_key is None or image_search_cx is None: raise RuntimeError(f'Google search API key or custom search engine not configured.') gis = GoogleImagesSearch(image_api_key, image_search_cx) gis.search(search_params=search_params) good_ext = {'jpg', 'jpeg', 'JPG', 'JPEG', 'png', 'PNG', 'gif', 'webm', 'mp4', 'wav', 'mp3', 'ogg'} urls = list(filter( lambda u: u.split('?')[0].split('.')[-1] in good_ext, map(lambda r: r.url, gis.results())) ) results = {'query': search_params['q'], 'safe': search_params['safe'], 'urls': urls, 'state': 0, 'date': datetime.datetime.utcnow()} coll.replace_one({'query': search_params['q'], 'safe': search_params['safe']}, results, upsert=True) if len(results['urls']) == 0: excuses = ['I cannot imagine that', 'I don\'t even know what that is'] return await msg.channel.send(f'{msg.author.mention} {random.choice(excuses)}') await msg.channel.send(results['urls'][results['state']]) next_state = (results['state'] + 1) % len(results['urls']) coll.update_one(results, {'$set': {'state': next_state}})
def fetch_images(countries): if not os.path.exists('data'): os.makedirs('data') os.chdir('./data') data_path = os.getcwd() print(data_path) gis = GoogleImagesSearch(config.api_key, config.cx) for country in countries: _search_params = {'q': country + ' food', 'num': 2} if not os.path.exists(country): os.makedirs(country) elif len([ name for name in os.listdir('./' + country) if os.path.isfile(name) ]) >= 10: print(country, 'maxed images') continue os.chdir('./' + country) temp_path = os.getcwd() gis.search(search_params=_search_params, path_to_dir=temp_path) os.chdir('..') time.sleep(0.3)
class ImageSearch(): def __init__(self): with open("config/tokens.json", "r") as f: data = json.load(f) self.gis = GoogleImagesSearch(data['google_api'], data['google_cx']) def search(self, keyword): """ Search for an image """ try: # Search for the image of space num = random.randint(0, MAX_SEARCH - 1) params = {'q': keyword, 'num': MAX_SEARCH, 'safe': 'off'} self.gis.search(search_params=params) # Return the random result counter = 0 for image in self.gis.results(): if counter == num or counter == MAX_SEARCH - 1: return image.url counter = counter + 1 except Exception as e: print('[ERROR] ' + e) return None
def google_im_search_palette(queries): gis = GoogleImagesSearch('AIzaSyA5H4YVZnReJRv7GZAx2m3wg3q3Q2OvOOw', '32e819b64b0302e9c') domcols = np.zeros((5, 3)) ## HACK - CONSIDER CHANGING FOR VARYING LABEL LIST LENGTHS for i in range(5): ## THIS IS SUPER HACKY RIGHT NOW, DON'T KNOW WHY SOME IMAGES CAN'T BE READ _search_params = { 'q': queries[i], 'num': 1, } my_bytes_io = BytesIO() # this will only search for images: gis.search(search_params=_search_params) for image in gis.results(): my_bytes_io.seek(0) raw_image_data = image.get_raw_data() image.copy_to(my_bytes_io, raw_image_data) my_bytes_io.seek(0) try: temp_img = pil.Image.open(my_bytes_io) dom = find_dom(temp_img, 5) domcols[i] = dom break except: print("exception") pass return domcols
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 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()
def get_google_image(folder, image, newText): txt_l = text_to_keyword(newText) txt_l_len = len(txt_l) print(txt_l_len, file=sys.stderr) 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') if os.path.exists(image): os.remove(image) else: print("The file does not exist") for image in gis.results(): image.download(folder) image.resize(500, 500)
async def img(self, ctx, *, query): '''Search for a image related to your query''' gis = GoogleImagesSearch(google_api_key, google_cse_key) _search_params = {'q': query, 'num': 3, 'safe': 'off'} gis.search(search_params=_search_params) embed = discord.Embed(title=query) embed.set_image(url=gis.results()[0].url) await ctx.send(embed=embed)
def get(self, request, key_word, count=4): gis = GoogleImagesSearch(self._developer_key, self._cx) search_params = { 'q': '{} {}'.format(request, key_word), 'num': count, 'fileType': 'jpg', 'imgType': 'photo' # 'huge|icon|large|medium|small|xlarge|xxlarge' } gis.search(search_params=search_params) return [image.url for image in gis.results()]
def search_g(query): gis = GoogleImagesSearch('AIzaSyBjMfb1TfPfhDRKbzyK9E6cDypYXHEbhQw', '000266786199815297998:e1orac7unwo') num = random.randint(1, 4) gis.search({'q': query, 'num': num}) result = "" for image in gis.results(): if (image.url.lower().find("https") == 0): result = image.url return result
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 get_urls(searches): gis = GoogleImagesSearch(developer_key, custom_search_cx, validate_images=False) # define search params: search_params = {'num': 1, 'safe': 'off'} urls = [] for search in searches: search_params['q'] = search gis.search(search_params) [urls.append(result.url) for result in gis.results()] return urls
def image_search(query): gis = GoogleImagesSearch(GCS_DEVELOPER_KEY, "016720228003584159752:xwo6ysur40a") _search_params = { "q": query, "safe": "off", } try: gis.search(search_params=_search_params) img = gis.results()[0].url return img except Exception: return ""
def gather_image(template_file): GCS_DEVELOPER_KEY = "AIzaSyBhT5S6xOtfiVj2q0B-hXrLJ8ToKs1ZtPA" GCS_CX = "b29678caa4b0cc505" gis = GoogleImagesSearch(GCS_DEVELOPER_KEY, GCS_CX) f = open(template_file) data = json.load(f) nouns = [] for d in data: nouns = nouns + d["nouns"] print(nouns) nouns = list(set(nouns)) print(nouns) for i, noun in enumerate(nouns): search_params = { 'q': noun, 'num': 1, 'safe': 'high', 'fileType': 'png', } for root, dir, files in os.walk(os.getcwd() + "\\img"): filename = noun + ".jpg" if filename not in files: gis.search(search_params=search_params, path_to_dir="./img/".format(i), custom_image_name=noun.format(noun)) # 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) # image.save(picture) f.close()
def image_search(query): gis = GoogleImagesSearch(GCS_DEVELOPER_KEY, '016720228003584159752:xwo6ysur40a') _search_params = { 'q': query, 'safe': 'off', } try: gis.search(search_params=_search_params) img = gis.results()[0].url return img except Exception as e: return ''
async def image(self, ctx, *, query): gis = GoogleImagesSearch(config['googleAPI'], config['googleCX']) imgDwnld = BytesIO() gis.search({'q': query, 'num': 1}) sendFile = None for image in gis.results(): imgDwnld.seek(0) raw_image_data = image.get_raw_data() image.copy_to(imgDwnld, raw_image_data) imgDwnld.seek(0) sendFile = discord.File(fp=imgDwnld, filename=f"{query}.png") try: await ctx.send(file=sendFile) except: await ctx.send("I cannot find any image for that search!")
def Search_Save(Champ, save_path): cx = '93e5e6f08c6709af0' # this my search engine cc if u wanna use or create one by yourself ^_^ api_key = get_my_key() # use your own API here this private stuff dude ^_^ gis = GoogleImagesSearch(api_key, cx) _search_params = { 'q': Champ, 'num': 1, 'safe': 'high', 'fileType': 'jpg', 'imgType': 'photo', 'imgSize': 'XXLARGE', } gis.search(search_params=_search_params, path_to_dir=save_path, custom_image_name=Champ)
def main(): # you can provide API key and CX using arguments, # or you can set environment variables: GCS_DEVELOPER_KEY, GCS_CX gis = GoogleImagesSearch('AIzaSyAJq0IAvV9rfCjtNUmjb_tdcTxGj-4VZFM', '18a3ed03f69d15370') for config_file_name in CONFIGS: get_images(gis, config_file_name)
async def img(self, ctx: commands.Context, *, query: str) -> None: await ctx.send("Aju photo ah hoadhaathaan...") out_dir = Path("img_cache") src_path = Path("img_cache/*") response = GoogleImagesSearch(os.environ["IMG_SEARCH_API_KEY"], os.environ["IMG_SEARCH_WEB_ID"]) args = {"q": query, "num": 1, "fileType": "jpg|png"} source_name = glob.glob(f"{src_path}") if source_name: path, fullname = os.path.split(f"{source_name[0]}") if "image" in fullname: os.remove(f"{source_name[0]}") print("File deleted.") else: pass response.search(search_params=args, path_to_dir=out_dir) source_name = glob.glob(f"{src_path}") embed: discord.Embed = None file: discord.File = None if source_name: path, fullname = os.path.split(f"{source_name[0]}") basename, ext = os.path.splitext(fullname) target_name = os.path.join(path, f"image{ext}") os.rename(source_name[0], target_name) print(f"Renamed {basename}{ext} to image{ext}.") embed = discord.Embed(title=query, colour=discord.Colour(0xE9ACFD)) embed.set_footer(text=f"Image requested by: {ctx.author}", icon_url=ctx.author.avatar_url) if ext == ".jpg": embed.set_image(url="attachment://image.jpg") file = discord.File("img_cache/image.jpg", filename="image.jpg") elif ext == ".png": embed.set_image(url="attachment://image.png") file = discord.File("img_cache/image.png", filename="image.png") else: print("File not found.") try: await ctx.send(file=file, embed=embed) except Exception as e: print(f"Error sending image: {e}")
def crawl_image(query_text, save_dir, num=10, fileType='jpg|png', imgSize='MEDIUM'): gis = GoogleImagesSearch(GCS_DEVELOPER_KEY, GCS_CX) # define search params: _search_params = { 'q': query_text, 'num': num, 'fileType': fileType, 'imgSize': imgSize } gis.search(search_params=_search_params) for image in tqdm(gis.results()): image.download(save_dir)
async def _search(self, ctx, query, size, file_type, count): gis = GoogleImagesSearch(self.api_token, self.api_cx) if count > MAX_IMG_COUNT: count = MAX_IMG_COUNT gis.search({'q': query, 'num': MAX_IMG_COUNT}) bytes_io = BytesIO() return_count = 0 for i, img in enumerate(gis.results()): try: bytes_io.seek(0) raw_image_data = img.get_raw_data() except Exception as e: print('There was an issue getting the image') print(e) continue try: print('Testing image...') _ = raw_image_data.decode('utf-8') print('Image test failed, ignoring image') except: img.copy_to(bytes_io, raw_image_data) img.copy_to(bytes_io) bytes_io.seek(0) img_size = sys.getsizeof(bytes_io) if img_size < MAX_IMG_SIZE_MB * (4**10): print('Image is valid') await ctx.send( file=discord.File(bytes_io, f'{query}_{i}.{file_type}') ) return_count += 1 if return_count >= count: break else: print( f'Image ({img_size}) is larger than {MAX_IMG_SIZE_MB * (4**10)}' )
def downloadImages(query, num=1): from google_images_search import GoogleImagesSearch from json import load with open('credentials.json') as f: j = load(f) key = j['key'] cx = j['cx'] gis = GoogleImagesSearch(key, cx) _search_params = { 'q': query, 'num': num, } # assumes there is a folder with name images/query/ gis.search(search_params=_search_params, path_to_dir='images/' + query)
def add_images(car_model): my_bytes_io = BytesIO() gis = GoogleImagesSearch( "AIzaSyDL-iX9_5bYDWB5BHzXuMcV7xHt4_7X2JM", "003405953032685171249:uzag_hgt6fs", ) gis.search({"q": str(car_model), "num": 3, "imgSize": "medium"}) for image in gis.results(): my_bytes_io.seek(0) image.copy_to(my_bytes_io) my_bytes_io.seek(0) response = cloudinary.uploader.upload(my_bytes_io) my_bytes_io.flush() # insert image carmodelimage = CarModelImage( model=car_model, name=response["public_id"] ) carmodelimage.save()
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": 10, "safe": "off", "fileType": "jpg", "imgType": "photo", "imgSize": "LARGE", } 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) == 10: break await message.reply_chat_action("upload_photo") await message.reply_media_group(ss, True) shutil.rmtree(PATH, ignore_errors=True) await message.delete()
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")
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 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
def search(): f = open('GoogleCustomSearchApiKey.txt') KEY = f.readline()[:-1] CX = f.readline()[:-1] gis = GoogleImagesSearch(KEY, CX) adjectives = [line[:-1] for line in open('adjectives.txt', 'r')] nouns = [line[:-1] for line in open('nouns.txt', 'r')] visited = [line[:-1] for line in open('AlreadyDone.txt', 'r')] searchPass = 1 while True: print "Pass: "******"%s %s" % (adjectives[random.randint( 0, len(adjectives) - 1)], nouns[random.randint(0, len(nouns) - 1)]) print "Generating Query" print "Query: " + query print "Forming Search Parameters" search_params = { 'q': query, 'num': 10, 'safe': 'off', 'fileType': 'png', 'imgType': 'photo', 'searchType': 'image', } print "Initiating Search" gis.search(search_params=search_params) print "Storing results" results = gis.results() print "Processing Results" if len(results) > 0: for i in range(len(results) - 1, -1, -1): fileName = gis.results( )[i].url[gis.results()[i].url.rfind('/') + 1:] if fileName in visited: del results[i] if len(results) > 0: index = random.randint(0, len(results) - 1) fileName = results[index].url[results[index].url.rfind('/') + 1:] visited.append(fileName) results[index].download('images') f = open('AlreadyDone.txt', 'w') toWrite = "" for term in visited: toWrite += term + "\n" f.write(toWrite) return 'images/' + fileName searchPass += 1
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)