All pastes #947368 Raw Edit

Meins

public python v1 · immutable
·published 2008-03-18 13:27 UTC
rendered paste body
#!/usr/bin/env python# -*- coding: iso8859-15 -*-import urllibimport mmsv2guiimport osimport sysimport StringIOimport Imageimport ImageFilter#import amazonimport sqlite3import ImageChopsclass PictureUpdater(mmsv2gui.Window):#	bg = None	tc = None	exit = None	height = 600	width = 800	defaultcolor=(0,0,0,255)	button_exit = None	butto_exitpos = (0,0)	pic = None	picsize = (0,0)	picpos = (0,0)	list = None	listsize = (0,0)	listpos = (0,0)	prog = None	progpos = (0,0)	progsize = (0,0)	title = None	titlepos = (0,0)	titlesize = (0,0)	run = None	runsize = (0,0)	runpos = (0,0)	up = None		def __init__(self):		self.height = self.getHeight()		self.width = self.getWidth()		self.tc = ThemeConfig()		self.button_exit = self.create_exit_button()		bgfile = self.tc.get_file("background","audio")		path,ext = os.path.splitext(bgfile)				if self.height /10 == self.width/16 :			bgfile = path + "-16-10"+ ext		elif self.height /9 == self.width/16 :			bgfile = path +"-16-9"+ ext		else:			bgfile = path +"-4-3"+ ext		self.bg =  mmsv2gui.ImageControl(0, 0, self.getWidth(), self.getHeight(), bgfile)		self.image = self.create_image(os.path.join(self.tc.get_themepath(),"question.png"))		self.list = self.create_list()		self.up = updatepics(amazon())		self.title = self.create_title()		self.run = self.create_run()		self.addControl(self.bg)		self.addControl(self.title)		self.addControl(self.button_exit)		self.addControl(self.list)		self.addControl(self.image)		self.addControl(self.run)		self.run.controlRight(self.button_exit)		self.button_exit.controlLeft(self.run)		self.setFocus(self.button_exit)		mmsv2gui.Window.__init__(self)			def create_run(self):		xpos = 75		ypos = self.height -150		xsize = 50		ysize = 50		run = mmsv2gui.ButtonControl(xpos,ypos,xsize,ysize,nofocus=self.tc.get_file("search","general"),focus=self.create_focused_image(self.tc.get_file("search","general")))		return run	def create_title(self):		xsize = 300		ysize = 50		xpos = (self.width - xsize)/2		ypos = 25		title = mmsv2gui.LabelControl(xpos, ypos, xsize, ysize)		title.setLabel("Cover downloader")		self.titlesize=(xsize,ysize)		self.titlepos=(xpos,ypos)		return title	def create_exit_button(self):		xsize,ysize = Image.open(self.tc.get_file("quit")).size		tmpfile= self.create_focused_image(self.tc.get_file("quit"))		return mmsv2gui.ButtonControl(self.width -120,self.height-150, xsize,ysize,focus = tmpfile, nofocus = self.tc.get_file("quit"))	def create_focused_image(self,img):		image = Image.open(img)		bgleft = Image.open(self.tc.get_file("marked_left","audio"))		bgright = Image.open(self.tc.get_file("marked_right","audio"))		xsize, ysize = image.size		ret = Image.new("RGBA",(xsize,ysize),(255,255,255,255))		ret.paste(bgleft.resize((xsize/2,ysize)),(0,0))		ret.paste(bgright.resize((xsize/2,ysize)),(xsize,0))		ret.paste(image,(0,0))		tmpfile = os.tmpnam()+".jpg"		print tmpfile		ret.save(tmpfile)		return tmpfile				def create_image(self,image):		xsize = self.width/4		ysize = xsize * 4/3		xpos = (self.width - xsize)/2		ypos = self.height / 8		print "imagepos:",xpos,ypos		print "to", xpos+xsize,ypos+ysize		print "screensize:", self.width, self.height		if isinstance(image,str):			image= Image.open(image)		image = image.resize((xsize,xsize))		ret = Image.new("RGBA",(xsize,ysize),None)		ref = image.crop((0,xsize*2/3,xsize,xsize)).transpose(Image.FLIP_TOP_BOTTOM).filter(ImageFilter.BLUR)		ret.paste(image,(0,0,xsize,xsize))		#print "size", ref.size ,xsize,ysize-xsize		ret.paste(ref,(0,xsize-1,xsize,ysize))				#ret.save("img.jpeg")		tmpfile = os.tmpnam()+".jpg"		ret.save(tmpfile)		return mmsv2gui.ImageControl(xpos,ypos,xsize,ysize,tmpfile)	def create_list(self):		xsize = self.width/2 ##200		ysize = self.height/4 ##150		xpos = (self.width - xsize)/2 ##300		ypos = self.height *3/4 ##450		print "listpos:",xpos,ypos		print "to", xpos+xsize,ypos+ysize		print "screensize:", self.width, self.height			self.listsize = (xsize,ysize)		self.listpos = (xpos,ypos)		print self.listpos,self.listsize		tmp = mmsv2gui.ListControl(xpos,ypos,xsize,ysize) 		#tmp.setLabel("Status")		return  tmp	def onAction(self,action):		print "action:",action		if action == "back":			self.setFocus(self.button_exit)		if action == "action":			if self.getFocus() == self.button_exit:				self.close()			elif self.getFocus() == self.run:				print "starting search"				imgs = dict()				print len(self.up.filenames)				for file in self.up.filenames:					print file['artist'],":",file['album']					item = mmsv2gui.ListItem()					print "item created"					item.setLabel(file['artist']+": "+file['album'])					print self.list.addItem(item)					print "added, starting download"					self.up.downloader.coverpath=os.path.dirname(file['filename'])					print "coverpath set"					filename = self.up.downloader.get_album_art(file['artist'],file['album'])					print "downloaded"					if filename != None:						loaded+=1						imgs[self.up.downloader.coverpath] = filename						self.image = self.create_image(filename)						print "OK"					else:						item.setLabel(file['artist']+": "+file['album']+"   .... failed")						print "failed"					#total +=1					self.redraw()				print "images:",len(imgs)				for p,f in imgs.iteritems():						print p,"#",f					try:						self.musicc.execute("INSERT INTO Covers VALUES (?,?)",(p+"/",f))					except sqlite3.IntegrityError:						self.musicc.execute("UPDATE Covers SET Cover=? WHERE Path=? AND Cover=''",(f,p+"/"))				print "finished"						class ThemeConfig():		themepath = ""	themeconfig = None	sectionconfig = None	section = "startmenu"	def __init__(self):		self.themeconfig = {}		try:			themeconf = os.expanduser("~/.mms/options/ThemeRuntime")			fd = open(themeconf)			theme = fd.read().split(",")[1].strip("\n\t ")						fd.close()		except:			theme = "standard"		print "theme:", theme		self.themepath = os.path.join("/usr/local/share/mms/themes/",theme)		themeconf = os.path.join(self.themepath,"theme.conf")		fd = open(themeconf)		for line in fd.readlines():			try:				tmp = line.split("=")				section = tmp[0].split(".")[0].strip(" \t\n")				key = tmp[0].split(".")[1].strip(" \t\n")				value = tmp[1].strip(" \t\n")				if not self.themeconfig.has_key(section):					self.themeconfig[section] = {key:value}				else:					s = self.themeconfig[section] 					s[key]= value			except:				pass#print "error",line,":",msg	def get_val(self,key,section=None):		if section == None:			section = self.section		try:			tmp = self.themeconfig[section]			return tmp[key]		except:			return None	def get_themepath(self):		return self.themepath		def get_file(self,key,section=None):				f = self.get_val(key,section)		tmp = os.path.join(self.themepath,f)		return tmp	def set_section(self,section):		self.section = section		self.sectionconfig = self.themeconfig[section]class amazon():		##path where the covers will be saved	coverpath = None	##the first part of the search url	url = "http://www.amazon.com/s/ref=nb_ss_/002-1992546-8939265?"	def __init__(self):		self.coverpath=os.path.expanduser("~/.mms/covers/")	def get_album_art(self,artist,album):		print "get_album_art"		image = Image.Image()		print "image created"		searchstring = ""		#artist = artist		#album = album		searchstring = self._fix_net_search_string(artist) + " " + self._fix_net_search_string(album)		if len(searchstring) <=3:						print "empty searchstring"			return None		print "searchstring:",searchstring,len(searchstring)		##parameters for the search			params = {"url":"search-alias=aps", 			"field-keywords": searchstring,			"ei":"UTF-8"}		print "parameters:",params		txdata = urllib.urlencode(params)		print "urlencoded"		url = self.url + txdata + "&x=0&y=0"		print "opening:", url		found = False		try:			sock = urllib.urlopen(url)			htmlsource = sock.read()			sock.close()		except Exception,msg:			print "could not open socket:",msg			return None		#find the detailpage of the album in the page		detaillocationstart = htmlsource.find('<tr><td align="center" width="115"><a href="') +44		if detaillocationstart > 44:			#get end of URL			detaillocationend = htmlsource.find('"',detaillocationstart)			detaillocation = htmlsource[detaillocationstart:detaillocationend]			#print "detaillocation:",detaillocation			try:				#visit the detailpage				sock = urllib.urlopen(detaillocation)				detailpage = sock.read()				sock.close()			except Exception,msg:				#print "could not load detailpage", msg				return None			#look for a big image			imagestart1 = detailpage.find('registerImage("original_image", "') + 33			#print "1",imagestart1			if imagestart1 > 33:				#find the big image				#print detailpage[imagestart1:imagestart1 +100]				imagestart = detailpage.find('"<a href="+\'"\'+"',imagestart1) + len('"<a href="+\'"\'+"')				#print "2",imagestart				if imagestart > 15:					imageend = detailpage.find('"', imagestart)					imagelocation = detailpage[imagestart:imageend]					#print "imagelocation",imagelocation					try:						sock = urllib.urlopen(imagelocation)						htmlsource = sock.read()						sock.close()					except Exception,msg:						#print "could not get image page", msg						return None					imgstart = htmlsource.find('<noscript><div id="imageViewerDiv"><img src="') +45					if imgstart > 45:						imgend = htmlsource.find('"',imgstart) 						imglocation = htmlsource[imgstart:imgend]						#print "imglocation",imglocation						sock = urllib.urlopen(imglocation)						#download the big image						image = sock.read()						sock.close()						#urllib.urlretrieve(imglocation,filename)						found = True				else:					imgstart = detailpage.find('"<img src="+\'"\'+"',imagestart1) +17					imageend = detailpage.find('"',imgstart)					imglocation = detailpage[imgstart:imageend]					#download mid image					sock = urllib.urlopen(imglocation)					image = sock.read()					sock.close()					found = True													else:				print "no small image found"				return None		else:			print "couldn't find details"			return None		if image == None:			return None		#remove the border		img = self.remove_border(Image.open(StringIO.StringIO(image)))		filename = os.path.join(self.coverpath,".front-cover.jpg")		print "image size:",img.size		img.save(filename)				return filename					def remove_border(self, img):		return img.crop(ImageChops.invert(img).getbbox())			def _fix_net_search_string(self, str):		s= ""		lastwasws = False		#print str		str = str.lower()		for c in str:			if c in ["\t",]:				continue			if c in ["_",":","?","/","-","~","[","]"," "]:				if lastwasws == True:					continue				else:					s+=" "					lastwasws= True			else:				s+=c				lastwasws = False		print "fixed:", s 		return s	def _fix_fs_filename(self, s):		s = s.replace(":"," ")		s = s.replace(";"," ")		s = s.replace("&"," and ")		s = s.replace("$"," ")		s = s.replace("?"," ")		s = s.replace("/"," ")		s = s.replace("~"," ")		s = s.replace("<"," ")		s = s.replace(">"," ")		s = s.replace("`"," ")		s = s.replace("\\"," ")		s = s.replace("  "," ")		s = s.replace("  "," ")		return s		##path where the covers will be saved	coverpath = None	##the first part of the search url	url = "http://www.amazon.com/s/ref=nb_ss_/002-1992546-8939265?"#if __name__ == "__main__":#	print "lalal"#	pu = PictureUpdater()class updatepics:	##Musicdatabase connection and cursor	musicc    = None	musiccon  = None	musiccur  = None	musicpath = None	##general database directory of mms	dbdir = ""	downloader = None	filenames = []		def __init__(self,d):		self.downloader = d		self.dbdir= os.path.expanduser("~/.mms/")		self.coverpath = os.path.expanduser("~/.mms/covers/")		#self.picpath =  os.path.join(self.dbdir,"pictures.db")		self.musicpath =  os.path.join(self.dbdir,"audio.db")		self.connect()		self.get_all()		#self.run()	def get_all(self):		self.filenames = self.musicc.execute("SELECT au.filename AS filename, ar.name AS artist, al.name AS album FROM Audio au,Artist ar, Album al WHERE (au.Artist=ar.id AND au.Album=al.id AND (ar.name <> '' OR al.name <> ''))  GROUP BY ar.name,al.name").fetchall()			def get_new(self):		parents = self.musicc.execute("SELECT parent From Folder WHERE is_folder = 0")		#self.filenames = self.musicc.execute("SELECT au.filename AS filename, ar.name AS artist, al.name AS album FROM Audio au,Artist ar, Album al,Covers c WHERE (au.Artist=ar.id AND au.Album=al.id AND c.Cover='') GROUP BY ar.name,al.name")	def run(self):		loaded=0		total = 0		imgs = dict()		for file in self.filenames:			print file['artist'],":",file['album']#,file['filename']			self.downloader.coverpath=os.path.dirname(file['filename'])			#print self.downloader.coverpath			filename = self.downloader.get_album_art(file['artist'],file['album'])			if filename != None:				loaded+=1				imgs[self.downloader.coverpath] = filename				print "OK"			total +=1		#print "images:",len(imgs)		for p,f in imgs.iteritems():				print p,"#",f			try:				self.musicc.execute("INSERT INTO Covers VALUES (?,?)",(p+"/",f))			except sqlite3.IntegrityError:				self.musicc.execute("UPDATE Covers SET Cover=? WHERE Path=? AND Cover=''",(f,p+"/"))					print loaded,"of", total		def connect(self):		self.musiccon = sqlite3.connect(self.musicpath)		self.musiccon.row_factory = sqlite3.Row		self.musiccon.text_factory=str		self.musicc   = self.musiccon.cursor()		print self.musiccon, self.musicc	def close(self):		self.musiccon.commit()		self.musiccon.close()		self.musiccon = None		self.musicc   = None		def update(self):		self.musiccon.commit()	def reconnect(self):		self.close()		self.connect()win =  PictureUpdater()win.doModal()del win