Beispiel #1
0
def flickr_upload(image, db, config):
    print('Uploading %s to flickr' % image)
    path = os.path.join(config['image_dir'], image)
    upload_time = datetime.now()
    flickr_api.upload(photo_file=path)
    print('Upload complete')

    db['last_upload'] = upload_time
    db['uploaded'].append(image)
    write_db(db, db_path)
Beispiel #2
0
def main():
    parser = argparse.ArgumentParser(description='''Upload one file to a user.''')
    parser.add_argument('-f', '--filepath', help='Path to file.', required=True)

    args = parser.parse_args()

    if args.filepath:
        file_path = args.filepath
        auth_file_name = '.flickr_auth'
        home_dir = os.path.expanduser('~')
        auth_file = os.path.join(home_dir, auth_file_name)
        f.set_auth_handler(auth_file)
        f.upload(photo_file = file_path, title='Cake!!')
Beispiel #3
0
def handle_set_title(message):
    try:
        flickr_api.set_auth_handler("./users_data/{}/auth_token.dat".format(
            hash(message.chat.id)))
        USERS[hash(message.chat.id)] = flickr_api.test.login()
        flickr_api.upload(photo_file="Photo",
                          title=message.text,
                          photo_file_data=urllib.request.urlopen(URLS[hash(
                              message.chat.id)]))
    except Exception:
        BOT.send_message(message.chat.id,
                         "Oops! Error! Try later or try another photo.")
        return

    BOT.send_message(message.chat.id, "Photo is uploaded!")
Beispiel #4
0
    def upload_photo(self, file_path):
        dir_path, name = os.path.split(file_path)
        name = os.path.splitext(name)[0]

        if not self.is_valid(file_path):
            print "Ignoring '%s'" % file_path
            return

        if self.recreate_exif:
            subprocess.check_call(["jhead", "-de", file_path],
                                  stdout=subprocess.PIPE)
            subprocess.check_call(["jhead", "-mkexif", file_path],
                                  stdout=subprocess.PIPE)

        if self.upload_to_set:
            photoset_title = os.path.basename(dir_path.rstrip("/"))
            # flickr_api seems to use unicode
            try:
                photoset_title = unicode(photoset_title)
            except UnicodeDecodeError:
                photoset_title = photoset_title.decode('iso8859-1')

            if self.exist_in_photoset(name, photoset_title):
                return

        flickr_photo = flickr_api.upload(photo_file=file_path,
                                         title=name,
                                         tags=self.tags,
                                         is_public=0)

        if self.upload_to_set:
            self.add_to_photoset(flickr_photo, photoset_title)
    def upload_photo(self, file_path):
        dir_path, name = os.path.split(file_path)
        name = os.path.splitext(name)[0]

        if not self.is_valid(file_path):
            print "Ignoring '%s'" % file_path
            return

        if self.recreate_exif:
            subprocess.check_call(["jhead", "-de", file_path],
                                  stdout=subprocess.PIPE)
            subprocess.check_call(["jhead", "-mkexif", file_path],
                                  stdout=subprocess.PIPE)

        if self.upload_to_set:
            photoset_title = os.path.basename(dir_path.rstrip("/"))
            # flickr_api seems to use unicode
            try:
                photoset_title = unicode(photoset_title)
            except UnicodeDecodeError:
                photoset_title = photoset_title.decode('iso8859-1')

            if self.exist_in_photoset(name, photoset_title):
                return

        flickr_photo = flickr_api.upload(photo_file=file_path,
                                         title=name,
                                         tags=self.tags,
                                         is_public=0)

        if self.upload_to_set:
            self.add_to_photoset(flickr_photo, photoset_title)
Beispiel #6
0
def upload_to_flickr(photo_file, title, comments, is_public, tags):
    """ Upload file to flickr """
    photo = flickr_api.upload(photo_file=photo_file, title=title, is_public=is_public,
                              tags=tags, description=comments)
    photo_info = photo.getInfo()
    photo_info['sizes'] = photo.getSizes()
    return photo_info
Beispiel #7
0
def flickr_upload(photo_file, album=None, title=None, group=None, is_public=1):

	## upload photo

	# print "Photo File:", photo_file

	photo = flickr_api.upload(photo_file = photo_file , title=title, is_public=is_public)

	## add to album/photoset

	if album:

		user = flickr_api.test.login()
		a = get_album(user,album)

		if a:
			a.addPhoto(photo = photo)

	if group:

		user = flickr_api.test.login()
		g = get_group(group)

		if g:
			g.addPhoto(photo = photo)
Beispiel #8
0
def upload(request):
    file = upload_receive(request)

    tmp_file = open(file.name, 'wb+')

    for chunk in file.chunks():
        tmp_file.write(chunk)

    tmp_file.close()
    photo = flickr_api.upload(photo_file=tmp_file.name, title=tmp_file.name, is_public=0)

    basename = os.path.basename(tmp_file.name)

    sizes = photo.getSizes()

    file_dict = {
        'name': basename,
        'size': file.size,
        'url': sizes['Original']['source'],
        'thumbnailUrl': sizes['Thumbnail']['source'],
        'deleteUrl': reverse('upload:upload_delete', kwargs={'pk': photo.id}),
        'deleteType': 'POST',
    }

    os.unlink(tmp_file.name)

    return UploadResponse(request, file_dict)
Beispiel #9
0
def add_people2flickrPhoto(photo_img = '', photo_title = '', defaultFaceSetName = 'yahoohack_faceset', username2user_id = {}, username='') :
    '''
    1.upload a photo to flickr
    2.get faces box
    3.add face to photo
    '''
    fOauth(username)
    upload_photo = flickr_api.upload(photo_file = photo_img, title = photo_title)
    photo_id = upload_photo['id']
    add_geo2photo(upload_photo, 20.1345,31.214)
    faces_box = face_identify(photo_img = photo_img)
    face2user_id = {}
    '''
    for face_id in faces_box :
        person_name = face_api.info.get_face(face_id = face_id)
        #['face_info'][0]['person'][0]['person_name']
        print person_name
    '''
    person_seen = {}
    for face_id in faces_box :
        person_name, box = faces_box[face_id]
        x,y,w,h = box[0], box[1], box[2] - box[0], box[3] - box[1]
        print x,y,w,h
        print person_name
        if person_seen.get(person_name,False) == False :
            print username2user_id[person_name]
            try :
                upload_photo.addPerson(user_id = username2user_id[person_name], person_x = x,person_y = y,person_w = w, person_h = h)
            except Exception,ex :
                print username2user_id[person_name]
                print ex
            person_seen[person_name] = True
def main():
	utils.flickr_login()

#	flickr_api.upload(photo_file='in.jpg', title='Test twice')

	img_data = convert.encode_to_png(open('in.mp3', 'rb').read(), font='in.ttf')

	try:
		fp = tempfile.NamedTemporaryFile(delete=False)
		fp.write(img_data)
		fp.close()

		flickr_api.upload(photo_file=fp.name, title='Final fusion')
	finally:
		try: os.remove(fp.name)
		except OSError: pass
Beispiel #11
0
def uploadPhoto(fil,titl):
  import datetime
  from PIL import Image
  global resize
  
  msg = 'ResizeOption[%d, %d] '%resize
  dt1 = datetime.datetime.now()
  if not ((resize[0]==1) and (resize[1]==1)):
    rsz = resize
    im = Image.open(fil)
    if resize[0]==0:
      rsz = (100000, resize[1])
    elif resize[1]==0:
      rsz = (resize[0], 100000)
    else:
      rat = resize[0]
      rsz = (round(im.size[0]*rat), round(im.size[1]*rat))
    msg += '... Orginal[%d,%d] -->'%im.size
    im.thumbnail(rsz,Image.ANTIALIAS)
    msg += 'Final[%d, %d]'%im.size
    im.save('tmp.jpg')
    fil = 'tmp.jpg'
    
  ph = flickr_api.upload(photo_file=fil, title=titl)
  dt2 = datetime.datetime.now()
  dd = dt2 - dt1
  msg += '... Uploaded photo %s, title %s, in %d s'%(fil, titl, dd.seconds)
  log(msg)
  return ph
Beispiel #12
0
def upload_to_flickr(photo_file, title, comments, is_public, tags):
    """ Upload file to flickr """
    photo = flickr_api.upload(photo_file=photo_file, title=title, is_public=is_public,
                              tags=tags, description=comments)
    photo_info = photo.getInfo()
    photo_info['sizes'] = photo.getSizes()
    return photo_info
Beispiel #13
0
def upload(dnz_id, IE_number):
    try:
#        photo_path = ('files/%s.jpg' % IE_number)
        photo_path = ('files/%s.tif' % IE_number)
        metadata = get_metadata(dnz_id)
        title = metadata['title']
        description = add_citation(metadata['description'], dnz_id)
        flickr_api.upload(photo_file = photo_path, title = title, description = description)
        print '%s uploaded!' % title
        status = open('files/%s.status' % IE_number, 'a')
        status.close
        return True
    except:
        print "Unexpected error!", sys.exc_info()[0]
        raise
        failure = open('files/%s.failure' % IE_number, 'a')
        failure.close
Beispiel #14
0
def upload_photos(upload_folder, max_retries):
    logger = logging.getLogger(LOGGER)
    user = flickr.test.login()
    logger.info("Logged in as %s", user.username)
    photosets = {p.title: p for p in user.getPhotosets()}

    if os.path.isdir(upload_folder):
        album_name = os.path.basename(upload_folder)
    else:
        logger.error("Must be run on a directory")
        sys.exit(1)

    # If we already have a photoset with this name, don't upload pictures we already have
    if album_name in photosets.keys():
        logger.info(
            "Photoset %s already exists.  Getting contents so we can resume if needed.",
            album_name)
        remote_photos = {p.title: p for p in photosets[album_name].getPhotos()}
    else:
        logger.info(
            "Photoset %s does not exist, so it will be created once the first photo is uploaded.",
            album_name)
        remote_photos = {}

    local_files = [
        f for f in os.listdir(upload_folder)
        if os.path.splitext(f)[1] in ('.jpg', '.png', '.gif')
    ]

    logger.info("Processing %d files", len(local_files))

    retries = 0
    for count, filename in enumerate(local_files, start=1):
        if os.path.splitext(filename)[0] in remote_photos.keys():
            print("Skipping file %s because it has already been uploaded" %
                  filename)
            continue
        logger.info("Starting upload of file %s", filename)
        while (retries <= max_retries) or (max_retries == -1):
            try:
                photo_obj = flickr.upload(photo_file=os.path.join(
                    upload_folder, filename),
                                          is_public="0",
                                          is_friend="0",
                                          is_family="0",
                                          hidden="2",
                                          async="0")
                logger.info("Uploaded file %s", filename)
                add_to_photoset(photo_obj, album_name, photosets)
                logger.info("Added file %s to album %s", filename, album_name)
                break
            except Exception:
                logger.error("Failed to upload file %s")
                if (retries <= max_retries) or (max_retries == -1):
                    logger.error("Retrying...")
        logger.info("Progress: %d%% (%d/%d)", count / len(local_files) * 100,
                    count, len(local_files))
Beispiel #15
0
 def upload(self, path, photoset, public, friend, family):
     picture = flickr.upload(photo_file=path, title=os.path.splitext(os.path.basename(path))[0],
                             is_public=public, is_friend=friend, is_family=family)
     if photoset is None:
         photoset = flickr.Photoset.create(title = os.path.basename(os.path.dirname(path)),
                                           primary_photo = picture)
     else:
         photoset.addPhoto(photo = picture)
     return picture, photoset
Beispiel #16
0
def main():
    utils.flickr_login()

    #	flickr_api.upload(photo_file='in.jpg', title='Test twice')

    img_data = convert.encode_to_png(open('in.mp3', 'rb').read(),
                                     font='in.ttf')

    try:
        fp = tempfile.NamedTemporaryFile(delete=False)
        fp.write(img_data)
        fp.close()

        flickr_api.upload(photo_file=fp.name, title='Final fusion')
    finally:
        try:
            os.remove(fp.name)
        except OSError:
            pass
Beispiel #17
0
	def upload_photo(self,**kwargs):
		if not 'path' in kwargs or not 'file' in kwargs: kwargs = self.extend_kwargs(**kwargs)
		if not 'path' in kwargs or not 'file' in kwargs: return -1
		try:
			self.log.info(self.current_file+": Uploading To Flickr")
			fp = flickr_api.upload(photo_file = os.path.join(kwargs['path'],kwargs['file']))
			return fp['id']
		except Exception, e: 
			self.log.exception(str(e))
			return 0
Beispiel #18
0
def upload_image_to_flickr(image_to_upload):
    PrintTimestamp("Uploading Image: " + image_to_upload)

    uploaded_photo = flickr_api.upload(photo_file=image_to_upload,
                                       title=datetime.datetime.now().strftime("%c"),
                                       hidden=0,
                                       is_public=1,
                                       tags='unprocessed WSJ2019 "World Scout Jamboree" "World Scout Jamboree 2019" "ScoutJamboree" "2019 WSJ" "Summit Bechtel Reserve" "24WSJ" "24th World Scout Jamboree"')
    photo_id = uploaded_photo.id
    PrintTimestamp("Uploaded '" + image_to_upload + "' to Flickr with ID " + photo_id)
    return photo_id
def upload(path):
    """Function, that uploads photos """
    
    urls={} 
    faild_files=[]
    for i in range(len(path)):
        try:
            upload_result=flickr_api.upload(photo_file =path[i])
            urls[upload_result.title]=flickr_api.Photo.getPageUrl(upload_result)
        except:
            faild_files.append(path[i]) 
    return urls,faild_files
Beispiel #20
0
def upload(filename):
    """Upload the named file to Flickr."""
    logger = logging.getLogger('main.flickr')
    try:
        response = flickr_api.upload(photo_file=filename,
                                     safety_level=1,
                                     is_public=1,
                                     content_type=1)
    except Exception:
        logger.exception("Flickr upload exception")
    else:
        logger.info('Flickr upload: ' + str(response))
Beispiel #21
0
 def upload_photo(self, **kwargs):
     if not 'path' in kwargs or not 'file' in kwargs:
         kwargs = self.extend_kwargs(**kwargs)
     if not 'path' in kwargs or not 'file' in kwargs: return -1
     try:
         self.log.info(self.current_file + ": Uploading To Flickr")
         fp = flickr_api.upload(
             photo_file=os.path.join(kwargs['path'], kwargs['file']))
         return fp['id']
     except Exception, e:
         self.log.exception(str(e))
         return 0
Beispiel #22
0
    def test_upload_not_200(self):
        from flickr_api import set_auth_handler
        auth_handler = AuthHandler(key="test",
                                   secret="test",
                                   access_token_key="test",
                                   access_token_secret="test")
        set_auth_handler(auth_handler)
        args = dict(photo_file='/tmp/test_file',
                    photo_file_data=StringIO("000000"))

        module = inspect.getmodule(upload)
        resp = Response()
        resp.status_code = 404
        resp.raw = BytesIO("Not Found".encode("utf-8"))
        module.requests.post = MagicMock(return_value=resp)

        with self.assertRaises(FlickrError) as context:
            upload(**args)

        print(context.exception)
        self.assertEquals("HTTP Error 404: Not Found", str(context.exception))
    def test_upload_not_200(self):
        from flickr_api import set_auth_handler
        auth_handler = AuthHandler(
            key="test",
            secret="test",
            access_token_key="test",
            access_token_secret="test")
        set_auth_handler(auth_handler)
        args = dict(
            photo_file='/tmp/test_file', photo_file_data=StringIO("000000"))

        module = inspect.getmodule(upload)
        resp = Response()
        resp.status_code = 404
        resp.raw = BytesIO("Not Found".encode("utf-8"))
        module.requests.post = MagicMock(return_value=resp)

        with self.assertRaises(FlickrError) as context:
            upload(**args)

        print(context.exception)
        self.assertEquals("HTTP Error 404: Not Found", str(context.exception))
def upload(path):
    """Function, that uploads photos """

    urls = {}
    faild_files = []
    for i in range(len(path)):
        try:
            upload_result = flickr_api.upload(photo_file=path[i])
            urls[upload_result.title] = flickr_api.Photo.getPageUrl(
                upload_result)
        except:
            faild_files.append(path[i])
    return urls, faild_files
def uploadUsingThread(photo):
    photo_file_path = photo.image.path
    result = {}

    if photo.flickr_photo_id == '':
        try_count = 3
        flickr_api.set_keys(api_key=__flickr_api_key,
                            api_secret=__flickr_api_secret)
        flickr_api.set_auth_handler('oauth_verifier.txt')

        while try_count > 0:
            try:
                flickr_response = flickr_api.upload(
                    photo_file=photo_file_path,
                    title=photo.title,
                    description=u'地點: ' + photo.location_marker.title +
                    u'\n拍攝者: ' + photo.owner.nickname + '\n\n' + photo.content,
                    tags=photo.tags,
                    is_public=1,
                    is_family=1,
                    is_friend=1,
                    safety_level=1,
                    content_type=1,
                    hidden=1,
                )
                photo.flickr_photo_id = flickr_response.id
                photo_info = flickr_response.getInfo()
                photo.flickr_photo_url = 'https://farm{}.staticflickr.com/{}/{}_{}_b.jpg'.format(
                    photo_info['farm'], photo_info['server'],
                    flickr_response.id, photo_info['secret'])
                photo.save()
                result['flickr_response'] = flickr_response
                break
            except Exception as e:
                print str(e)
                try_count -= 1
            time.sleep(10)
    else:
        result['flickr_response'] = 'already upload to flickr'

    if photo.facebook_post_id == '':
        result['facebook_response'] = uploadToFacebook(photo)
    else:
        result['facebook_response'] = updateFlickrPhotoURL(photo)

    print 'uploadPhotoresult' + str(result)

    photo.isReady = True
    photo.image.delete()
    photo.save()
    return result
Beispiel #26
0
 def upload(self, path, photoset, public, friend, family):
     picture = flickr.upload(photo_file=path,
                             title=os.path.splitext(
                                 os.path.basename(path))[0],
                             is_public=public,
                             is_friend=friend,
                             is_family=family)
     if photoset is None:
         photoset = flickr.Photoset.create(title=os.path.basename(
             os.path.dirname(path)),
                                           primary_photo=picture)
     else:
         photoset.addPhoto(photo=picture)
     return picture, photoset
def upload_image(img_path, title='Uploaded by Line Bot', photo_set=None):
    photo = flickr_api.upload(photo_file=img_path, title=title)
    photo_url = photo.getPageUrl()
    if photo_set is None:
        return photo_url

    if get_photoset(photo_set) is None:
        print 'Create photoset {0}'.format(photo_set)
        create_photoset(photo_set, photo)
    else:
        print 'Add photo to {0}'.format(photo_set)
        ps = get_photoset(photo_set)
        ps.addPhoto(photo=photo)
    return photo_url
Beispiel #28
0
def uploadPhoto(filename, newAlbum = False):
    if not filename[-4:] in ['.jpg', 'jpeg', '.JPG', 'JPEG', '.png', '.PNG']:
        print 'Not a image'
        print 'Skip', filename
        return

    dirname = os.path.basename(os.path.dirname(filename))
    print 'Prepare to upload', filename
    print 'Which is based in', dirname

    if type(dirname) == type('string'):
        dirname = dirname.decode('utf-8')

    #print currentPhotosetsPhotos
    if len(currentPhotosetsPhotos['photos']) == 0 and dirname in photosetDict:
        photoset = photosetDict[dirname]
        print "Building photos' info in album", dirname
        #photos = photoset.getPhotos()
        w = flickr_api.Walker(photoset.getPhotos)
        for photo in w:
            if len(photo.title) > 0:
                #print photo.title
                currentPhotosetsPhotos['photos'][photo.title] = photo
            else:
                pass

    title = os.path.basename(filename)
    if title[-4] == ".":
        title = title[:-4]
    elif title[-5] == '.':
        title = title[:-5]
    else:
        title = title.split('.')[0]
    title = title.decode('utf-8')
    if title in currentPhotosetsPhotos['photos']:
        print 'Already uploaded. Skip',title
    else:
        print 'Uploading', title
        photo = flickr_api.upload(photo_file = filename, is_public = 0, is_friend = 0, is_family = 0)
        print 'Uploaded', photo

        if dirname in photosetDict:
            photoset = photosetDict[dirname]
            photoset.addPhoto(photo = photo)
            print 'Add photo', photo, 'into', photoset
        elif newAlbum:
            photoset = createNewAlbum(dirname, photo)
            print 'Add photo', photo, 'into', photoset

        currentPhotosetsPhotos['photos'][photo.title] = photo
Beispiel #29
0
def upload():
    success_dir = settings.get('success_dir', 'success')
    for file in get_list():
        try:
            content_type = 2 if file.lower().endswith('.png') else 1
            print(flickr.upload(photo_file=file, content_type=content_type))
        except flickr.FlickrError as e:
            print(file, e)
            break
        except IOError:
            print(file, 'not found')
            continue
        else:
            filename = os.path.basename(file)
            os.rename(file, os.path.join(success_dir, filename))
Beispiel #30
0
def upload():
    success_dir = settings.get('success_dir', 'success')
    for file in get_list():
        try:
            content_type = 2 if file.lower().endswith('.png') else 1
            print(flickr.upload(photo_file=file, content_type=content_type))
        except flickr.FlickrError as e:
            print(file, e)
            break
        except IOError:
            print(file, 'not found')
            continue
        else:
            filename = os.path.basename(file)
            os.rename(file, os.path.join(success_dir, filename))
Beispiel #31
0
def uploadUsingThread(photo):
	photo_file_path = photo.image.path
	result = {}

	if photo.flickr_photo_id=='':
		try_count = 3
		flickr_api.set_keys(api_key = __flickr_api_key, api_secret = __flickr_api_secret)
		flickr_api.set_auth_handler('oauth_verifier.txt')

		while try_count > 0 :
			try :
				flickr_response = flickr_api.upload(
					photo_file = photo_file_path,
					title =photo.title,
					description = u'地點: '+photo.location_marker.title+u'\n拍攝者: '+photo.owner.nickname+'\n\n'+photo.content,
					tags = photo.tags,
					is_public = 1,
					is_family = 1,
					is_friend = 1,
					safety_level =1,
					content_type  =1,
					hidden = 1,
				)
				photo.flickr_photo_id = flickr_response.id
				photo_info = flickr_response.getInfo()
				photo.flickr_photo_url = 'https://farm{}.staticflickr.com/{}/{}_{}_b.jpg'.format(photo_info['farm'], photo_info['server'], flickr_response.id, photo_info['secret'])
				photo.save()
				result['flickr_response'] = flickr_response
				break;
			except Exception as e:
				print str(e)
				try_count -= 1
			time.sleep(10)
	else:
		result['flickr_response'] = 'already upload to flickr'

	if photo.facebook_post_id =='':
		result['facebook_response'] = uploadToFacebook(photo)
	else:
		result['facebook_response'] = updateFlickrPhotoURL(photo)

	print 'uploadPhotoresult' + str(result)

	photo.isReady = True
	photo.image.delete()
	photo.save()
	return result
Beispiel #32
0
def upload(rootdir, current_sets):
    '''
    Upload files from the ``rootdir`` to Flickr. It will create a PhotoSet for
    each directory in ``rootdir``. It will upload each file in a directory
    and add it to the set. If a set already exists, it will be reused and new
    photos will be added to it. If a file is already uploaded to the PhotoSet,
    it will be skipped.

    rootdir
        The root directory to sync.

    current_sets
        A dict of PhotoSets by title that are already uploaded.
    '''
    uploaded = 0
    dirs = [dir_ for dir_ in listdir(rootdir) if isdir(pjoin(rootdir, dir_))]

    for dir_ in dirs:
        files = list()
        uploaded_photos = list()
        current_photos = list()

        # Attempt to get the set that would match this dir.
        album = current_sets.get(dir_)
        if album:
            # Set already exists. Get all photos in set by title.
            for photo in album.getPhotos():
                current_photos.append(photo.title)

        # Get all the files in this dir.
        fulldir = pjoin(rootdir, dir_)
        files = [file_ for file_ in listdir(fulldir) if isfile(pjoin(fulldir,
                                                                     file_))]

        # Upload new files. Storing the returned Photo in uploaded_photos.
        for file_ in files:
            if not splitext(file_)[0] in current_photos:
                print 'Uploading photo: {0}'.format(file_)
                uploaded_photos.append(fapi.upload(photo_file=pjoin(fulldir,
                                                                    file_)))
                uploaded += 1

        if len(uploaded_photos) > 0:
            if not album:
                album = create_album(dir_, uploaded_photos[0])
            populate_album(album, uploaded_photos[1:])
    return uploaded
    def upload_photo(self, photo_file, photo_title, file_extension,
                     photoset_title, make_public, is_hidden):
        """
        Uploads a given photo to a given photoset. Photo is set to private for all users
        """

        if photo_title == ".DS_Store" or file_extension.lower(
        ) not in self.valid_extensions:
            logging.debug("Invalid file type, cannot upload...")
            return

        logging.info(
            "Attempting to upload photo [%s] then add to photoset [%s]." %
            (photo_title, photoset_title))

        upload_result = flickr.upload(
            **{
                "photo_file": photo_file,
                "is_public": make_public,
                "is_friend": "0",
                "is_family": "0",
                "hidden": is_hidden,
                "async": 1
            })

        if isinstance(upload_result, flickr.Photo):
            logging.info("\tphoto uploaded immediately! Photo ID: [%s]" %
                         upload_result.id)
            photo = flickr.Photo(id=upload_result.id)
            self.add_to_photoset(photo, photoset_title)
            return "DONE"

        elif isinstance(upload_result, UploadTicket):
            logging.info(
                "\tadded to Flickr upload queue, will check on shortly. UploadTicket ID: [%s]"
                % upload_result.id)
            self._upload_tickets[upload_result.id] = photoset_title
            self._syncing = True
            _thread.start_new_thread(self.poll_upload_tickets, ())
            return "QUEUED"

        else:
            logging.info("Unknown response received: %s" % upload_result)
            return "FAIL"
    def upload_photo(self, file_path):
        dir_path, name = os.path.split(file_path)

        if not self.is_valid(file_path):
            print "Ignoring '%s'" % file_path
            return

        if self.recreate_exif:
            subprocess.check_call(["jhead", "-de", file_path],
                                  stdout=subprocess.PIPE)
            subprocess.check_call(["jhead", "-mkexif", file_path],
                                  stdout=subprocess.PIPE)

        flickr_photo = flickr_api.upload(photo_file=file_path,
                                         title=name,
                                         is_public=0)

        if self.upload_to_set:
            photoset_title = os.path.basename(dir_path.rstrip("/"))
            self.add_to_photoset(flickr_photo, photoset_title)
Beispiel #35
0
    def upload_photo(self, photo_title, file_extension, photoset_title):
        """
        Uploads a given photo to a given photoset. Photo is set to private for all users
        """

        if photo_title == ".DS_Store" or file_extension.lower(
        ) not in self.valid_extensions:
            return

        photo_file = self.get_path(photoset_title, photo_title, file_extension)
        upload_ticket = flickr.upload(photo_file=photo_file,
                                      is_public="0",
                                      is_friend="0",
                                      is_family="0",
                                      hidden="2",
                                      async="1")

        self._upload_tickets[upload_ticket["id"]] = photoset_title

        logging.info("\tuploading photo: %s" % photo_title)
 def upload_photo(self, photo, tags, permissions, path_ignore=None):
     modified_path = photo.photo_path        
     if path_ignore != None:
         modified_path = modified_path.replace(path_ignore, '')
     flickr_info_dict = dict()
     flickr_info_dict['path'] = photo.photo_path        
     flickr_info_dict['public'] = permissions['is_public']
     flickr_info_dict['family'] = permissions['is_family']
     flickr_info_dict['friend'] = permissions['is_friend']
     flickr_info_dict['upload_time'] = datetime.datetime.now()
     flickr_photo = flickr_api.upload(photo_file = flickr_info_dict['path'],
                                      description = 'sync_path|'+modified_path+'|end_sync_path',
                                      title = photo.filename,
                                      tags = " ".join(tags),
                                      is_public=flickr_info_dict['public'],
                                      is_friend=flickr_info_dict['friend'],
                                      is_family=flickr_info_dict['family'])
     flickr_info_dict['fid'] = flickr_photo.id
     self.stale = True
     return flickr_info_dict
Beispiel #37
0
def photos(request):
    try:
        val = request.POST.get(Const.cUID)
        fi.set_auth_handler(Const.cFILENAME)
        user = fi.test.login()
        photo = request.FILES.get('image')
        photoName = val+photo.name
        handle_uploaded_file(photo,photoName)
        tags = request.POST.get(Const.cTAGS)
        tag = tags.split('%2C')
        tagWithSpaces = ''
        for i in tag:
            tagWithSpaces+=i+' '
                        
        response = fi.upload(photo_file = Const.cMEDIA+photoName, title = photoName, tags=tagWithSpaces)

        for t in tag:
            photo = Photo.objects.create_photo(user.username,Const.cMEDIA+photoName,t)
        
        to_json = {Const.cSTATUS : '203'}
    
        return HttpResponse(json.dumps(to_json), mimetype='application/json')
    except Exception as e:
        print ('Exception: %s (%s)' % (e.message, type(e)))
  <li><strong>Author:</strong> {1}</li>
  <li><strong>Page:</strong> {6}</li>
  <li><strong>Year:</strong> {2}</li>
  <li><strong>Place:</strong> {3}</li>
  <li><strong>Publisher:</strong> {4}</li>
</ul>
<p><em>Following the link above will take you to the British Library's integrated catalogue. You will be able to download a PDF of the book this image is taken from, as well as view the pages up close with the 'itemViewer'. Click on the 'related items' to search for the electronic version of this work.</em></p>{8}
""".format(*decoded)
            uploaded_title=u"Image taken from page {1} of '{0}'".format(decoded[0].decode("utf-8"), page.decode("utf-8"))
            try:
              uploaded_title = u"Image taken from page {1} of '{0}'".format(decoded[0].decode("utf-8"), str(int(page)).decode("utf-8"))
            except:
              pass
            uploaded = flickr_api.upload(photo_file=location,
                            title=uploaded_title,
                            description = desc.decode("utf-8"),
                            tags=u"bldigital date:{0} pubplace:{1} public_domain mechanicalcurator".format(decoded[2].decode("utf-8"), re.sub(" ", "_", decoded[3].decode("utf-8"))),
                            is_public=1, is_friend=1, is_family=1,
                            content_type="photo", hidden=0, async=0)
            r.lpush("uploaded", "{0}\t{1}".format(location, str(uploaded.id)))
            print("http://www.flickr.com/photos/mechanicalcuratorcuttings/{0} uploaded".format(str(uploaded.id)))
            clear_job(workerid, job)
          except flickr_api.FlickrError,e:
            print "Flickr Error"
            print e
            from datetime import datetime
            r.lpush("uploaderror", "{0}\t{2}\t{1}".format(job, str(e), datetime.now().isoformat()))
            r.lpush("failedupload", job)
            clear_job(workerid, job) 
      else:
        clear_job(workerid, job)
      job = get_job(workerid)
import flickr_api

API_KEY = 'api-key'
API_SECRET = 'api-secret'
flickr_api.set_keys(api_key=API_KEY, api_secret=API_SECRET)
a = flickr_api.auth.AuthHandler()  #creates the AuthHandler object
perms = "write"  # set the required permissions
url = a.get_authorization_url(perms)
print url

# Run up to this point and go to url
# Copy the oauth_verification

a.set_verifier("oauth-verifier")
flickr_api.set_auth_handler(a)

# Uploading image to flickr

import flickr_api

filename = "./flickrauth"

API_KEY = 'api-key'
API_SECRET = 'api-secret'
flickr_api.set_keys(api_key=API_KEY, api_secret=API_SECRET)

a = flickr_api.auth.AuthHandler.load(filename)
flickr_api.set_auth_handler(a)

flickr_api.upload(photo_file="image-path", title="My title")
https://learn.adafruit.com/adafruits-raspberry-pi-lesson-12-sensing-movement
(we'll be adding the sensing part pretty soon)
'''

#!/usr/bin/env python
import sys
import os
import flickr_api
import time
import RPi.GPIO as io
from flickr_keys import *		#import your keys, this is in th flickr_api tutorial
io.setmode(io.BCM)

pir_pin = 18					#connect the PIR sensor to pin 18 on the Pi's GPIO
io.setup(pir_pin, io.IN)         # activate input

#get api key and api secret key
flickr_api.set_keys(api_key = FLICKR_API_KEY, api_secret = FLICKR_API_SECRET)

#get oauth_verifier
#a = flickr_api.auth.AuthHandler.load("verifier.txt")
flickr_api.set_auth_handler("verifier.txt")

while True:
    print(io.input(pir_pin))
    if io.input(pir_pin):
	os.system('sudo fswebcam -r 640x480 -S 20 webcam.jpg')
	flickr_api.upload(photo_file = "webcam.jpg", title = "Done IT!")
	time.sleep(5)
    time.sleep(0.25)
Beispiel #41
0
	return None

## Load authentication handler

AUTH_HANDLER_FILENAME = 'auth_handler'

flickr_api.set_auth_handler(AUTH_HANDLER_FILENAME)

user = flickr_api.test.login()

## Add Photo

start = datetime.now()

photo = flickr_api.upload(photo_file = "image01.jpg", title = "Tester")

duration = datetime.now() - start

print "Upload time:", duration


## Add to group

GROUP = 'Photoboof_test'

### Get group

start = datetime.now()

group = get_group(GROUP)
Beispiel #42
0
API_KEY =  'api-key'
API_SECRET = 'api-secret'
flickr_api.set_keys(api_key = API_KEY, api_secret = API_SECRET)
a = flickr_api.auth.AuthHandler() #creates the AuthHandler object
perms = "write" # set the required permissions
url = a.get_authorization_url(perms)
print url

# Run up to this point and go to url
# Copy the oauth_verification

a.set_verifier("oauth-verifier")
flickr_api.set_auth_handler(a)




# Uploading image to flickr

import flickr_api 
filename = "./flickrauth"

API_KEY =  'api-key'
API_SECRET = 'api-secret'
flickr_api.set_keys(api_key = API_KEY, api_secret = API_SECRET)

a = flickr_api.auth.AuthHandler.load(filename)
flickr_api.set_auth_handler(a)

flickr_api.upload(photo_file = "image-path", title = "My title")
Beispiel #43
0
import flickr_api;

flickr_api.set_keys(api_key = 'INSERT_API_KEY_HERE' , api_secret = 'INSERT_API_SECRET_HERE' );

auth = flickr_api.auth.AuthHandler();

auth.set_verifier("INSERT_VERIFIER_CODE_HERE");

flickr_api.set_auth_handler(auth);

start = 1;

uploaded = 0;

for line in open('newfilelist'):
  line = line.strip("\n");
  t = line.split("/")[-1].split(".")[0];
  uploaded = uploaded + 1;

  if uploaded >= start:
    print "[" + uploaded + "] Uploading file .. " + line;
    try:
      flickr_api.upload(photo_file = line, title = t);
    except:
      print "[Error] " + uploaded + " lines processed so far. Error while uploading " + line + " in input file.\n";

    
     
Beispiel #44
0
def upload():
    file = input("Enter Image Path : ")
    title = input("Enter Image Title : ")
    return flickr.upload(photo_file=file, title=title)
Beispiel #45
0
	interval = DEFAULT_INTERVAL

camera = picamera.PiCamera()
camera.resolution = (2592, 1944)
img_idx = 0

try:
    GPIO.add_event_detect(PIR_PIN, GPIO.RISING, callback=motion_cbk)
    while True:
        n = d.now()
        if motion_detected:
            try:
                camera.led = True
                fname = n.strftime('%Y%m%d%H%M') + '.jpg'
                camera.capture(fname)
                photo = flickr_api.upload(photo_file=fname)
                p.addPhoto(photo_id = photo.id)
                os.remove(fname)
                camera.led = False
                motion_detected = False
            except:
                print("Encountered an exception")
                e = sys.exc_info()[0]
                logging.error(e)
                camera.led = False

            time.sleep(interval*60)

except KeyboardInterrupt:
    print("Quitting...")
    GPIO.cleanup()
Beispiel #46
0
        while i < len(data):
            Title = data[i]['title']
            filepath = data[i]['filepath']
            #file = filepath.replace('S:\Collection Imaging\Hub photos clearance needed by Zoe\Human History', '')
            Titletag = Title.replace(' ', '-')
            Titletag = Titletag.replace(',', '')
            print Titletag
            print file
            Tags = data[i]['tags']
            #Tags = str("Natural-Science") +str(" ") + str("CC-BY") +str(" ") + Titletag
            Description = data[i]['Description']

            #use for API
            filehandler = urllib.urlopen(filepath)
            flickr_api.upload(photo_file=filepath,
                              photo_file_data=filehandler,
                              title=Title,
                              tags=Tags,
                              description=Description,
                              is_public="0")

            #use for local filepaths
            # flickr_api.upload(photo_file = filepath, title = Title, tags = Tags, description = Description, is_public="0")
            i = i + 1
            time.sleep(30)
    except flickr_api.FlickrError as ex:
        print("Error code:")
        print filepath
        print ex
        i = i + 1