def AudioFileFilter(f, filter_type=None): if filter_type: filter_start = filter_type.split('/')[0] else: filter_start = filter_type if os.path.isdir(f): ftype = self.DIRECTORY elif eyeD3.isMp3File(f): ftype = self.AUDIO elif os.path.splitext(f)[1].lower() in PLAYLISTS: ftype = self.PLAYLIST elif os.path.splitext(f)[1].lower() in TRANSCODE: ftype = self.AUDIO else: ftype = False if filter_start == self.AUDIO: if ftype == self.AUDIO: return ftype else: return False else: return ftype
def get_play_time(path): if eyeD3.isMp3File(path): audioFile = eyeD3.Mp3AudioFile(path) tag = audioFile.getTag() return audioFile.getPlayTime() else: return 0
def __filter_and_store_file(self, fpath): ''' Test whether file is suitable, read it's tags and store information. @type fpath: string @param fpath: path of file to be tested ''' tH = taghandler.TagHandler(self.__settings) # this is the data structure which holds information of file file = { 'path': fpath, 'artist': '', 'track': '', 'album': '', 'lyrics': '', 'order_number': None, 'modified': False } if not eyeD3.isMp3File(file['path']): self.__ignored_files_count += 1 return False else: tH.set_MP3_tags(file['path']) (file['artist'], file['track'], file['album'], file['lyrics'], file['order_number']) = tH.get_MP3_tags() if self.__settings['force'] is False and bool(file['lyrics']): return False else: self.__file_container.append(file) self.__added_files_count += 1
def __init__(self, filepath=None): if filepath == None: self.path = "Uknown" self.artist = "Uknown" self.title = "Uknown" self.album = "Uknown" self.length = "Uknown" self.genre = "Uknown" return self.path = filepath if eyeD3.isMp3File(filepath): audioFile = eyeD3.Mp3AudioFile(filepath) tag = audioFile.getTag() if tag == None: self.artist = "Uknown" self.title = "Uknown" self.album = "Uknown" self.length = audioFile.getPlayTime() self.genre = "Uknown" else: self.artist = tag.getArtist() if self.artist.strip() == "": self.artist = "Uknown" self.title = tag.getTitle() if self.title.strip() == "": self.title = "Uknown" self.album = tag.getAlbum() if self.album.strip() == "": self.album = "Uknown" self.length = audioFile.getPlayTime() self.genre = tag.getGenre()
def from_file(self, filename): """ Generate entry from a mp3 file @param filename: The file name relative to the collection path """ fullname = os.path.join(self.collection_path, filename) if eyeD3.isMp3File(fullname): audioFile = eyeD3.Mp3AudioFile(fullname) tag = audioFile.getTag() if tag: self.meta["Error"] = None self.meta["Album"] = tag.getAlbum().encode("utf-8") self.meta["Artist"] = tag.getArtist().encode("utf-8") self.meta["DiscNum"] = tag.getDiscNum()[0] self.meta["DiscNumMax"] = tag.getDiscNum()[1] try: if tag.getGenre(): self.meta["Genre"] = tag.getGenre().getName().encode("utf-8") except eyeD3.tag.GenreException: self.meta["Error"] = "Broken Genre" pass # Genre string cannot be parsed with '^([A-Z 0-9+/\-\|!&'\.]+)([,;|][A-Z 0-9+/\-\|!&'\.]+)*$': Hörbuch für Kinder self.meta["Title"] = tag.getTitle().encode("utf-8") #self.meta["Images"] = tag.getImages() self.meta["TrackNum"] = tag.getTrackNum()[0] self.meta["TrackNumMax"] = tag.getTrackNum()[1] #self.meta["Urls"] = tag.getURLs() self.meta["Year"] = tag.getYear() #self.meta["FileIDs"] = tag.getUniqueFileIDs() self.meta["Filename"] = filename
def __init__(self, path): if not os.path.isfile(path) and eyeD3.isMp3File(path): raise IOError(path) self.audio_file = eyeD3.Mp3AudioFile(path) self.tag = self.audio_file.getTag() self.mod_time = os.stat(path)[stat.ST_MTIME] self.path = path
def check_mp3_filename(mp3): "Check if the title, album and artist are present in the filename" if not eyeD3.isMp3File(mp3): print "---ERROR: %s is not a valid MP3" % mp3 return mp3file = None mp3file = eyeD3.Mp3AudioFile(mp3) tag = mp3file.getTag() if not tag: print "---ERROR processing %s" % mp3 return title = tag.getTitle().replace('/', safechar) album = tag.getAlbum().replace('/', safechar) artist = tag.getArtist().replace('/', safechar) #Make filename safe: for unsafe in unsafechars: title = title.replace(unsafe, safechar) album = album.replace(unsafe, safechar) artist = artist.replace(unsafe, safechar) title = re.sub('\.+$', '', title) album = re.sub('\.+$', '', album) artist = re.sub('\.+$', '', artist) filename = os.path.realpath(mp3) try: #if artist and filename.find(artist) == -1: print "Check %s: %s" % (filename, artist) if artist and (filename.find(artist) == -1 and (not artist.startswith("The ") or filename.find(artist[4:] + ", The") == -1)): print "Check %s: %s" % (filename, artist) if album and filename.find(album) == -1: print "Check %s: %s - %s" % (filename, artist, album) if title and filename.find(title) == -1: print "Check %s: %s - %s - %s" % (filename, artist, album, title) except: print "ERROR trying to display", mp3
def processDir(dir): def processEntry(): tag = eyeD3.Tag() try: if not tag.link(fullpath): print "something wrong with file " + fullpath return except: print fullpath + ": error, may be tags corrupted" return newTitle = entry.partition('.')[0] tag.setTitle(newTitle) tag.update() printOutput("%s: updated, new title is %s" % (fullpath, newTitle)) if os.path.isfile(dir): entriesList = [dir] else: entriesList = os.listdir(dir) for entry in entriesList: fullpath = os.path.join(dir, entry) if (os.path.isfile(fullpath) and eyeD3.isMp3File(fullpath)): processEntry() elif os.path.isdir(fullpath): processDir(fullpath) else: printOutput(fullpath + ": skipped")
def AudioFileFilter(f, filter_type=None): if filter_type: filter_start = filter_type.split("/")[0] else: filter_start = filter_type if os.path.isdir(f): ftype = self.DIRECTORY elif eyeD3.isMp3File(f): ftype = self.AUDIO elif os.path.splitext(f)[1].lower() in PLAYLISTS: ftype = self.PLAYLIST elif os.path.splitext(f)[1].lower() in TRANSCODE: ftype = self.AUDIO else: ftype = False if filter_start == self.AUDIO: if ftype == self.AUDIO: return ftype else: return False else: return ftype
def upload_file(request): logging.debug('Upload file 1') if request.method == 'POST': logging.debug('Upload file 2') form = UploadMp3FileForm(request.POST, request.FILES) logging.debug('upload'+str(form.errors)) if form.is_valid(): file_path = handle_upload_mp3file(request.FILES['mp3_file']) # Determen the play time of the uploaded mp3 import eyeD3 if eyeD3.isMp3File(file_path): logging.debug('eyeD3 %s' % file_path) audio_file = eyeD3.Mp3AudioFile(file_path) duration = audio_file.getPlayTime() song = Song( title=form.cleaned_data['title'], duration=duration, file_path=file_path) song.save() return HttpResponseRedirect(reverse('player-index')) else: # return error: The uploaded file is not a mp3 return HttpResponseRedirect(reverse('player-index')) else: form = UploadMp3FileForm() return HttpResponseRedirect(reverse('player-index'))
def getNumFiles(self): count = long(0) for (root, dirs, files) in os.walk(self.config.root): for f in files: f = os.path.abspath(root + os.sep + f) if not self._isExcluded(f) and eyeD3.isMp3File(f): count += 1 return count
def eyeD3parse(entry): if eyeD3.isMp3File(entry['location'].encode('utf8')): try: mp3 = eyeD3.Mp3AudioFile(entry['location'].encode('utf8')) entry['mp3'] = {} entry['mp3']['parser'] = 'eyeD3' entry['mp3']['vbr'], entry['mp3']['bitrate'] = mp3.getBitRate() entry['mp3']['freq'] = mp3.getSampleFreq() entry['mp3']['length'] = mp3.getPlayTime() if mp3.tag: if mp3.tag.getArtist(): entry['mp3']['artist'] = mp3.tag.getArtist() if mp3.tag.getTitle(): entry['mp3']['title'] = mp3.tag.getTitle() if mp3.tag.getAlbum(): entry['mp3']['album'] = mp3.tag.getAlbum() if mp3.tag.getYear(): entry['mp3']['year'] = mp3.tag.getYear() if mp3.tag.getTrackNum(): entry['mp3']['track'] = mp3.tag.getTrackNum() if mp3.tag.getDiscNum(): entry['mp3']['disc'] = mp3.tag.getDiscNum() if mp3.tag.getVersion(): entry['mp3']['version'] = mp3.tag.getVersion() if mp3.tag.getVersionStr(): entry['mp3']['versionstring'] = mp3.tag.getVersionStr() try: if mp3.tag.getBPM(): entry['mp3']['bpm'] = mp3.tag.getBPM() except ValueError: pass if mp3.tag.getPublisher(): entry['mp3']['publiser'] = mp3.tag.getPublisher() if mp3.tag.getDate(): entry['mp3']['date'] = map(lambda x: x.getDate(), mp3.tag.getDate()) if mp3.tag.getComments(): entry['mp3']['comments'] = map(lambda x: x.__unicode__(), mp3.tag.getComments()) if mp3.tag.getLyrics(): entry['mp3']['lyrics'] = map(lambda x: x.__unicode__(), mp3.tag.getLyrics()) if mp3.tag.getUserTextFrames(): entry['mp3']['usertext'] = map(lambda x: x.__unicode__(), mp3.tag.getUserTextFrames()) except: print strftime("[%Y-%m-%d %H:%M:%S] " ) + 'eyeD3 Error with ' + entry['location'].encode( 'utf8') + ' ', sys.exc_info() return entry
def is_mp3(target): """ Return true if `target` is an mp3 target :param target: file to test """ try: t = get_filename(target) target = t except: pass return eyeD3.isMp3File(target)
def set_MP3_tags(self, file): ''' Reads and stores MP3 tags (artist, track, lyrics). @type file: string @param file: name of tagged MP3 file to read tags from ''' if eyeD3.isMp3File(file): tag = eyeD3.Tag() tag.link(file) self.artist = tag.getArtist(eyeD3.ARTIST_FID) self.track = tag.getTitle() self.lyrics = self.get_lyrics_from_tag(tag) self.album = tag.getAlbum() self.order_number = tag.getTrackNum()
def main(all_dirs): t = eyeD3.Tag() for dir in all_dirs: for root, dirs, files in os.walk(dir): print "===>", root for f in files: fp = os.path.join(root, f) if eyeD3.isMp3File(fp): t.link(fp, eyeD3.ID3_V2) t.frames.removeFramesByID('TPE2') t.frames.removeFramesByID('TDAT') t.frames.removeFramesByID('TPUB') t.update(eyeD3.ID3_V2_3) else: print f
def save(self, *args, **kwargs): self.file_size = self.file.size super(Song, self).save(*args, **kwargs) file_path = os.path.join(settings.MEDIA_ROOT, self.file.name) if eyeD3.isMp3File(file_path): audioFile = eyeD3.Mp3AudioFile(file_path) self.duration = audioFile.getPlayTime() tag = audioFile.getTag() self.artist = tag.getArtist() self.album = tag.getAlbum() self.track_number = tag.getTrackNum() super(Song, self).save(*args, **kwargs)
def scan_folder(path): artists_list = [] for root, dirs, files in os.walk(path): for name in files: filename = os.path.join(root, name) if os.path.isfile(filename) and eyeD3.isMp3File(filename): tag = eyeD3.Tag() try: tag.link(filename) if tag.getArtist() not in artists_list: artists_list.append(tag.getArtist()) except : pass return artists_list
def main(): rss = PyRSS2Gen.RSS2( title = "Assorted Podcasts", link = baseUrl, description = "Just a bunch of MP3s in a directory somewhere.", lastBuildDate = datetime.now(), items = [] ) for file in os.listdir(path): if not eyeD3.isMp3File(file): continue; rss.items.append(buildRssItem(file)) rss.write_xml(sys.stdout)
def eyeD3parse(entry): if eyeD3.isMp3File(entry['location'].encode('utf8')): try: mp3 = eyeD3.Mp3AudioFile(entry['location'].encode('utf8')) entry['mp3'] = {} entry['mp3']['parser'] = 'eyeD3' entry['mp3']['vbr'], entry['mp3']['bitrate'] = mp3.getBitRate() entry['mp3']['freq'] = mp3.getSampleFreq() entry['mp3']['length'] = mp3.getPlayTime() if mp3.tag: if mp3.tag.getArtist(): entry['mp3']['artist'] = mp3.tag.getArtist() if mp3.tag.getTitle(): entry['mp3']['title'] = mp3.tag.getTitle() if mp3.tag.getAlbum(): entry['mp3']['album'] = mp3.tag.getAlbum() if mp3.tag.getYear(): entry['mp3']['year'] = mp3.tag.getYear() if mp3.tag.getTrackNum(): entry['mp3']['track'] = mp3.tag.getTrackNum() if mp3.tag.getDiscNum(): entry['mp3']['disc'] = mp3.tag.getDiscNum() if mp3.tag.getVersion(): entry['mp3']['version'] = mp3.tag.getVersion() if mp3.tag.getVersionStr(): entry['mp3']['versionstring'] = mp3.tag.getVersionStr() try: if mp3.tag.getBPM(): entry['mp3']['bpm'] = mp3.tag.getBPM() except ValueError: pass if mp3.tag.getPublisher(): entry['mp3']['publiser'] = mp3.tag.getPublisher() if mp3.tag.getDate(): entry['mp3']['date'] = map(lambda x: x.getDate(), mp3.tag.getDate()) if mp3.tag.getComments(): entry['mp3']['comments'] = map(lambda x: x.__unicode__(), mp3.tag.getComments()) if mp3.tag.getLyrics(): entry['mp3']['lyrics'] = map(lambda x: x.__unicode__(), mp3.tag.getLyrics()) if mp3.tag.getUserTextFrames(): entry['mp3']['usertext'] = map(lambda x: x.__unicode__(), mp3.tag.getUserTextFrames()) except: print strftime("[%Y-%m-%d %H:%M:%S] ") + 'eyeD3 Error with ' + entry['location'].encode('utf8') + ' ', sys.exc_info() return entry
def files(self): for (root, dirs, files) in os.walk(self.config.root): for f in files: f = os.path.abspath(root + os.sep + f) if not self._isExcluded(f) and eyeD3.isMp3File(f): try: af = ArchiveFile(f) if not af.tag: self.sync_log.warn("Missing tag '%s'" % f) continue except (eyeD3.InvalidAudioFormatException, eyeD3.TagException), ex: if isinstance(ex, eyeD3.InvalidAudioFormatException): self.sync_log.warn("Bad AUDIO '%s'" % (str(ex))) elif isinstance(ex, eyeD3.TagException): self.sync_log.warn("Bad TAG '%s'" % (str(ex))) continue yield af
def replace_music_eyed3(name, path, newname, newpath): """ Pattern replace for mp3 """ file = get_new_path(name, path) if eyeD3.isMp3File(file): try: audioFile = eyeD3.Mp3AudioFile(file, eyeD3.ID3_ANY_VERSION) tag = audioFile.getTag() except Exception, e: print "ERROR eyeD3:", e newpath = get_new_path('', path) return '', unicode(newpath) try: artist = clean_metadata(tag.getArtist()) except Exception, e: print "ERROR eyeD3:", e artist = None
def extract_image(self, filename): """extract image from the podcast file""" imagefile = None try: if eyeD3.isMp3File(filename): tag = eyeD3.Mp3AudioFile(filename).getTag() images = tag.getImages() if images: tempdir = tempfile.gettempdir() img = images[0] imagefile = img.getDefaultFileName() img.writeFile(path=tempdir, name=imagefile) imagefile = "%s/%s" % (tempdir, imagefile) else: logger.info(u"No image found in %s" % filename) except: pass return imagefile
def __extract_image(self, filename): """ extract image from the podcast file """ imagefile = None try: if eyeD3.isMp3File(filename): tag = eyeD3.Mp3AudioFile(filename).getTag() images = tag.getImages() if images: tempdir = tempfile.gettempdir() img = images[0] imagefile = img.getDefaultFileName() img.writeFile(path=tempdir, name=imagefile) imagefile = "%s/%s" % (tempdir, imagefile) else: log(u'No image found in %s' % filename) except: pass return imagefile
def analyze(self, artist="", genre=""): print "Analysing '%s'" % self.__filename if not eyeD3.isMp3File(self.__filename): raise Exception, "File is not a Mp3 file" # get __old_tags self.retrieveTags() # try to set the __new_tags searched = self.__regex.search(self.__filename) if not searched: # couldn't get __new_tags raise Exception, "Couldn't guess tags through filepath" d = searched.groupdict() # converting d to utf8 before storing in __new_tags self.__new_tags = {} for key in d.iterkeys(): if key == 'Year': # if unicode the isUpdatable will fail the comparison self.__new_tags[key] = d[key] if d[key] else "" else: # to unicode self.__new_tags[key] = d[key].decode("utf8") if d[key] else "" # but we still miss the genre genre_obj = eyeD3.Genre() # parsing it may throw eyeD3.GenreException. Let it be propagated if genre: genre_obj.parse(genre) # genre must be str, not unicode (setGenre requirement) self.__new_tags["Genre"] = genre else: genre_obj.parse(self.__new_tags["Genre"]) # can't handle unicode... # Also my genres are comma separated, fix it g = str(self.__new_tags["Genre"]) g = g.split(', ') g.reverse() self.__new_tags["Genre"] = ' '.join(g) if artist: self.__new_tags["Artist"] = artist
def read(self): """ Read id3 tags stored in mp3 file. Tags are restricted to the subset configured in the constructor. Returns a dict. """ if eyeD3.isMp3File(str(self.filename)): logger.debug("File is an mp3") self.tagobject = eyeD3.Tag() self.tagobject.link(str(self.filename)) self.tagobject.setVersion(eyeD3.ID3_V2_3) else: logger.debug("File is not an mp3") raise IOError, "can't ID3 tag %s" % self.filename tagdict = {} for tag in self.taglist: cmd = "content = self.tagobject.get%s()" % str(tag) try: exec(cmd) tagdict[tag] = content logger.debug("Found tag: %s = %s" % (tag, content)) except: print "id3 comments read",e return tagdict
# remember already downloaded cover images from last.fm # it is also only necessary to download the cover for at least one file of every album coverDictionary = {"artistAndAlbum" : "path"} # add every musicfile with id3tag information to db # unique track id for every song starting with zero id = 0 for file in fileList : tag = eyeD3.Tag() try: tag.link(file) if eyeD3.isMp3File(file): audioFile = eyeD3.Mp3AudioFile(file) albumartpath = "" # prevent that empty tagged music files get into the db if tag.getArtist() == "" or tag.getAlbum() == "" or tag.getTitle() == "" : continue # get album cover path and copy all cover images to webserver image folder illegalChars = re.compile(r'[\/:*?"<>| ]+',re.U) for coverpath in coverArtList : if os.path.dirname(file) == os.path.split(coverpath)[0] : albumartpath = "images/" + illegalChars.sub(' ',tag.getArtist()) +"_" + illegalChars.sub(' ',tag.getAlbum()) +".jpg" try: shutil.copy2(coverpath, albumartpath)
def handle_track(self, track, options): args = [] # Add the command line to read the source audio. args.append(track['input_cmdline']) # Pipe the source audio to this encoder. args.append('|') # Add arguments for MP3 encoder. args.append(qstr(self.cmd)) args.append(track.get('output_option')) args.append(track.get('output_option_tag')) args.append('-') args.append(qstr(track['output'])) # Execute the command. cmdline = args_to_string(args) ret = self.console.execute(cmdline) if ret != 0: return ret # Add Tag if not eyeD3.isMp3File(track['output'].encode(options.syscharset)): return -1 trknum = None tag = eyeD3.Tag() tag.link(track['output'].encode(options.syscharset)) if self.tagversion == 23: tag.setVersion(eyeD3.ID3_V2_3) elif self.tagversion == 24: tag.setVersion(eyeD3.ID3_V2_4) else: tag.setVersion(eyeD3.ID3_V2_3) try: charset = codecs.lookup(self.tagcharset).name if 'iso8859-1' in charset: tag.setTextEncoding(eyeD3.LATIN1_ENCODING) elif 'utf-8' in charset: tag.setTextEncoding(eyeD3.UTF_8_ENCODING) elif 'utf-16' in charset: tag.setTextEncoding(eyeD3.UTF_16_ENCODING) else: tag.setTextEncoding(eyeD3.LATIN1_ENCODING) except LookupError: tag.setTextEncoding(eyeD3.LATIN1_ENCODING) self.console.write("================ ID3 TAG (eyeD3) ================") if track.get('TITLE'): tag.setTitle(track.get('TITLE')) self.__formattag(track, 'TITLE') if track.get('ARTIST'): tag.setArtist(track.get('ARTIST')) self.__formattag(track, 'ARTIST') if track.get('ALBUM'): tag.setAlbum(track.get('ALBUM')) self.__formattag(track, 'ALBUM') if track.get('GENRE'): tag.setGenre(eyeD3.Genre(None,track.get('GENRE').encode(options.syscharset))) self.__formattag(track, 'GENRE') if track.get('DATE'): tag.setDate(track.get('DATE')) self.__formattag(track, 'DATE') if track.get('BPM'): tag.setBPM(track.get('BPM')) self.__formattag(track, 'BPM') if track.get('ALBUMARTIST'): tag.setArtist(track.get('ALBUMARTIST'), eyeD3.frames.BAND_FID) self.__formattag(track, 'ALBUMARTIST') if track.get('COMPOSER'): tag.setArtist(track.get('COMPOSER'), eyeD3.frames.COMPOSER_FID) self.__formattag(track, 'COMPOSER') if track.get('COPYRIGHT'): tag.setArtist(track.get('COPYRIGHT'), "TCOP") self.__formattag(track, 'COPYRIGHT') Nums = [None, None] if track.get('TRACKNUMBER'): trknum = track.get('TRACKNUMBER') Nums[0] = int(trknum) self.__formattag(track, 'TRACKNUMBER') if track.get('TOTALTRACKS'): Nums[1] = int(track.get('TOTALTRACKS')) self.__formattag(track, 'TOTALTRACKS') tag.setTrackNum(tuple(Nums)) Nums = [None, None] if track.get('DISCNUMBER'): Nums[0] = int(track.get('DISCNUMBER')) self.__formattag(track, 'DISCNUMBER') if track.get('TOTALDISCS'): Nums[1] = int(track.get('TOTALDISCS')) self.__formattag(track, 'TOTALDISCS') tag.setDiscNum(tuple(Nums)) if track.get('COMPILATION'): if bool(track['COMPILATION']): tag.setTextFrame("TCMP", "1") self.console.write(TAG_FMT % ('COPMPILATION', u"1")) if track.get('ALBUMART'): # Numbered cover img = track.get('ALBUMART') (fname, ext) = os.path.splitext(img) nimg = fname + "_" + trknum + ext if trknum is not None and os.path.isfile(nimg.encode(options.syscharset)): img = nimg elif not os.path.isfile(img.encode(options.syscharset)): img = None if img is not None: tag.addImage(eyeD3.ImageFrame.FRONT_COVER, img.encode(options.syscharset)) self.console.write(TAG_FMT % ('ALBUMART', img)) if track.get('COMMENT'): tag.removeComments() tag.addComment(track.get('COMMENT')) self.console.write(TAG_FMT % ('COMMENT', '\n' + track.get('COMMENT', u""))) self.console.write("=================================================") tag.update() return 0
def getInfo(hashMap): songs = [] albumHash = {} apiKey = "fa01536e58ada86f1e25b1313956739d" fingerprint = "" for key, value in hashMap.items(): newMap = {} #newMap[''] = rootQuery[''] try: response = urllib2.urlopen("http://ws.audioscrobbler.com/2.0/?format=json&method=track.getfingerprintmetadata&fingerprintid=" + str(value) + "&api_key=" + apiKey) theResp = json.loads(response.read()) print theResp, "\n\n" rootQuery = theResp['tracks']['track'][0] newMap['songName'] = rootQuery['name'] newMap['songMbid'] = rootQuery['mbid'] newMap['length'] = rootQuery['duration'] newMap['artist'] = rootQuery['artist']['name'] newMap['artistMbid'] = rootQuery['artist']['mbid'] albumHash[newMap['artist']] except KeyError: albumHash[newMap['artist']] = {} response = urllib2.urlopen("http://ws.audioscrobbler.com/2.0/?format=json&method=track.getInfo&mbid=" + newMap['songMbid'] + "&api_key=" + apiKey) theResp = json.loads(response.read()) #print theResp, "\n" rootQuery = theResp['track'] #newMap['album'] = rootQuery['album']['title'] newMap['albumMbid'] = "" newMap['trackNum'] = "" newMap['url'] = key newMap['fileType'] = "mp3" newMap['album'] = "" #newMap['name'] = rootQuery['name'] if eyeD3.isMp3File(key): audioFile = eyeD3.Mp3AudioFile(key) tag = audioFile.getTag() album = tag.getAlbum() #if(newMap['songName'].lower() == "merry-go-round"): # print "\n\n\n\n\n\n\n\n\n\n\n", newMap, "\n\n\n\n\n\n\n\n\n\n\n\n" try: try: newMap['album'] = rootQuery['album']['title'] newMap['albumMbid'] = rootQuery['album']['mbid'] newMap['trackNum'] = rootQuery['album']['@attr']['position'] albumHash[newMap['artist']][newMap['album']] = newMap['albumMbid'] except Exception: raise KeyError except KeyError: #print "In" try: response = urllib2.urlopen("http://ws.audioscrobbler.com/2.0/?format=json&method=album.getInfo&artist=" + newMap['artist'] + "&album=" + album + "&api_key=" + apiKey) theResp = json.loads(response.read()) rootQuery = theResp['album'] newMap['album'] = rootQuery['name'] newMap['albumMbid'] = rootQuery['mbid'] for item in rootQuery['tracks']['track']: if(item['name'] == newMap['songName']): newMap['trackNum'] = item['@attr']['rank'] #albumHash[newMap['artist']][newMap['album']] = newMap['albumMbid'] #try: #except KeyError: # albumHash[newMap['artist']][newMap['album']] = newMap['albumMbid'] except Exception: pass if(newMap['album'] == ""): newMap['album'] = album print newMap, "\n" songs.append(newMap) return [songs, albumHash]
def getEyeD3Info(current_dir, songs, logging): logging.debug("getEyeD3Info(" + current_dir + ", songs)") dir_contents = os.listdir(current_dir) to_return = {} to_return["songs"] = [] to_return["folders"] = [] # # Iterate over dir contents & generate 2 lists. music_list && dir_list # Then iterate over each of these lists. # For each music list, append to songs array. # For each dir list, call getEyeD3Info & append to list. (recursion) # subfolder_list = [] subfile_list = [] for x in dir_contents: x_full_path = current_dir + "/" + x if os.path.isdir(x_full_path): subfolder_list.append(x_full_path) #print("------- " + x) elif os.path.isfile(x_full_path) and not (x.startswith(".")) and eyeD3.isMp3File(x_full_path): subfile_list.append(x) # I know have a list of files and dirs. #sys.exit(1) # Now it"s time to do directories. This is where recursion will come in. for d in subfolder_list: folder = { "folder_name": d, "contents": getEyeD3Info(d, songs, logging) } to_return["folders"].append(folder) # Create a collection of song dictionaries. subfolder_song_list = [] for f in subfile_list: my_mp3 = MP3.MP3(current_dir + "/" + f, logging) try: my_mp3.getTagInfo() my_mp3.log_object_info() song = { "file_name": f, "artist" : my_mp3.artist, "album": my_mp3.album, "title": my_mp3.title, "genre": my_mp3.genre, "track": my_mp3.track_num } subfolder_song_list.append(song) except Exception, e: logging.exception ("This is the mp3 causing the error: " + (current_dir + "/" + f)) logging.exception(e)
def replace_music_eyed3(name, path, newname, newpath): """ Pattern replace for mp3 """ file = get_new_path(name, path) if eyeD3.isMp3File(file): try: audioFile = eyeD3.Mp3AudioFile(file, eyeD3.ID3_ANY_VERSION) tag = audioFile.getTag() except Exception as e: print("ERROR eyeD3:", e) newpath = get_new_path('', path) return '', str(newpath) try: artist = clean_metadata(tag.getArtist()) except Exception as e: print("ERROR eyeD3:", e) artist = None try: album = clean_metadata(tag.getAlbum()) except Exception as e: print("ERROR eyeD3:", e) album = None try: title = clean_metadata(tag.getTitle()) except Exception as e: print("ERROR eyeD3:", e) title = None try: track = clean_metadata(tag.getTrackNum()[0]) except Exception as e: print("ERROR eyeD3:", e) track = None try: trackt = clean_metadata(tag.getTrackNum()[1]) except Exception as e: print("ERROR eyeD3:", e) trackt = None try: genre = clean_metadata(tag.getGenre().getName()) except Exception as e: print("ERROR eyeD3:", e) genre = None try: year = clean_metadata(tag.getYear()) except Exception as e: print("ERROR eyeD3:", e) year = None if artist != None: newname = newname.replace('{artist}', artist) else: newname = newname.replace('{artist}', '') if album != None: newname = newname.replace('{album}', album) else: newname = newname.replace('{album}', '') if title != None: newname = newname.replace('{title}', title) else: newname = newname.replace('{title}', '') if track != None: newname = newname.replace('{track}', str(track)) else: newname = newname.replace('{track}', '') if trackt != None: newname = newname.replace('{tracktotal}', str(trackt)) else: newname = newname.replace('{tracktotal}', '') if genre != None: newname = newname.replace('{genre}', genre) else: newname = newname.replace('{genre}', '') if year != None: newname = newname.replace('{myear}', year) else: newname = newname.replace('{myear}', '') else: newname = newname.replace('{artist}', '') newname = newname.replace('{album}', '') newname = newname.replace('{title}', '') newname = newname.replace('{track}', '') newname = newname.replace('{tracktotal}', '') newname = newname.replace('{genre}', '') newname = newname.replace('{myear}', '') # Returns new name and path newpath = get_new_path(newname, path) return str(newname), str(newpath)
def handle_track(self, track, options): args = [] # Add the command line to read the source audio. args.append(track['input_cmdline']) # Pipe the source audio to this encoder. args.append('|') # Add arguments for MP3 encoder. args.append(qstr(self.cmd)) args.append(track.get('output_option')) args.append(track.get('output_option_tag')) args.append('-') args.append(qstr(track['output'])) # Execute the command. cmdline = args_to_string(args) ret = self.console.execute(cmdline) if ret != 0: return ret # Add Tag if not eyeD3.isMp3File(track['output'].encode(options.syscharset)): return -1 trknum = None tag = eyeD3.Tag() tag.link(track['output'].encode(options.syscharset)) if self.tagversion == 23: tag.setVersion(eyeD3.ID3_V2_3) elif self.tagversion == 24: tag.setVersion(eyeD3.ID3_V2_4) else: tag.setVersion(eyeD3.ID3_V2_3) try: charset = codecs.lookup(self.tagcharset).name if 'iso8859-1' in charset: tag.setTextEncoding(eyeD3.LATIN1_ENCODING) elif 'utf-8' in charset: tag.setTextEncoding(eyeD3.UTF_8_ENCODING) elif 'utf-16' in charset: tag.setTextEncoding(eyeD3.UTF_16_ENCODING) else: tag.setTextEncoding(eyeD3.LATIN1_ENCODING) except LookupError: tag.setTextEncoding(eyeD3.LATIN1_ENCODING) self.console.write("================ ID3 TAG (eyeD3) ================") if track.get('TITLE'): tag.setTitle(track.get('TITLE')) self.__formattag(track, 'TITLE') if track.get('ARTIST'): tag.setArtist(track.get('ARTIST')) self.__formattag(track, 'ARTIST') if track.get('ALBUM'): tag.setAlbum(track.get('ALBUM')) self.__formattag(track, 'ALBUM') if track.get('GENRE'): tag.setGenre( eyeD3.Genre(None, track.get('GENRE').encode(options.syscharset))) self.__formattag(track, 'GENRE') if track.get('DATE'): tag.setDate(track.get('DATE')) self.__formattag(track, 'DATE') if track.get('BPM'): tag.setBPM(track.get('BPM')) self.__formattag(track, 'BPM') if track.get('ALBUMARTIST'): tag.setArtist(track.get('ALBUMARTIST'), eyeD3.frames.BAND_FID) self.__formattag(track, 'ALBUMARTIST') if track.get('COMPOSER'): tag.setArtist(track.get('COMPOSER'), eyeD3.frames.COMPOSER_FID) self.__formattag(track, 'COMPOSER') if track.get('COPYRIGHT'): tag.setArtist(track.get('COPYRIGHT'), "TCOP") self.__formattag(track, 'COPYRIGHT') Nums = [None, None] if track.get('TRACKNUMBER'): trknum = track.get('TRACKNUMBER') Nums[0] = int(trknum) self.__formattag(track, 'TRACKNUMBER') if track.get('TOTALTRACKS'): Nums[1] = int(track.get('TOTALTRACKS')) self.__formattag(track, 'TOTALTRACKS') tag.setTrackNum(tuple(Nums)) Nums = [None, None] if track.get('DISCNUMBER'): Nums[0] = int(track.get('DISCNUMBER')) self.__formattag(track, 'DISCNUMBER') if track.get('TOTALDISCS'): Nums[1] = int(track.get('TOTALDISCS')) self.__formattag(track, 'TOTALDISCS') tag.setDiscNum(tuple(Nums)) if track.get('COMPILATION'): if bool(track['COMPILATION']): tag.setTextFrame("TCMP", "1") self.console.write(TAG_FMT % ('COPMPILATION', u"1")) if track.get('ALBUMART'): # Numbered cover img = track.get('ALBUMART') (fname, ext) = os.path.splitext(img) nimg = fname + "_" + trknum + ext if trknum is not None and os.path.isfile( nimg.encode(options.syscharset)): img = nimg elif not os.path.isfile(img.encode(options.syscharset)): img = None if img is not None: tag.addImage(eyeD3.ImageFrame.FRONT_COVER, img.encode(options.syscharset)) self.console.write(TAG_FMT % ('ALBUMART', img)) if track.get('COMMENT'): tag.removeComments() tag.addComment(track.get('COMMENT')) self.console.write(TAG_FMT % ('COMMENT', '\n' + track.get('COMMENT', u""))) self.console.write("=================================================") tag.update() return 0
def fix_mp3_case(mp3, prompt, rename, renamepattern): "Uses eyeD3 to extract the title, album and artist names and correct their capitalisation" updated = False if not eyeD3.isMp3File(mp3): corruptfiles.append(mp3) print "---ERROR: %s is not a valid MP3" % mp3 return mp3file = None try: mp3file = eyeD3.Mp3AudioFile(mp3) except: corruptfiles.append(mp3) print "---ERROR processing %s" % mp3 return tag = mp3file.getTag() if not tag: corruptfiles.append(mp3) print "---ERROR processing %s" % mp3 return title = tag.getTitle() album = tag.getAlbum() artist = tag.getArtist() fixedtitle = fixcase(title) fixedalbum = fixcase(album) fixedartist = fixcase(artist) if title != fixedtitle or album != fixedalbum or artist != fixedartist: print 'About to alter "%s" as follows:' % mp3 if title != fixedtitle: print ' Title: "%s"\n ==> "%s"' % (title, fixedtitle) if album != fixedalbum: print ' Album: "%s"\n ==> "%s"' % (album, fixedalbum) if artist != fixedartist: print 'Artist: "%s"\n ==> "%s"' % (artist, fixedartist) if not prompt or raw_input("Is that OK? ").lower().find('y') == 0: tag.setTitle(fixedtitle) tag.setAlbum(fixedalbum) tag.setArtist(fixedartist) tag.update() updated = True if rename: renamedpatternmatched = False for renpat in renamepattern: #eyeD3 replaces / with -, but I want it replaced with _ like Amarok: tag.setTitle(tag.getTitle().replace('/', safechar)) tag.setAlbum(tag.getAlbum().replace('/', safechar)) tag.setArtist(tag.getArtist().replace('/', safechar)) renamestr = tag.tagToString(renpat) if renamestr.find("%") == -1: renamedpatternmatched = True #Make filename safe: for unsafe in unsafechars: renamestr = renamestr.replace(unsafe, safechar) #Remove trailing dots if present to mimic amarok renamestr = re.sub('\.+$', '', renamestr) filename = os.path.basename(mp3file.fileName) if filename != renamestr + ".mp3": try: sys.stdout.write( 'ABOUT TO RENAME: "%s"\n TO: "%s"' % (filename, renamestr + ".mp3")) except: sys.stdout.write( 'ABOUT TO RENAME: "%s"\n TO: "%r" (Note: Unprintable characters should not cause any issues during rename)' % (filename, renamestr + ".mp3")) if not prompt or raw_input(", OK? ").lower().find( 'y') == 0: if not prompt: print mp3file.rename(renamestr, sys.getfilesystemencoding()) if updated: #Look for changed values that were not included in the rename: if title != fixedtitle and renpat.find("%t") == -1: temp = "FROM: %s - %s - %s\n ===> %s - %s - %s" % ( artist, album, title, fixedartist, fixedalbum, fixedtitle) if temp not in warntitle: warntitle.append(temp) if album != fixedalbum and renpat.find("%a") == -1: temp = "FROM: %s - %s\n ===> %s - %s" % ( artist, album, fixedartist, fixedalbum) if temp not in warnalbum: warnalbum.append(temp) if artist != fixedartist and renpat.find("%A") == -1: temp = "FROM: %s\n ===> %s" % (artist, fixedartist) if temp not in warnartist: warnartist.append(temp) break if not renamedpatternmatched: warnrename.append( "FROM: %s - %s - %s\n ===> %s - %s - %s" % (artist, album, title, fixedartist, fixedalbum, fixedtitle))
def fix_mp3_case(mp3, prompt, rename, renamepattern): "Uses eyeD3 to extract the title, album and artist names and correct their capitalisation" updated = False if not eyeD3.isMp3File(mp3): corruptfiles.append(mp3) print "---ERROR: %s is not a valid MP3" % mp3 return mp3file = None try: mp3file = eyeD3.Mp3AudioFile(mp3) except: corruptfiles.append(mp3) print "---ERROR processing %s" % mp3 return tag = mp3file.getTag() if not tag: corruptfiles.append(mp3) print "---ERROR processing %s" % mp3 return title = tag.getTitle() album = tag.getAlbum() artist = tag.getArtist() fixedtitle = fixcase(title) fixedalbum = fixcase(album) fixedartist = fixcase(artist) if title != fixedtitle or album != fixedalbum or artist != fixedartist: print 'About to alter "%s" as follows:' % mp3 if title != fixedtitle: print ' Title: "%s"\n ==> "%s"' % (title, fixedtitle) if album != fixedalbum: print ' Album: "%s"\n ==> "%s"' % (album, fixedalbum) if artist != fixedartist: print 'Artist: "%s"\n ==> "%s"' % (artist, fixedartist) if not prompt or raw_input("Is that OK? ").lower().find('y') == 0: tag.setTitle(fixedtitle) tag.setAlbum(fixedalbum) tag.setArtist(fixedartist) tag.update() updated = True if rename: renamedpatternmatched = False for renpat in renamepattern: #eyeD3 replaces / with -, but I want it replaced with _ like Amarok: tag.setTitle(tag.getTitle().replace('/', safechar)) tag.setAlbum(tag.getAlbum().replace('/', safechar)) tag.setArtist(tag.getArtist().replace('/', safechar)) renamestr = tag.tagToString(renpat) if renamestr.find("%") == -1: renamedpatternmatched = True #Make filename safe: for unsafe in unsafechars: renamestr = renamestr.replace(unsafe, safechar) #Remove trailing dots if present to mimic amarok renamestr = re.sub('\.+$', '', renamestr) filename = os.path.basename(mp3file.fileName) if filename != renamestr + ".mp3": try: sys.stdout.write('ABOUT TO RENAME: "%s"\n TO: "%s"' % (filename, renamestr + ".mp3")) except: sys.stdout.write('ABOUT TO RENAME: "%s"\n TO: "%r" (Note: Unprintable characters should not cause any issues during rename)' % (filename, renamestr + ".mp3")) if not prompt or raw_input(", OK? ").lower().find('y') == 0: if not prompt: print mp3file.rename(renamestr, sys.getfilesystemencoding()) if updated: #Look for changed values that were not included in the rename: if title != fixedtitle and renpat.find("%t") == -1: temp = "FROM: %s - %s - %s\n ===> %s - %s - %s" % (artist, album, title, fixedartist, fixedalbum, fixedtitle) if temp not in warntitle: warntitle.append(temp) if album != fixedalbum and renpat.find("%a") == -1: temp = "FROM: %s - %s\n ===> %s - %s" % (artist, album, fixedartist, fixedalbum) if temp not in warnalbum: warnalbum.append(temp) if artist != fixedartist and renpat.find("%A") == -1: temp = "FROM: %s\n ===> %s" % (artist, fixedartist) if temp not in warnartist: warnartist.append(temp) break if not renamedpatternmatched: warnrename.append("FROM: %s - %s - %s\n ===> %s - %s - %s" % (artist, album, title, fixedartist, fixedalbum, fixedtitle))
import eyeD3 import sys import os import glob if __name__ == "__main__": if len(sys.argv) != 3: print >>sys.stderr, "Usage: mp3name2tag <mp3_directory> index(ex[0:3])" sys.exit() if os.path.isdir(sys.argv[1]) == False: print >>sys.stderr, "Usage: mp3name2tag <mp3_directory> index" sys.exit() files = glob.glob(sys.argv[1] + os.sep + "*" ) mp3files = [ f for f in files if eyeD3.isMp3File(f) ] for mp3 in mp3files: try: mp3name = os.path.basename(mp3) tag = eyeD3.Tag() success = tag.link(mp3) if success == False: tag.header.setVersion(eyeD3.ID3_V2_3) trackNum = int(eval("mp3name"+sys.argv[2])) tag.setTrackNum((trackNum, trackNum)) tag.setDiscNum((trackNum, trackNum)) success = tag.update() if success == False: raise