Skip to content

Instantly share code, notes, and snippets.

@rtanglao
Created September 29, 2010 04:23
Show Gist options
  • Select an option

  • Save rtanglao/602287 to your computer and use it in GitHub Desktop.

Select an option

Save rtanglao/602287 to your computer and use it in GitHub Desktop.
get average colour of flickr photos from serialized JSON
#!/usr/bin/env ruby
require 'net/http'
require 'uri'
require 'xmlsimple'
require 'pp'
require 'json'
#pp data["variable"][6]["statistic"][0]["rgb"] # or "hex" or "value"
ARGF.each_line do |line|
serializedJSON = line
flickr_data_page = JSON.parse(serializedJSON)
total = flickr_data_page["photos"]["total"].to_i
page = flickr_data_page["photos"]["page"].to_i
total_pages = flickr_data_page["photos"]["pages"].to_i
if page == total_pages
limit = total % 250
else
limit = 250
end
0.upto limit-1 do |photo_index|
if flickr_data_page["photos"]["photo"][photo_index].has_key?("url_m")
mkavgcolour_url = "http://mkweb.bcgsc.ca/color_summarizer/?xml=1&url=" +
flickr_data_page["photos"]["photo"][photo_index]["url_m"] +
"&precision=medium"
mkavgcolour_params = "?xml=1&url=" +
flickr_data_page["photos"]["photo"][photo_index]["url_m"] +
"&precision=medium"
begin
url = URI.parse(mkavgcolour_url)
$stderr.printf("url:%s host:%s port:%d path:%s\n",mkavgcolour_url, url.host, url.port,url.path)
$stderr.printf("concatenated url:%s\n", url.path+mkavgcolour_params)
http = Net::HTTP.new(url.host, url.port)
http.read_timeout = 160 # seconds
http.open_timeout = 160
resp = http.start() {|http|
http.get(url.path+mkavgcolour_params)
}
if resp.code == "200"
xml_data = resp.body
flickr_data_page["photos"]["photo"][photo_index]["avg_colour_m"] = XmlSimple.xml_in(xml_data)
$stderr.printf "page:%d photo:%d ", page, photo_index
PP::pp(flickr_data_page["photos"]["photo"][photo_index]["avg_colour_m"],$stderr)
else
$stderr.printf("HTTP GET failed on:%s HTTP response code:%d\n", url.path+mkavgcolour_params,resp.code)
end
rescue => e
PP::pp(e,$stderr)
rescue Timeout::Error => e
PP::pp(e,$stderr)
end
end
end
print JSON.generate(flickr_data_page), "\n"
end
@rtanglao
Copy link
Author

reads serialized JSON flickr meta data from stdin
and then calls Martin K's web service on each "url_m" photo which calculates the average colour
and then adds the average colour info to the JSON and serializes it to stdout

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment