def pixabay_parse_resp(subject): """ From Pixabay API, collect the top 4 images from results. :param subject: The subject to be used for the image search or type(None). If None, random photos are fetched. :rtype images: A list containing data on the fetched images. :except AttributeErrror: Occurs when resp fails to fetch images and enumerate cannot parse resp. """ pix = Image(PIXABAY_API_KEY) if subject is not None: resp = pix.search(q=subject, per_page=4, image_type="photo") else: # give more randomized image selections resp = pix.search(q=randomize_query(), per_page=4, image_type="photo", page=randint(1, 10)) images = [] try: for num, item in enumerate(resp["hits"], 1): image_info = { "author_name": item["user"], "full_image": item["largeImageURL"], "image_id": item["id"], "author_profile": f"https://pixabay.com/en/users/{item['user_id']}", } images.append(image_info) return images except AttributeError as err: handle_err( f"Failed to parse pixabay resp object: {err}\nCheck that your API_KEYs are setup correctly." )
def get_image(keyword="食物", per_page=20): # 默认下载 20 张图 image = Image(API_KEY) image.search() ims = image.search(q=keyword, lang='zh', image_type='photo', safesearch='true', order='latest', page=1, per_page=per_page) return ims
def download(self): logger.info('Downloading pics...') pix = Image(config.PIXABAY_API_KEY) i = 0 while i < self.download_num: search = utils.generate_keyword() img_search = pix.search(q=search, page=1, per_page=30) hits = len(img_search['hits']) if hits: index = random.randint(0, hits - 1) url = img_search['hits'][index]['webformatURL'] pic_path = config.PIC_PATH + str(i) + '.jpg' args = ','.join("{0}".format(arg) for arg in [url, pic_path]) cmd = ['runp', 'Downloaders.py', 'downloader:' + args] p = subprocess.Popen(cmd) pid = utils.wait_timeout(p, config.DOWNLOAD_TIMEOUT) if pid is not None: logger.info('Picture downloader ran successfully!') store(self.id, url, 'pic') self.tags.append(search) i += 1 else: utils.clear_file(pic_path) logger.info('Picture downloader timeout out!')
def find_image(search): API_KEY = '19162245-447c77f2e91a2fe67d8cd3dad' # image operations image = Image(API_KEY) # default image search img = image.search(search) hits = img['hits'] i = 0 for element in hits: i = i + 1 # print(i) try: num = random.randint(0, i - 1) img = hits[num] url = img['largeImageURL'] # print(url) except: url = '' pass return url
def pixabay(self, init_id=0): #Key of the user(vriegc00) api_key = '12304969-479982339d49683b58ae74908' #It is necessary to add a version to download images class AppURLopener(urllib.request.URLopener): version = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.69 Safari/537.36" urllib._urlopener = AppURLopener() #Foreach category for i in range(0, self.categories): category_name = self.categories_name[i] #print("Category name: {}".format(category_name)) #For each search word for j in range (0,len(self.categories_search[i])): search_word = self.categories_search[i][j] #print(" - {}".format(search_word)) #Search image = Image(api_key) ims = image.search(q=search_word, page=1, per_page=self.images_search) #Download image one by one for image in ims['hits']: extension = os.path.splitext(image['largeImageURL'])[-1] urllib._urlopener.retrieve(image['largeImageURL'], self.folder+category_name+"/"+str(init_id).zfill(6)+extension) init_id = init_id +1
def fetch_image_path(self): image = Image(self.api_key) image_path_array = [] selected_search_terms = [] if self.search_terms.__len__() <= 3: selected_search_terms = self.search_terms else: while selected_search_terms.__len__() < 3: selected_search_terms.append(self.search_terms[random.randint( 0, self.search_terms.__len__() - 1)]) for term in selected_search_terms: try: ims = image.search(q=term, image_type='photo', orientation='vertical') number_of_hits = ims['hits'].__len__() selected_index_array = [] if 2 >= number_of_hits > 0: while selected_index_array.__len__() <= number_of_hits: selected_index = random.randint(0, number_of_hits - 1) selected_index_array.append(selected_index) else: while selected_index_array.__len__() < 2: selected_index = random.randint(0, number_of_hits - 1) selected_index_array.append(selected_index) for selected_index in selected_index_array: image_path = ims['hits'][selected_index]['largeImageURL'] image_path_array.append(image_path) except IndexError: continue except ValueError: continue if len(image_path_array) == 0: term = 'sorry' try: ims = image.search(q=term, image_type='photo', orientation='vertical') image_path_array = { 'apology_image': ims['hits'][0]['largeImageURL'] } except IndexError: print("Index Error") except ValueError: print("Value Error") return image_path_array
async def inline(client, query): results = [] string = query.query.lower() if string == "": await query.answer( results=DEFAULT_RESULTS, cache_time=CACHE_TIME, switch_pm_text="How do I work", switch_pm_parameter="start", ) return else: image = Image(config.get('api', 'key')) image.search() ims = image.search(q=string.split()[1], lang='en', image_type='photo', orientation='horizontal', category=string.split()[0], safesearch='true', order='latest', page='backgrounds', per_page=50) for item in ims['hits']: picture_url = item["largeImageURL"] text = await text_parser(item) buttons = [[ InlineKeyboardButton('Link', url=f'{item["pageURL"]}'), InlineKeyboardButton( 'Author', url= f'https://pixabay.com/users/{item["user"]}-{item["user_id"]}/' ) ]] results.append( InlineQueryResultPhoto( photo_url=picture_url, title=f'Result:{item["id"]}', caption=text, description=f"Nothing", reply_markup=InlineKeyboardMarkup(buttons))) await client.answer_inline_query(query.id, results=results, is_gallery=True, cache_time=CACHE_TIME) return
def _search_image_from_pixabay(keyword): # https://github.com/momozor/python-pixabay # https://pixabay.com/api/docs/ # image operations image = Image(PIXABAY_API_KEY) # custom image search result = image.search( q = keyword, lang = 'zh', page = 1, per_page = 3, image_type='photo', orientation = 'all', # "all", "horizontal", "vertical" order = 'popular', # "popular", "latest" safesearch = 'true') return result
def getFromPixabay(): api_key="useyourownapi" image=Image(api_key) listurl=[] ims=image.search(q='',category="nature",min_width="1366", min_height="768",page=random.randrange(1,25),safesearch="yes") #print(ims["hits"]) for i in ims["hits"]: listurl.append(i["fullHDURL"]) print(len(listurl)) for i in range(len(listurl)): try: print(listurl[i]) opener=urllib.request.Request(listurl[i]) opener.add_header('User-Agent','Mozilla/5.0 (X11; Linux x86_64; rv:65.0) Gecko/20100101 Firefox/65.0') fx = open('/home/devnull/Pictures/background/background.jpg','wb') fx.write(urllib.request.urlopen(opener).read()) fx.close() #listurl.remove(listurl[i]) time.sleep(660) except IndexError: print("List Index Out of Range") break
from urllib.request import Request, urlopen import os from pathlib import Path import shutil import requests as r API_KEY = os.environ.get('PixabayApiKey') #IndexError()()()()()()()())())))()()(()()()()()()()()()() # image operations image = Image(API_KEY) # custom image search q = input("Enter the name as per your requirement:") ims = image.search( q=str(q), lang='en', #image_type='photo', orientation='horizontal', category='butterfly', #safesearch='true', order='latest', page=1, ) #per_page=3) print(ims['hits']) url = [ims['hits'][i]['largeImageURL'] for i in range(3)] #as per the user requirement print(url) def total_images(num): url = [ims['hits'][i]['largeImageURL'] for i in range(num)] return url
# Lightning Code # Created by Jachimike Onuoha. # Copyright © 2019 Jachimike Onuoha. All rights reserved. from pixabay import Image, Video import urllib.request import pprint import os # Assign your Api key to the environment variable "PIXABAY_API_KEY" and the working variable API_KEY os.environ["PIXABAY_API_KEY"] = YOUR_API_KEY API_KEY = YOUR_API_KEY # Search for any image using the Image query Image = Image(API_KEY) newImage = Image.search(q='YOUR_SEARCH') # Pretty print response to improve readability pp = pprint.PrettyPrinter(indent=4) pp.pprint(newImage) # Get the value for the preview URL payload_one = newImage['hits'][15]['previewURL'] print("This is the preview URL {}".format(payload_one)) # Search for any video using the Video query Video = Video(API_KEY) newVideo = Video.search(q='YOUR_SEARCH') # Pretty print response to improve readability pp = pprint.PrettyPrinter(indent=4)
class PixabaySkill(MycroftSkill): # The constructor of the skill, which calls MycroftSkill's constructor def __init__(self): super(PixabaySkill, self).__init__(name="PixabaySkill") def initialize(self): self.add_event('pixabay-skill.aiix.home', self.handle_pixabay_homescreen) self.gui.register_handler("pixabay.show.image", self.handle_pixabay_show_image) self.gui.register_handler("pixabay.show.video", self.handle_pixabay_show_video) self.gui.register_handler("pixabay.gallery.next", self.handle_gallery_next_page) self.gui.register_handler("pixabay.gallery.previous", self.handle_gallery_previous_page) self.gui.register_handler("pixabay.idle.set_idle", self.handle_set_idlescreen_type) self.gui.register_handler("pixabay.idle.enableTime", self.handle_idle_enable_time) self.gui.register_handler("pixabay.idle.disableTime", self.handle_idle_disable_time) self.gui.register_handler("pixabay.idle.updateTime", self.handle_idle_update_time) self.gui.register_handler("pixabay.idle.removeConfigPage", self.handle_remove_configure_idle_screen) self.entKey = base64.b64decode( "MTcyMjI5NDctYTlmNTQxNmQ2ODhkNDVmNmJkZmY4ZWEzYQ==") self.video = Video(self.entKey) self.image = Image(self.entKey) self.shownPageNumber = None self.numberOfAvailablePages = None self.previousQuery = None self.currentType = None self.currentDir = dirname(dirname(abspath(__file__))) self.wantedDir = "pixabayData" self.dataPath = join(self.currentDir, self.wantedDir) self.videoPath = join(self.dataPath, "video.mp4") # Set All Paths try: os.mkdir(self.dataPath) except OSError as error: print("Directory Already Exist Skipping") self.storeDB = join(self.dataPath, 'pixabay-idle.db') self.idle_db = JsonStorage(self.storeDB) self.configDB = join(self.dataPath, 'pixabay-config.db') self.idle_config_db = JsonStorage(self.configDB) # Make Import For TimeData try: time_date_path = "/opt/mycroft/skills/mycroft-date-time.mycroftai/__init__.py" time_date_id = "datetimeskill" datetimeskill = load_skill_module(time_date_path, time_date_id) from datetimeskill import TimeSkill self.dt_skill = TimeSkill() except: print("Failed To Import DateTime Skill") def handle_pixabay_homescreen(self, message): self.handle_pixabay_display("Homescreen") @intent_file_handler("PixabaySearchImage.intent") def handle_pixabay_search_image_type(self, message): query = message.data["query"] self.previousQuery = query self.shownPageNumber = 1 self.currentType = "Image" ims = self.image.search(q=query, lang='en', image_type='photo', orientation='vertical', category='all', safesearch='true', order='latest', page=1, per_page=6) totalImages = ims['total'] totalHits = ims['totalHits'] self.handle_number_of_pages(totalImages, totalHits) self.gui["currentPageNumber"] = self.shownPageNumber self.gui["showMoreAvailable"] = self.handle_show_more_available( self.shownPageNumber) self.gui["imageGalleryModel"] = ims['hits'] self.handle_pixabay_display("ImageGallery") def handle_pixabay_show_image(self, message): self.gui["imageURL"] = message.data["largeImageURL"] self.handle_pixabay_display("Image") @intent_file_handler("PixabaySearchVideo.intent") def handle_pixabay_search_video_type(self, message): query = message.data["query"] self.previousQuery = query self.shownPageNumber = 1 self.currentType = "Video" vis = self.video.search(q=query, lang='en', video_type='all', category='all', page=1, per_page=6) totalImages = vis['total'] totalHits = vis['totalHits'] print(totalImages) print(totalHits) self.handle_number_of_pages(totalImages, totalHits) self.gui["currentPageNumber"] = self.shownPageNumber self.gui["showMoreAvailable"] = self.handle_show_more_available( self.shownPageNumber) self.gui["videoGalleryModel"] = vis['hits'] addr = vis['hits'] print(addr) self.handle_pixabay_display("VideoGallery") def handle_pixabay_show_video(self, message): orignalurl = message.data['videourl'] videoURL = self.handle_pixabay_extract_video(orignalurl) self.gui["videoURL"] = videoURL self.handle_pixabay_display("Video") def handle_pixabay_extract_video(self, videoURL): extractvideofromloc = requests.get(videoURL, allow_redirects=False) actualVideoUrl = extractvideofromloc.headers['location'] r = requests.get(actualVideoUrl, stream=True) with open(self.videoPath, 'wb') as f: for chunk in r.iter_content(chunk_size=1024 * 1024): if chunk: f.write(chunk) videoURL = self.videoPath return videoURL def handle_pixabay_display(self, state): if state is "Image": self.gui["setMessage"] = "" self.gui.show_page("Image.qml", override_idle=True) elif state is "Video": self.gui["setMessage"] = "" self.gui.show_page("Video.qml", override_idle=True) elif state is "Homescreen": self.gui.show_page("Homepage.qml", override_idle=True) else: self.gui["pageState"] = state self.gui.show_page("pixabayLoader.qml", override_idle=True) def handle_gallery_next_page(self, message): galleryType = message.data["galleryType"] pageNumber = message.data["currentPageNumber"] if pageNumber < self.numberOfAvailablePages: pageNumber = self.shownPageNumber + 1 self.shownPageNumber = pageNumber if galleryType == "Image": ims = self.image.search(q=self.previousQuery, lang='en', image_type='all', orientation='vertical', category='all', safesearch='true', order='latest', page=self.shownPageNumber, per_page=6) self.gui["currentPageNumber"] = self.shownPageNumber self.gui[ "showMoreAvailable"] = self.handle_show_more_available( self.shownPageNumber) self.gui["imageGalleryModel"] = ims['hits'] elif galleryType == "Video": vis = self.video.search(q=self.previousQuery, lang='en', video_type='all', category='all', page=self.shownPageNumber, per_page=6) self.gui["currentPageNumber"] = self.shownPageNumber self.gui[ "showMoreAvailable"] = self.handle_show_more_available( self.shownPageNumber) self.gui["videoGalleryModel"] = vis['hits'] self.handle_pixabay_display("VideoGallery") else: print("Valid Type Not Found") def handle_gallery_previous_page(self, message): galleryType = message.data["galleryType"] pageNumber = message.data["currentPageNumber"] if pageNumber > 1: pageNumber = self.shownPageNumber - 1 self.shownPageNumber = pageNumber if galleryType == "Image": ims = self.image.search(q=self.previousQuery, lang='en', image_type='all', orientation='all', category='all', safesearch='true', order='latest', page=self.shownPageNumber, per_page=6) self.gui["currentPageNumber"] = self.shownPageNumber self.gui[ "showMoreAvailable"] = self.handle_show_more_available( self.shownPageNumber) self.gui["imageGalleryModel"] = ims['hits'] elif galleryType == "Video": vis = self.video.search(q=self.previousQuery, lang='en', video_type='all', category='all', page=self.shownPageNumber, per_page=6) self.gui["currentPageNumber"] = self.shownPageNumber self.gui[ "showMoreAvailable"] = self.handle_show_more_available( self.shownPageNumber) self.gui["videoGalleryModel"] = vis['hits'] self.handle_pixabay_display("VideoGallery") else: print("Valid Type Not Found") @intent_handler( IntentBuilder("HandleAudioGalleryNext").require( "PixabayGalleryNextKeyword").build()) def handle_audio_gallery_next(self): currentPageNumber = self.shownPageNumber self.handle_gallery_next_page( Message( "data", { "currentPageNumber": currentPageNumber, "galleryType": self.currentType })) @intent_handler( IntentBuilder("HandleAudioGalleryNext").require( "PixabayGalleryPreviousKeyword").build()) def handle_audio_gallery_previous(self): currentPageNumber = self.shownPageNumber self.handle_gallery_previous_page( Message( "data", { "currentPageNumber": currentPageNumber, "galleryType": self.currentType })) def handle_number_of_pages(self, total, totalhits): if total > totalhits: orgNumPage = totalhits / 6 if orgNumPage > 10: self.numberOfAvailablePages = 10 return 10 else: orgNumPage = totalhits / 6 self.numberOfAvailablePages = orgNumPage return orgNumPage elif total < totalhits: orgNumPage = total / 6 if orgNumPage > 10: self.numberOfAvailablePages = 10 return 10 else: orgNumPage = totalhits / 6 self.numberOfAvailablePages = orgNumPage return orgNumPage elif total == totalhits: orgNumPage = total / 6 if orgNumPage > 10: self.numberOfAvailablePages = 10 return 10 else: self.numberOfAvailablePages = orgNumPage return orgNumPage def handle_show_more_available(self, currentPage): if currentPage < self.numberOfAvailablePages: return True else: return False def handle_set_idlescreen_type(self, message): idleType = message.data["idleType"] self.idle_db.clear() if idleType == "Image": idleImageURL = message.data["idleImageURL"] imageType = idleImageURL.split('.')[-1] imagePath = join(self.dataPath, str("pixabay-idle" + "." + imageType)) self.extract_image_for_idle(idleImageURL, imagePath) self.gui["idleType"] = "ImageIdle" self.gui["idleGenericURL"] = imagePath self.idle_db["idleInfo"] = { "idleType": "ImageIdle", "idleGenericURL": imagePath } self.idle_db.store() self.gui["setMessage"] = "New Homescreen Set" if idleType == "Video": idleVideoURL = message.data["idleVideoURL"] self.gui["idleType"] = "VideoIdle" self.gui["idleGenericURL"] = idleVideoURL self.idle_db["idleInfo"] = { "idleType": "VideoIdle", "idleGenericURL": idleVideoURL } self.idle_db.store() self.gui["setMessage"] = "New Homescreen Set" def handle_idlescreen_first_run(self): # Check If Idle Screen DB Exist and Not Empty # Retrive and Set Idle Screen if Available # If idle unset, get random and store if 'idleInfo' in self.idle_db.keys(): self.gui["idleType"] = self.idle_db["idleInfo"]["idleType"] self.gui["idleGenericURL"] = self.idle_db["idleInfo"][ "idleGenericURL"] else: imageURL = self.generate_random_idle() imageType = imageURL.split('.')[-1] imagePath = join(self.dataPath, str("pixabay-idle" + "." + imageType)) self.extract_image_for_idle(imageURL, imagePath) self.idle_db["idleInfo"] = { "idleType": "ImageIdle", "idleGenericURL": imagePath } self.idle_db.store() self.gui["idleType"] = "ImageIdle" self.gui["idleGenericURL"] = imagePath if 'showTime' in self.idle_config_db.keys(): if self.idle_config_db["showTime"] == True: self.gui["showTime"] = True self.gui[ 'time_string'] = self.dt_skill.get_display_current_time() else: self.gui["showTime"] = False self.gui["time_string"] = "" else: self.gui["showTime"] = False self.gui["time_string"] = "" def generate_random_idle(self): ims = self.image.search(q="galaxy", lang='en', image_type='photo', orientation='vertical', category='all', safesearch='true', order='latest', page=4, per_page=6) randomImageUrl = ims['hits'][4]["largeImageURL"] return randomImageUrl @resting_screen_handler('Pixabay') def handle_idle(self, message): self.gui.clear() self.log.debug('Activating Time/Date resting page') self.handle_idlescreen_first_run() self.gui.show_page('pixabayIdleLoader.qml') def extract_image_for_idle(self, url, localpath): try: image = requests.get(url) except OSError: return False if image.status_code == 200: with open(localpath, "wb") as k: k.write(image.content) else: print("Saving Image Failed") def handle_idle_enable_time(self): self.speak("I am enabling time") self.idle_config_db["showTime"] = True self.gui["showTime"] = True self.idle_config_db.store() # Send Time Data Here First self.handle_idle_update_time() def handle_idle_disable_time(self): self.speak("I am disabling time") self.idle_config_db["showTime"] = False self.gui["showTime"] = False self.idle_config_db.store() def handle_idle_update_time(self): self.gui['time_string'] = self.dt_skill.get_display_current_time() @intent_handler( IntentBuilder("PixabayIdleConfigure").require( "PixabayIdleConfigure").build()) def handle_configure_idle_screen(self): self.gui.show_page("ConfigurePixabayIdle.qml") def handle_remove_configure_idle_screen(self): self.gui.remove_page("ConfigurePixabayIdle.qml") def stop(self): pass
API_KEY = os.getenv('API_KEY') image = Image(API_KEY) while True: for n in range(1,2): try: ims = image.search( q="streets", lang="en", image_type="all", orientation="all", category="all", min_width=0, min_height=0, colors="", editors_choice="false", safesearch="true", order="popular", page=n, per_page=200, callback="", pretty="true") imageUrls = [] for i in range(0, 200): payload = ims['hits'][i]['largeImageURL'] imageUrls.append(payload) if imageUrls: for k in range(0,6):
def get_list_img(api_token, keyword): """Get the list of image objects from pixabay.com follow keyword""" image = Image(api_token) imgs = image.search(q=keyword, image_type='photo', order='latest') return imgs['hits']