def test_one_valid_two_invalid(tmpdir): """Test when one FLAC file is fully valid and another one isn't.""" flac_dir = tmpdir.mkdir('flac') flac_files = [] # Valid. flac = flac_dir.join('Artist2 - 2012 - Album - 01 - Title.flac').ensure(file=True) with open(os.path.join(os.path.dirname(__file__), '1khz_sine.flac'), 'rb') as f: flac.write(f.read(), 'wb') tags = FLAC(str(flac.realpath())) tags.update(dict(artist='Artist2', date='2012', album='Album', tracknumber='01', title='Title')) tags.save() flac_files.append(str(flac.realpath())) # Invalid. flac = flac_dir.join('Artist - 2014 - Album - 01 - Title.flac').ensure(file=True) with open(os.path.join(os.path.dirname(__file__), '1khz_sine.flac'), 'rb') as f: flac.write(f.read(), 'wb') tags = FLAC(str(flac.realpath())) tags.update(dict(artist='Artist2', date='2014', album='Album', tracknumber='01', title='Title')) tags.save() flac_files.append(str(flac.realpath())) # Test. a_messages = find_inconsistent_tags(flac_files, True, True) e_messages = {flac_files[1]: [ "Artist mismatch: Artist != Artist2", ]} assert e_messages == a_messages
def test_two_invalid(tmpdir): """Test when two FLAC files have invalid tags.""" flac_dir = tmpdir.mkdir('flac') flac_files = [] # One. flac = flac_dir.join('Artist2 - 202 - Album - 01 - Title.flac').ensure(file=True) with open(os.path.join(os.path.dirname(__file__), '1khz_sine.flac'), 'rb') as f: flac.write(f.read(), 'wb') tags = FLAC(str(flac.realpath())) tags.update(dict(artist='Artist2', date='2012', album='Album', tracknumber='01', title='Title')) tags.save() flac_files.append(str(flac.realpath())) # Two. flac = flac_dir.join('Artist - 2014 - Album - 01 - Title.flac').ensure(file=True) with open(os.path.join(os.path.dirname(__file__), '1khz_sine.flac'), 'rb') as f: flac.write(f.read(), 'wb') tags = FLAC(str(flac.realpath())) tags.update(dict(artist='Artist2', date='2014', album='Album', tracknumber='01', title='Title')) tags.save() flac_files.append(str(flac.realpath())) # Test. a_messages = find_inconsistent_tags(flac_files, True, True) e_messages = { flac_files[0]: ["Filename date not four digits."], flac_files[1]: ["Artist mismatch: Artist != Artist2"], } assert e_messages == a_messages
def as_flac(self, path, metadata, cached_albumart=None): logger.debug('Writing FLAC metadata to "{path}".'.format(path=path)) # For supported flac tags: # https://github.com/quodlibet/mutagen/blob/master/mutagen/mp4/__init__.py # Look for the class named `MP4Tags` in the linked source file audiofile = FLAC(path) self._embed_basic_metadata(audiofile, metadata, "flac") if metadata["year"]: audiofile["year"] = metadata["year"] provider = metadata["provider"] audiofile["comment"] = metadata["external_urls"][provider] if metadata["lyrics"]: audiofile["lyrics"] = metadata["lyrics"] image = Picture() image.type = 3 image.desc = "Cover" image.mime = "image/jpeg" if cached_albumart is None: cached_albumart = urllib.request.urlopen( metadata["album"]["images"][0]["url"] ).read() albumart.close() image.data = cached_albumart audiofile.add_picture(image) audiofile.save()
def _tag_flac(self, trackno): """ Calls the mutagen library to perform metadata changes for FLAC files """ logging.debug("Tagging '%s'" % os.path.join(self.dest_dir_name, self.file_tag_map[trackno][1])) audio = FLAC(os.path.join(self.dest_dir_name, self.file_tag_map[trackno][1])) try: encoding = audio["ENCODING"] except: encoding = "" audio.delete() # add FLAC tag data audio["TITLE"] = self.tracks[trackno][1] audio["ARTIST"] = self.tracks[trackno][0] audio["ALBUM"] = self.title audio["COMPOSER"] = self.artist audio["ORGANIZATION"] = self.label audio["CATALOGNUM"] = self.catno audio["GENRE"] = self.genre audio["YEAR"] = self.year audio["TRACKNUMBER"] = str(trackno) audio["TRACKTOTAL"] = str(len(self.tracks)) audio["DESCRIPTION"] = '::> Don\'t believe the hype! <::' if(len(encoding) != 0): audio["ENCODING"] = encoding audio.pprint() try: audio.save() except: logging.error("Unable to tag '%s'" % self.file_tag_map[trackno][1]) raise DiscogsTaggerError, "Unable to write tag '%s'" % \ self.file_tag_map[trackno][1]
def update_flac_id3(flac_path): global previous global previous_path flac = FLAC(flac_path) print(flac_path) save = False for key in KEYS: try: print('{}: {}'.format(key, flac[key][0] or '')) except KeyError: if (key in previous.keys() and previous[key] != '' and previous_path == os.path.dirname(flac_path)): prompt = '{} ({})'.format(key, previous[key]) else: prompt = '{}'.format(key) print(prompt) value = input('Enter value: ') if (key in previous.keys() and previous[key] != '' and value == '' and previous_path == os.path.dirname(flac_path)): flac[key] = previous[key] else: flac[key] = value if key in previous.keys() and value != '': previous[key] = value save = True previous_path = os.path.dirname(flac_path) if save: flac.save()
def test_write_tags(tmpdir): """Test writing tags from a FLAC to mp3 file.""" # Prepare. flac = tmpdir.mkdir('flac').join('song.flac').ensure(file=True) mp3 = tmpdir.mkdir('mp3').join('song.mp3').ensure(file=True) with open(os.path.join(os.path.dirname(__file__), '1khz_sine.flac'), 'rb') as f: flac.write(f.read(), 'wb') with open(os.path.join(os.path.dirname(__file__), '1khz_sine.mp3'), 'rb') as f: mp3.write(f.read(), 'wb') flac, mp3 = str(flac.realpath()), str(mp3.realpath()) tags = FLAC(flac) tags.update(dict(artist='Artist2', date='2012', album='Album', tracknumber='01', title='Title', unsyncedlyrics='L')) image = Picture() image.type, image.mime = 3, 'image/jpeg' with open(os.path.join(os.path.dirname(__file__), '1_album_art.jpg'), 'rb') as f: image.data = f.read() tags.add_picture(image) tags.save() # Test. ConvertFiles.write_tags(flac, mp3) # Check. id3 = ID3(mp3) assert 'Artist2' == id3['TPE1'] assert '2012' == id3['TDRC'] assert 'Album' == id3['TALB'] assert '01' == id3['TRCK'] assert 'Title' == id3['TIT2'] assert 'L' == id3["USLT:Lyrics:'eng'"].text with open(os.path.join(os.path.dirname(__file__), '1_album_art.jpg'), 'rb') as f: assert f.read() == id3['APIC:'].data assert ({}, [], [], []) == find_files(str(tmpdir.join('flac')), str(tmpdir.join('mp3')))
def tag_flac(file, path, d, album, istrack=True): audio = FLAC(file) audio["TITLE"] = d["title"] # TRACK TITLE audio["TRACKNUMBER"] = str(d["track_number"]) # TRACK NUMBER try: audio["COMPOSER"] = d["composer"]["name"] # COMPOSER except KeyError: pass try: audio["ARTIST"] = d["performer"]["name"] # TRACK ARTIST except KeyError: if istrack: audio["ARTIST"] = d["album"]["artist"]["name"] # TRACK ARTIST else: audio["ARTIST"] = album["artist"]["name"] if istrack: audio["GENRE"] = ", ".join(d["album"]["genres_list"]) # GENRE audio["ALBUMARTIST"] = d["album"]["artist"]["name"] # ALBUM ARTIST audio["TRACKTOTAL"] = str(d["album"]["tracks_count"]) # TRACK TOTAL audio["ALBUM"] = d["album"]["title"] # ALBUM TITLE audio["YEAR"] = d["album"]["release_date_original"].split("-")[0] else: audio["GENRE"] = ", ".join(album["genres_list"]) # GENRE audio["ALBUMARTIST"] = album["artist"]["name"] # ALBUM ARTIST audio["TRACKTOTAL"] = str(album["tracks_count"]) # TRACK TOTAL audio["ALBUM"] = album["title"] # ALBUM TITLE audio["YEAR"] = album["release_date_original"].split("-")[0] # YEAR audio.save() title = sanitize_filename(d["title"]) os.rename(file, "{}/{:02}. {}.flac".format(path, d["track_number"], title))
def as_flac(self, path, metadata, cached_albumart=None): """ Apply metadata on MP3 media files. Parameters ---------- path: `str` Path to the media file. metadata: `dict` Metadata (standardized) to apply to the media file. cached_albumart: `bool` An albumart image binary. If passed, the albumart URL present in the ``metadata`` won't be downloaded or used. """ logger.debug('Writing FLAC metadata to "{path}".'.format(path=path)) # For supported flac tags: # https://github.com/quodlibet/mutagen/blob/master/mutagen/mp4/__init__.py # Look for the class named `MP4Tags` in the linked source file audiofile = FLAC(path) self._embed_basic_metadata(audiofile, metadata, "flac") self._embed_ogg_metadata(audiofile, metadata) self._embed_mbp_picture(audiofile, "metadata", cached_albumart, "flac") audiofile.save()
def write_field(self, file, field, value, bypassdbwrite=False): filename, extension = os.path.splitext(file) if extension.upper() == '.MP3': # Try to open the ID3 tags try: audio = ID3(file) except mutagen.id3.ID3NoHeaderError: # Save a blank ID3 header first audio = ID3() id3field = self.MAP_ID3_FIELDS[field] fieldtype, unused, fieldname = id3field.partition(':') gentag = getattr(mutagen.id3, fieldtype) audio[id3field] = gentag(encoding=3, desc=u'%s' % fieldname, text=value) #audio['TXXX:TAG'] = TXXX(encoding=3, desc=u'TAG', text=tags) elif extension.upper() == '.FLAC': audio = FLAC(file) audio[self.MAP_FLAC_FIELDS[field]] = value audio.save(file) print "[LIBRARY] Field '%s' written in file %s" % (field, os.path.basename(file)) # Update DB if needed if file in self.map_track_info: self.map_track_info[file][field] = value if not bypassdbwrite: self.save_database()
def changeArtist(self): try: audio = EasyID3(self.path) except: audio = FLAC(self.path) audio['artist'] = self.albumArtist audio.save()
def changeTitle(self): try: audio = EasyID3(self.path) except: audio = FLAC(self.path) audio['title'] = self.title audio.save()
class Id3tool: ''' class to read/write mp3 tags ''' def __init__(self, fn): ''' allow throw if file not supported ''' if fnmatch.fnmatch(fn, '*.ogg'): self.tag_obj = OggVorbis(fn) elif fnmatch.fnmatch(fn, '*.flac'): self.tag_obj = FLAC(fn) else: self.tag_obj = EasyID3(fn) def save(self): self.tag_obj.save() def readTag(self, tag): if self.tag_obj: tmp = self.tag_obj.get(unicode(tag)) return tmp[0] if tmp else '' else: return '' def writeTag(self, tag, val): self.tag_obj[unicode(tag)] = unicode(val)
def on_save(self): audio = FLAC(self.song.get("~filename", "")) ## if file has no images -> leave if (audio.pictures is None) or (len(audio.pictures) <= 0): return ## first,clear all pictures, then add the images in order try: audio.clear_pictures() except: self.printError() return False for row in self.liststore: img = row[1] try: audio.add_picture(img) except: self.printError() return False audio.save() count = 0 if (audio.pictures is None) or (len(audio.pictures) <= 0): pass else: count = str(len(audio.pictures)) self.song["pictures"] = count app.window.emit("artwork-changed", [self.song]) del self.coverlist[:] self.liststore.clear() self.start_search() return True
def setSortTags(path): ext = os.path.splitext(path)[1].lower() meta = None try: if ext == '.mp3': meta = MP3(path) elif ext == '.m4a': meta = MP4(path) elif ext == '.flac': meta = FLAC(path) else: return except: pass if meta: tagsToProcess = ('ALBUM', 'ALBUMARTIST', 'ARTIST', 'TITLE') save = False try: for tag in tagsToProcess: processed = checkTagMakeSort(path, meta, tag) if (processed): save = True if save: meta.save() except: pass
def test_largest_valid(self): f = FLAC(self.filename) pic = Picture() pic.data = b"\x00" * (2**24 - 1 - 32) self.assertEqual(len(pic.write()), 2**24 - 1) f.add_picture(pic) f.save()
def test_get_images(self): pic = Picture() pic.data = _get_jpeg() pic.type = APICType.COVER_FRONT b64pic_cover = base64.b64encode(pic.write()).decode("ascii") # metadata_block_picture song = FLAC(self.filename) song["metadata_block_picture"] = [b64pic_cover] song.save() song = FLACFile(self.filename) self.assertEqual(len(song.get_images()), 1) self.assertEqual(song.get_images()[0].type, APICType.COVER_FRONT) # flac Picture song = FLAC(self.filename) pic = Picture() pic.data = _get_jpeg() pic.type = APICType.COVER_BACK song.add_picture(pic) song.save() song = FLACFile(self.filename) self.assertEqual(len(song.get_images()), 2) self.assertEqual(song.get_images()[-1].type, APICType.COVER_BACK)
def test_force_shrink(self): self.test_force_grow() f = FLAC(self.NEW) f["faketag"] = "foo" f.save() f = FLAC(self.NEW) self.failUnlessEqual(f["faketag"], ["foo"])
def test_largest_valid(self): f = FLAC(self.filename) pic = Picture() pic.data = b"\x00" * (2 ** 24 - 1 - 32) self.assertEqual(len(pic.write()), 2 ** 24 - 1) f.add_picture(pic) f.save()
def tag_flac(self, file_path, track_info, album_info, lyrics, album_art_path=None): tagger = FLAC(file_path) self._meta_tag(tagger, track_info, album_info, 'flac') if self.fmtopts['embed_album_art'] and album_art_path is not None: pic = Picture() with open(album_art_path, 'rb') as f: pic.data = f.read() # Check if cover is smaller than 16MB if len(pic.data) < pic._MAX_SIZE: pic.type = PictureType.COVER_FRONT pic.mime = u"image/jpeg" tagger.add_picture(pic) else: print( '\tCover file size is too large, only {0:.2f}MB are allowed.' .format(pic._MAX_SIZE / 1024**2)) print( '\tSet "artwork_size" to a lower value in config/settings.py' ) # Set lyrics from Deezer if lyrics: tagger['lyrics'] = lyrics tagger.save(file_path)
def setImage(self, song): audio = FLAC(song.get("~filename", "")) if len(self.imgFiles) <= 0: return for p in self.imgFiles: try: audio.add_picture(p) except: printError() return False audio.save() ## and now count the images count = "0" ## if file has no images -> set to 0 if (audio.pictures is None) or (len(audio.pictures) <= 0): pass else: count = str(len(audio.pictures)) if not "pictures" in song: song["pictures"] = count if song["pictures"] <> count: song["pictures"] = count app.window.emit("artwork-changed", [song]) return
def write_tags(f, meta, cov): if f.endswith('.mp3'): try: audio = id3.ID3(f) except ID3NoHeaderError: audio = id3.ID3() audio['TRCK'] = id3.TRCK(encoding=3, text=str(meta['TRACK']) + "/" + str(meta['TRACKTOTAL'])) legend = { "ALBUM": id3.TALB, "ALBUMARTIST": id3.TPE2, "ARTIST": id3.TPE1, "COPYRIGHT": id3.TCOP, "TITLE": id3.TIT2, "YEAR": id3.TYER } for tag, value in meta.items(): if not tag in ['UPC', 'TRACK', 'TRACKTOTAL']: id3tag = legend[tag] audio[id3tag.__name__] = id3tag(encoding=3, text=value) with open(cov, 'rb') as cov_obj: audio.add(id3.APIC(3, 'image/jpeg', 3, '', cov_obj.read())) audio.save(f, 'v2_version=3') else: audio = FLAC(f) for tag, value in meta.items(): audio[tag] = str(value) image = Picture() image.type = 3 image.mime = "image/jpeg" with open(cov, 'rb') as cov_obj: image.data = cov_obj.read() audio.add_picture(image) audio.save()
def write_tags(f, meta, cov, com, fmt): if fmt == "FLAC": audio = FLAC(f) for tag, value in meta.items(): if value: audio[tag] = str(value) if com: audio['COMMENT'] = com else: audio = MP4(f) audio['\xa9nam'] = meta['TITLE'] audio['\xa9alb'] = meta['ALBUM'] audio['aART'] = meta['ALBUMARTIST'] audio['\xa9ART'] = meta['ARTIST'] audio['trkn'] = [(meta['TRACK'], meta['TRACKTOTAL'])] audio['\xa9day'] = meta['YEAR'] if meta['COPYRIGHT']: audio['cprt'] = meta['COPYRIGHT'] if com: audio['\xa9cmt'] = com with open(cov, 'rb') as cov_obj: if fmt == "FLAC": image = Picture() image.type = 3 image.mime = "image/jpeg" image.data = cov_obj.read() audio.add_picture(image) else: audio['covr'] = [ MP4Cover(cov_obj.read(), imageformat=MP4Cover.FORMAT_JPEG) ] audio.save()
class FlacStripper(MutagenStripper): """ Represent a Flac audio file """ def _create_mfile(self): self.mfile = FLAC(self.filename) def remove_all(self): """ Remove the "metadata" block from the file """ super(FlacStripper, self).remove_all() self.mfile.clear_pictures() self.mfile.save() return True def is_clean(self): """ Check if the "metadata" block is present in the file """ return super(FlacStripper, self).is_clean() and not self.mfile.pictures def get_meta(self): """ Return the content of the metadata block if present """ metadata = super(FlacStripper, self).get_meta() if self.mfile.pictures: metadata['picture:'] = 'yes' return metadata
def test_add_picture(self): f = FLAC(self.NEW) c = len(f.pictures) f.add_picture(Picture()) f.save() f = FLAC(self.NEW) self.failUnlessEqual(len(f.pictures), c + 1)
def tag(self): if self.type == 'Free Lossless Audio Codec': f = FLAC(self.name) tags = CUE_META.flac_tags(self.track_nr) for t in tags[0]: f[t] = tags[0][t] f.save()
def main(): root = tkinter.Tk() root.withdraw() root.update() folder = askdirectory(title="choose the dir u want get tags to", initialdir=r"C:\Users\User\Desktop", mustexist=True) root.destroy() for root, dirs, files in os.walk(folder): for name in files: if name.endswith((".mp3", ".flac")): fileType = os.path.splitext(name)[1] if fileType == ".mp3": audio = ID3(root + "\\" + name) # audio["USLT::'eng'"] = "" audio.delall(u"USLT") audio.save(root + "\\" + name) print("deleted lyrics from the file " + name) elif fileType == ".flac": audio = FLAC(root + "\\" + name) audio["Lyrics"] = "" audio["ALBUMARTIST"] = "" audio.save() print("deleted lyrics from the file " + name)
def setSortTags(path): ext = os.path.splitext(path)[1].lower() meta = None try: if ext == '.mp3': meta = MP3(path) elif ext == '.m4a': meta = MP4(path) elif ext == '.flac': meta = FLAC(path) else: return except: logging.warning('unknown file type:{0}'.format(path)) pass if meta: tagsToProcess = ('ALBUM', 'ALBUMARTIST', 'ARTIST', 'TITLE') save = False try: for tag in tagsToProcess: processed = checkTagMakeSort(path, meta, tag) if (processed): save = True if save: meta.save() except Exception as e: logging.warning('Save tag for {0} failure'.format(path)) logging.exception(e) pass
def upload(): form = request.form user = form.get('user') noise = request.files.get('noise') if not noise or not user: return abort(400) # TODO: group uploads by user? userdir = secure_filename(user) fulldir = os.path.join('upload', userdir) if not os.path.exists(fulldir): os.makedirs(fulldir) path = secure_filename(noise.filename) path = os.path.join('upload', userdir, path) base, ext = os.path.splitext(path) n = 0 while os.path.exists(path): n += 1 path = '{}-{}{}'.format(base, n, ext) noise.save(path) mic_name = form.get('mic') if mic_name: try: f = FLAC(path) f['microphone'] = str(mic_name)[:256] f.save() except Exception: import traceback traceback.print_exc() return 'ok'
def copy_tags(filejoin, filenames): """ Copia los tags de filenames a join """ extension = os.path.splitext(filejoin)[1] if extension == '.flac': tags_ori = FLAC(filenames[0]) tags_joi = FLAC(filejoin) elif extension == '.ogg': tags_ori = OggVorbis(filenames[0]) tags_joi = OggVorbis(filejoin) else: return for item in tags_ori.items(): tags_joi[item[0]] = item[1] # falta añadir lo del título... pero primero lo borramos for ori in filenames[1:]: if extension == '.flac': tags_ori = FLAC(ori) elif extension == '.ogg': tags_ori = OggVorbis(ori) last_track = tags_ori['tracknumber'] last_discnumber = tags_ori['discnumber'] print tags_ori['title'] tags_joi['title'] = tags_joi['title'] + tags_ori['title'] tags_joi['gapless_join'] = str(len(filenames)) tags_joi['gapless_last_track'] = last_track tags_joi['gapless_last_discnumber'] = last_discnumber tags_joi.save()
def TAG_it(output_format, track_path, artist, album_title, index, track): if output_format in TAG_formats: print("\t\tTagging") if output_format == "mp3": from mutagen.easyid3 import EasyID3 song = EasyID3(track_path) elif output_format == "mp4" or output_format == "m4a": from mutagen.easymp4 import EasyMP4 song = EasyMP4(track_path) elif output_format == 'ogg': from mutagen import File as mFile song = mFile(track_path) elif output_format == 'flac': from mutagen.flac import FLAC song = FLAC(track_path) else: from mutagen import File as mFile song = mFile(track_path) if artist: song['artist'] = artist if album_title: song['album'] = album_title song['title'] = track song['tracknumber'] = str(index + 1) song.save() else: print("Tagging is not supported on {} format at this moment.".format( output_format)) return
def parse_dir_update_tags(self, path, ref_path, b_initial=True): # Reset container for failed files if path == ref_path: self.failed = [] for elem in os.listdir(path): full_path_in = os.path.join(path, elem) if os.path.isdir(full_path_in): self.parse_dir_update_tags(full_path_in, ref_path, b_initial=False) elif full_path_in.endswith(".flac"): tags = self._extract_tags(full_path_in, ref_path) try: song = FLAC(full_path_in) song.clear() song.update(tags) song.save() except Exception as e: print(e.__class__.__name__) print(e) self.failed.append(full_path_in) if b_initial: print() if not self.failed: print("All files converted successfully.") else: for e in self.failed: print(f"Failed to process: [{e}]")
def fix_tags(abs, ext, f_meta): """ :param abs: Path of the file we're tagging :param ext: Extension of the file we're tagging :param f_meta: Dict containing the metadata of the track we're tagging. """ if ext == "mp3": try: audio = id3.ID3(abs) except ID3NoHeaderError: audio = id3.ID3() audio['TRCK'] = id3.TRCK(text=str(audio['TRCK']) + "/" + str(f_meta['track_total'])) audio['TPOS'] = id3.TPOS(text=str(audio['TPOS']) + "/" + str(f_meta['disc_total'])) audio['TDRC'] = id3.TPOS(text=f_meta['release_date']) audio['TPUB'] = id3.TPOS(text=f_meta['planning']) audio['TPE1'] = id3.TPE1(text=f_meta['track_artist']) audio['TPE2'] = id3.TPE2(text=f_meta['album_artist']) audio.save(abs, "v2_version=3") else: audio = FLAC(abs) audio['TRACKTOTAL'] = str(f_meta['track_total']) audio['DISCTOTAL'] = str(f_meta['disc_total']) audio['DATE'] = f_meta['release_date'] audio['LABEL'] = f_meta['planning'] audio['ARTIST'] = f_meta['track_artist'] audio['ALBUMARTIST'] = f_meta['album_artist'] audio.save()
def test_get_images(self): pic = Picture() pic.data = _get_jpeg() pic.type = APICType.COVER_FRONT b64pic_cover = base64.b64encode(pic.write()) # metadata_block_picture song = FLAC(self.filename) song["metadata_block_picture"] = [b64pic_cover] song.save() song = FLACFile(self.filename) self.assertEqual(len(song.get_images()), 1) self.assertEqual(song.get_images()[0].type, APICType.COVER_FRONT) # flac Picture song = FLAC(self.filename) pic = Picture() pic.data = _get_jpeg() pic.type = APICType.COVER_BACK song.add_picture(pic) song.save() song = FLACFile(self.filename) self.assertEqual(len(song.get_images()), 2) self.assertEqual(song.get_images()[-1].type, APICType.COVER_BACK)
def set_image(self, image): """Replaces all embedded images by the passed image""" with translate_errors(): tag = FLAC(self["~filename"]) try: data = image.read() except EnvironmentError as e: raise AudioFileError(e) pic = Picture() pic.data = data pic.type = APICType.COVER_FRONT pic.mime = image.mime_type pic.width = image.width pic.height = image.height pic.depth = image.color_depth tag.add_picture(pic) with translate_errors(): tag.save() # clear vcomment tags super(FLACFile, self).clear_images() self.has_images = True
def tagFile(self, filename, metadata, art_url): image = None if art_url is not None: self.getFile('artwork.jpg', art_url, True) try: with open('artwork.jpg', 'rb') as file: image = file.read() except: pass if filename.endswith('.mp3'): audio = MP3(filename, ID3=ID3) try: audio.add_tags() except: pass audio.tags.add( APIC(encoding=3, mime='image/jpeg', type=3, desc=u'Cover', data=image)) audio.tags["TIT2"] = TIT2(encoding=3, text=metadata['title']) audio.tags["TPE1"] = TPE1(encoding=3, text=metadata['artist']) audio.tags["TDRC"] = TDRC(encoding=3, text=unicode(metadata['year'])) audio.tags["TCON"] = TCON(encoding=3, text=metadata['genre']) audio.save() elif filename.endswith('.flac'): audio = FLAC(filename) try: audio.add_tags() except: pass audio.tags['title'] = metadata['title'] audio.tags['artist'] = metadata['artist'] audio.tags['year'] = metadata['year'] audio.tags['genre'] = metadata['genre'] audio.tags.add( APIC(encoding=3, mime='image/jpeg', type=3, desc=u'Cover', data=image)) audio.save() elif filename.endswith('.m4a'): audio = MP4(filename) try: audio.add_tags() except: pass covr = [] covr.append(MP4Cover(image, MP4Cover.FORMAT_JPEG)) audio.tags['covr'] = covr audio.tags['title'] = metadata['title'] audio.tags['artist'] = metadata['artist'] #audio.tags['year'] = metadata['year'] audio.tags['genre'] = metadata['genre'] audio.save() if os.path.isfile('artwork.jpg'): os.remove('artwork.jpg')
def fileTagsUpdate(self, force=False): path = self.file_path if Path(self.file_name).suffix == ".flac": audiof = FLAC(path) elif Path(self.file_name).suffix == ".mp3": audiof = EasyID3(path) # don't implicitly overwrite existing tags if len(audiof) != 0: print(f"\n** file contains tags already {path}") if force: print(f"*** overwriting tags") else: print(f"*** clean tags (-c) or force overwrite (-f)") return # single artist if len(self.artists) == 1: audiof['ARTIST'] = self.artists # multiple artists else: temp = "" for i, artist in enumerate(self.artists): temp += artist if i < len(self.artists) - 1: temp += ", " audiof['ARTIST'] = [temp] audiof['DATE'] = self.released[:4] audiof['GENRE'] = self.genre audiof['ORGANIZATION'] = self.label audiof['TITLE'] = self.title + " (" + self.remixer + ")" audiof['ALBUM'] = self.album audiof['BPM'] = str(self.bpm) audiof.save()
def main(): print("start") tracks = [] root = tkinter.Tk() root.withdraw() root.update() folder = askdirectory(title = "choose the dir u want to delete on tags in",initialdir = r"C:\Users\User\Desktop", mustexist=True ) root.destroy() for root, dirs, files, in os.walk(folder): for name in files: if name.endswith((".mp3", ".flac")): print("the name= "+os.path.splitext(name)[0]) print("the type= "+os.path.splitext(name)[1]) if(name.endswith(".flac")): print("its .flac") audio=FLAC(root + "\\" + name) audio.delete() audio.clear_pictures() audio.save() if(name.endswith(".mp3")): print("its .mp3") audio=MP3(root + "\\" + name) audio.delete() audio.clear() audio.save()
def write_tags(self, song, data): try: tag = mutagen.File(song, easy=True) tag.add_tags() except mutagen.flac.FLACVorbisError: tag = FLAC(song) tag.delete() images = Picture() images.type = 3 images.data = data['image'] tag.add_picture(images) except mutagen.id3._util.error: pass tag['artist'] = data['artist'] tag['title'] = data['music'] tag['date'] = data['year'] tag['album'] = data['album'] tag['tracknumber'] = data['tracknum'] tag['discnumber'] = data['discnum'] tag['genre'] = " & ".join(data['genre']) tag['albumartist'] = data['ar_album'] tag.save() try: audio = ID3(song) audio['APIC'] = APIC(encoding=3, mime="image/jpeg", type=3, desc=u"Cover", data=data['image']) audio.save() except mutagen.id3._util.ID3NoHeaderError: pass
def set_image(self, image): """Replaces all embedded images by the passed image""" with translate_errors(): tag = FLAC(self["~filename"]) try: data = image.read() except EnvironmentError as e: raise AudioFileError(e) pic = Picture() pic.data = data pic.type = APICType.COVER_FRONT pic.mime = image.mime_type pic.width = image.width pic.height = image.height pic.depth = image.color_depth tag.add_picture(pic) with translate_errors(): tag.save() # clear vcomment tags super().clear_images() self.has_images = True
def download(trlist): global music_dir, m if not os.path.exists(music_dir): os.mkdir(music_dir) for i in trlist: dcl = dcloud(dcloud_token, dcloud_url, "auth", "") if (dcl == True): dcl = dcloud(dcloud_token, dcloud_url, "add", str(i[0])) if (dcl['code'] == 200): if (dcl['message'] == ""): if (m != 7): if (m != 8): print("Track was added to Dcloud") else: if (m != 7): if (m != 8): print("Dcloud message: " + dcl['message']) print(i[1].artist.name + " - " + i[1].title) trurl = "https://dz.loaderapp.info/deezer/1411/" + i[1].link if (download_server != ""): trurl = download_server + i[1].link d(trurl, music_dir + translit(i[1].title, "ru", reversed=True) + ".flac") audio = FLAC(music_dir + translit(i[1].title, "ru", reversed=True) + ".flac") audio['albumartist'] = i[1].artist.name audio['artist'] = i[1].artist.name audio['comment'] = str(i[0]) audio.save() print("Done")
def test_write_reread(self): flac = FLAC(self.NEW) del(flac["artist"]) flac.save() flac2 = FLAC(self.NEW) self.failUnlessEqual(flac["title"], flac2["title"]) data = open(self.NEW, "rb").read(1024) self.failIf("Tunng" in data)
def write_genre(self, file_path, file_ext, genre): '''write genre to a single file''' if file_ext == '.flac': tag = FLAC(file_path) elif file_ext == '.mp3': tag = EasyID3(file_path) tag['genre'] = genre tag.save()
def test_clear_pictures(self): f = FLAC(self.NEW) c1 = len(f.pictures) c2 = len(f.metadata_blocks) f.clear_pictures() f.save() f = FLAC(self.NEW) self.failUnlessEqual(len(f.metadata_blocks), c2 - c1)
def handle_audio_file(audio_file): print('Handling audio file', audio_file) extension = os.path.splitext(os.path.basename(audio_file))[1] if extension == '.mp3': mp3 = MP3(audio_file, ID3=ID3) print(list(dict(mp3).keys())) if not regex_list(dict(mp3).keys(), re.compile('[Aa][Pp][Ii][Cc].*')): artist = mp3['TPE1'][0] album = mp3['TALB'][0] cover_data = open(get_cover_art(artist, album, audio_file), mode='rb') apic = APIC() apic.encoding = 3 apic.mime = 'image/jpg' apic.type = PictureType.COVER_FRONT apic.desc = u'Cover' apic.data = cover_data.read() cover_data.close() print('Adding cover art', cover_data.name, '->', audio_file) mp3['APIC'] = apic mp3.save() else: print(audio_file, 'already has cover artwork.') elif extension == '.m4a' or extension is '.aac': m4a = MP4(audio_file) print(list(dict(m4a).keys())) if 'covr' not in m4a: artist = m4a['\xa9ART'][0] album = m4a['\xa9alb'][0] cover_data = open(get_cover_art(artist, album, audio_file), mode='rb') covr = MP4Cover() covr.imageformat = AtomDataType.JPEG covr.data = cover_data.read() cover_data.close() print('Adding cover art', cover_data.name, '->', audio_file) m4a['covr'] = [covr] m4a.save() else: print(audio_file, 'already has cover artwork.') elif extension == '.flac': flac = FLAC(audio_file) print(list(dict(flac).keys())) if not flac.pictures: artist = flac['artist'][0] album = flac['album'][0] cover_data = open(get_cover_art(artist, album, audio_file), mode='rb') picture = Picture() picture.type = 3 picture.mime = 'image/jpg' picture.desc = u'Cover' picture.data = cover_data.read() cover_data.close() print('Adding cover artwork', cover_data.name, '->', audio_file) flac.add_picture(picture) flac.save() else: print(audio_file, 'already has cover artwork.') move_or_overwrite(audio_file, dest_audio, os.path.join(dest_audio, os.path.basename(audio_file)))
def test_write_changetitle_unicode_value(self): f = FLAC(self.NEW) if PY3: self.assertRaises(ValueError, f.__setitem__, b'title', u"A Unicode Title \u2022") else: f[b'title'] = u"A Unicode Title \u2022" f.save() f = FLAC(self.NEW) self.failUnlessEqual(f[b"title"][0], u"A Unicode Title \u2022")
def test_write_changetitle(self): f = FLAC(self.NEW) if PY3: self.assertRaises(ValueError, f.__setitem__, b'title', b"A New Title") else: f[b'title'] = b"A New Title" f.save() f = FLAC(self.NEW) self.failUnlessEqual(f[b"title"][0], b"A New Title")
def flac_write_tags(self, path, tag_type, input_string): try: flac_audio = FLAC(path) #Reading tags except mutagen.flac.FLACNoHeaderError: print ("%r is not a valid FLAC file") \ % (path.encode(sys.stdout.encoding or "utf-8", "replace"), ) return flac_audio[tag_type] = input_string flac_audio.save()
def _tag(self): w = FLAC(self.track_path) for k, v in self.tags.items(): w[k] = v w.save() self.stop()
def test_write_changetitle_unicode_key(self): f = FLAC(self.NEW) f[u"title"] = b"A New Title" if PY3: self.assertRaises(ValueError, f.save) else: f.save() f = FLAC(self.NEW) self.failUnlessEqual(f[u"title"][0], b"A New Title")
def test_delete_id3(self): id3 = ID3() id3.add(TIT2(encoding=0, text='id3 title')) id3.save(self.NEW, v1=2) f = FLAC(self.NEW) f['title'] = 'vc title' f.save(deleteid3=True) self.failUnlessRaises(ID3NoHeaderError, ID3, self.NEW) f = FLAC(self.NEW) self.failUnlessEqual(f['title'], ['vc title'])
def test_delete_multiple_fail(self): f = FLAC(self.filename) with pytest.raises(MutagenError): f.delete(os.devnull) f.save() # if delete failed we shouldn't see a difference f = FLAC(self.filename) assert f.metadata_blocks[2] is f.tags assert f.metadata_blocks[3].code == f.tags.code
def embed_cover_art(self, audio_file, cover_file): """Embeds cover art into an audio file. Arguments: audio_file (str): The path to the audio file to embed the artwork in. cover_file (str): The path to the artwork file to embed. """ if path.isfile(audio_file) and path.isfile(cover_file): mimetype = "image/png" if cover_file.endswith("png") else "image/jpeg" artwork = open(cover_file, "rb").read() desc = u"Cover Art" # Determine which filetype we're handling if audio_file.endswith("m4a"): audio = MP4(audio_file) covr = [] if cover_file.endswith("png"): covr.append(MP4Cover(artwork, MP4Cover.FORMAT_PNG)) else: covr.append(MP4Cover(artwork, MP4Cover.FORMAT_JPEG)) audio.tags["covr"] = covr elif audio_file.endswith("mp3"): audio = MP3(audio_file, ID3=ID3) # Add ID3 tags if they don't exist try: audio.add_tags() except error: pass audio.tags.add( APIC( encoding=3, # 3 is UTF-8 mime=mimetype, type=3, # 3 is for cover artwork desc=desc, data=artwork, ) ) elif audio_file.endswith("flac"): audio = FLAC(audio_file) image = Picture() image.type = 3 # 3 is for cover artwork image.mime = mimetype image.desc = desc image.data = artwork audio.clear_pictures() # Clear existing pictures audio.add_picture(image) # Save the audio file audio.save()
def test_ignore_id3(self): id3 = ID3() id3.add(TIT2(encoding=0, text='id3 title')) id3.save(self.NEW) f = FLAC(self.NEW) f['title'] = 'vc title' f.save() id3 = ID3(self.NEW) self.failUnlessEqual(id3['TIT2'].text, ['id3 title']) f = FLAC(self.NEW) self.failUnlessEqual(f['title'], ['vc title'])