def tags_win_update(self): current_tag = self.tags[self.tagnum] tag = tagpy.FileRef(current_tag['fullpath']).tag() # Update interface: for entry_name, entry in self.entries.items(): # Only retrieve info from the file if the info hasn't changed if not current_tag[entry_name + "-changed"]: current_tag[entry_name] = getattr(tag, entry_name, '') tag_value = current_tag[entry_name] if tag_value == 0: tag_value = '' try: entry.set_text(str(tag_value).strip()) except AttributeError: pass # Revert text color if this tag wasn't changed by the user if not current_tag[entry_name + "-changed"]: self.tags_win_entry_revert_color(entry) self.curr_mpdpath = GLib.filename_display_name(current_tag['mpdpath']) filename = self.curr_mpdpath if not self.use_mpdpaths: filename = os.path.basename(filename) self.file_label.set_text(filename) self.entries['title'].grab_focus() self.edit_window.set_title( _("Edit Tags - %s of %s") % (self.tagnum + 1, len(self.tags)))
def run(arquivo, extensao, saida, mode): a = tagpy.FileRef(arquivo) tag = a.tag() dirdst = setdirdst(tag, saida) if dirdst == 0: print_all(arquivo) return 0 filedst = setfiledst(tag, extensao) if filedst == 0: print_all() return 0 #print dirdst+filedst try: os.makedirs(dirdst) except: pass print_all(arquivo, dirdst, filedst, tag, extensao) if mode == 1: mover(dirdst, filedst, arquivo, tag, extensao) elif mode == 2: copiar(dirdst, filedst, arquivo, tag, extensao) else: pass
def getIntLength(fpath): "Get length of a music file via tagpy" filename = str(fpath) #tagfile = TagLib.FileRef(filename, True, TagLib.AudioProperties.Accurate) tagfile = tagpy.FileRef(filename) audioproperties = tagfile.audioProperties() if not audioproperties: raise NamingMuseError("failed to get audioproperties: broken file?") length = audioproperties.length # XXX: try various fallback methods if length == 0: print NamingMuseWarning("using fallback: getMP3Length(%s)" % filename) if fpath.getExt().lower() == ".mp3": length = getMP3Length(filename) # raise exception; or discid generation will fail # and user doesn't know why if length == 0: raise NamingMuseError("taglib audioproperties " \ "failed to get length of: %s" % filename) return length
def tags_win_response(self, window, response, tags, entries, entries_names): if response == gtk.RESPONSE_REJECT: self.tags_win_hide(window, None, tags) elif response == gtk.RESPONSE_ACCEPT: window.action_area.set_sensitive(False) while window.action_area.get_property("sensitive") or gtk.events_pending(): gtk.main_iteration() filetag = tagpy.FileRef(tags[self.tagnum]['fullpath']) tag = filetag.tag() # Set tag fields according to entry text for entry, field in zip(entries, entries_names): tag_value = entry.get_text().strip() if field in ('year', 'track'): if len(tag_value) == 0: tag_value = '0' tag_value = int(tag_value) if field is 'comment': if len(tag_value) == 0: tag_value = ' ' setattr(tag, field, tag_value) save_success = filetag.save() if not (save_success): # FIXME: was (save_success and self.conn and self.status): ui.show_msg(self.window, _("Unable to save tag to music file."), _("Edit Tags"), 'editTagsError', gtk.BUTTONS_CLOSE, response_cb=ui.dialog_destroy) if self.tags_next_tag(tags): # Next file: self.tags_win_update(window, tags, entries, entries_names) else: # No more (valid) files: self.tagnum = self.tagnum + 1 # To ensure we update the last file in tags_mpd_update self.tags_win_hide(window, None, tags)
def _indexFile(self, root, file): """ Index one track in redis based on id3 tags """ path = '%s/%s' % (root, file) try: try: f = tagpy.FileRef(path) except: return t = f.tag() try: p = f.audioProperties() length = p.length except: length = 0 trk = Track(path=path, title=t.title, album=t.album, artist=t.artist, year=t.year, genre=t.genre, length=length) trk.save() except: logging.exception("could not index file")
def GetAlbums(music_location): """Get a list of albums from the list of music""" # Get music files music_files = GetMusicFiles(music_location) # Initiate a list of albums albums = [] # Initiate a list of failed music files failed_files = [] # Loop through the music files, read their album info for file in music_files: music = tagpy.FileRef(file).tag() # Read the artist name try: artist = music.artist if artist == "": artist = None except AttributeError: # If the tag doesn't exist artist = None # Read the album name try: album = music.album if album == "": album = None except AttributeError: # If the tag doesn't exist album = None # If it isn't already in the albums db, add it if (artist, album) not in albums and None not in (artist, album): albums.append((artist, album)) elif None in (artist, album): failed_files.append(file) return albums, failed_files
def main(): """Main function""" if (len(sys.argv) == 2): print 3 * '*', sys.argv[1], 3 * '*' print file_ref = tagpy.FileRef(sys.argv[1]) tags = file_ref.tag() print "artist :", tags.artist print "album :", tags.album print "title :", tags.title print "track :", tags.track print "year :", tags.year print "genre :", tags.genre print "comment :", tags.comment audio_properties = file_ref.audioProperties() print "length :", audio_properties.length print "bitrate :", audio_properties.bitrate print "sample rate :", audio_properties.sampleRate print "channels :", audio_properties.channels
def tags_win_update(self, window, tags, entries, entries_names): current_tag = tags[self.tagnum] tag = tagpy.FileRef(current_tag['fullpath']).tag() # Update interface: for entry, entry_name in zip(entries, entries_names): # Only retrieve info from the file if the info hasn't changed if not current_tag[entry_name + "-changed"]: current_tag[entry_name] = getattr(tag, entry_name, '') tag_value = current_tag[entry_name] if tag_value == 0: tag_value = '' entry.set_text(str(tag_value).strip()) # Revert text color if this tag wasn't changed by the user if not current_tag[entry_name + "-changed"]: self.tags_win_entry_revert_color(entry) self.curr_mpdpath = gobject.filename_display_name( current_tag['mpdpath']) filename = self.curr_mpdpath if not self.use_mpdpaths: filename = os.path.basename(filename) self.filelabel.set_text(filename) entries[0].grab_focus() window.set_title( _("Edit Tags") + " - " + str(self.tagnum + 1) + " " + _("of") + " " + str(len(tags))) self.tags_win_set_sensitive(window.action_area)
def music_to_m4a(filename, tottracks=None, album_path=None, outfile=None, verbose=True): if not _can_convert_file(filename): raise ValueError("Error, cannot convert %s to m4a." % filename) tags = tagpy.FileRef(filename).tag() artist = tags.artist title = titlecase.titlecase(tags.title) trackno = tags.track # if outfile is None: outfile = '%s.%s.m4a' % (artist, title) exec_path = [ '/usr/bin/avconv', '-y', '-i', filename, '-map', '0:0', '-strict', 'experimental', '-aq', '400', outfile ] proc = subprocess.Popen(exec_path, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout_val, stderr_val = proc.communicate() if verbose: print stdout_val mp4tags = mutagen.mp4.MP4(outfile) mp4tags['\xa9nam'] = [ title, ] if tottracks is not None: if 'trkn' not in mp4tags.tags.keys(): mp4tags.tags['trkn'] = [ (trackno, tottracks), ] else: trkno, tottrks = max(mp4tags.tags['trkn']) if tottrks == 0: mp4tags.tags['trkn'] = [ (trackno, tottracks), ] else: if 'trkn' not in mp4tags.tags.keys(): mp4tags.tags['trkn'] = [ (trackno, 0), ] if album_path is not None: file_data = _get_file_data(album_path) fmttype = _get_file_type(file_data) if fmttype is not None: mp4tags.tags['covr'] = [ mutagen.mp4.MP4Cover(file_data, fmttype), ] mp4tags.save()
def __init__(self, archivo): ''' Constructor de Track param archivo La ruta y nombre del archivo de audio.''' self.archivo = archivo arch = tagpy.FileRef(self.archivo) my_tag = arch.tag() self.artista = my_tag.artist self.titulo = my_tag.title self.album = my_tag.album
def read_tags_using_tagpy(filename): fileref = tagpy.FileRef(filename) tag = fileref.tag() compilation = extract_compilation_flag_using_tagpy(fileref) tagdict = dict(title=tag.title, artist=tag.artist, album=tag.album, tracknum=tag.track, compilation=compilation) return tagdict
def tags_next_tag(self): # Returns true if next tag found (and self.tagnum is updated). # If no next tag found, returns False. while self.tagnum < len(self.tags) - 1: self.tagnum = self.tagnum + 1 if os.path.exists(self.tags[self.tagnum]['fullpath']): fileref = tagpy.FileRef(self.tags[self.tagnum]['fullpath']) if not fileref.isNull(): return True return False
def getAttributes(self, fileName, fileObject, fileStat, fileAttributes): try: useFileName = fileName if isinstance(fileName, unicode): useFileName = fileName.encode("utf-8") ref = tagpy.FileRef(useFileName) except ValueError: return None tags = ref.tag() title = tags.title album = tags.album artist = tags.artist genre = tags.genre track = tags.track year = tags.year data = fileAttributes data[u"class"] = u"audio" if title is not None and len(title) > 0: data[ATTR_GENERIC_TITLE] = safeEncode(title) if album is not None and len(album) > 0: data[ATTR_GENERIC_ALBUM] = safeEncode(album) if artist is not None and len(artist) > 0: data[ATTR_GENERIC_ARTIST] = safeEncode(artist) if genre is not None and len(genre) > 0: data[ATTR_GENERIC_GENRE] = safeEncode(genre) if track is not None and track > 0: data[u"audio/trackno"] = safeEncode(track) if year is not None and year > 0: data[ATTR_GENERIC_YEAR] = safeEncode(year) file = ref.file() if "xiphComment" in dir(file): xiph = file.xiphComment() fields = xiph.fieldListMap() if "DISCNUMBER" in fields: value = safeEncode(fields["DISCNUMBER"][0]) if len(value) > 0 and int(value) > 0: data[u"audio/discno"] = value if "TOTALDISCS" in fields: value = safeEncode(fields["TOTALDISCS"][0]) if len(value) > 0 and int(value) > 0: data[u"audio/totaldiscs"] = value if "TOTALTRACKS" in fields: value = safeEncode(fields["TOTALTRACKS"][0]) if len(value) > 0 and int(value) > 0: data[u"audio/totaltracks"] = value if "RATING:BANSHEE" in fields: value = safeEncode(fields["RATING:BANSHEE"][0]) if len(value) > 0: data[ATTR_GENERIC_RATING] = value return data
def read(self, filename): """ Reads tag info from 'filename' and saves a dictionary with artist, title and album strings. """ tag = tagpy.FileRef(filename).tag() d = {} d.update(location='file://' + urllib.quote(filename)) d.update(artist=tag.artist or "Unknown Artist") d.update(title=tag.title or "Unknown Title") d.update(album=tag.album or '') self.__dicts.append(d)
def save(self, force_insert=False, force_update=False): if type(self.filename).__name__ == 'unicode': self.filename = smart_str(self.filename) if not (access(str(self.filename), (F_OK or R_OK))): return ref = tagpy.FileRef(self.filename) tags = ref.tag() props = ref.audioProperties() #take care of the non-relational fields first self.title = tags.title self.year = tags.year self.length = props.length self.sample_rate = props.sampleRate self.bitrate = props.bitrate ext = path.splitext(self.filename) self.format = ext[len(ext) - 1] if not (tags.track): self.track = 1 else: self.track = tags.track # now take care of ForeignKeys a, created = Artist.objects.get_or_create(name=tags.artist) if (created): self.artist = a else: self.artist = a try: b = Album.objects.get(name=tags.album, artist=a) self.album = b except Album.DoesNotExist: try: b = Album.objects.get(name=tags.album) b.artist.add(a) b.save() except Album.DoesNotExist: b = Album.objects.create(name=tags.album) b.artist.add(a) b.save() self.album = b created = False a, created = Genre.objects.get_or_create(name=tags.genre) if (created): self.genre = a else: self.genre = a super(Song, self).save(force_insert, force_update)
def GetMusicFiles(music_location): """Get a list of music files in the location""" # Use the find unix command to get all files in the location all_files = os.popen('find %s' % music_location).read().split('\n') # Extract the music files from the list and put them into a new one music_files = [] for file in all_files: # Try opening with tagpy try: tagpy.FileRef(file) music_files.append(file) # If it fails, then it is not a music file except ValueError: pass return music_files
def load_files(self, loadpath): for dirpath, dirnames, filenames in os.walk(loadpath): filenames.sort() for filename in filenames: path = os.path.join(dirpath, filename) ext = os.path.splitext(path)[1] if ext in (".mp3", ".ogg"): print "Loading: %s" % path f = tagpy.FileRef(path) tag = f.tag() desc = { "title": tag.title, "album": tag.album, "artist": tag.artist, "genre": tag.genre } self.tracks[self._desc_to_tuple(desc)] = path self.conductor.touch_track(desc)
def main(): """Main function""" if (len(sys.argv) == 2): print 3 * '*', sys.argv[1], 3 * '*' print file_ref = tagpy.FileRef(sys.argv[1]) tags = file_ref.tag() tags.artist = "artist test" tags.album = "album test" tags.title = u"a title with accents éèàç" tags.track = 1 tags.year = 2000 tags.genre = "genre test" tags.comment = u"a comment with accents éèàç" file_ref.save()
def readTag(self): if self._tag: tag = self._tag else: fpath = str(self.fpath) if fpath.lower().endswith('mp3'): fileref = tagpy.mpeg.File(fpath) tag = fileref.ID3v2Tag() if not tag: tag = fileref.ID3v1Tag() elif fpath.lower().endswith('ogg'): fileref = tagpy.ogg.vorbis.File(fpath) tag = fileref.tag() elif fpath.lower().endswith('flac'): fileref = flac.File(fpath) tag = fileref.xiphComment() elif fpath.lower().endswith('mpc'): fileref = mpc.File(fpath) tag = fileref.APETag() else: fileref = tagpy.FileRef(fpath) tag = fileref.tag() #fileref = tagpy.FileRef(fpath) #tag = fileref.tag() if not tag or tag.isEmpty(): return None self._fileref = fileref # must save, or destroys tag self._tag = tag self.artist = self._tag.artist self.title = self._tag.title self.number = self._tag.track return tag
def save_tag(self): filetag = tagpy.FileRef(self.tags[self.tagnum]['fullpath']) tag = filetag.tag() # Set tag fields according to entry text for field, entry in self.entries.items(): tag_value = entry.get_text().strip() if field in ('year', 'track'): if len(tag_value) == 0: tag_value = '0' tag_value = int(tag_value) if field is 'comment': if len(tag_value) == 0: tag_value = ' ' setattr(tag, field, tag_value) save_success = filetag.save() if not (save_success ): # FIXME: was (save_success and self.conn and self.status): ui.show_msg(self.window, _("Unable to save tag to music file."), _("Edit Tags"), 'editTagsError', Gtk.ButtonsType.CLOSE, response_cb=ui.dialog_destroy)
def get_tags(filename): audio_file = tagpy.FileRef(filename) return _dict_from_tags(audio_file.tag())
# former crash bug by Andreas Hemel <*****@*****.**> import tagpy import tagpy.id3v2 fileref = tagpy.FileRef('la.mp3') file = fileref.file() tag = file.ID3v2Tag(True) frame = tagpy.id3v2.UniqueFileIdentifierFrame('blah', 'blah') tag.addFrame(frame) file.save()
def tagfile(fpath, album, track, options): """ Tag the file with metadata """ if not hasattr(tagpy.FileRef, 'create'): print 'warning: using generic tagging. upgrade to tagpy 0.94.5 or later.' fileref = tagpy.FileRef(str(fpath)) tag = fileref.tag() tag.year = album.year tag.genre = album.genre tag.artist = track.artist tag.album = album.title tag.title = track.title tag.track = track.number #TODO comment #tag.setComment(comment) return fileref.save() ftype = fpath.getFileType() if ftype == 'mp3': #fileref = tagpy.FileRef(str(fpath)) fileref = tagpy.mpeg.File(str(fpath)) hadID3v2Tag = fileref.ID3v2Tag() # Preserve old idv1 comments oldcomment = None if not hadID3v2Tag: id1tag = fileref.ID3v1Tag() if id1tag and not id1tag.isEmpty(): oldcomment = id1tag.comment if oldcomment == "": oldcomment = None # strip id3v1tag, bool freeMemory = False fileref.strip(tagpy.mpeg.TagTypes.ID3v1) ## Have to make new fileref, since the old one still contains an ID3v1 ## tag (in memory) which we do not want to merge into our new tag ## TODO: Is this true for new bindings? #del fileref #fileref = tagpy.mpeg.File(str(fpath)) tag = fileref.ID3v2Tag(True) # Insert old id3v1 comment in id3v2tag if oldcomment: cf = id3v2.CommentsFrame() cf.setText(oldcomment) tag.addFrame(cf) # gather frame values framedict = {} footprintdict = album.footprint() footprintdict["TNMU"] = TAGVER framedict.update(footprintdict) del footprintdict framedict.update({ "TDRC": str(album.year), "TCON": album.genre, "TPE1": track.artist, "TALB": album.title, "TIT2": track.title, "TRCK": "%s/%s" % (track.number, len(album.tracks)) }) if 'UTF' in options.tagencoding.upper(): tagpyenc = tagpy.StringType.UTF8 else: tagpyenc = tagpy.StringType.Latin1 id3v2.FrameFactory.instance().setDefaultTextEncoding(tagpyenc) # append namingmuse footprint for key, text in framedict.items(): tag.removeFrames(key) if not text == "": #if isinstance(text, unicode): # print 'uni', text # text = text.encode(options.tagencoding) #,'ignore') #else: # print 'not uni', text tf = id3v2.TextIdentificationFrame(key, tagpyenc) tf.setText(text) tag.addFrame(tf) retval = fileref.save(tagpy.mpeg.TagTypes.ID3v2) if not retval: print NamingMuseWarning('Failed to save tag in %s' % fpath) return retval elif ftype in ('ogg', 'flac', 'mpc'): if ftype == 'ogg': fileref = tagpy.ogg.vorbis.File(str(fpath)) tag = fileref.tag() elif ftype == 'flac': fileref = tagpy.flac.File(str(fpath)) tag = fileref.xiphComment() elif ftype == 'mpc': fileref = tagpy.mpc.File(str(fpath)) tag = fileref.APETag(True) tagencoding = 'UTF-8' if ftype in ('ogg', 'flac'): fields = { 'ALBUM': album.title, 'ARTIST': track.artist, 'DATE': str(album.year), 'GENRE': album.genre, 'TITLE': track.title, 'TRACKNUMBER': str(track.number) } elif ftype == 'mpc': fields = { 'ALBUM': album.title, 'ARTIST': track.artist, 'GENRE': album.genre, 'TITLE': track.title, 'TRACK': str(track.number), 'YEAR': str(album.year) } footprintdict = album.footprint() footprintdict['TNMU'] = TAGVER fields.update(footprintdict) for key, value in fields.items(): #key = key.encode(tagencoding) #value = value.encode(tagencoding) if ftype in ('ogg', 'flac'): tag.addField(key, value, True) # replace = True elif ftype == 'mpc': tag.addValue(key, value, True) # replace = True fileref.save() elif fpath.getFileType() == 'mpcold': raise Exception("Not converted to new code yet") fileref = tagpy.mpc.File(str(fpath)) tag = fileref.APETag(True) # create = True ape_encoding = 'UTF-8' footprintdict = album.footprint() footprintdict['TNMU'] = TAGVER fields.update(footprintdict) for key, value in fields.items(): key = key.decode(album.encoding).encode(ape_encoding) value = value.decode(album.encoding).encode(ape_encoding) tag.addValue(key, value, True) # replace = True fileref.save() else: fileref = tagpy.FileRef(str(fpath)) tag = fileref.tag() tag.year = album.year tag.genre = album.genre tag.artist = track.artist tag.album = album.title tag.title = track.title tag.track = track.number #TODO comment #tag.setComment(comment) fileref.save()
import tagpy f = tagpy.FileRef("la.ogg") t = f.tag() print t.artist print t.title print t.album print t.year t.artist = "Andreas" t.title = "Laaa-ahh" t.album = "Shake what'cha got" t.year = 2006 f.save()
def test_non_existing_fileref(): with pytest.raises(IOError): tagpy.FileRef('does_not_exist.ogg')