def main(): if len(sys.argv) <= 3: usage() sys.exit(2) mtp = pymtp.MTP() mtp.connect() source = sys.argv[1] target = sys.argv[2] parent = int(sys.argv[3]) id3data = pyid3lib.tag(source) metadata = pymtp.LIBMTP_Track() if (hasattr(id3data, 'artist')): metadata.artist = id3data.artist if (hasattr(id3data, 'title')): metadata.title = id3data.title if (hasattr(id3data, 'album')): metadata.album = id3data.album if (hasattr(id3data, 'tracknum')): metadata.tracknumber = id3data.tracknum track_id = mtp.send_track_from_file(source, target, metadata, parent=parent) print "Created new track with ID: %s" % (track_id) mtp.disconnect()
def on_new_file(self, url, filepath, content_type): if content_type != "audio/mpeg": os.unlink(filepath) return id3 = pyid3lib.tag(filepath) try: tracknum, total = id3.tracknum except: try: album = id3.album if album in self.albumTrackCounter: self.albumTrackCounter[album] += 1 else: self.albumTrackCounter[album] = 1 tracknum = self.albumTrackCounter[album] except: self.counter += 1 tracknum = self.counter try: name = ("%02d-%s-%s" % (tracknum, id3.artist, id3.title)).replace(' ', '_') except: name = "unknown-%02d" % (self.counter) print "new file: %s" % (name) shutil.copy(filepath, '%s%s.mp3' % (self.targetPath, name))
def organiseMP3(tempFileName): try: id3tag = tag(tempFileName) try: title = id3tag.title except: title = "Unknown Title" try: artist = id3tag.artist except: artist = "Unknown Artist" try: album = id3tag.album except: album = "Unknown Album" fileName = "%s.mp3" % (title) songDir = os.path.join("/tmp", artist, album) try: os.makedirs(songDir) except OSError, e: if e.errno != errno.EEXIST: raise e target = os.path.join(songDir, fileName) shutil.move(tempFileName, target) print "Pwn'd an MP3 file: %s" % (target)
def organiseMP3(tempFileName): try: id3tag = tag(tempFileName) try: title = id3tag.title except: title = 'Unknown Title' try: artist = id3tag.artist except: artist = 'Unknown Artist' try: album = id3tag.album except: album = 'Unknown Album' fileName = "%s.mp3" % (title) songDir = os.path.join('/tmp', artist, album) try: os.makedirs(songDir) except OSError, e: if e.errno != errno.EEXIST: raise e target = os.path.join(songDir, fileName) shutil.move(tempFileName, target) print "Pwn'd an MP3 file: %s" % (target)
def info_from_mp3(filename): try: tags = pyid3lib.tag(filename) try: track = tags.track except AttributeError: track = find_track(filename) return { 'artist': getattr(tags, 'artist', None), 'album': getattr(tags, 'album', None), 'track': track, 'title': getattr(tags, 'title', None), 'encoding': 'mp3', } except AttributeError, e: raise BadFile, str(e)
def _findmusic(self, arg, dirname, fnames): cur = arg print "Dir: %s" % dirname songs = map(lambda x: "%s/%s" % (dirname, x), filter(lambda x: x[-4:] == ".mp3", fnames)) log = open("/tmp/id3log", "w") for s in songs: tag = pyid3lib.tag(s) binds = { "artist": getattr(tag, "artist", "Unknown"), "album": getattr(tag, "album", "Unknown"), "title": getattr(tag, "title", "Unknown"), "genre": getattr(tag, "genre", "Unknown"), "filename": s, } log.write("%s\n" % binds); log.flush() cur.execute("INSERT INTO music (artist, album, title, genre, filename) VALUES (:artist, :album, :title, :genre, :filename)", binds) log.close()
def get_tags(filename): audio_file = pyid3lib.tag(filename) return _dict_from_tags(audio_file)
def retrieve(table, path = "/PATH/", sSostAuthor = ''): import os, pyid3lib cur = getCon().cursor() cur.execute("select id, url, author, title, description from %s where state = 0" % table) curUpdate = getCon().cursor() for (id, url, author, title, description) in cur: # qui i replace servono ad evitare che si tenti di scrivere un file con nome # non valido (con dentro delle /, cosi` le sostituisco con dei -). Utile con # certe date. filename = ("%s/%s.mp3" % (path, title.replace("/", "-"))).replace("\"", "\\\"") # replace dovrebbe prevenire eventuali virgolette (NON PROVATO) # NOTA: non si puo` usare ', perche' sh non prevede caratteri di escape per correggere l' eventuale presenza di ' nel filename h = os.popen("wget -c -o /dev/stdout -O \"%s\".tmp.mp3 %s" % (filename, url)) completed = False notFound = False while 1: line = h.readline() if not line: break ## 416 Requested Range Not Satisfiable: cioe` file completato if re.match(".*416 Requested Range.*", line): completed = True if re.match(".*416 Unknown.*", line): # a volte dà questo messaggio d'errore... completed = True ## 404 Not Found: bisogna impostare la colonna della tabella che lo indica if re.match(".*404 Not Found.*", line): notFound = True ## le quadre servono per togliere l'"a capo", che verrebbe duplicato dal print line print line[:-1] err = h.close() if (not completed) and (not err): ## not completed: file scaricato ora; not err: file completo ## ricomprimi TODO: mettere una flag, non tutti i podcast potrebbero essere da ricomprimere cmd = "lame -h -v --vbr-new -V 8 -s 24 -q 0 \"%s\".tmp.mp3 \"%s\"" % (filename, filename) print cmd h = os.popen(cmd) h.close() ## aggiorna l'ID3 if not author: ## imposta autore se non c'e` nel podcast author = sSostAuthor x = pyid3lib.tag( filename ) x.artist = author x.title = title ## per il commento l'unico modo e` questo d = { 'frameid' : 'COMM', 'text' : description } x.append( d ) x.update() completed = True if notFound or completed: ## aggiorna lo stato del record: non si trova piu`, non scaricarlo query = "update %s set state = 1 where id = '%s'" % (table, id) print "aggiorna tabella" curUpdate.execute(query) getCon().commit()
#!/usr/bin/env python import os import pyid3lib for root, dirs, files in os.walk('/home/jonojono/Desktop/Music'): for f in files: if f.endswith('.MP3') or f.endswith('.mp3'): song = os.path.join(root, f) dir = os.path.dirname(song) dirlist = dir.split('/') id3info = pyid3lib.tag(song) if dirlist[-2] == "Music": id3info.artist = dirlist[-2] else: id3info.album = dirlist[-1] id3info.artist = dirlist[-2] id3info.update()
def tag(self): ''' The tag mapping from `self.pathname`. ''' import pyid3lib return pyid3lib.tag(self.pathname)
def __init__(self, file): self.filename = file if supported_File_Types.count(file[-3:]) < 1 and supported_File_Types.count(file[-4:]) < 1: raise FileNotSupported, file + ' is not of supported type' if file[-4:] == '.mp3': self.type = 1 # try: self.tag = pyid3lib.tag( file ) # except eyeD3.tag.InvalidAudioFormatException: # raise FileNotSupported, file + ' is not of supported type' try: self.album = self.tag.album except AttributeError: self.album = None try: self.artist = self.tag.artist except AttributeError: self.artist = None self.vendor = None try: self.title = self.tag.title except AttributeError: self.title = None try: self.tracktotal = self.tag.track[1] except AttributeError: self.tracktotal = None try: self.tracknumber = self.tag.track[0] except AttributeError: self.tracknumber = None try: self.genre = self.tag[self.tag.index('TCON')]['text'] except ValueError: self.genre = None try: self.date = self.tag.year except AttributeError: self.date = None try: self.discnum = self.tag[self.tag.index('TPOS')]['text'] except ValueError: self.discnum = None try: self.comment = self.tag[self.tag.index('COMM')]['text'] except ValueError: self.comment = None if DEBUG == 1: for i in self.tag: print i elif file[-4:] == '.ogg': self.type = 2 try: self.tag = ogg.vorbis.VorbisFile(file) except ogg.vorbis.VorbisError: raise FileNotSupported, file + ' is not of supported type' values = self.tag.comment().as_dict() if DEBUG == 1: print values try: self.album = values['ALBUM'].pop() except KeyError: self.album = None try: self.artist = values['ARTIST'].pop() except KeyError: self.artist = None try: self.vendor = values['VENDOR'].pop() #? except KeyError: self.vendor = None try: self.title = values['TITLE'].pop() except KeyError: self.title = None try: self.tracktotal = values['TRACKTOTAL'].pop() except KeyError: self.tracktotal = None try: self.tracknumber = values['TRACKNUMBER'].pop() except KeyError: self.tracknumber = None try: self.genre = values['GENRE'].pop() except KeyError: self.genre = None try: self.discnum = values['DISCNUMBER'].pop() except KeyError: self.discnum = None try: self.date = values['DATE'].pop() except KeyError: self.date = None try: self.comment = values['DESCRIPTION'].pop() except KeyError: self.comment = None elif file[-5:] == '.flac': self.type = 3 # MUCH of the following is taken from the python-flac example code # create a chain chain = metadata.Chain() chain.read(file) # get iterator, init it = metadata.Iterator() it.init(chain) while 1: if it.get_block_type() == metadata.VORBIS_COMMENT: block = it.get_block() vc = metadata.VorbisComment(block) break if not it.next(): break if vc: if DEBUG == 1: for c in vc.comments: print c try: self.album = vc.comments['ALBUM'] except KeyError: self.album = None try: self.artist = vc.comments['ARTIST'] except KeyError: self.artist = None try: self.vendor = vc.comments['VENDOR'] except KeyError: self.vendor = None try: self.title = vc.comments['TITLE'] except KeyError: self.title = None try: self.tracktotal = vc.comments['TRACKTOTAL'] except KeyError: self.tracktotal = None try: self.tracknumber = vc.comments['TRACKNUMBER'] except KeyError: self.tracknumber = None try: self.genre = vc.comments['GENRE'] except KeyError: self.genre = None try: self.discnum = vc.comments['DISCNUMBER'] except KeyError: self.discnum = None try: self.date = vc.comments['DATE'] except KeyError: self.date = None try: self.comment = vc.comments['DESCRIPTION'] except KeyError: self.comment = None self.chain = chain self.vc = vc
def set_info_mp3(filename, updating, data): tags = pyid3lib.tag(filename) for key, before, after in updating: setattr(tags, key, data[key]) tags.update()