genre-tagger.py

January 28th, 2010 Leave a comment Go to comments

I created this script to update tracks in my iTunes library with relevant genre information.  This script works by downloading the top tags assigned to the given artist from Last.FM and setting the #1 tag as the genre.  It used to also add the additional tags to the comment field of the track, but I've been getting numerous errors, and have commented it out for the time being.

I would like to eventually port this script to C# and add a GUI interface to make it more user friendly.  In the mean time, it seems to work well enough, and isn't too difficult to use.

Installation and Usage

  1. Need to install Python 2.x (I use 2.6.3) - http://python.org
  2. You will also need to install a few libraries for Python. You can either use the easy_install Python tools, or use the installers
  3. After installing the libraries, it's just a matter of selecting the songs in iTunes, and then running the script

Code:

import win32com.client
import urllib2
from BeautifulSoup import BeautifulSoup
import unicodedata
 
lastFMUrl = "http://ws.audioscrobbler.com/2.0/?method="
apiKey = "YOUR-API-KEY-HERE"
itunes = None
 
def getArtistTags(artist):
	url = lastFMUrl + "artist.getTopTags&artist=" + urllib2.quote(unicodedata.normalize("NFKD", artist).encode("ascii", "ignore")) + "&api_key=" + apiKey
	data = urllib2.urlopen(url).read()
 
	soup = BeautifulSoup(data)
 
	tagsxml = soup.findAll("tag")
	tags = []
	for x in tagsxml:
		name = urllib2.unquote(x.find("name").next)
		words = name.split(" ")
		name = ""
		for word in words:
			name = name + word.capitalize() + " "
		name = name[:-1]
		count = int(x.find("count").next)
		tags.append({"name" : name, "count" : count})
 
	return tags
 
def main():
	itunes = win32com.client.gencache.EnsureDispatch("iTunes.Application")
	raw_input("Please ensure that at least one track is selected in iTunes...")
 
	tracks = itunes.SelectedTracks
	count = 1
 
	artistTags = {}
 
	for track in tracks:
		print "Track: " + str(count) + " of " + str(len(tracks))
 
		try:
			if not artistTags.has_key(track.Artist):
				artistTags[track.Artist] = getArtistTags(track.Artist)
		except:
			print track.Artist
 
		tags = artistTags[track.Artist][:]
 
		count = count + 1
		if len(tags) == 0:
			continue
		track.Genre = tags[0]["name"]
		tags.pop(0)
 
		if len(tags) == 0:
			continue
		'''track.Comment = tags[0]["name"]'''
		tags.pop(0)
 
		'''for t in tags:
			if t["count"] >= 20:
				track.Comment = track.Comment + ", " + t["name"]'''
 
if __name__ == "__main__":
	main()
 
  1. No comments yet.
  1. No trackbacks yet.