Skip to content

Instantly share code, notes, and snippets.

@hawx
Created July 5, 2010 11:02
Show Gist options
  • Save hawx/464238 to your computer and use it in GitHub Desktop.
Save hawx/464238 to your computer and use it in GitHub Desktop.
# Gets the genres for tracks in a playlist called 'Genres'in iTunes
# and sets them using data from wikipedia.
#
# Uses the album name for the search, but won't try anything fancy
# if it can't find the labum it will just ignore it.
#
# ref: http://www.apeth.com/rbappscript/05propel.html
require 'appscript'
require 'nokogiri'
require 'open-uri'
gem 'dm-core', '=0.10.2'
require 'dm-core'
require 'highline/import'
class Genre
include DataMapper::Resource
property :id, Serial
property :name, String
end
DataMapper.setup(:default, "sqlite3://#{Dir.pwd}/genres.db")
DataMapper.auto_upgrade!
include Appscript
def get_genres( album )
begin
arg = album.gsub(' ', '_')
url = "http://en.wikipedia.org/wiki/#{arg}"
doc = Nokogiri::HTML( open(url) )
genres = []
doc.css('td.category').each do |a|
a.css('a').each do |l|
l.to_s =~ /title="([a-zA-Z0-9_ -]+)"/
genres << $1
end
end
return genres
rescue OpenURI::HTTPError => e
puts "Bad status code: #{e.message}"
return nil
end
end
def choose_genre(genres)
genres.each_with_index do |g, i|
if Genre.first(:name => g)
puts "#{i}. #{g} (used)"
else
puts "#{i}. #{g}"
end
end
i = ask("Choose a genre from the list above, use the index! Or type your own!")
genre = genres[i.to_i] if Float(i) rescue genre = i
Genre.create(:name => genre) unless Genre.first(:name => genre)
genre
end
def sort_tracks(tracks)
a = Hash.new {|h, k| h[k] = []}
tracks.each do |t|
a[t.album.get] << t.get
end
a
end
def process_album(album, tracks)
puts "Getting genre for #{album}..."
genres = get_genres(album)
return nil if genres.nil? || genres.length == 0
genre = ''
if genres.length == 1
genre = genres[0]
else
genre = choose_genre(genres)
end
tracks.each do |t|
t.genre.set(genre)
end
end
itunes = app('iTunes.app')
@albums = sort_tracks(itunes.playlists["Genres"].tracks.get)
puts "Sorted tracks..."
@albums.each do |a, ts|
process_album(a, ts)
end
puts "Done"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment