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 set_art(self, art_file): art_tag = mutagen.File(self.path, None, False) if type(art_tag) is mutagen.mp3.MP3: with open(art_file, 'rb') as f: image = f.read() art_tag.tags.delall('APIC') art_tag.tags.add(APIC( encoding=3, # 3 is for utf-8 mime='image/jpg', # image/jpeg or image/png type=3, # 3 is for the cover image desc=u'Cover', data=image )) art_tag.save() print 'Wrote embedded MP3 art.' if type(art_tag) is mutagen.flac.FLAC: image = Picture() image.type = 3 image.mime = 'image/jpg' image.desc = 'front cover' with open(art_file, 'rb') as f: image.data = f.read() art_tag.clear_pictures() art_tag.add_picture(image) art_tag.save() print 'Wrote embedded FLAC art'
def test_flac_sort_pics_after_tags(self): pic1 = Picture() pic2 = Picture() pic3 = Picture() tags = VCFLACDict() pad = Padding() blocks = [] vorbis.flac_sort_pics_after_tags(blocks) self.assertEqual([], blocks) blocks = [tags] vorbis.flac_sort_pics_after_tags(blocks) self.assertEqual([tags], blocks) blocks = [tags, pad, pic1] vorbis.flac_sort_pics_after_tags(blocks) self.assertEqual([tags, pad, pic1], blocks) blocks = [pic1, pic2, tags, pad, pic3] vorbis.flac_sort_pics_after_tags(blocks) self.assertEqual([tags, pic1, pic2, pad, pic3], blocks) blocks = [pic1, pic2, pad, pic3] vorbis.flac_sort_pics_after_tags(blocks) self.assertEqual([pic1, pic2, pad, pic3], blocks)
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 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): # coverart + coverartmime data = _get_jpeg() song = self.MutagenType(self.filename) song["coverart"] = base64.b64encode(data).decode("ascii") song["coverartmime"] = u"image/jpeg" song.save() song = self.QLType(self.filename) self.assertEqual(len(song.get_images()), 1) self.assertEqual(song.get_images()[0].mime_type, "image/jpeg") # metadata_block_picture pic = Picture() pic.data = _get_jpeg() pic.type = APICType.COVER_FRONT b64pic_cover = base64.b64encode(pic.write()).decode("ascii") song = self.MutagenType(self.filename) song["metadata_block_picture"] = [b64pic_cover] song.save() song = self.QLType(self.filename) self.assertEqual(len(song.get_images()), 2) self.assertEqual(song.get_images()[0].type, APICType.COVER_FRONT)
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 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 add_pic(obj, path): if pict_test(obj): #art is already there return mimetype = 'image/jpeg' if type(path) == str: with open(path, 'rb') as f: imagedata = f.read() if path.endswith('png'): mimetype = 'image/png' else: mimetype = 'image/jpeg' else: imagedata = path if type(obj) == EasyID3: id3 = obj._EasyID3__id3 id3.add(APIC(3, mimetype, 3, 'Front cover', imagedata)) id3.add(TIT2(encoding=3, text='title')) id3.save(v2_version=3) elif type(obj) == FLAC: image = FlacPic() image.type = 3 image.desc = 'front cover' image.data = imagedata obj.add_picture(image)
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()
def _add_picture(self, mime, type_, desc, data): picture = Picture() picture.data = data picture.mime = mime picture.type = type_ picture.desc = desc self._flac.add_picture(picture)
def download_and_fix_ogg(ogg, audio_metadata, cover_art_file): global DRY_RUN if DRY_RUN: print "This is a dry run. So pretending to download the ogg..." return "/tmp/ogg" print "Now downloading the ogg in order to set the metadata in it..." if not LIVE and len(sys.argv) >= 6 and os.path.exists(sys.argv[5]): ogg_local_fn = sys.argv[5] print "(using presupplied file %s)" % ogg_local_fn else: f, metadata = client.get_file_and_metadata(ogg) ogg_local_fn = fetch_file(f, metadata) print "Successfully downloaded (to %s): now editing metadata..." % ogg_local_fn audio = OggVorbis(ogg_local_fn) for k in audio_metadata.keys(): audio[k] = audio_metadata[k] # add cover art im = Image.open(cover_art_file) w, h = im.size p = Picture() imdata = open(cover_art_file, 'rb').read() p.data = imdata p.type = 3 p.desc = '' p.mime = 'image/jpeg' p.width = w p.height = h p.depth = 24 dt = p.write() enc = base64.b64encode(dt).decode('ascii') audio['metadata_block_picture'] = [enc] audio.save() print "Successfully updated metadata." return ogg_local_fn
def test_get_images(self): # coverart + coverartmime data = _get_jpeg() song = self.MutagenType(self.filename) song["coverart"] = base64.b64encode(data) song["coverartmime"] = "image/jpeg" song.save() song = self.QLType(self.filename) self.assertEqual(len(song.get_images()), 1) self.assertEqual(song.get_images()[0].mime_type, "image/jpeg") # metadata_block_picture pic = Picture() pic.data = _get_jpeg() pic.type = APICType.COVER_FRONT b64pic_cover = base64.b64encode(pic.write()) song = self.MutagenType(self.filename) song["metadata_block_picture"] = [b64pic_cover] song.save() song = self.QLType(self.filename) self.assertEqual(len(song.get_images()), 2) self.assertEqual(song.get_images()[0].type, APICType.COVER_FRONT)
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 add_flac_cover(self, audio, albumart, desc='Album cover', file_type=3): image = Picture() image.type = file_type image.desc = desc with open(albumart, 'rb') as f: image.data = f.read() audio.add_picture(image)
def flacPicture(*args, **kwargs): ''' Creates a mutagen.flac.Picture object, sets its mimetype, its type and its description. Then loads the selected img and returns the Picture object. ''' # Set the corresponding mime type if img_path.endswith('png'): mime_type = 'image/png' else: mime_type = 'image/jpg' # Open bytes like object for the image albumart = open(img_path, 'rb').read() # create img object for flacs and set its properties img = FlacPicture() # type 3 is for cover image img.type = 3 # Set the corresponding mime type img.mime = mime_type # Set description img.desc = 'front cover' img.data = albumart return img
def test_handle_picture_block(self): pic = Picture() pic.data = _get_jpeg() pic.type = APICType.COVER_FRONT b64pic_cover = base64.b64encode(pic.write()).decode("ascii") pic2 = Picture() pic2.data = _get_jpeg(size=6) pic2.type = APICType.COVER_BACK b64pic_other = base64.b64encode(pic2.write()).decode("ascii") song = self.MutagenType(self.filename) song["metadata_block_picture"] = [b64pic_other, b64pic_cover] song.save() song = self.QLType(self.filename) self.failUnlessEqual(song("~picture"), "y") fn = song.get_primary_image().file self.failUnlessEqual(pic.data, fn.read()) song.write() song = self.MutagenType(self.filename) self.failUnless(b64pic_other in song["metadata_block_picture"]) self.failUnless(b64pic_cover in song["metadata_block_picture"]) song["metadata_block_picture"] = [b64pic_other] song.save() song = self.QLType(self.filename) fn = song.get_primary_image().file self.failUnlessEqual(pic2.data, fn.read())
def export_digital(item): """ Export and/or split digital files for an item (parallelized) """ logging.warning('{0} -> {1}'.format(item.name, DIGITAL_FOLDER)) if 'std' in item.option: if JUST_ADD_TAGS: if item.digital_ext == 'mp3': mutagen_audio = EasyID3(item.digital_file_path) elif item.digital_ext == 'flac': mutagen_audio = FLAC(item.digital_file_path) else: raise Exception('Format {0} not recognized for item {1}.'.format(item.digital_ext, item.name)) mutagen_audio['title'] = item.album mutagen_audio['artist'] = item.artist mutagen_audio['albumartist'] = item.artist mutagen_audio['album'] = item.album mutagen_audio.save() else: # Export audio file digital_file = AudioSegment.from_wav(item.path) digital_file.export(out_f=item.digital_file_path, format=item.digital_ext, bitrate='192k', tags={ 'title':(item.album or item.artist), 'artist':item.artist, 'albumartist':item.artist, 'album':(item.album or item.artist)}) # Add cover art if item.thumb and (item.digital_ext == 'mp3'): mutagen_audio = MP3(item.digital_file_path, ID3=ID3) try: # Add ID3 tag if it doesn't exist mutagen_audio.add_tags() except error: pass mutagen_audio.tags.add( APIC( encoding=3, # 3 is for utf-8 mime='image/jpeg', # image/jpeg or image/png type=3, # 3 is for the cover image desc=u'Cover', data=open(item.thumb_path, 'rb').read() ) ) mutagen_audio.save() elif item.thumb and (item.digital_ext == 'flac'): mutagen_audio = File(item.digital_file_path) flac_image = Picture() flac_image.type = 3 mime = 'image/jpeg' flac_image.desc = 'Cover' with open(item.thumb_path, 'rb') as f: flac_image.data = f.read() mutagen_audio.add_picture(flac_image) mutagen_audio.save() else: logging.warning('No cover found for item {0}'.format(item.name)) if JUST_ADD_TAGS: os.rename(item.digital_file_path, item.digital_rename_path) if DROPBOX_COPY: # Copy finished digital file to Dropbox order folder shutil.copy2(item.digital_file_path, item.dropbox_order_folder) # Deluxe / 45 else: split.split_item(item, DIGITAL_FOLDER, DROPBOX_COPY)
def write_tags(song, data): try: tag = FLAC(song) tag.delete() images = Picture() images.type = 3 images.data = data["image"] tag.clear_pictures() tag.add_picture(images) tag["lyrics"] = data["lyric"] except FLACNoHeaderError: try: tag = File(song, easy=True) tag.delete() except: if isfile(song): remove(song) raise exceptions.TrackNotFound("") except NOTVALIDSONG: raise exceptions.TrackNotFound("") 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"] = data["genre"] tag["albumartist"] = data["ar_album"] tag["author"] = data["author"] tag["composer"] = data["composer"] tag["copyright"] = data["copyright"] tag["bpm"] = data["bpm"] tag["length"] = data["duration"] tag["organization"] = data["label"] tag["isrc"] = data["isrc"] tag["lyricist"] = data["lyricist"] tag.save() try: audio = ID3(song) audio.add( APIC( encoding=3, mime="image/jpeg", type=3, desc=u"Cover", data=data["image"], )) audio.add( USLT(encoding=3, lang=u"eng", desc=u"desc", text=data["lyric"])) audio.save() except ID3NoHeaderError: pass
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 add_flac_cover(filename, albumart): audio = File(str(filename)) image = Picture() image.type = 3 image.mime = "image/jpeg" with open(albumart, 'rb') as f: image.data = f.read() audio.add_picture(image) audio.save()
def flac(): song = FLAC(file) write_keys(song) if exists(cover_img): pic = Picture() pic.data = open(cover_img, 'rb').read() pic.mime = 'image/jpeg' song.add_picture(pic) song.save()
def ogg(): song = OggVorbis(file) write_keys(song) if exists(cover_img): pic = Picture() pic.data = open(cover_img, 'rb').read() pic.mime = 'image/jpeg' song["metadata_block_picture"] = [base64.b64encode(pic.write()).decode('ascii')] song.save()
def write_tags(f, meta, tag_cfg, cov, ext, embed_cov): if ext == ".flac": audio = FLAC(f) for k, v in meta.items(): if tag_cfg[k]: audio[k] = str(v) if embed_cov and cov: with open(cov, 'rb') as cov_obj: image = Picture() image.type = 3 image.mime = "image/jpeg" image.data = cov_obj.read() audio.add_picture(image) audio.save() elif ext == ".mp3": try: audio = id3.ID3(f) except ID3NoHeaderError: audio = id3.ID3() if tag_cfg['TRACKNUMBER'] and tag_cfg['TRACKTOTAL']: audio['TRCK'] = id3.TRCK(encoding=3, text=str(meta['TRACKNUMBER']) + "/" + str(meta['TRACKTOTAL'])) elif tag_cfg['TRACKNUMBER']: audio['TRCK'] = id3.TRCK(encoding=3, text=str(meta['TRACKNUMBER'])) if tag_cfg['DISCNUMBER']: audio['TPOS'] = id3.TPOS(encoding=3, text=str(meta['DISCNUMBER']) + "/" + str(meta['DISCTOTAL'])) legend = { "ALBUM": id3.TALB, "ALBUMARTIST": id3.TPE2, "ARTIST": id3.TPE1, "COMMENT": id3.COMM, "COMPOSER": id3.TCOM, "COPYRIGHT": id3.TCOP, "DATE": id3.TDAT, "GENRE": id3.TCON, "ISRC": id3.TSRC, "LABEL": id3.TPUB, "PERFORMER": id3.TOPE, "TITLE": id3.TIT2, # Not working. "URL": id3.WXXX, "YEAR": id3.TYER } for k, v in meta.items(): try: if tag_cfg[k]: id3tag = legend[k] audio[id3tag.__name__] = id3tag(encoding=3, text=v) except KeyError: pass if embed_cov and cov: with open(cov, 'rb') as cov_obj: audio.add(id3.APIC(3, 'image/jpeg', 3, '', cov_obj.read())) audio.save(f, 'v2_version=3')
def download_and_fix_ogg(ogg, audio_metadata, cover_art_file): global DRY_RUN if DRY_RUN: print "This is a dry run. So pretending to download the ogg..." return "/tmp/ogg" print "Now downloading the ogg in order to set the metadata in it..." if not LIVE and len(sys.argv) >= 6 and os.path.exists(sys.argv[5]): ogg_local_fn = sys.argv[5] print "(using presupplied file %s)" % ogg_local_fn else: f, metadata = client.get_file_and_metadata(ogg) ogg_local_fn = fetch_file(f, metadata) print "Successfully downloaded (to %s): now editing metadata..." % ogg_local_fn audio = OggVorbis(ogg_local_fn) for k in audio_metadata.keys(): audio[k] = audio_metadata[k] # add cover art im=Image.open(cover_art_file) w,h=im.size p=Picture() imdata=open(cover_art_file,'rb').read() p.data=imdata p.type=3 p.desc='' p.mime='image/jpeg'; p.width=w; p.height=h p.depth=24 dt=p.write(); enc=base64.b64encode(dt).decode('ascii'); audio['metadata_block_picture']=[enc]; audio.save() print "Successfully updated metadata." return ogg_local_fn
def embed_metadata(music_file, cover_image, song): """Add metadata to extracted OGG files. For details on the METADATA_BLOCK_PICTURE struct format, see https://xiph.org/flac/format.html#metadata_block_picture """ music_file.seek(0) audio = OggVorbis(music_file) audio["title"] = song.title audio["artist"] = song.artist audio["album"] = song.album_name audio["tracknumber"] = str(song.track_number) audio["tracktotal"] = str(song.track_total) if song.genre is not None: audio["genre"] = song.genre picture = Picture() # PIL does not allow for direct saving to bytes cover_image_file = io.BytesIO() cover_image.save(cover_image_file, format="png") picture.data = cover_image_file.getvalue() picture.type = 3 # Cover (front) picture.mime = "image/png" picture.width = cover_image.width picture.height = cover_image.height # PIL does not give depth, so we assert then hardcode assert cover_image.mode == "RGBA" picture.depth = 32 audio["metadata_block_picture"] = [ base64.b64encode(picture.write()).decode("ascii") ] audio.save(music_file)
def write_tags(pre_abs, meta, fmt, cov_abs): if fmt == "FLAC": audio = FLAC(pre_abs) del meta['track_padded'] for k, v in meta.items(): if v: audio[k] = str(v) if cov_abs: with open(cov_abs, "rb") as f: image = Picture() image.type = 3 image.mime = "image/jpeg" image.data = f.read() audio.add_picture(image) elif fmt == "MP3": try: audio = id3.ID3(pre_abs) except ID3NoHeaderError: audio = id3.ID3() audio['TRCK'] = id3.TRCK(encoding=3, text="{}/{}".format(meta['track'], meta['tracktotal'])) legend = { "album": id3.TALB, "albumartist": id3.TPE2, "artist": id3.TPE1, #"comment": id3.COMM, "copyright": id3.TCOP, "isrc": id3.TSRC, "label": id3.TPUB, "title": id3.TIT2, "year": id3.TYER } for k, v in meta.items(): id3tag = legend.get(k) if v and id3tag: audio[id3tag.__name__] = id3tag(encoding=3, text=v) if cov_abs: with open(cov_abs, "rb") as cov_obj: audio.add(id3.APIC(3, "image/jpeg", 3, None, cov_obj.read())) else: audio = MP4(pre_abs) 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'] audio['cprt'] = meta['copyright'] if cov_abs: with open(cov_abs, "rb") as f: audio['covr'] = [ MP4Cover(f.read(), imageformat=MP4Cover.FORMAT_JPEG) ] audio.save(pre_abs)
def _addCoverToFile(self, album): if self.fileType == 'FLAC': if not self.hasCover or ( self.audioTag.pictures[0].height != 1000 and self.audioTag.pictures[0].width != 1000): if self.hasCover: self.audioTag.clear_pictures() # Build the file path by concatenating folder in the file path path = '' for folder in self.pathList: path += '{}/'.format(folder) path += album.coverName with open(path, "rb") as img: data = img.read() # Open physical image im = PIL.Image.open(path) width, height = im.size # Create picture and set its internals picture = Picture() picture.data = data picture.type = 3 # COVER_FRONT picture.desc = path.rsplit('/', 1)[-1] # Add picture name as a description picture.mime = mimetypes.guess_type(path)[0] picture.width = width picture.height = height picture.depth = mode_to_bpp[im.mode] # Save into file's audio tag self.audioTag.add_picture(picture) self.audioTag.save() else: # TODO for APIC frame pass
def set_image(self, image): """Replaces all embedded images by the passed image""" with translate_errors(): audio = self.MutagenType(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 audio.pop("coverart", None) audio.pop("coverartmime", None) audio["metadata_block_picture"] = base64.b64encode( pic.write()).decode("ascii") with translate_errors(): audio.save() self.has_images = True
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_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 writeAlbumCover(songPath: str, coverPath: str, picData=None): """ 给音频文件写入封面 Parameters ---------- songPath: 音频文件路径\n coverPath: 封面图片路径\n picData: 封面图片二进制数据 """ id_card = File(songPath) # 读取封面数据 if not picData: with open(coverPath, 'rb') as f: picData = f.read() # 获取音频数据和图片数据后缀名 audioSuffix = id_card.mime[0].split('/')[-1] try: picSuffix = imghdr.what(None, picData) except: picSuffix = 'jpeg' mimeType = 'image/' + picSuffix # 开始写入封面 if audioSuffix == 'mp3': keyName = 'APIC:' keyName_list = [] # 获取可能已经存在的封面键名 for key in id_card.tags.keys(): if key.startswith('APIC'): keyName = key keyName_list.append(key) # 弹出所有旧标签才能写入新数据 for key in keyName_list: id_card.pop(key) id_card[keyName] = APIC(encoding=0, mime=mimeType, type=3, desc='', data=picData) elif audioSuffix == 'flac': # 创建Picture实例 picture = Picture() # 设置属性值 picture.mime = mimeType picture.data = picData picture.type = 0 # 清除原来的图片数据 id_card.clear_pictures() # 添加图片 id_card.add_picture(picture) elif audioSuffix == 'mp4': try: id_card['covr'][0] = picData except: id_card['covr'] = [picData] # 没有键时需要创建一个 id_card.save()
def write_tags(song, data): try: tag = FLAC(song) tag.delete() images = Picture() images.type = 3 images.data = data['image'] tag.clear_pictures() tag.add_picture(images) tag['lyrics'] = data['lyric'] except FLACNoHeaderError: try: tag = File(song, easy=True) tag.delete() except: raise exceptions.TrackNotFound("") except error: raise exceptions.TrackNotFound("") 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'] = data['genre'] tag['albumartist'] = data['ar_album'] tag['author'] = data['author'] tag['composer'] = data['composer'] tag['copyright'] = data['copyright'] tag['bpm'] = data['bpm'] tag['length'] = data['duration'] tag['organization'] = data['label'] tag['isrc'] = data['isrc'] tag['replaygain_*_gain'] = data['gain'] tag['lyricist'] = data['lyricist'] tag.save() try: audio = ID3(song) audio.add( APIC(encoding=3, mime="image/jpeg", type=3, desc=u"Cover", data=data['image'])) audio.add( USLT(encoding=3, lang=u"eng", desc=u"desc", text=data['lyric'])) audio.save() except _util.ID3NoHeaderError: pass
def write_tags(f, meta, cov): audio = FLAC(f) for tag, value in meta.items(): if value: audio[tag] = str(value) if cov: image = Picture() image.type = 3 image.mime = "image/jpeg" image.data = cov audio.add_picture(image) audio.save()
def tag(album, track, file_path, cover_path): lyrics = get_lyrics(track['lyrics_tp'], track['track_id']) meta = utils.organize_meta(album=album, track=track, lyrics=lyrics) if str(file_path).endswith('.flac'): if cover_path: f_file = FLAC(file_path) f_image = Picture() f_image.type = 3 f_image.desc = 'Front Cover' with open(cover_path, 'rb') as f: f_image.data = f.read() f_file.add_picture(f_image) f_file.save() f = FLAC(file_path) logger_bugs.debug("Writing tags to {}".format( os.path.basename(file_path))) for k, v in meta.items(): f[k] = str(v) f.save() if str(file_path).endswith('.mp3'): legend = { "ALBUM": id3.TALB, "ALBUMARTIST": id3.TPE2, "ARTIST": id3.TPE1, "TRACKNUMBER": id3.TRCK, "DISCNUMBER": id3.TPOS, "COMMENT": id3.COMM, "COMPOSER": id3.TCOM, "COPYRIGHT": id3.TCOP, "DATE": id3.TDRC, "GENRE": id3.TCON, "ISRC": id3.TSRC, "LABEL": id3.TPUB, "PERFORMER": id3.TOPE, "TITLE": id3.TIT2, "LYRICS": id3.USLT } try: audio = id3.ID3(file_path) except ID3NoHeaderError: audio = id3.ID3() logger_bugs.debug("Writing tags to {}".format( os.path.basename(file_path))) for k, v in meta.items(): try: id3tag = legend[k] audio[id3tag.__name__] = id3tag(encoding=3, text=v) except KeyError: pass if cover_path: with open(cover_path, 'rb') as cov_obj: audio.add(id3.APIC(3, 'image/jpg', 3, '', cov_obj.read())) audio.save(file_path, 'v2_version=3')
def test_get_image(self): data = b"abc" song = FLAC(self.filename) pic = Picture() pic.data = data song.add_picture(pic) song.save() song = FLACFile(self.filename) self.failUnless(song("~picture")) fn = song.get_primary_image().file self.failUnlessEqual(fn.read(), pic.data)
def test_picture(self): data = "abc" song = FLAC(self.filename) pic = Picture() pic.data = data song.add_picture(pic) song.save() song = FLACFile(self.filename) self.failUnless(song("~picture")) fn = song.find_cover() self.failUnlessEqual(fn.read(), pic.data)
async def add(self): loop = asyncio.get_event_loop() await loop.run_in_executor( None, super().__init__, f"{self.trackInfo['trackId']}.ogg" ) async with httpx.AsyncClient() as client: albumArtResponse = await client.get(self.trackInfo["albumArtHigh"]) picture = Picture() picture.data = albumArtResponse.content """ Initially Vorbis comments didn't contain album arts, now they can keep album arts according to FLAC's specifications, thus using Picture class from flac. mutagen example uses picture.type = 17 here: https://mutagen.readthedocs.io/en/latest/user/vcomment.html. Keeping it's value as 17 makes Android's MediaMetadataRetriever to not detect the album art. What on earth is "A bright coloured fish" ? Reference: https://xiph.org/flac/format.html#metadata_block_picture. """ picture.type = 3 picture.desc = "Cover (front)" picture.mime = "image/jpeg" picture.width = 544 picture.height = 544 encoded_data = base64.b64encode(picture.write()) vcomment_value = encoded_data.decode("ascii") """ Sets album art. """ self["metadata_block_picture"] = [vcomment_value] """ In Vorbis comments, a key e.g. "artists" can have more than one value. In mutagen implementation, that's why we give values in a list. Reference: https://gitlab.gnome.org/GNOME/rhythmbox/-/issues/16 """ self["title"] = [self.trackInfo["trackName"]] self["album"] = [self.trackInfo["albumName"]] """ This is where we can simply provide simply a list of artists, as written above (for having mutiple value for the same key). But, by that MediaMetadataRetriever is just shows first artist :-(. So, I'm just joining all artists with "/" separator. (Though, this is incorrect according to official reference). """ self["artist"] = ["/".join(self.trackInfo["trackArtistNames"])] """ No reference of this comment at http://age.hobba.nl/audio/mirroredpages/ogg-tagging.html, still using because a mutagen example uses it. Thus, unable to read. """ self["albumartist"] = [self.trackInfo["albumArtistName"]] """ This needs a fix. Vorbis comment keeps date instead of year & MediaMetadataRetriever is unable to read this. Fix if you get to know something... """ self["date"] = [str(self.trackInfo["year"])] self["tracknumber"] = [f"{self.trackInfo['trackNumber']}/{self.trackInfo['albumLength']}"] """ Again, no official reference of this one at http://age.hobba.nl/audio/mirroredpages/ogg-tagging.html. Thus, unable to read. """ self["tracktotal"] = [str(self.trackInfo["albumLength"])] loop = asyncio.get_event_loop() await loop.run_in_executor(None, self.save) """
def add_flac_tags(path, tags, image, lyrics=None, image_mimetype='image/jpg'): tag = FLAC(path) pic = Picture() pic.data = image pic.type = 3 pic.mime = image_mimetype tag.add_picture(pic) for key, val in tags.items(): try: tag[key] = str(val) except Exception as e: print(e) tag.save()
def test_clear_images(self): data = "abc" song = FLAC(self.filename) pic = Picture() pic.data = data song.add_picture(pic) song.save() song = FLACFile(self.filename) self.assertTrue(song.get_primary_image()) song.clear_images() song.clear_images() song = FLACFile(self.filename) self.assertFalse(song.get_primary_image())
def test_handle_picture_block(self): pic = Picture() pic.data = _get_jpeg() pic.type = APICType.COVER_FRONT b64pic_cover = base64.b64encode(pic.write()) pic2 = Picture() pic2.data = _get_jpeg(size=6) pic2.type = APICType.COVER_BACK b64pic_other = base64.b64encode(pic2.write()) song = self.MutagenType(self.filename) song["metadata_block_picture"] = [b64pic_other, b64pic_cover] song.save() song = self.QLType(self.filename) self.failUnlessEqual(song("~picture"), "y") fn = song.get_primary_image().file self.failUnlessEqual(pic.data, fn.read()) song.write() song = self.MutagenType(self.filename) self.failUnless(b64pic_other in song["metadata_block_picture"]) self.failUnless(b64pic_cover in song["metadata_block_picture"]) song["metadata_block_picture"] = [b64pic_other] song.save() song = self.QLType(self.filename) fn = song.get_primary_image().file self.failUnlessEqual(pic2.data, fn.read())
def test_handle_picture_block(self): pic = Picture() pic.data = self.__get_jpeg() pic.type = 3 b64pic_cover = base64.b64encode(pic.write()) pic2 = Picture() pic2.data = self.__get_jpeg(size=6) pic2.type = 4 b64pic_other= base64.b64encode(pic2.write()) song = self.MutagenType(self.filename) song["metadata_block_picture"] = [b64pic_other, b64pic_cover] song.save() song = self.QLType(self.filename) self.failUnlessEqual(song("~picture"), "y") fn = song.find_cover() self.failUnlessEqual(pic.data, fn.read()) song.write() song = self.MutagenType(self.filename) self.failUnless(b64pic_other in song["metadata_block_picture"]) self.failUnless(b64pic_cover in song["metadata_block_picture"]) song["metadata_block_picture"] = [b64pic_other] song.save() song = self.QLType(self.filename) fn = song.find_cover() self.failUnlessEqual(pic2.data, fn.read())
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 add_flac_cover(filename, albumart): audio = File(filename) image = Picture() image.type = 3 if albumart.endswith('png'): mime = 'image/png' else: mime = 'image/jpeg' image.desc = 'front cover' with open(albumart, 'rb') as f: # better than open(albumart, 'rb').read() ? image.data = f.read() audio.add_picture(image) audio.save()
def _set_tag(self, raw, tag, value): if tag == '__cover': raw.clear_pictures() for v in value: picture = Picture() picture.type = v.type picture.desc = v.desc picture.mime = v.mime picture.data = v.data raw.add_picture(picture) return # flac has text based attributes, so convert everything to unicode value = [xl.unicode.to_unicode(v) for v in value] CaseInsensitveBaseFormat._set_tag(self, raw, tag, value)
def __setattr__(self, attr, value): if attr in self.VALID_TAG_KEYS: if isinstance(value, Artwork): picture = Picture() picture.type = 3 picture.mime = value.mime picture.data = value.data self.audio.clear_pictures() self.audio.add_picture(picture) elif isinstance(value, str): self.audio[attr] = [value] else: raise TagValueError(value) else: object.__setattr__(self, attr, value)
def get_cover_picture(self, cover): """ Returns mutage Picture class for the cover image Usefull for OGG and FLAC format Picture type = cover image see http://flac.sourceforge.net/documentation_tools_flac.html#encoding_options """ f = file(cover) p = Picture() p.type = 3 p.data = f.read() p.mime = mimetypes.guess_type(cover)[0] f.close() return p
def AddImages(self): MadeUrls = [] MadeUrlsResults = [] QueriedImagesKeys = self.QueriedImages.keys() QueriedImagesKeys.sort() for flacPath in QueriedImagesKeys: index = -1 for Query in self.QueriedImages[flacPath]: try: index = MadeUrls.index(Query) except ValueError: #print ' filling --- cache %s:%s' % (Query,flacPath) #print MadeUrls try: #print "Query=%s,%s" % (Query,type(Query)) data = urllib2.urlopen(Query ) except urllib2.URLError: print "Could not open URL: %s for file : %s" % (Query,flacPath) continue MadeUrls.append(Query) MadeUrlsResults.append(data.read()) index = MadeUrls.index(Query) if index == -1: # we had succesfull urls for this file continue if len(MadeUrlsResults[index]) == 0: # we had no data continue #print ' have %s for %s' % (Query,flacPath) try: metadata = FLAC(flacPath) except FLACNoHeaderError as (strerror): print strerror continue if pict_test(metadata): print "Already has cover are:%s" % (flacPath) continue image = Picture() image.type = 3 image.desc = 'front cover' if Query.endswith('png'): mime = 'image/png' if Query.endswith('jpg'): mime = 'image/jpeg' image.data = MadeUrlsResults[index] metadata.add_picture(image) metadata.save()
def test_invalid_overflow_recover_and_save_back(self): # save a picture which is too large for flac, but still write it # with a wrong block size f = FLAC(self.filename) f.clear_pictures() pic = Picture() pic.data = b"\x00" * (2 ** 24 - 32) pic._invalid_overflow_size = 42 f.add_picture(pic) f.save() # make sure we can read it and save it again f = FLAC(self.filename) self.assertTrue(f.pictures) self.assertEqual(len(f.pictures[0].data), 2 ** 24 - 32) f.save()
def test_art_lyrics(tmpdir): """Test when everything is valid.""" flac_dir = tmpdir.mkdir('flac') 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', 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() a_messages = find_inconsistent_tags([str(flac.realpath())], False, False) assert {} == a_messages
def __setattr__(self, attr, value): if attr in self.VALID_TAG_KEYS: if isinstance(value, Artwork): picture = Picture() picture.type = 3 picture.mime = value.mime picture.data = value.data self.audio['metadata_block_picture'] = [ b64encode(picture.write()).decode('utf-8') ] elif isinstance(value, str): self.audio[attr] = [value] else: raise TagValueError(value) else: object.__setattr__(self, attr, value)
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 get_image_size(fname): '''Determine the image type of fhandle and return its size. from draco''' with open(fname, 'rb') as fhandle: head = fhandle.read(24) if len(head) != 24: return if imghdr.what(fname) == 'png': check = struct.unpack('>i', head[4:8])[0] if check != 0x0d0a1a0a: return width, height = struct.unpack('>ii', head[16:24]) elif imghdr.what(fname) == 'gif': width, height = struct.unpack('<HH', head[6:10]) elif imghdr.what(fname) == 'jpeg': try: fhandle.seek(0) # Read 0xff next size = 2 ftype = 0 while not 0xc0 <= ftype <= 0xcf: fhandle.seek(size, 1) byte = fhandle.read(1) while ord(byte) == 0xff: byte = fhandle.read(1) ftype = ord(byte) size = struct.unpack('>H', fhandle.read(2))[0] - 2 # We are at a SOFn block fhandle.seek(1, 1) # Skip `precision' byte. height, width = struct.unpack('>HH', fhandle.read(4)) except Exception: #IGNORE:W0703 printError() return else: return fhandle.seek(0) imgdata = fhandle.read() img = Picture() img.data = imgdata img.width = width img.height = height return img
def test_get_metadata(tmpdir): flac_dir = tmpdir.mkdir('flac') mp3_dir = '/tmp/mp3_dir' flac = flac_dir.join('Artist - 2001 - Album (Disc 1) - 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)) tags.update(dict(artist='Artist', date='2001', album='Album', discnumber='1', 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() song = Song(str(flac), str(flac_dir), mp3_dir) song.get_metadata() assert dict() == OPTIONS assert ['Artist', '2001', 'Album'] == [song.flac_artist, song.flac_date, song.flac_album] assert ['01', 'Title'] == [song.flac_track, song.flac_title] assert [True, True] == [song.flac_has_lyrics, song.flac_has_picture] assert song.metadata_ok
def ogg_coverart(config): print("Adding " + config.coverart_mime + " cover art to " + config.ogg_file) coverart = config.coverart imgdata = open(coverart,'rb').read() im = Image.open(coverart) w,h = im.size p = Picture() p.data = imgdata p.type = 3 p.desc = 'Cover' p.mime = config.coverart_mime p.width = w p.height = h p.depth = 24 dt=p.write() enc=base64.b64encode(dt).decode('ascii') audio = OggVorbis(config.ogg_file) audio['metadata_block_picture']=[enc] audio.save()
def _set_tag(self, raw, tag, value): if tag == 'metadata_block_picture': new_value = [] for v in value: picture = Picture() picture.type = v.type picture.desc = v.desc picture.mime = v.mime picture.data = v.data new_value.append(base64.b64encode(picture.write())) value = new_value else: # vorbis has text based attributes, so convert everything to unicode value = [xl.unicode.to_unicode(v) for v in value] CaseInsensitveBaseFormat._set_tag(self, raw, tag, value)
def set_image(self, image): """Replaces all embedded images by the passed image""" try: audio = self.MutagenType(self["~filename"]) data = image.file.read() except EnvironmentError: return 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 audio.pop("coverart", None) audio.pop("coverartmime", None) audio["metadata_block_picture"] = base64.b64encode(pic.write()) audio.save() self.has_images = True