I'm writing a script to add a genre artist and title of song to django project. Here are parts from my models
class GenreManager(models.Manager):
def isGenreInDb(self,genre):
try:
genre=self.get(name__iexact=genre)
return genre.id
except Genre.DoesNotExist:
return False
def addGenreToDb(self,genre):
new=Genre(name=genre)
new.save()
return new.id
class Genre(models.Model):
name=models.CharField(max_length=100,unique=True)
objects=GenreManager()
def __unicode__(self):
return self.name
class ArtistManager(models.Manager):
#check if artist in in database and return True else return False
def isArtistInDb(self,artist):
try:
artist=self.get(name__iexact=artist)
return True
except Artist.DoesNotExist:
return False
def getArtistId(self,artist):
try:
temp=Artist.objects.get(name__iexact=artist)
return temp.id
except Artist.DoesNotExist:
return False
#add artist to db and return it's id
def addArtist(self,artist):
new=Artist(name=artist)
new.save()
return new.id
class Artist(models.Model):
name=models.CharField(max_length=100,default="Unknown",unique=True)
objects=ArtistManager()
def __unicode__(self):
return self.name
class Mp3Manager(models.Manager):
#try to serch if a mp3 already exist and if not return False else return True
def getMp3(self,artist,title):
try:
temp=Artist.objects.get(name__iexact=artist)
q=self.get(artist=temp,title__iexact=title)
return True
except Mp3.DoesNotExist:
return False
class Mp3(models.Model):
genre=models.ForeignKey('Genre')
addedby=models.ForeignKey(User)
artist=models.ForeignKey('Artist')
title=models.CharField(max_length=30)
valid=models.BooleanField(default=False)
location=models.CharField(max_length=200,unique=True)
length=models.CharField(max_length=10)
And here it script to adding mp3 to database. Script have access to my django app models
# additional variables
badFiles=0 # num of files which are causing problems
#check if values are set and non empty
def defined(value):
try:
if len(value)==0 or value==None:
return False
return True
except TypeError:
return False
#try to get artist or title using mutagen library
def mutagen(path,what):
try:
audio = ID3(path)
if what=="artist":
return audio['TPE1'].text[0]
else:
return audio["TIT2"].text[0]
except KeyError:
return False
#try to get id3 tag using eyed3 module
def eyed3Fun(path):
global genreLog,invalidLog,badFiles,statusLog
try:
trackInfo = eyeD3.Mp3AudioFile(path)
tag = trackInfo.getTag()
tag.link(path)
artist=tag.getArtist()
title=tag.getTitle()
genre=tag.getGenre()
time=trackInfo.getPlayTimeString() # assums that it always return a true value??
results={}
results['genre']=genre
results['time']=time
if defined(artist) and defined(title) == True: # if we have bouth artist and title
results['artist']=artist
results['title']=title
if defined(title)==False:
results['artist']=artist
results['title']=False
if defined(artist)==False:
results['artist']=False
results['title']=title
return results
except eyeD3.tag.GenreException as e:
message="Problem while processing genre in %s \n" % path
genreLog.write(message)
statusLog.write("Problem with parsing tag\n")
badFiles=badFiles+1
return False
except eyeD3.InvalidAudioFormatException as e:
message="Invalid file in %s \n" % path
invalidLog.write(message)
statusLog.write("Invalid file type \n")
badFiles=badFiles+1
return False
except AttributeError as e:
message="can't read tag for %s " % path + str(e) + "\n"
pathLog.write(message)
statusLog.write("Attribute error\n")
badFiles=badFiles+1
return False
def addToDatabase(path,artist,title,genre,time):
global statusLog
if genre==None: genreId=1 # if we don't know genre set to unknown
elif Genre.objects.isGenreInDb(genre)==True: # if it already exsist
temp=Genre.objects.get(name=genre)
genreId=temp.id
else: #if it is not in db we have to create it
genreId=Genre.objects.addGenreToDb(genre)
#artist part
if Artist.objects.isArtistInDb(artist)==True:
artistId=Artist.objects.getArtistId(artist)
else:
artistId=Artist.objects.addArtist(artist)
if Mp3.objects.getMp3(artist,title): # file exsist in database already skip
statusLog.write("File already is in db abort\n\n")
return
mp3=Mp3(title=title,location=path,valid=True,length=time)
mp3.genre=Genre.objects.get(id=genreId)
mp3.artist=Artist.objects.get(id=artistId)
mp3.addedby=User.objects.get(id=1) # have to be added bot in users table
mp3.save()
statusLog.write("Saved into db")
#this function is called when found valid mp3 file
def FoundMp3(path):
global statusLog
statusLog.write("Processing %s \n" % path)
results=eyed3Fun(path)
if not results : return # if we have a whatever exception in id3 than skip
if not results['artist']: #if eye d3 can't get artist try to get using mutagen
temp=mutagen(path,"artist")
if defined(temp):
results['artist']=temp
if not results['title']: # the same as above but for title开发者_如何学JAVA
temp=mutagen(path,"title")
if defined(temp)==True:
results['title']=temp
#know we should have all info about mp3 so add it to database
if defined(results['artist']) and defined(results['title'])== True:
statusLog.write(str(results))
addToDatabase(path,results['artist'],results['title'],results['genre'],results['time'])
statusLog.write("\n************\n")
else:
statusLog.write("Can't get artist or title\n")
#script starts
mp3Num=0 # num of mp3 files scanned
temp=os.walk('folder with music')
for root, dirs, files in temp:
for i in files:
if os.path.join(root,i):
temp=os.path.splitext(i)
temp[1].lower()
if temp[1]=='.mp3':
mp3Path=os.path.join(root,i)
mp3Path=os.path.abspath(mp3Path)
FoundMp3(mp3Path)
mp3Num+=1
else:
print "Invalid path"
print " Found %d mp3 files" % mp3Num
print "Invalid files %d" % badFiles
And I have few problems which I can't solve. Sometimes it try do add a genre that is already in a database and second sometimes it crashing because of adding to database field genre with eyed3 instance not a valid id. I don't know how to solve these problems. I will appreciate any help. Thx in advance
精彩评论