1#!/usr/bin/python 2 3## Copyright (C) 2005 Nick Piper <nick-gtkpod at nickpiper co uk> 4## Part of the gtkpod project. 5 6## URL: http://www.gtkpod.org/ 7## URL: http://gtkpod.sourceforge.net/ 8 9## The code contained in this file is free software; you can redistribute 10## it and/or modify it under the terms of the GNU Lesser General Public 11## License as published by the Free Software Foundation; either version 12## 2.1 of the License, or (at your option) any later version. 13 14## This file is distributed in the hope that it will be useful, 15## but WITHOUT ANY WARRANTY; without even the implied warranty of 16## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 17## Lesser General Public License for more details. 18 19## You should have received a copy of the GNU Lesser General Public 20## License along with this code; if not, write to the Free Software 21## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 22 23## $Id$ 24 25 26import os, os.path 27import gpod 28import sys 29from xml import xpath 30from xml.dom import minidom 31from xml.parsers.expat import ExpatError 32import urllib2, urllib 33 34TRUST_LIMIT = 10 35dbname = os.path.join(os.environ['HOME'],".gtkpod/local_0.itdb") 36 37 38itdb = gpod.itdb_parse_file(dbname, None) 39if not itdb: 40 print "Failed to read %s" % dbname 41 sys.exit(2) 42 43cache={} 44for track in gpod.sw_get_tracks(itdb): 45 if track.artist is None: 46 continue 47 48 key = track.artist.upper() 49 if not cache.has_key(key): 50 url = "http://ws.audioscrobbler.com/1.0/artist/%s/toptags.xml" % urllib.quote(track.artist) 51 52 try: 53 reply = urllib2.urlopen(url).read() 54 xmlreply = minidom.parseString(reply) 55 attlist = xpath.Evaluate("//toptags/tag[1]/@name",xmlreply) 56 count = xpath.Evaluate("//toptags/tag[1]/@count",xmlreply) 57 if attlist and count and int(count[0].value) > TRUST_LIMIT: 58 cache[key] = str(attlist[0].value.title()) # no unicode please :-) 59 except urllib2.HTTPError, e: 60 pass 61 #print "Urllib failed.", e 62 except ExpatError, e: 63 print "Failed to parse,", e 64 print reply 65 66 if cache.has_key(key): 67 track.genre = cache[key] 68 print "%-25s %-20s %-20s --> %s" % (track.title, 69 track.album, 70 track.artist, 71 track.genre) 72 else: 73 print "%-25s %-20s %-20s === %s" % (track.title, 74 track.album, 75 track.artist, 76 track.genre) 77 78 79gpod.itdb_write_file(itdb, dbname, None) 80