def run(write_directory, exiv2_file_path, from_date): """Fetch all geotagged photos and write exiv2 script for them. Retrieve all geotagged photos taken since `from_date` to `write_directory` and write a set of exiv2(1) commands storing geotags in EXIF to `exiv2_file_path`. `from_date` is a string YYYY-MM-DD, `write_directory` and `exiv2_file_path` are valid directory and file names, respectively. """ exiv2_file = open(exiv2_file_path, 'w') # Start flickring flickr = FlickrAPI(API_KEY, API_SECRET, format='etree') # Authorize (token, frob) = flickr.get_token_part_one(perms='read') if not token: raw_input('Press ENTER after you authorized this program') flickr.get_token_part_two((token, frob)) print 'Retrieving list of geotagged photos taken since %s...' % from_date photos = flickr.photos_getWithGeoData(min_date_taken=from_date).getiterator('photo') # Retrieve photo to `write_directory`, write exiv2 commands to # scriptfile. for photo in photos: title, url, location = get_photo_data(flickr, photo) print 'Retrieving photo %s...' % title filename, headers = urlretrieve(url, os.path.join(write_directory, \ os.path.basename(url))) write_location_commands(os.path.abspath(filename), location, exiv2_file)
def test_authenticate_fail(self): flickr = FlickrAPI(FAKEKEY, FAKESECRET) try: (token, frob) = flickr.get_token_part_one(perms='write') if not token: raw_input("Press ENTER after you authorized this program") flickr.get_token_part_two((token, frob)) except FlickrError as e: self.assertEqual(e[0], u'Error: 100: Invalid API Key (Key not found)')
def get_flickr(API_KEY, SECRET, TOKEN=None): if TOKEN is None: flickr = FlickrAPI(API_KEY, SECRET) (token, frob) = flickr.get_token_part_one(perms='write') if not token: raw_input("Press ENTER after you authorized this program") flickr.get_token_part_two((token, frob)) else: flickr = FlickrAPI(api_key=API_KEY, secret=SECRET, token=TOKEN) return flickr
class Offlickr: def __init__( self, key, secret, httplib=None, dryrun=False, verbose=False, ): """Instantiates an Offlickr object An API key is needed, as well as an API secret""" self.__flickrAPIKey = key self.__flickrSecret = secret self.__httplib = httplib # Get authentication token # note we must explicitly select the xmlnode parser to be compatible with FlickrAPI 1.2 self.fapi = FlickrAPI(self.__flickrAPIKey, self.__flickrSecret, format='xmlnode') (token, frob) = self.fapi.get_token_part_one() if not token: raw_input('Press ENTER after you authorized this program') self.fapi.get_token_part_two((token, frob)) self.token = token test_login = self.fapi.test_login() uid = test_login.user[0]['id'] self.flickrUserId = uid self.dryrun = dryrun self.verbose = verbose def __testFailure(self, rsp): """Returns whether the previous call was successful""" if rsp['stat'] == 'fail': print 'Error!' return True else: return False def getPhotoList(self, dateLo, dateHi): """Returns a list of photo given a time frame""" n = 0 flickr_max = 500 photos = [] print 'Retrieving list of photos' while True: if self.verbose: print 'Requesting a page...' n = n + 1 rsp = self.fapi.photos_search( api_key=self.__flickrAPIKey, auth_token=self.token, user_id=self.flickrUserId, per_page=str(flickr_max), page=str(n), min_upload_date=dateLo, max_upload_date=dateHi, ) if self.__testFailure(rsp): return None if rsp.photos[0]['total'] == '0': return None photos += rsp.photos[0].photo if self.verbose: print ' %d photos so far' % len(photos) if len(photos) >= int(rsp.photos[0]['total']): break return photos def getGeotaggedPhotoList(self, dateLo, dateHi): """Returns a list of photo given a time frame""" n = 0 flickr_max = 500 photos = [] print 'Retrieving list of photos' while True: if self.verbose: print 'Requesting a page...' n = n + 1 rsp = \ self.fapi.photos_getWithGeoData(api_key=self.__flickrAPIKey, auth_token=self.token, user_id=self.flickrUserId, per_page=str(flickr_max), page=str(n)) if self.__testFailure(rsp): return None if rsp.photos[0]['total'] == '0': return None photos += rsp.photos[0].photo if self.verbose: print ' %d photos so far' % len(photos) if len(photos) >= int(rsp.photos[0]['total']): break return photos def getPhotoLocation(self, pid): """Returns a string containing location of a photo (in XML)""" rsp = \ self.fapi.photos_geo_getLocation(api_key=self.__flickrAPIKey, auth_token=self.token, photo_id=pid) if self.__testFailure(rsp): return None doc = libxml2.parseDoc(rsp.xml) info = doc.xpathEval('/rsp/photo')[0].serialize() doc.freeDoc() return info def getPhotoLocationPermission(self, pid): """Returns a string containing location permision for a photo (in XML)""" rsp = \ self.fapi.photos_geo_getPerms(api_key=self.__flickrAPIKey, auth_token=self.token, photo_id=pid) if self.__testFailure(rsp): return None doc = libxml2.parseDoc(rsp.xml) info = doc.xpathEval('/rsp/perms')[0].serialize() doc.freeDoc() return info def getPhotosetList(self): """Returns a list of photosets for a user""" rsp = self.fapi.photosets_getList(api_key=self.__flickrAPIKey, auth_token=self.token, user_id=self.flickrUserId) if self.__testFailure(rsp): return None return rsp.photosets[0].photoset def getPhotosetInfo(self, pid, method): """Returns a string containing information about a photoset (in XML)""" rsp = method(api_key=self.__flickrAPIKey, auth_token=self.token, photoset_id=pid) if self.__testFailure(rsp): return None doc = libxml2.parseDoc(rsp.xml) info = doc.xpathEval('/rsp/photoset')[0].serialize() doc.freeDoc() return info def getPhotoMetadata(self, pid): """Returns an array containing containing the photo metadata (as a string), and the format of the photo""" if self.verbose: print 'Requesting metadata for photo %s' % pid rsp = self.fapi.photos_getInfo(api_key=self.__flickrAPIKey, auth_token=self.token, photo_id=pid) if self.__testFailure(rsp): return None doc = libxml2.parseDoc(rsp.xml) metadata = doc.xpathEval('/rsp/photo')[0].serialize() doc.freeDoc() return [metadata, rsp.photo[0]['originalformat']] def getPhotoComments(self, pid): """Returns an XML string containing the photo comments""" if self.verbose: print 'Requesting comments for photo %s' % pid rsp = \ self.fapi.photos_comments_getList(api_key=self.__flickrAPIKey, auth_token=self.token, photo_id=pid) if self.__testFailure(rsp): return None doc = libxml2.parseDoc(rsp.xml) comments = doc.xpathEval('/rsp/comments')[0].serialize() doc.freeDoc() return comments def getPhotoSizes(self, pid): """Returns a string with is a list of available sizes for a photo""" rsp = self.fapi.photos_getSizes(api_key=self.__flickrAPIKey, auth_token=self.token, photo_id=pid) if self.__testFailure(rsp): return None return rsp def getOriginalPhoto(self, pid): """Returns a URL which is the original photo, if it exists""" source = None rsp = self.getPhotoSizes(pid) if rsp == None: return None for s in rsp.sizes[0].size: if s['label'] == 'Original': source = s['source'] for s in rsp.sizes[0].size: if s['label'] == 'Video Original': source = s['source'] return [source, s['label'] == 'Video Original'] def __downloadReportHook( self, count, blockSize, totalSize, ): if not self.__verbose: return p = ((100 * count) * blockSize) / totalSize if p > 100: p = 100 print '\r %3d %%' % p, sys.stdout.flush() def downloadURL( self, url, target, filename, verbose=False, ): """Saves a photo in a file""" if self.dryrun: return self.__verbose = verbose tmpfile = '%s/%s.TMP' % (target, filename) if self.__httplib == 'wget': cmd = 'wget -q -t 0 -T 120 -w 10 -c -O %s %s' % (tmpfile, url) os.system(cmd) else: urllib.urlretrieve(url, tmpfile, reporthook=self.__downloadReportHook) os.rename(tmpfile, '%s/%s' % (target, filename))
bild.save(Datei) t = splitext(basename(Datei))[0] PiCam.stop_preview() PiCam.preview_fullscreen= False PiCam.start_preview() print "Auf Flicker hochladen..." response=flickr.upload(filename=Datei, title=t, is_public=1, format='etree') photoID = response.find('photoid').text photoURL = 'http://www.flickr.com/photos/%s/%s/' % (flickruser, photoID) print "Fertig" time.sleep(1) flickr = FlickrAPI(key, secret) (token, frob) = flickr.get_token_part_one(perms='write') if not token: raw_input("Bitte Anwendung im Browser autorisieren und dann ENTER druecken") flickr.get_token_part_two((token, frob)) PiCam = picamera.PiCamera() PiCam.preview_fullscreen= False PiCam.resolution=(1024, 768) PiCam.preview_window = (1, 1 , 800, 600) PiCam.start_preview() IO.setwarnings(False) IO.setmode(IO.BCM) Taster = 23 IO.setup(Taster, IO.IN, pull_up_down=IO.PUD_DOWN)
def test_authenticate(self): flickr = FlickrAPI(API_KEY, API_SECRET) (token, frob) = flickr.get_token_part_one(perms='write') if not token: raw_input("Press ENTER after you authorized this program") flickr.get_token_part_two((token, frob))
def getFlickr(key=API_KEY, secret=API_SECRET): flickr = FlickrAPI(key, secret) (token, frob) = flickr.get_token_part_one(perms='write') if not token: raw_input("Press ENTER after you authorized this program") flickr.get_token_part_two((token, frob)) return flickr
class FlickrCommunicator(object): """ The interface to the Flickr API. Attributes: flickr: The FlickrAPI object that allows communication with Flickr services. app_name: The application name to be assoicated with the uploaded images. """ def __init__(self): """ Initializes the link between this app and Flickr API using stored configuration values. Due to the way the Flickr API authorizes, the first time a set of credentials are used on a given system, this must be initialized within a context that allows a browser window to open and username and password to be entered. """ config_dict = utils.read_config_dict("FlickrCommunicator") self.flickr = FlickrAPI(config_dict['api_key'], config_dict['api_secret']) self.app_name = config_dict['app_name'] (token, frob) = self.flickr.get_token_part_one(perms='write') if not token: raw_input("Press ENTER after you authorized this program") self.flickr.get_token_part_two((token, frob)) def upload_photo(self, filename, sample_num, timestamp): """ Post an image to the Flickr account. Args: filename: The filename of the image to be uploaded. sample_num: The sample number associated with the image. timestamp: A string representing the date and time the image was taken. Returns: A shortened url that points to the image uplaoded to Flickr. """ #build a description string time, date = self._get_timestamp_strings(timestamp) description = "Sample %d taken at %s on %s" %(sample_num, time, date) #generate the tag string tags = "pellinglab, %s, 'sample %d'" %(self.app_name, sample_num) #generate the title string title = "Pellinglab image. %s" %date feedback = self.flickr.upload(filename = filename, title = title, description = description, tags = tags) for elem in feedback: photoID = elem.text return shorturl.url(photoID) def _get_timestamp_strings(self, timestamp): """ A helper method to create the time and date strings from a datetime timestamp """ months = { 1:"Jan", 2:"Feb", 3:"Mar", 4:"Apr", 5:"May", 6:"Jun", 7:"Jul", 8:"Aug", 9:"Sep", 10:"Oct", 11:"Nov", 12:"Dec" } time = "%02d:%02d:%02d" %(timestamp.hour, timestamp.minute, timestamp.second) date = "%s %02d, %d" %(months[timestamp.month], timestamp.day, timestamp.year) return time, date