class FlickrCollage::Flickr
Class for Flickr
. Get and download top-rated images for keywords
Constants
- API_KEY
- SEARCH_COUNT
- SEARCH_KEYWORD
- SHARED_SECRET
Attributes
@return [String] Path for saving images
Public Class Methods
# File lib/FlickrCollage.rb, line 48 def initialize(opts = {}) opts[:api_key] ||= API_KEY opts[:shared_secret] ||= SHARED_SECRET opts[:img_path] ||= IMG_PATH FlickRaw.api_key = opts[:api_key] FlickRaw.shared_secret = opts[:shared_secret] @img_path = opts[:img_path] end
Public Instance Methods
Download images from urls
@param [Array<Hash>] opts @option opts [String] :keyword keyword for file name @option opts [String] :url image url
@return [Array<String>] files paths for downloaded images @return [String] file path for downloaded image
# File lib/FlickrCollage.rb, line 95 def download(opts = {}) opts ||= [] photos = [] return photos unless opts.any? opts = [keyword: opts[:keyword], url: opts[:url]] unless opts.is_a?(Array) FileUtils.mkdir_p("#{@img_path}tmp") begin opts.each do |img| debug "flickr.download: #{img[:keyword]} #{img[:url]}" next unless defined?(img[:url]) && !img[:url].nil? open(img[:url]) do |url| File.open("#{@img_path}tmp/#{img[:keyword]}.jpg", "wb") do |file| file.puts url.read end file = "#{@img_path}tmp/#{img[:keyword]}.jpg" debug "flickr.download: file #{file}" photos << file if Image.valid?(file) end end rescue StandardError => e warn "flickr.download: caught exception: #{e.inspect}" raise e if RAISE_ERROR end photos.size > 1 ? photos : photos.first end
Scrape top-rated images for keyword
@param [Hash] opts @option opts [String] :keyword ('Giant Robots Smashing into Other Giant Robots') keyword for scrape
@return [String] file path for downloaded image
# File lib/FlickrCollage.rb, line 128 def scrape(opts = {}) opts[:keyword] ||= SEARCH_KEYWORD url = search(keyword: opts[:keyword]) debug "flickr.scrape: #{opts[:keyword]} #{url}" download(keyword: opts[:keyword], url: url) end
Search top-rated images for keyword
@param [Hash] opts @option opts [String] :keyword ('Giant Robots Smashing into Other Giant Robots') keyword for search @option opts [Number] :count (1) how many images you need
@return [Array<String>] urls with top-rated images for keyword @return [String] url with top-rated image for keyword
# File lib/FlickrCollage.rb, line 66 def search(opts = {}) opts[:keyword] ||= SEARCH_KEYWORD opts[:count] ||= SEARCH_COUNT photos = [] begin list = flickr.photos.search(text: opts[:keyword], sort: "interestingness-desc", per_page: opts[:count]) debug "flickr.search: #{opts[:keyword]} (img: #{list.size})" list.each do |photo| info = flickr.photos.getInfo(photo_id: photo.id) debug "flickr.search: get image url for #{photo.id}" # debug "flickr.search: #{FlickRaw.url_photopage(info)}" photos << FlickRaw.url_c(info) end rescue StandardError => e warn "flickr.search: caught exception #{e}" raise e if RAISE_ERROR end photos.size > 1 ? photos : photos.first end