QML: Correct threading to load images
[mussorgsky] / src / qml / aa_search.py
1 #!/usr/bin/env python2.5
2 import os
3 from aa_spec import getCoverArtFileName, getCoverArtThumbFileName, get_thumb_filename_for_path
4 from utils import UrllibWrapper
5 import dbus, time
6 import string
7 import urllib
8
9 try:
10     import libxml2
11     libxml_available = True
12 except ImportError:
13     libxml_available = False
14
15 try:
16     import PIL
17     import Image
18 except ImportError:
19     import sys
20     print "Please install python-imaging package"
21     sys.exit (-1)
22
23
24 LASTFM_APIKEY = "1e1d53528c86406757a6887addef0ace"
25 BASE_LASTFM = "http://ws.audioscrobbler.com/2.0/?method=album.getinfo"
26
27
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"
33
34 CACHE_LOCATION = os.path.join (os.getenv ("HOME"), ".cache", "mussorgsky")
35 # LastFM:
36 # http://www.lastfm.es/api/show?service=290
37 #
38
39
40 import threading
41 class AADownloadThread (threading.Thread):
42
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 ()
50
51     def grab_image (self, image_url):
52         print "Working", self.counter
53         image = self.urllib_wrapper.get_url (image_url)
54         if (image):
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)
59         
60     def get_result (self):
61         return self.image_path, self.thumb_path
62
63
64
65 class MussorgskyAlbumArt:
66
67     def __init__ (self):
68         bus = dbus.SessionBus ()
69
70         if (not os.path.exists (CACHE_LOCATION)):
71             os.makedirs (CACHE_LOCATION)
72             
73         self.thumbnailer = LocalThumbnailer ()
74         self.urllib_wrapper = UrllibWrapper ()
75
76     def get_possible_url (self, artist, album, amount=4):
77             results_page = self.__msn_images (artist, album)
78             return self.__get_url_from_msn_results_page (results_page)
79         
80
81     def get_album_art (self, artist, album, force=False):
82         """
83         Return a tuple (album_art, thumbnail_album_art)
84         """
85         filename = getCoverArtFileName (album)
86         thumbnail = getCoverArtThumbFileName (album)
87
88         album_art_available = False
89         if (os.path.exists (filename) and not force):
90             print "Album art already there " + filename
91             album_art_available = True
92         else:
93             results_page = self.__msn_images (artist, album)
94             for online_resource in self.__get_url_from_msn_results_page (results_page):
95                 print "Choosed:", online_resource
96                 content = self.urllib_wrapper.get_url (online_resource)
97                 if (content):
98                     print "Albumart: %s " % (filename)
99                     self.urllib_wrapper.save_content_into_file (content, filename)
100                     album_art_available = True
101                     break
102
103         if (not album_art_available):
104             return (None, None)
105
106         if (not os.path.exists (thumbnail) or force or album_art_available):
107             if (not self.__request_thumbnail (filename)):
108                 print "Failed doing thumbnail. Probably album art is not an image!"
109                 os.remove (filename)
110                 return (None, None)
111         else:
112             print "Thumbnail exists (and probably valid) " + thumbnail
113             
114         return (filename, thumbnail)
115
116
117     def get_alternatives (self, artist, album, max_alternatives=4):
118         """
119         return a list of paths of possible album arts
120         """
121         results_page = self.__msn_images (artist, album)
122         return self.__process_results_page (results_page, max_alternatives)
123
124     def get_alternatives_free_text (self, search_text, max_alternatives=4):
125         results_page = self.__msn_images_free_text (search_text)
126         return self.__process_results_page (results_page, max_alternatives)
127
128     def __process_results_page (self, results_page, max_alternatives):
129         counter = 0
130         threads = []
131         for image_url in self.__get_url_from_msn_results_page (results_page):
132             if (not image_url):
133                 # Some searches doesn't return anything at all!
134                 break
135
136             if (counter >= max_alternatives):
137                 break
138             
139             t = AADownloadThread (image_url, counter)
140             t.start ()
141             threads.append (t)
142             counter += 1
143
144         for t in threads:
145             t.join (5)
146             if (t.isAlive ()):
147                 yield (None, None)
148             else:
149                 yield t.get_result ()
150             
151
152     def save_alternative (self, artist, album, img_path, thumb_path):
153         if not os.path.exists (img_path) or not os.path.exists (thumb_path):
154             print "**** CRITICAL **** image in path", path, "doesn't exist!"
155             return (None, None)
156         
157         filename = getCoverArtFileName (album)
158         thumbnail = getCoverArtThumbFileName (album)
159
160         os.rename (img_path, filename)
161         os.rename (thumb_path, thumbnail)
162
163         return (filename, thumbnail)
164
165     def reset_alternative (self, artist, album):
166
167         for filepath in [getCoverArtFileName (album),
168                          getCoverArtThumbFileName (album)]:
169             if os.path.exists (filepath):
170                 os.remove (filepath)
171
172     def __msn_images (self, artist, album):
173
174         good_artist = self.__clean_string_for_search (artist)
175         good_album = self.__clean_string_for_search (album)
176         
177         if (good_album and good_artist):
178             full_try = BASE_MSN + good_album + "+" + good_artist + MSN_MEDIUM + MSN_SQUARE
179             print "Searching (album + artist): %s" % (full_try)
180             result = self.urllib_wrapper.get_url (full_try)
181             if (result and result.find ("no_results") == -1):
182                 return result
183
184         if (album):
185             if (album.lower ().find ("greatest hit") != -1):
186                 print "Ignoring '%s': too generic" % (album)
187                 pass
188             else:
189                 album_try = BASE_MSN + good_album + MSN_MEDIUM + MSN_SQUARE
190                 print "Searching (album): %s" % (album_try)
191                 result = self.urllib_wrapper.get_url (album_try)
192                 if (result and result.find ("no_results") == -1):
193                     return result
194             
195         if (artist):
196             artist_try = BASE_MSN + good_artist + "+CD+music"  + MSN_SMALL + MSN_SQUARE + MSN_PHOTO
197             print "Searching (artist CD): %s" % (artist_try)
198             result = self.urllib_wrapper.get_url (artist_try)
199             if (result and result.find ("no_results") == -1):
200                 return result
201         
202         return None
203
204     def __msn_images_free_text (self, search_text):
205         full_try = BASE_MSN + self.__clean_string_for_search (search_text) + MSN_MEDIUM + MSN_SQUARE
206         result = self.urllib_wrapper.get_url (full_try)
207         return result
208     
209
210     def __get_url_from_msn_results_page (self, page):
211         if (not page):
212             return
213
214         current_option = None
215         starting_at = 0
216
217         # 500 is just a safe limit
218         for i in range (0, 500):
219             # Iterate until find a jpeg
220             start = page.find ("imgurl:"", starting_at)
221             if (start == -1):
222                 yield None
223             end = page.find ("&", start + len ("imgurl:""))
224             current_option = page [start + len ("imgurl:""): end].replace ("amp;", "")
225             if (current_option.lower().endswith (".jpg") or
226                 current_option.lower().endswith (".jpeg")):
227                 yield current_option
228             starting_at = end
229         
230
231     def __clean_string_for_search (self, text):
232         if (not text or len (text) < 1):
233             return None
234             
235         bad_stuff = "_:?\\-~"
236         clean = text
237         for c in bad_stuff:
238             clean = clean.replace (c, " ")
239
240         clean.replace ("/", "%2F")
241         clean = clean.replace (" CD1", "").replace(" CD2", "")
242         return urllib.quote(clean)
243
244     def __request_thumbnail (self, filename):
245         thumbFile = get_thumb_filename_for_path (filename)
246         return self.thumbnailer.create (filename, thumbFile)
247             
248
249
250 class LocalThumbnailer:
251     def __init__ (self):
252         self.THUMBNAIL_SIZE = (124,124)
253
254     def create (self, fullCoverFileName, thumbFile):
255         if (os.path.exists (fullCoverFileName)):
256             try:
257                 image = Image.open (fullCoverFileName)
258                 image = image.resize (self.THUMBNAIL_SIZE, Image.ANTIALIAS )
259                 image.save (thumbFile, "JPEG")
260                 print "Thumbnail: " + thumbFile
261             except IOError, e:
262                 print e
263                 return False
264         return True
265             
266
267
268 if __name__ == "__main__":
269     import sys
270     from optparse import OptionParser
271
272     parser = OptionParser()
273     parser.add_option ("-p", "--print", dest="print_paths",
274                        action="store_true", default=True,
275                        help="Print the destination paths")
276     parser.add_option ("-r", "--retrieve", dest="retrieve",
277                        action="store_true", default=False,
278                        help="Try to retrieve the online content")
279     parser.add_option ("-m", "--multiple", dest="multiple",
280                        action="store_true", default=False,
281                        help="Show more than one option")
282     parser.add_option ("-a", "--artist", dest="artist", type="string",
283                        help="ARTIST to look for", metavar="ARTIST")
284     parser.add_option ("-b", "--album", dest="album", type="string",
285                        help="ALBUM to look for", metavar="ALBUM")
286
287     (options, args) = parser.parse_args ()
288     print options
289     if (not options.artist and not options.album):
290         parser.print_help ()
291         sys.exit (-1)
292
293     if (options.multiple and options.retrieve):
294         print "Multiple and retrieve are incompatible"
295         parser.print_help ()
296         sys.exit (-1)
297         
298     if options.print_paths and not options.retrieve:
299         print "Album art:", getCoverArtFileName (options.album)
300         print "Thumbnail:", getCoverArtThumbFileName (options.album)
301
302     if options.retrieve:
303         maa = MussorgskyAlbumArt ()
304         maa.get_album_art (options.artist, options.album)
305
306     if options.multiple:
307         start = time.time ()
308         maa = MussorgskyAlbumArt ()
309         for (img, thumb) in  maa.get_alternatives (options.artist, options.album, 5):
310             print img
311             print thumb
312         end = time.time ()
313         print end - start