Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-10 of 10 total  RSS 

Python Flickr Backup Script (Untested)


# flickrbackup.py - Matt Croydon - http://postneo.com
import flickr # http://jamesclarke.info/projects/flickr/
import BitBucket # http://www.other10percent.com/?p=15
import urllib
me = flickr.people_findByUsername("postneo")
bucket = BitBucket.BitBucket("postneo-flickr")
page = 1
total_photos = found_photos = 0
while 1:
    try:
        photos = flickr.people_getPublicPhotos(me.id, 100, page)
        for photo in photos:
            total_photos = total_photos + 1
            if bucket.has_key("%s-%s" % (photo.title, photo.id)):
                pass # we already have this photo
            else:
                data = urllib.urlretrieve("http://static.flickr.com/%s/%s_%s_o.jpg" % (photo.server, photo.id, photo.secret), "flickr.jpg")
                bits = BitBucket.Bits(filename="flickr.jpg")
                bucket["%s-%s" % (photo.title, photo.id)] = bits
                print "saving %s" % photo.title
                found_photos = found_photos + 1
        page = page + 1
    except AttributeError:
        break # We probably got an empty bucket
print "Found %s photos, saved %s new photos" % (total_photos, found_photos)

flickr to desktop background

// description of your code here

#!/usr/bin/env ruby

########################################
# config
########################################

groups = ['trees']
flick_api_key = 'cc0880a9d309466758fecb6557d7040b'

# proxy just comment out to disable, types: http, sspi
#http_proxy = {:host=> 'name', :port => 80, :type => :sspi}


# temp files for imagemagick
p1 = 'c:/tmp/img.jpg'
p2 = 'c:\\tmp\\img.bmp'

# Imagemagick path
# http://www.imagemagick.org/script/binary-releases.php#windows
# Recommended package: ImageMagick-6.3.5-6-Q8-windows-static.exe
# convert.exe is needed only, so Imagemagick can be uninstalled.
imagick_path = 'convert.exe'

# images with larger/smaller width will be skipped
skip_small = 1000
skip_big = 2100

########################################
# code
########################################

require 'Win32API'
require 'net/http'
require 'win32/sspi'
require 'json'
require 'yaml'
require "win32/open3"
require "win32/process"

def parse_url(url)
  m = /(?:.*?\/\/)(.*?)(\/.*)/.match(url)
  [ m[1] , m[2] ]
end

class NetWrap
  def initialize(p_type = nil, p_host = nil, p_port = nil)
    if !p_type
      @conn = Net::HTTP
    else
      @conn = Net::HTTP.Proxy(p_host, p_port)
    end
    @p_type = p_type
  end
  
  def download(url)
    site, path = parse_url(url)
    data = ''
    @conn.start(site) do |http|
      if @p_type && @p_type == :sspi
        resp, data = Win32::SSPI::NegotiateAuth.proxy_auth_get(http, path)
      else
        resp, data = http.get(path)
      end
    end
    return data
  end
end

class FlickR
  def initialize(apikey, netw)
    @apikey = apikey
    @netw = netw
  end
  
  def request(api_meth,params = {})
    url = "http://api.flickr.com/services/rest/?method=#{api_meth}&api_key=#{@apikey}&format=json"
    params.each {|key,val| url << "&#{key}=#{val}"}
    res = @netw.download(url)
    JSON.parse(res['jsonFlickrApi('.size..-(');'.size)])
  end
  
  def group_photos(id)
    request('flickr.groups.pools.getPhotos', :group_id => id)['photos']['photo']
  end
  
  def group_lookup(name)
    request('flickr.urls.lookupGroup', :url => "http://flickr.com/groups/#{name}/pool/")['group']['id']
  end

  def photo_urls(id)
    request('flickr.photos.getSizes', :photo_id => id)['sizes']['size']
  end
  
  def photo_best(id, width)
    sizes = photo_urls(id).sort {|a,b| a['width'].to_i <=> b['width'].to_i}
    return sizes.find {|x| x['width'].to_i > width} || sizes.last()
  end
end

class ImgList
  def initialize(cfgname)
    @cfg = cfgname
    @saw = {}
    begin
      if f = open(@cfg,'r')
        @saw = YAML.load(f)
        f.close()
        cnt = 0
        @saw.each {|key,val| cnt += 1 if val[1]}
      end
    rescue
    end
  end
  
  def save()
    if f = open(@cfg,'w+')
      f.write(@saw.to_yaml)
      f.close()
    end
  end
  
  def next()
    img = @saw.detect {|x| !x[1]}
    return img[0] if img
    img
  end
  
  def add(url)
    if !@saw.has_key?(url)
      @saw[url] = false
    end
  end
  
  def mark(url)
    @saw[url] = true
  end
  
  def reset()
    @saw.each {|key,val| @saw[key] = false}
  end
end

if defined?(http_proxy)
  netw = NetWrap.new(http_proxy[:type], http_proxy[:host], http_proxy[:port])
else
  netw = NetWrap.new()
end

scr_w = Win32API.new("user32", "GetSystemMetrics", ['I'] , 'I').call(0)

il = ImgList.new('wpcache.yaml')

photo_url = il.next()

if !photo_url
  fr = FlickR.new(flick_api_key, netw)
  groups.each do |group|
    fr.group_photos(fr.group_lookup(group)).each do |x|
      next if !x['ispublic']
      photo = fr.photo_best(x['id'],scr_w)
      next if skip_small && photo['width'].to_i < skip_small
      next if skip_big && photo['width'].to_i > skip_big
      url = photo['source']
      il.add(url)
    end
  end  
  photo_url = il.next()
end

if !photo_url
  il.reset()
  photo_url = il.next()
end

il.mark(photo_url)
il.save()

open(p1,'wb+') { |f|  f.write(netw.download(photo_url)) }

cmdline = "#{imagick_path} -resize #{scr_w} #{p1} bmp3:#{p2}"
Process::waitpid2(Open4::popen4(cmdline)[3])

Win32API.new("user32", "SystemParametersInfo", ['L','L','P','L'] , 'L').Call(20,0,p2,3)

Quick Flickr search in Ruby

// Examples for the three listed APIs weren't working. Instead of choosing one and debugging it, I chose to do something quick and dirty. "MY_API_KEY" and other params would need to be removed to make this more generic. A naive mapping of API method calls that take hashes, and returns an OpenStruct is an approach I'm considering, as it would likely break less often and require less code.

require 'net/http'
require 'rexml/document'
require 'ostruct'

class Flickr < OpenStruct
  include REXML

  def Flickr.search(text)
    doc = Document.new(
            Net::HTTP.get(
              URI.parse('http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=MY_API_KEY' +
                        '&extras=license,owner_name,original_format&license=4,5&per_page=20&sort=interestingness-desc' +
                        '&text=' + text)))
     throw "flickr error" unless doc.root.attributes['stat'] == "ok"
     doc.root.elements['photos'].get_elements('//photo').collect {|photo| photo << Flickr.new(photo) }
  end

  def initialize(e)
    super(e.attributes)
    self.new_ostruct_member("photo_id")
    self.photo_id = e.attributes['id']
  end

  def to_url(image_type="s")
    "http://farm#{farm}.static.flickr.com/#{server}/#{photo_id}_#{secret}_#{image_type}.jpg"
  end
end

Build Logo using Flickr alphabet pictures in newLISP

// it uses my FLICKR context for newLISP
// demo available at http://terpri.com
(define (alphabet-flickr myletter, alph y myurl)
    (setq alph (xml-digest (FLICKR "flickr.groups.pools.getPhotos" nil
                  (append "group_id=27034531@N00&tags=" myletter))))
    (setq alph (clean nil? (map (lambda(x) (if (= myletter ((x (chop(ref 'title x))) 1)) x)) (\
2 -1 (alph 0 2)))))
    (setq y (first (randomize (sequence 0 (length alph)))))
    (setq y (alph y 1))
    (setq myurl (format "http://static.flickr.com/%s/%s_%s_s.jpg"
                       (lookup 'server y)(lookup 'id y)(lookup 'secret y)))
    (println "<img src=" myurl " border=0>"))

    (if (= page-name "Home")
      (begin
            (println {<div class="flickr_banner">})
            (map (lambda (x) (alphabet-flickr x)) '("T" "E" "R" "P" "R" "I"))
            (println "</div>")))

PHP Flickr! personal photo album

This code uses your Flickr! account and creates the URLs to the pictures for display on your own personal website! The full documentation is available at http://www.strydominc.za.net/index.php?p=projectdetail&d=phpflickrphoto

<?php
/**********************************************************************************************
www.strydominc.za.net
Created by Jurgen Strydom, 19-08-2006, jurgen.strydom@gmail.com
Read the readme.txt
Version 1.01, 19-08-2006
**********************************************************************************************/
?>
<link href="pagefloat.css" rel="stylesheet" type="text/css">
<?php
//Stuff you should update for your script
$api_key = "6cacc91553b802874c6bbad658c9ce94"; // get yours at http://flickr.com/services/api/key.gne
$my_id = "46772344@N00"; // use idgetr: http://idgettr.com/ to find yours if you already changed it to a name
$rows = 10;
//Let the code do the walking from here on
$photos = ($rows * 2);
if (empty($_REQUEST['n'])) {
$pagenum = 1;
} else {
$pagenum = $_REQUEST['n'];
}
//http://static.flickr.com/{server-id}/{id}_{secret}_[mstb].jpg //how the url is created for the images
$xml = simplexml_load_file("http://flickr.com/services/rest/?method=flickr.people.getPublicPhotos&user_id=$my_id&api_key=$api_key&per_page=$photos&page=$pagenum");
$total = $xml->photos['total'];
$pages = $total % $photos;
$pages = ($total + $photos - $pages) / $photos;

?><table width="700" border="0" cellpadding="0" cellspacing="0">
<tr><td height="10" colspan="2" valign="top" align="left">Please select a page: <?php
for ($k = 1; $k<=$pages; $k++) { ?>
<table width="25" border="0" cellpadding="0" cellspacing="0" align="center" class="pagefloat"> <?php
?>
  <tr>
    <td width="25" height="10" valign="top" align="center"><a href="photos.php?n=<?php echo $k?>">
	<?php if ($k == $pagenum) {
		 	echo "<u><b>", $k, "</b></u>";
		 } else {
		 	echo "<b>", $k, "</b>";
		 } ?></a></td>
  </tr>
</table>
<?php } 
?>
</td></tr>
<tr>
    <td height="10" colspan="2" valign="top" align="left">&nbsp;</td>
</tr>
<?php

if (($pagenum * $photos) > $total) {
	$to = $total % $photos;
} else { $to = $photos; }
for ($k = 0; $k<$to; $k++) {
if (($k % 2) == 0) {
?>
<tr>
<td width="350" height="100" valign="top" align="center">
<?php } else {?>
<td width="350" valign="top" align="center">
<?php }
echo "<b>" , $xml->photos->photo[$k]['title'], "</b>";
?>
<br>
<a href="http://www.flickr.com/photos/jurgenstrydom/<?php echo $xml->photos->photo[$k]['id'];?>"><img src="<?php 
echo "http://static.flickr.com/";
echo $xml->photos->photo[$k]['server'];
echo "/";
echo $xml->photos->photo[$k]['id'];
echo "_";
echo $xml->photos->photo[$k]['secret'];
echo "_m.jpg"; 
?>"
alt="<?php echo $xml->photos->photo[$k]['title'] ?>" border="0"></a>
</td>
<?php
if (($k % 2) == 1) {
?> </tr>  <tr>
    <td height="10" colspan="2" valign="top" align="left">&nbsp;</td>
  </tr>  
  <?php
}
}
?>
</table>
<?php
/**********************************************************************************************
Changelog:

Version 1.01
Fixed a bug that caused code below this script to output incorrect display.

Version 1
First release.
**********************************************************************************************/
?>

newLISP code to fetch flickr interesting photos and display on screen via TK

// simple newLISP code to fetch interesting pictures from
// flickr and display on the monitor using TK

(set 'api "/services/rest")
(set 'apikey "YOUR-OWN-KEY-HERE")
(set 'host "http://flickr.com")
(set 'email "")
(set 'password "")

(define (doget method auth params)
  (setq url (append host api "/?api_key=" apikey "&method=" method))
  (if (list? params) 
   (setq url (append url "&" (urlencode params))))
  (if (not (nil? auth)) 
   (setq url (append url "&email=" email "&password=" password)))
  (setq xmldata (get-url url)))


(define (urlencode params)
  (setq urlstring "")
  (dolist (param1 params) 
   (if (not (= urlstring "")) 
    (setq urlstring (append urlstring "&"))) 
   (setq urlstring (append urlstring (nth 0 param1) "=" (nth 1 param1)))))

(define (xmlconvert data)
  (xml-type-tags nil nil nil nil)
  (setq sxmldata (xml-parse data (+ 1 2 4 8 16))))
  
(define (getphotos data)
  (if (ref 'photo sxmldata) 
   (setq photolist (slice (data (chop (ref 'photo data) 2)) 2 -1)) 
   (setq photolist '())))

(define (handlephotos sxmldata)
  (dolist (aphoto (getphotos sxmldata)) 
   (setq pr (first (rest aphoto))) 
   (print (format "http://static.flickr.com/%s/%s_%s_o.jpg" (lookup 
      'server pr) 
     (lookup 'id pr) 
     (lookup 'secret pr)))))

(define (fiv)
  (tk "package require Img")
  (tk "destroy .fivwin")
  (tk "toplevel  .fivwin")
  
  (tk "wm geometry .fivwin [winfo screenwidth .]x[winfo screenheight .]+0+0")
  
  ;; uncomment the following lines to make display "fullscreen"
  ;;(tk "bind .fivwin <Key> {destroy .fivwin}")
  ;;(tk "bind .fivwin <Motion> {destroy .fivwin}")
  ;;(tk "bind .fivwin <Button> {destroy .fivwin}")
  ;;(tk "wm overrideredirect .fivwin yes; focus -force .fivwin")

  (setq picture (tk "image create photo "))
  (tk (append "label .fivwin.picture  -image " picture))
  (tk "pack .fivwin.picture")

  (setq xmldata
            (doget "flickr.interestingness.getList" nil  
             '(("per_page" "100")("page" "1"))))		;; how many per page , from which page
  (setq sxmldata (xmlconvert xmldata))
  
  (if (ref 'photo sxmldata) 
   (setq photolist (slice (sxmldata (chop (ref 'photo sxmldata) 2)) 2 -1)) 
   (exit))
   
  (dolist (aphoto photolist)
  	(if (= "0" (tk "winfo exists .fivwin"))
  		(exit))
    (setq photodesc (first (rest aphoto)))
    (setq photourl (format "http://static.flickr.com/%s/%s_%s_o.jpg" 
                            (lookup 'server photodesc)
                            (lookup 'id photodesc)
                            (lookup 'secret photodesc)))
    (tk "update idletasks")

    (setq file (last (parse photourl "/")))
    (write-file file (get-url photourl))
    (tk (append picture " configure -file " file))
     (delete-file file)))
 

Download recent flickr pictures with ruby and the flickr api

// To make this work, you need to get your own flickr api key.
// Get one here: http://www.flickr.com/services/api/misc.api_keys.html
// Other than that, just plug and chug and have fun!
// The "b" in "wb" in the second open method may not be necessary in
// non-windows environments.

require 'open-uri'
require 'rexml/document'

open('http://www.flickr.com/services/rest/?method=flickr.photos.getRecent&api_key=YOUR_KEY_HERE') { |f|
    doc = REXML::Document.new f.read
    i = 0
    doc.elements.each("rsp/photos/photo") { |element|
        if i < 3
            open("images/file" << i.to_s << ".jpg", "wb").
                write(open("http://static.flickr.com/" << \
                element.attributes["server"] << "/" << \
                element.attributes["id"] << "_" << \
                element.attributes["secret"] << "_o.jpg").read)
        else
            break
        end
        i = i + 1
    }
}

puts "Done!"

Java - getHTMLpage

// Scarica dalla rete una pagina HTML

package HttpGetIMGs;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

/*
 * 
 * Fa una richiesta di connessione al web e scarica la pagina...
 */

public class RandomIMGs
{
	private BufferedReader br;
	private OutputStreamWriter osw;
	private String data;
	private String line;
	private URL url;
	private URLConnection conn;
		
	public RandomIMGs()
	{
		try
		{
			url = new URL("http://flickr.com/photos");
			conn = url.openConnection();
			conn.setDoOutput(true);
			
			osw = new OutputStreamWriter(conn.getOutputStream());
			
			data = URLEncoder.encode("start", "utf-8") + "=" + URLEncoder.encode("1", "utf-8");
			osw.write(data);
			osw.flush();
			
			br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			
			while((line = br.readLine()) != null)
			{
				System.out.println(line);
			}
			
			osw.close();
			br.close();
		}
		catch(MalformedURLException e)
		{
			e.printStackTrace();
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args)
	{
		new RandomIMGs();
	}
}

Python - randomFlickr

// Create a sample directory flickrIMGs

import os
import random
import re
import urllib
import urllib2

class flickrImages(object):
    
    RE_IMAGEURL = re.compile('src="(http://static.flickr.com/.+?_t.jpg)"', re.DOTALL | re.IGNORECASE)
    
    def __init__(self):
        
        self.imagesURLs = {}
    
    def getRandomImages(self):
        '''        
        Scarica dal sito FlickrImages delle immagini in maniera random...
        '''
        
        htmlPage = ''
        request = ''
                
        requestURL = 'http://flickr.com/photos?start=%d' % (random.randint(0, 5000))
        requestHeaders = {'User-Agent':'flickrImages/1.0'}
        
        try:
            request = urllib2.Request(requestURL, None, requestHeaders)
            htmlPage = urllib2.urlopen(request).read(500000)
        except:
            pass
        
        results = flickrImages.RE_IMAGEURL.findall(htmlPage)
        
        if len(results) > 0:
            for image in results:
                imageURL = urllib.unquote_plus(image)
                if not imageURL.startswith('http://'): imageURL = 'http://'+imageURL
                imageURL = imageURL.replace('_t.jpg', '_o.jpg') # Prende il formato piu' grande
                self.imagesURLs[imageURL] = 0
    
    def downloadImages(self):
        '''
        Scarica nella cartella googleIMGs le foto che vengono trovate in rete...
        '''
        
        numberIMGs = len(self.imagesURLs)
        posIMGs = 1
        
        for imageName in self.imagesURLs:
            print '[' + str(posIMGs) + '/' + str(numberIMGs) + '] - ' + imageName
            urllib.urlretrieve(imageName, 'flickrIMGs' + os.sep + os.path.split(imageName)[1])
            posIMGs += 1
    
if __name__ == '__main__':
    
    test = flickrImages()
    
    test.getRandomImages()
    test.downloadImages()
    
    print 'Finito...'

Random Flickr Photo

// description of your code here

<?php

    // Displays a single random photo from recent flickr photos with a given tag.
    // Original code stolen from many sources including http://www.thebishop.net/geodog/archives/2004/09/29/fun_hacking_with_flickr_making_a_homemade_flickr_tag_badge_with_magpierss.html and http://prwdot.org/archives/002468.html


    // USER CONFIGURATION SECTION

    // MagpieRSS Configuration
    // This is an example based on my system;
    // you will need to customize it for your system
    // and your preferences. You can remove it entirely
    // if you have done it elsewhere
    // refer to http://magpierss.sourceforge.net/
    require_once('/var/www/bradford/magpierss-0.61/rss_fetch.inc');
    error_reporting(E_ERROR);
    define(MAGPIE_CACHE_ON, true);
    define(MAGPIE_CACHE_DIR, '/var/www/bradford/magpie_cache');
    define(MAGPIE_CACHE_AGE, 300);
    define(MAGPIE_CACHE_FRESH_ONLY, false);
    define(MAGPIE_DETECT_ENCODING, true);
    define(MAGPIE_DEBUG, 0);
    define(MAGPIE_FETCH_TIME_OUT, 15);
    define(MAGPIE_USE_GZIP, true);    

    // flickr configuration
    // How many photos you want to display
    $num_photos = 2; // for some reason it doesn't like 1
    $tag = 'Bradford';
    // URL for the flickr feed you want to use
    $flickr_feed_url ='http://www.flickr.com/services/feeds/photos_public.gne?tags='.$tag.'&format=rss_200';
?>

<?php
    // Fetch the feed
    $flickr = fetch_rss( $flickr_feed_url );
    if ($flickr) {
        $flickr_title = $flickr->channel["title"];
        $flickr_link = $flickr->channel["link"];
?>

<!-- Display the title and link to the feed -->

<?php
    // Pick some random photos
        $random_photos = array_rand($flickr->items,$num_photos);
        foreach ( $random_photos as $random_photo ) {
            $description = explode("\n\n",$flickr->items[$random_photo]["description"]);
?>

    <!-- Display the given photo -->

	<?php echo ereg_replace('<img src=(.*) width=(.*)>', '<img src=\\1 width="150px"/>', $description[1]);
	  die();?> // ok we've got our first photo - lets exit

<?php
        }
      } else {
?>

<!-- Display an error message if things didn't work -->
<p>An error occurred in the MagpieRSS parser:</p>

<p><?php echo magpie_error(); ?></p>

<?php
    } 
?>

« Newer Snippets
Older Snippets »
Showing 1-10 of 10 total  RSS