# Bens amazing 'folder structure of mp3 files -> folder of book cover images' convertor. # March, 2010 # # Freeware. Use it for the benefit of mankind (or not, it's up to you). # Credit Ben Dunham [www.toasta.com] if you feel like it. require 'ftools' require 'rubygems' require "mp3info" require 'amazon/aws/search' require 'open-uri' include Amazon::AWS include Amazon::AWS::Search # Initialise the cache of previously extracted Albums found = [] # Initialise the image file name counter i = 0 # A dirty, but easy deep scan of all the Music folders on the NAS. Negates the need for recursion. Dir.glob('/Volumes/media/Music/**/*.mp3').each do |mp3| # Use mp3info to read the ID3 tag from each MP3 file Mp3Info.open(mp3) do |mp3| # Don't bother checking if we have already dealt with an MP3 from this Album (doesn't # cater for the case where multiple Albums from different artists have the same name!) unless found.include?(mp3.tag2.TALB) # Store the Album name in the cache found << mp3.tag2.TALB # If the MP3 has an embedded Artwork field... if mp3.tag2.APIC # Increment the counter i += 1 # Extract the Image data text_encoding, mime_type, picture_type, description, picture_data = mp3.tag2["APIC"].unpack("c Z* c Z* a*") # Write it to the image folder File.open('../music/' + i.to_s + '.' + mime_type.split('/').last,'w'){|f| f.write(picture_data) } # Otherwise, look up the item in Amazon else begin # Initialise the Search objects (use a variety of MP3 ID3 tags to deduce the band name) is = ItemSearch.new('Music', { 'Artist' => (mp3.tag2.TPE1 || mp3.tag2.TCOM || mp3.tag2.TPE2).to_s, 'Title' => mp3.tag2.TALB.to_s } ) rg = ResponseGroup.new( 'Large' ) req = Request.new # Restrict to Amazon UK req.locale = 'uk' # Do the search resp = req.search( is, rg ) # If any items were matched... if resp.item_search_response[0].items.any? # Increment the counter i += 1 # Download the file image = open(resp.item_search_response[0].items[0].item[0].small_image.url) # And write it to disk File.open('../music/' + i.to_s + '.jpg','w'){|f| f.write(image.read) } image.close end rescue # No image found. Oh well! end end end end end