예제 #1
0
    def test_short_url(self):
        '''Test photo ID to short URL conversion.'''

        self.assertEqual(shorturl.url(u'4325695128'),
                         u'https://flic.kr/p/7Afjsu')
        self.assertEqual(shorturl.url(u'2811466321'),
                         u'https://flic.kr/p/5hruZg')
예제 #2
0
    def test_short_url(self):
        '''Test photo ID to short URL conversion.'''

        self.assertEqual(shorturl.url('4325695128'),
                'http://flic.kr/p/7Afjsu')
        self.assertEqual(shorturl.url('2811466321'),
                'http://flic.kr/p/5hruZg')
예제 #3
0
def flickr():
    flickr = flickrapi.FlickrAPI(FLICKR_KEY, FLICKR_SECRET, format='etree')

    photos = flickr.photos_search(per_page=100,
                                  page=random_page,
                                  user_id=USER_ID,
                                  tag_mode='any',
                                  extras='url_c,description',
                                  sort='relevance')

    soup = BeautifulSoup(ET.tostring(photos, encoding='utf8', method='xml'),
                         "html.parser")
    possibilities = soup.find_all('photo')

    for p in possibilities:
        tag = p.has_attr('url_c')
        description = p.findNext('description').contents[0]
        length = len(description)
        if tag and length < 116:  #minus away a spacing and 23 character for short url
            photo_list.append(p)

    #print photo_list
    p_shuffle = shuffle(photo_list)
    p_choice = choice(photo_list)

    p_url = p_choice['url_c']
    p_id = p_choice['id']
    p_owner = p_choice['owner']
    p_description = p_choice.findNext('description').contents[0]
    p_weburl = "https://www.flickr.com/photos/" + p_owner + "/" + p_id
    p_shorturl = shorturl.url(p_id)
    print p_shorturl
    urllib.urlretrieve(p_url, "image.jpg")
    text = p_description + " " + p_shorturl
    return text
 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)
예제 #5
0
def post_to_flickr(file,title):
    try :
        flickr = flickrapi.FlickrAPI(flickr_consumer_key, flickr_consumer_secret)
    except :
        raise 'Error in app consumer key'
        return 0
    token = globals.flickr_token 
    if token is None :
        try : 
            (token, frob) = flickr.get_token_part_one(perms='write')
        except :
            raise 'Error in authenticating user'
            return 0

    #UI comes into picture here
    # Change this to some OK button or so..
    if not token: raw_input("Press ENTER after you authorized this program")
    try :
        flickr.get_token_part_two((token, frob))
        globals.flickr_token = token
    except :
        raise 'Error in authorizing'
        return 0
    
    try :
        resp = flickr.upload(filename=file, callback=func, title=title)
        photoid = resp.find('photoid').text
        photourl = shorturl.url(photoid)
        return photourl
    except :
        raise 'Error uploading'
        return 0

#post_to_flickr('/home/pali/Downloads/flickr-yahoo-logo.png.jpg', 'flickr')
예제 #6
0
def upload(path):

    API_KEY = pbserver.config.get('flickr', 'api_key')
    API_SECRET = pbserver.config.get('flickr', 'api_secret')
    TOKEN = pbserver.config.get('flickr', 'auth_token')
    
    if not TOKEN:
        raise ValueError('invalid or missing token')
    
    flickr = flickrapi.FlickrAPI(API_KEY, API_SECRET, token=TOKEN)

    params = {
        'filename': path,
        'title': '%s' % datetime.datetime.now(),
        'is_public': pbserver.config.get('flickr', 'is_public'),
        'format': 'etree',
    }
    
    tags = pbserver.config.get('flickr', 'tags')
    if tags:
        params['tags'] = tags

    resp = flickr.upload(**params)
    photo_id = resp.find('photoid').text

    photoset_id = pbserver.config.get('flickr', 'photoset')
    if photoset_id:
        flickr.photosets_addPhoto(photoset_id=photoset_id, photo_id=photo_id)

    return shorturl.url(photo_id)
예제 #7
0
def currentFlickrURL(kind, format = ""):
  '''Return a URL for the Flickr image currently showing in the browser.
  
  The string parameter "kind" can be either "Short" or one of the standard
  Flickr image sizes: "Original", "Large", "Medium 640", "Medium", "Small",
  "Thumbnail", or "Square". If it's Short, the function will return a
  flic.kr URL for the image page. If it's one of the others, the function
  will return the URL of the image of that size, if available.
  
  The function works through Apple Events and supports only the Safari and
  Chrome browsers.'''
  
  # Flickr parameters
  fuser = '******'
  key = 'Get key from Flickr'
  secret = 'Get secret from Flickr'
  
  # Make sure we're asking for a legitimate kind.
  kind = kind.capitalize()
  kinds = ["Short", "Original", "Large", "Medium 640",
           "Medium", "Small", "Thumbnail", "Square"]
  if kind not in kinds:
    return "Not a legitimate kind of URL"

  # Get the image ID.
  try:
    imageID = currentFlickrID()
  except IndexError:
    return "Not a Flickr image"
  
  # Establish the connection with Flickr.
  flickr = FlickrAPI(api_key=key, secret=secret)

  # Get the URL.
  if kind == "Short":
    return shorturl.url(photo_id = imageID)
  else:
    esizes = flickr.photos_getSizes(photo_id = imageID, format = 'etree')
    if format == '':
      for i in esizes[0]:
        if i.attrib['label'] == kind:
          return i.attrib['source']
          break
      # If the size wasn't found.
      return "Size not found"

    elif format == 'md':
      einfo = flickr.photos_getInfo(photo_id = imageID, format = 'etree')
      photourl = einfo.find('photo/urls/url').text
      phototitle = einfo.find('photo/title').text
      if not phototitle:
        phototitle = "Untitled"
      for i in esizes[0]:
        if i.attrib['label'] == kind:
          jpgurl = i.attrib['source']
          return "[![" + phototitle + "](" + jpgurl + ")](" + photourl + ")"
          break
      # If the size wasn't found.
      return "Size not found"
예제 #8
0
def main():
    favs = flickr.walk(tags="kittens", extras="geo")
    for photo in favs:
        if photo.get('latitude') != '0':
            print photo.get('title')
            title = photo.get('title')
            print photo.get('latitude')
            latitude = float(photo.get('latitude'))
            print photo.get('longitude')
            longitude = float(photo.get('longitude'))
            print photo.get('id')
            identity = photo.get('id')
            print shorturl.url(photo.get('id'))
            url = shorturl.url(photo.get('id'))
            submit_to_scraperwiki(identity, title, latitude, longitude, url)

    scraperwiki.status('ok', "OK")
예제 #9
0
def create_message(entity):
    """Takes Photo entity and returns message string."""
    title = entity.get("title")
    photographer = entity.get("ownername")
    shortlink = shorturl.url(entity.get("id"))
    message = f"{title} by {photographer} {shortlink} #birbybot"
    logger.debug(message)
    return message
예제 #10
0
def currentFlickrURL(kind):
    '''Return a URL for the Flickr image currently showing in the browser.

  The string parameter "kind" can be either "Short" or one of the
  standard Flickr image sizes: "Original", "Large", "Medium 800",
  "Medium 640", "Medium", "Small 320", "Small", "Thumbnail", "Large
  Square", or "Square". If it's Short, the function will return a
  flic.kr URL for the image page. If it's one of the others, the
  function will return the URL of the image of that size, if
  available.

  The function works through Apple Events and supports only the Safari
  browser.'''

    # Flickr parameters
    fuser = '******'
    key = 'Get key from Flickr'
    secret = 'Get secret from Flickr'

    # Make sure we're asking for a legitimate kind.
    kind = ' '.join([x.capitalize() for x in kind.split()])
    kinds = [
        "Short", "Original", "Large", "Medium 800", "Medium 640", "Medium",
        "Small 320", "Small", "Thumbnail", "Large Square", "Square"
    ]
    if kind not in kinds:
        return "Not a legitimate kind of URL"

    # Get the image ID.
    try:
        imageID = currentFlickrID()
    except IndexError:
        return "Not a Flickr image"

    # Establish the connection with Flickr.
    flickr = FlickrAPI(api_key=key, secret=secret)

    # Get the URL.
    if kind == "Short":
        return shorturl.url(photo_id=imageID)
    else:
        etree = flickr.photos_getSizes(photo_id=imageID, format='etree')
        for i in etree[0]:
            if i.attrib['label'] == kind:
                return i.attrib['source']
                break

        # If the size wasn't found.
        return "Size not found"
예제 #11
0
def currentFlickrURL(kind):
  '''Return a URL for the Flickr image currently showing in the browser.

  The string parameter "kind" can be either "Short" or one of the
  standard Flickr image sizes: "Original", "Large", "Medium 800",
  "Medium 640", "Medium", "Small 320", "Small", "Thumbnail", "Large
  Square", or "Square". If it's Short, the function will return a
  flic.kr URL for the image page. If it's one of the others, the
  function will return the URL of the image of that size, if
  available.

  The function works through Apple Events and supports only the Safari
  browser.'''


  # Flickr parameters
  fuser = '******'
  key = 'Get key from Flickr'
  secret = 'Get secret from Flickr'

  # Make sure we're asking for a legitimate kind.
  kind = ' '.join([x.capitalize() for x in kind.split()])
  kinds = ["Short", "Original", "Large", "Medium 800", "Medium 640",
           "Medium", "Small 320", "Small",  "Thumbnail",
           "Large Square", "Square"]
  if kind not in kinds:
    return "Not a legitimate kind of URL"

  # Get the image ID.
  try:
    imageID = currentFlickrID()
  except IndexError:
    return "Not a Flickr image"

  # Establish the connection with Flickr.
  flickr = FlickrAPI(api_key=key, secret=secret)

  # Get the URL.
  if kind == "Short":
    return shorturl.url(photo_id = imageID)
  else:
    etree = flickr.photos_getSizes(photo_id = imageID, format = 'etree')
    for i in etree[0]:
      if i.attrib['label'] == kind:
        return i.attrib['source']
        break

    # If the size wasn't found.
    return "Size not found"
예제 #12
0
def search_flickr(searchvalue):
    favs = flickr.walk(tags=searchvalue, extras="geo")
    rows = []
    for i, photo in enumerate(favs):
        if photo.get('latitude') != '0':
            row = OrderedDict()
            row['id'] = photo.get('id')
            row['title'] = photo.get('title')
            row['latitude'] = float(photo.get('latitude'))
            row['longitude'] = float(photo.get('longitude'))
            row['url'] = shorturl.url(photo.get('id'))
            rows.append(row)
        if i < 10000:
            break
    submit_to_scraperwiki(rows, searchvalue)
예제 #13
0
  def get(self, page=0):
    from flickrapi import shorturl
    import urllib2
    api_key = '37de50729a2c36edc9ab0e607128cc30'
    secret = '03ee8a50859eb21b'
    uid = '65817552@N07'
    per_page = 10
    
    flickr = flickrapi.FlickrAPI(api_key, format='json')
    photos = eval(flickr.photos_search(user_id=uid, per_page='10', page=page).replace('jsonFlickrApi(', '')[:-1])

    for p in photos['photos']['photo']:
      p['title'] = p['title'].decode('raw_unicode_escape')
      p['shorturl'] = shorturl.url(p['id'])

    self.render("kiss.html", 
      kiss=photos,
      isMobile=self.isMobile(), 
    )
예제 #14
0
파일: bats.py 프로젝트: rayramsay/birbybot
def tweet_photo_entity(entity):
    name = entity.key.name
    logger.info(f"Tweeting {name}...")
    logger.debug(entity)

    # Write a message.
    title = entity.get("title")
    photographer = entity.get("ownername")
    shortlink = shorturl.url(entity.get("id"))
    message = f"{title} by {photographer} {shortlink} #HappyHalloween"
    logger.debug(message)

    # Download image if we somehow don't already have it.
    filepath = os.path.join(os.path.dirname(__file__), f'assets/{name}.jpg')
    if not pathlib.Path(filepath).exists():
        filepath = download_image(url=entity.get("download_url"),
                                  name=name)

    # Load image and tweet.
    try:
        with io.open(filepath, 'rb') as img:
            upload_resp = twitter.upload_media(media=img)
            logger.debug(upload_resp)
        tweet_resp = twitter.update_status(status=message,
                                           media_ids=[upload_resp["media_id"]])
        logger.debug(tweet_resp)
    except Exception as e:
        logger.exception(e)
        sys.exit()

    # Finally, let's remember when we tweeted.
    try:
        entity.update({
            "last_tweeted": parser.parse(tweet_resp.get("created_at"))
        })
        ds_client.put(entity)
    except Exception as e:
        logger.exception(e)
예제 #15
0
파일: lclclr.py 프로젝트: lumilux/lclclr
def getColors(urldict, url_type=None):
    means = {}
    n = len(urldict)
    if n == 0:
        return None, None
    r_tot, g_tot, b_tot = 0, 0, 0
    for id in urldict.keys():
        #means[id] = getImageMeans(urldict[id][0])
        means[id] = getDominantColor(urldict[id][0])
        r_tot += int(means[id][0])
        g_tot += int(means[id][1])
        b_tot += int(means[id][2])
        if url_type == 'fl':
            url = shorturl.url(id)
        elif url_type == 'hp':
            url = 'http://hyperpublic.com/places/'+id
        elif url_type == 'tw':
            url = 'http://twitpic.com/'+id
        else:
            url = urldict[id][0]
        means[id].append(url)
        means[id].append([urldict[id][1], urldict[id][2]])
    mean_color = int(r_tot/n), int(g_tot/n), int(b_tot/n)
    return means, mean_color
예제 #16
0
 def get_photo_url(self, slug):
     return url(slug)
    def test_short_url(self):
        """Test photo ID to short URL conversion."""

        self.assertEqual(shorturl.url(u"4325695128"), u"http://flic.kr/p/7Afjsu")
        self.assertEqual(shorturl.url(u"2811466321"), u"http://flic.kr/p/5hruZg")
예제 #18
0
def currentFlickrURL(kind, linkformat = ""):
  '''Return a URL for the Flickr image currently showing in the browser.

  The string parameter "kind" can be either "Short" or one of the
  standard Flickr image sizes: "Original", "Large", "Medium 800",
  "Medium 640", "Medium", "Small 320", "Small", "Thumbnail", "Large
  Square", or "Square". If it's Short, the function will return a
  flic.kr URL for the image page. If it's one of the others, the
  function will return the URL of the image of that size, if
  available.
  
  The "linkformat" parameter can be omitted, or can be supplied as
  either "md" or "html" as long as "kind" is not "Short".
  Pass "md" to create a Markdown image reference where the image is linked
  back to its Flickr page, or provide "html" to create an HTML
  img tag surrounded by an a tag linking to the image's Flickr page.

  The function works through Apple Events and supports only the Safari
  browser.'''


  # Flickr parameters
  fuser = '******'
  key = 'Get key from Flickr'
  secret = 'Get secret from Flickr'

  # Make sure we're asking for a legitimate kind.
  kind = ' '.join([x.capitalize() for x in kind.split()])
  kinds = ["Short", "Original", "Large", "Medium 800", "Medium 640",
           "Medium", "Small 320", "Small",  "Thumbnail",
           "Large Square", "Square"]
  if kind not in kinds:
    return "Not a legitimate kind of URL"

  # Get the image ID.
  try:
    imageID = currentFlickrID()
  except IndexError:
    return "Not a Flickr image"

  # Establish the connection with Flickr.
  flickr = FlickrAPI(api_key=key, secret=secret)

  # Get the URL.
  if kind == "Short":
    return shorturl.url(photo_id = imageID)
  else:
    etree = flickr.photos_getSizes(photo_id = imageID, format = 'etree')
    if linkformat == '':
      for i in etree[0]:
        if i.attrib['label'] == kind:
          return i.attrib['source']
          break

      # If the size wasn't found.
      return "Size not found"

    elif linkformat == 'md':
      einfo = flickr.photos_getInfo(photo_id = imageID, format = 'etree')
      photourl = einfo.find('photo/urls/url').text
      phototitle = einfo.find('photo/title').text
      if not phototitle:
        phototitle = "Untitled"
      for i in etree[0]:
        if i.attrib['label'] == kind:
          jpgurl = i.attrib['source']
          return "[![" + phototitle + "](" + jpgurl + ")](" + photourl + ")"
          break
      # If the size wasn't found.
      return "Size not found"

    elif linkformat == 'html':
      einfo = flickr.photos_getInfo(photo_id = imageID, format = 'etree')
      photourl = einfo.find('photo/urls/url').text
      phototitle = einfo.find('photo/title').text
      if not phototitle:
        phototitle = "Untitled"
      for i in etree[0]:
        if i.attrib['label'] == kind:
          jpgurl = i.attrib['source']
          photowidth = i.attrib['width']
          photoheight = i.attrib['height']          
          return "<a href='" + photourl + "' title='" + phototitle + "'><img src='" + jpgurl + "' width='" + photowidth + "' height='" + photoheight + "'></a>"
          break
      # If the size wasn't found.
      return "Size not found"
     
    else:
      return "Invalid link format requested"