1 #!/usr/bin/env python2.5
3 from album_art_spec import getCoverArtFileName, getCoverArtThumbFileName, get_thumb_filename_for_path
4 from utils import UrllibWrapper
11 libxml_available = True
13 libxml_available = False
20 print "Please install python-imaging package"
24 LASTFM_APIKEY = "1e1d53528c86406757a6887addef0ace"
25 BASE_LASTFM = "http://ws.audioscrobbler.com/2.0/?method=album.getinfo"
28 BASE_MSN = "http://www.bing.com/images/search?q="
29 MSN_MEDIUM = "+filterui:imagesize-medium"
30 MSN_SMALL = "+filterui:imagesize-medium"
31 MSN_SQUARE = "+filterui:aspect-square"
32 MSN_PHOTO = "+filterui:photo-graphics"
34 CACHE_LOCATION = os.path.join (os.getenv ("HOME"), ".cache", "mussorgsky")
36 # http://www.lastfm.es/api/show?service=290
41 class AADownloadThread (threading.Thread):
43 def __init__ (self, url, counter):
44 threading.Thread.__init__ (self, target=self.grab_image, args=(url,))
45 self.thumbnailer = LocalThumbnailer ()
46 self.counter = counter
47 self.image_path = None
48 self.thumb_path = None
49 self.urllib_wrapper = UrllibWrapper ()
51 def grab_image (self, image_url):
52 print "Working", self.counter
53 image = self.urllib_wrapper.get_url (image_url)
55 self.image_path = os.path.join (CACHE_LOCATION, "alternative-" + str(self.counter))
56 self.thumb_path = os.path.join (CACHE_LOCATION, "alternative-" + str(self.counter) + "thumb")
57 self.urllib_wrapper.save_content_into_file (image, self.image_path)
58 self.thumbnailer.create (self.image_path, self.thumb_path)
60 def get_result (self):
61 return self.image_path, self.thumb_path
65 class MussorgskyAlbumArt:
68 bus = dbus.SessionBus ()
70 if (not os.path.exists (CACHE_LOCATION)):
71 os.makedirs (CACHE_LOCATION)
73 self.thumbnailer = LocalThumbnailer ()
74 self.urllib_wrapper = UrllibWrapper ()
76 def get_album_art (self, artist, album, force=False):
78 Return a tuple (album_art, thumbnail_album_art)
80 filename = getCoverArtFileName (album)
81 thumbnail = getCoverArtThumbFileName (album)
83 album_art_available = False
84 if (os.path.exists (filename) and not force):
85 print "Album art already there " + filename
86 album_art_available = True
88 results_page = self.__msn_images (artist, album)
89 for online_resource in self.__get_url_from_msn_results_page (results_page):
90 print "Choosed:", online_resource
91 content = self.urllib_wrapper.get_url (online_resource)
93 print "Albumart: %s " % (filename)
94 self.urllib_wrapper.save_content_into_file (content, filename)
95 album_art_available = True
98 if (not album_art_available):
101 if (not os.path.exists (thumbnail) or force or album_art_available):
102 if (not self.__request_thumbnail (filename)):
103 print "Failed doing thumbnail. Probably album art is not an image!"
107 print "Thumbnail exists (and probably valid) " + thumbnail
109 return (filename, thumbnail)
112 def get_alternatives (self, artist, album, max_alternatives=4):
114 return a list of paths of possible album arts
117 results_page = self.__msn_images (artist, album)
119 for image_url in self.__get_url_from_msn_results_page (results_page):
121 # Some searches doesn't return anything at all!
124 if (counter >= max_alternatives):
127 t = AADownloadThread (image_url, counter)
137 yield t.get_result ()
140 def save_alternative (self, artist, album, img_path, thumb_path):
141 if not os.path.exists (img_path) or not os.path.exists (thumb_path):
142 print "**** CRITICAL **** image in path", path, "doesn't exist!"
145 filename = getCoverArtFileName (album)
146 thumbnail = getCoverArtThumbFileName (album)
148 os.rename (img_path, filename)
149 os.rename (thumb_path, thumbnail)
151 return (filename, thumbnail)
153 def reset_alternative (self, artist, album):
155 for filepath in [getCoverArtFileName (album),
156 getCoverArtThumbFileName (album)]:
157 if os.path.exists (filepath):
160 def __msn_images (self, artist, album):
162 good_artist = self.__clean_string_for_search (artist)
163 good_album = self.__clean_string_for_search (album)
165 if (good_album and good_artist):
166 full_try = BASE_MSN + good_album + "+" + good_artist + MSN_MEDIUM + MSN_SQUARE
167 print "Searching (album + artist): %s" % (full_try)
168 result = self.urllib_wrapper.get_url (full_try)
169 if (result and result.find ("no_results") == -1):
173 if (album.lower ().find ("greatest hit") != -1):
174 print "Ignoring '%s': too generic" % (album)
177 album_try = BASE_MSN + good_album + MSN_MEDIUM + MSN_SQUARE
178 print "Searching (album): %s" % (album_try)
179 result = self.urllib_wrapper.get_url (album_try)
180 if (result and result.find ("no_results") == -1):
184 artist_try = BASE_MSN + good_artist + "+CD+music" + MSN_SMALL + MSN_SQUARE + MSN_PHOTO
185 print "Searching (artist CD): %s" % (artist_try)
186 result = self.urllib_wrapper.get_url (artist_try)
187 if (result and result.find ("no_results") == -1):
193 def __get_url_from_msn_results_page (self, page):
198 current_option = None
201 # 500 is just a safe limit
202 for i in range (0, 500):
203 # Iterate until find a jpeg
204 start = page.find ("furl=", starting_at)
207 end = page.find ("\"", start + len ("furl="))
208 current_option = page [start + len ("furl="): end].replace ("amp;", "")
209 if (current_option.lower().endswith (".jpg") or
210 current_option.lower().endswith (".jpeg")):
215 def __clean_string_for_search (self, text):
216 if (not text or len (text) < 1):
219 bad_stuff = "_:?\\-~"
222 clean = clean.replace (c, " ")
224 clean.replace ("/", "%2F")
225 clean = clean.replace (" CD1", "").replace(" CD2", "")
226 return urllib.quote(clean)
228 def __request_thumbnail (self, filename):
229 thumbFile = get_thumb_filename_for_path (filename)
230 return self.thumbnailer.create (filename, thumbFile)
234 class LocalThumbnailer:
236 self.THUMBNAIL_SIZE = (124,124)
238 def create (self, fullCoverFileName, thumbFile):
239 if (os.path.exists (fullCoverFileName)):
241 image = Image.open (fullCoverFileName)
242 image = image.resize (self.THUMBNAIL_SIZE, Image.ANTIALIAS )
243 image.save (thumbFile, "JPEG")
244 print "Thumbnail: " + thumbFile
252 if __name__ == "__main__":
254 from optparse import OptionParser
256 parser = OptionParser()
257 parser.add_option ("-p", "--print", dest="print_paths",
258 action="store_true", default=True,
259 help="Print the destination paths")
260 parser.add_option ("-r", "--retrieve", dest="retrieve",
261 action="store_true", default=False,
262 help="Try to retrieve the online content")
263 parser.add_option ("-m", "--multiple", dest="multiple",
264 action="store_true", default=False,
265 help="Show more than one option")
266 parser.add_option ("-a", "--artist", dest="artist", type="string",
267 help="ARTIST to look for", metavar="ARTIST")
268 parser.add_option ("-b", "--album", dest="album", type="string",
269 help="ALBUM to look for", metavar="ALBUM")
271 (options, args) = parser.parse_args ()
273 if (not options.artist and not options.album):
277 if (options.multiple and options.retrieve):
278 print "Multiple and retrieve are incompatible"
282 if options.print_paths and not options.retrieve:
283 print "Album art:", getCoverArtFileName (options.album)
284 print "Thumbnail:", getCoverArtThumbFileName (options.album)
287 maa = MussorgskyAlbumArt ()
288 maa.get_album_art (options.artist, options.album)
292 maa = MussorgskyAlbumArt ()
293 for (img, thumb) in maa.get_alternatives (options.artist, options.album, 5):