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 _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 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 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 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 _embed_flac_img(root_dir, audio: FLAC): emb_image = os.path.join(root_dir, "cover.jpg") multi_emb_image = os.path.join( os.path.abspath(os.path.join(root_dir, os.pardir)), "cover.jpg") if os.path.isfile(emb_image): cover_image = emb_image else: cover_image = multi_emb_image try: # rest of the metadata still gets embedded # when the image size is too big if os.path.getsize(cover_image) > FLAC_MAX_BLOCKSIZE: raise Exception("downloaded cover size too large to embed. " "turn off `og_cover` to avoid error") image = Picture() image.type = 3 image.mime = "image/jpeg" image.desc = "cover" with open(cover_image, "rb") as img: image.data = img.read() audio.add_picture(image) except Exception as e: logger.error(f"Error embedding image: {e}", exc_info=True)
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 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 _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 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 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 embed_art(self, art_path): pic = Picture() with open(art_path, "rb") as f: pic.data = f.read() pic.type = 3 # front cover pic.mime = MetaAudio.get_mime_type(art_path) pic.desc = 'front cover' self.audio[ART_TAG] = base64.b64encode(pic.write()).decode('utf8')
def picture(self, url): from mutagen.flac import Picture image = Picture() image.type = 3 image.mime = 'image/jpeg' image.desc = 'front cover' image.data = get(url).content self.audio.add_picture(image)
def embed_art(self, art_path): pic = Picture() with open(art_path, "rb") as f: pic.data = f.read() pic.type = 3 # front cover pic.mime = MetaAudio.get_mime_type(art_path) pic.desc = 'front cover' self.audio.add_picture(pic)
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)))
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 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 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 update_flac(self, path: str, track: beatport.Track): f = FLAC(path) if UpdatableTags.title in self.config.update_tags and self.config.overwrite: f['TITLE'] = track.title if UpdatableTags.artist in self.config.update_tags and self.config.overwrite: f['ARTIST'] = self.config.artist_separator.join( [a.name for a in track.artists]) if UpdatableTags.album in self.config.update_tags and ( self.config.overwrite or f.get('ALBUM') == None): f['ALBUM'] = track.album.name if UpdatableTags.label in self.config.update_tags and ( self.config.overwrite or f.get('LABEL') == None): f['LABEL'] = track.label.name if UpdatableTags.bpm in self.config.update_tags and ( self.config.overwrite or f.get('BPM') == None): f['BPM'] = str(track.bpm) if UpdatableTags.genre in self.config.update_tags and ( self.config.overwrite or f.get('GENRE') == None): f['GENRE'] = ', '.join([g.name for g in track.genres]) if UpdatableTags.date in self.config.update_tags and ( self.config.overwrite or f.get('DATE') == None): f['DATE'] = track.release_date.strftime('%Y-%m-%d') #Year - part of date if UpdatableTags.key in self.config.update_tags and ( self.config.overwrite or f.get('INITIALKEY') == None): f['INITIALKEY'] = track.id3key() if UpdatableTags.publishdate in self.config.update_tags and ( self.config.overwrite or f.get('ORIGINALDATE') == None): f['ORIGINALDATE'] = str(track.publish_date.year) #Other tags if UpdatableTags.other in self.config.update_tags: f['WWWAUDIOFILE'] = track.url() f['WWWPUBLISHER'] = track.label.url('label') #Redownlaod cover if self.config.replace_art: try: url = track.art(self.config.art_resolution) r = requests.get(url) image = Picture() image.type = 3 image.mime = 'image/jpeg' image.desc = 'Cover' image.data = r.content f.clear_pictures() f.add_picture(image) except Exception: logging.warning('Error downloading cover for file: ' + path) f.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_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 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 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 _add_ogg_image(audio: File, image: Image, image_data: bytes): picture = Picture() picture.data = image_data picture.type = 3 # Front cover picture.desc = u"Cover Art" picture.mime = _image_mimes[image.format] picture.width = image.width picture.height = image.height picture.depth = 24 picture_data = picture.write() encoded_data = base64.b64encode(picture_data) vcomment_value = encoded_data.decode("ascii") audio["metadata_block_picture"] = [vcomment_value] audio.save()
def download_flac(track): url = session.get_media_url(track_id=track.id) name_tag = translit(""+track.name, "ru", reversed=True).encode("UTF-8") name = translit(""+track.name, "ru", reversed=True).encode("UTF-8").replace("?", "").replace("(", "").replace(")", "").replace("<", "").replace(">", "").replace(":", "").replace("/", "").replace("|", "").replace('"', "").replace("*", "") artist_name = translit(u""+track.artist.name, "ru", reversed=True).encode("UTF-8") album_name = translit(u""+track.album.name, "ru", reversed=True).encode("UTF-8") releaseDate = str(track.album.release_date) print(name+' - '+url) album_artist = translit(u""+track.album.artist.name, "ru", reversed=True).encode("UTF-8") try: if ".m4a" not in url: download(url, "music/"+name+".flac") except Exception: flac = 0 try: if ".m4a" not in url: download(track.album.image, 'music/'+name+'.png') except Exception: flac = 0 if os.path.exists("music/"+name+".flac"): flac = 1 if not os.path.exists("music/"+name+".flac"): flac = 0 if ".flac" not in url: flac = 0 if ".flac" in url: flac = 1 if flac == 1: audio = FLAC("music/"+name+".flac") albumart = "music/"+name+".png" image = Picture() image.type = 3 mime = 'image/png' image.desc = 'front cover' with open(albumart, 'rb') as f: image.data = f.read() audio['artist'] = track.artist.name audio['title'] = track.name audio['album'] = track.album.name audio['date'] = releaseDate audio.add_picture(image) audio.save() os.remove("music/"+name+".png") elif flac == 0: print(name+" isn't in flac or can't be downloaded in this country.") else: print("Unknown error.")
def create_album_art(self, art_location: str): with open(art_location, 'rb') as image: image_data = image.read() image = Image.open(io.BytesIO(image_data)) picture = Picture() picture.data = image_data picture.type = 3 # COVER_FRONT picture.mime = file_type(art_location) picture.width, picture.height = image.size picture.depth = mode_to_depth(image.mode) picture.desc = "Front Cover" image.close() return picture
def _embed_cover(audio_file, song_obj, encoding): image = Picture() image.type = 3 image.desc = "Cover" image.mime = "image/jpeg" image.data = urlopen(song_obj.get_album_cover_url()).read() if encoding == "flac": audio_file.add_picture(image) elif encoding == "ogg" or encoding == "opus": # From the Mutagen docs (https://mutagen.readthedocs.io/en/latest/user/vcomment.html) image_data = image.write() encoded_data = base64.b64encode(image_data) vcomment_value = encoded_data.decode("ascii") audio_file["metadata_block_picture"] = [vcomment_value] return audio_file
def add_albumart(working_dir, folder_name, title): audio = File(os.path.join(working_dir, folder_name, f'{title}.flac')) image = Picture() image.type = 3 mime = 'image/png' image.desc = 'front cover' # better than open(albumart, 'rb').read() ? with open( os.path.join(working_dir, folder_name, 'albumart', f'{title}.png'), 'rb') as f: image.data = f.read() audio.add_picture(image) audio.save()
def saveArtwork(self): if Path(self.file_name).suffix == ".flac": audiof = FLAC(self.file_path) if len(audiof.pictures) != 0: return dl_img = urllib3.PoolManager(cert_reqs='CERT_NONE', assert_hostname=False).request('GET', self.artwork_url).data img = Picture() img.type = 3 img.desc = 'artwork' img.data = dl_img audiof.add_picture(img) elif Path(self.file_name).suffix == ".mp3": audiof = ID3(self.file_path) if hasattr(audiof, "pictures") and len(audiof.pictures) != 0: return dl_img = urllib3.PoolManager(cert_reqs='CERT_NONE', assert_hostname=False).request('GET', self.artwork_url).data audiof.add(mutagen.id3.APIC(3, 'image/jpeg', 3, 'Front cover', dl_img)) audiof.save()
def resolve_flac_metadata(song, path, picture, config): try: tagger = FLAC(path) except mutagen.flac.FLACNoHeaderError: raise InvalidFileError() tagger["title"] = song.name tagger["album"] = song.album.name tagger["artist"] = song.get_primary_artist_name(config) tagger["albumartist"] = song.album.get_primary_artist_name(config) tagger["tracknumber"] = str(song.track_number) tagger["discnumber"] = str(song.disc_number) if picture: flac_picture = FLACPicture() flac_picture.type = 3 flac_picture.desc = "Cover" flac_picture.mime = picture["mime"] flac_picture.data = picture["data"] tagger.add_picture(flac_picture) tagger.save()
def _embed_mbp_picture(self, audiofile, metadata, cached_albumart, encoding): 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() image.data = cached_albumart if encoding == "flac": audiofile.add_picture(image) elif encoding == "ogg" or encoding == "opus": # From the Mutagen docs (https://mutagen.readthedocs.io/en/latest/user/vcomment.html) image_data = image.write() encoded_data = base64.b64encode(image_data) vcomment_value = encoded_data.decode("ascii") audiofile["metadata_block_picture"] = [vcomment_value]
def addCover(self): if self.fileSuffix == "mp3" or self.fileSuffix == "MP3": self.songFile.tags.add( APIC(encoding=3, mime='image/jpeg', type=3, desc="Cover", data=self.albumart)) elif self.fileSuffix == "flac" or self.fileSuffix == "FLAC": image = Picture() image.type = id3.PictureType.COVER_FRONT image.mime = 'image/jpeg' image.desc = "Cover" image.data = self.albumart image.width = 500 image.height = 500 image.depth = 16 self.songFile.add_picture(image) self.songFile.save()
def updateCoverOgg(lossyFileName, artworkFileName): # # Embed album art into transcoded file: OGG # import base64 from mutagen.oggvorbis import OggVorbis from mutagen.flac import Picture import PIL.Image import tempfile from shutil import copyfile # Use copyfile b/c this will *not* copy rights (which is error prone on gvfs/samba) log('- embedding album art ' + artworkFileName + ' to ' + lossyFileName) # Copy lossy file to a local location; to prevent (save) errors in a samba environment tempLossyFile = tempfile.gettempdir() + '/' + 'temp.ogg' copyfile(lossyFileName, tempLossyFile) # Embed the image o = OggVorbis(tempLossyFile) im = PIL.Image.open(artworkFileName) w, h = im.size p = Picture() imdata = open(artworkFileName, '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') o['metadata_block_picture'] = [enc] o.save() # Now we are ready; copy the file to the desired output directory copyfile(tempLossyFile, lossyFileName) os.remove(tempLossyFile) # Remove the temporary file(s) return
def resolve_flac_metadata(config: dict, track: Track, path: str, cover: Optional[Cover]) -> None: try: tagger = FLAC(path) except mutagen.flac.FLACNoHeaderError: raise InvalidFileError() tagger["title"] = track.name tagger["album"] = track.album.name tagger["artist"] = [artist.name for artist in track.artists] tagger["albumartist"] = [artist.name for artist in track.album.artists] tagger["tracknumber"] = str(track.track_number) tagger["discnumber"] = str(track.disc_number) if cover: flac_picture = FLACPicture() flac_picture.type = 3 flac_picture.desc = "Cover" flac_picture.mime = cover.mime flac_picture.data = cover.data tagger.add_picture(flac_picture) tagger.save()
def as_flac(self): music_file = self.music_file meta_tags = self.meta_tags audiofile = FLAC(music_file) self._embed_basic_metadata(audiofile) audiofile['year'] = meta_tags['year'] audiofile['comment'] = meta_tags['external_urls']['spotify'] if meta_tags['lyrics']: audiofile['lyrics'] = meta_tags['lyrics'] image = Picture() image.type = 3 image.desc = 'Cover' image.mime = 'image/jpeg' albumart = urllib.request.urlopen(meta_tags['album']['images'][0]['url']) image.data = albumart.read() albumart.close() audiofile.add_picture(image) audiofile.save() return True
def as_flac(self): music_file = self.music_file meta_tags = self.meta_tags audiofile = FLAC(music_file) self._embed_basic_metadata(audiofile) audiofile["year"] = meta_tags["year"] audiofile["comment"] = meta_tags["external_urls"][self.provider] if meta_tags["lyrics"]: audiofile["lyrics"] = meta_tags["lyrics"] image = Picture() image.type = 3 image.desc = "Cover" image.mime = "image/jpeg" albumart = urllib.request.urlopen( meta_tags["album"]["images"][0]["url"]) image.data = albumart.read() albumart.close() audiofile.add_picture(image) audiofile.save() return True
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 split_item(item, digital_folder=digital_folder, dropbox_move=True): logging.info("BLOOOAAARRRRGHHGGGGHHHHH!!! (Please hold...)") audio = wave.open(item.path) audio.params = audio.getparams() # Load AudioSegment for encoded segments if item.digital_ext is not "wav": audio_segment = AudioSegment.from_wav(item.path) # Loop through cues and write regions (assumes start and end markers) for i, track in enumerate(item.tracks): # Build track filename digital_track_name = "{0} - {1} - {2}".format(item.digital_file_name, str(i + 1), track.title) digital_track_name = "".join( [c for c in digital_track_name if c.isalpha() or c.isdigit() or c in "'- ._()!@#$%^&*"] ).rstrip(". ") if dropbox_move: digital_track_path = os.path.join(item.dropbox_order_folder, digital_track_name) + "." + item.digital_ext else: digital_track_path = os.path.join(digital_folder, digital_track_name) + "." + item.digital_ext logging.info("Region {0} | {1} -> {2}".format(i + 1, track.duration, digital_track_path)) # Split, export track if "wav" not in item.digital_ext: digital_track = audio_segment[(item.cues[i] / 44.1) : (item.cues[i + 1] / 44.1)] tags = { "title": track.title or "Track {0}".format(i + 1), "artist": item.artist, "albumartist": item.artist, "album": (item.album or item.artist), "track": (i + 1), } digital_track.export( out_f=digital_track_path, format=item.digital_ext, bitrate=item.bitrate, tags=tags, id3v2_version="3" ) # Add cover art if item.thumb and (item.digital_ext == "mp3"): mutagen_audio = MP3(digital_track_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(v2_version=3) elif item.thumb and (item.digital_ext == "flac"): mutagen_audio = File(digital_track_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)) else: digital_track = wave.open(digital_track_path, "w") digital_track.setparams(audio.params) region_length = item.cues[i + 1] - item.cues[i] digital_track.writeframes(audio.readframes(region_length)) digital_track.close() audio.close()
def export_digital(item): """ Export and/or split digital files for an item (parallelized) """ logging.info('{0} -> {1}'.format(item.name, digital_folder)) if 'std' in item.option: if just_add_tags: if item.digital_ext == 'mp3': mutagen_audio = ID3(item.digital_file_path) mutagen_audio.add(TIT2(encoding=3, text=item.album)) mutagen_audio.add(TOA(encoding=3, text=item.artist)) mutagen_audio.add(TP1(encoding=3, text=item.artist)) mutagen_audio.add(TP2(encoding=3, text=item.artist)) mutagen_audio.add(TP4(encoding=3, text=item.artist)) mutagen_audio.add(TAL(encoding=3, text=item.album)) mutagen_audio.save(v2_version=3) elif item.digital_ext == 'flac': mutagen_audio = FLAC(item.digital_file_path) mutagen_audio['title'] = item.album mutagen_audio['artist'] = item.artist mutagen_audio['albumartist'] = item.artist mutagen_audio['album'] = item.album mutagen_audio.save() else: raise Exception('Format {0} not recognized for item {1} tags.'.format(item.digital_ext, item.name)) 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=item.bitrate, tags={ 'title':(item.album or item.artist), 'artist':item.artist, 'albumartist':item.artist, 'album':(item.album or item.artist)}, id3v2_version='3') # 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(v2_version=3) 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() elif item.image: 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) # Deluxe / 45 else: split.split_item(item, digital_folder, dropbox_move)
def export_digital(item): """ Export and/or split digital files for an item (parallelized) """ logging.info('{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=item.bitrate, 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) # Deluxe / 45 else: split.split_item(item, digital_folder, dropbox_move, item.bitrate) # Move original wave to mp3 folder, so we don't see it in the to-burn list if not 'cd' in item.format: shutil.move(item.path, os.path.join(digital_folder, item.filename)) try: shutil.move(os.path.splitext(item.path)[0] + '.pkf', os.path.join(digital_folder, os.path.splitext(item.filename)[0] + '.pkf')) except IOError: pass
def split_item(item, DIGITAL_FOLDER=mp3_folder, DROPBOX_COPY=False): logging.info('BLOOOAAARRRRGHHGGGGHHHHH!!! (Please hold...)') audio = wave.open(item.path) audio.params = audio.getparams() # Load AudioSegment for encoded segments if item.digital_ext is not 'wav': audio_segment = AudioSegment.from_wav(item.path) # Loop through cues and write regions (assumes start and end markers) for i, track in enumerate(item.tracks): # Build track filename digital_track_name = '{0} - {1} - {2}'.format(item.digital_file_name, str(i + 1), track.title) digital_track_name = ''.join([c for c in digital_track_name if c.isalpha() or c.isdigit() or c in "'- ._()!@#$%^&*"]).rstrip('. ') digital_track_path = os.path.join(DIGITAL_FOLDER, digital_track_name) + '.' + item.digital_ext logging.info('Region {0} | {1} -> {2}'.format(i + 1, track.duration, digital_track_path)) # Split, export track if 'wav' not in item.digital_ext: digital_track = audio_segment[(item.cues[i] / 44.1):(item.cues[i + 1] / 44.1)] tags = {'title':track.title, 'artist':item.artist, 'albumartist':item.artist, 'album':(item.album or item.artist), 'track':(i + 1)} digital_track.export(out_f=digital_track_path, format=item.digital_ext, bitrate='192k', tags=tags) # Add cover art if item.thumb and (item.digital_ext == 'mp3'): mutagen_audio = MP3(digital_track_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(digital_track_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)) else: digital_track = wave.open(digital_track_path, 'w') digital_track.setparams(audio.params) region_length = item.cues[i + 1] - item.cues[i] digital_track.writeframes(audio.readframes(region_length)) digital_track.close() if DROPBOX_COPY: # Copy finished digital file to Dropbox order folder shutil.copy2(digital_track_path, item.dropbox_order_folder) audio.close()
def export_digital(item): """ Export and/or split digital files for an item (parallelized) """ logging.info("{0} -> {1}".format(item.name, config.digital_folder)) if "std" in item.option: if config.just_add_tags: if item.digital_ext == "mp3": mutagen_audio = ID3(item.digital_file_path) mutagen_audio.add(TIT2(encoding=3, text=item.album)) mutagen_audio.add(TOA(encoding=3, text=item.artist)) mutagen_audio.add(TP1(encoding=3, text=item.artist)) mutagen_audio.add(TP2(encoding=3, text=item.artist)) mutagen_audio.add(TP4(encoding=3, text=item.artist)) mutagen_audio.add(TAL(encoding=3, text=item.album)) mutagen_audio.save(v2_version=3) elif item.digital_ext == "flac": mutagen_audio = FLAC(item.digital_file_path) mutagen_audio["title"] = item.album mutagen_audio["artist"] = item.artist mutagen_audio["albumartist"] = item.artist mutagen_audio["album"] = item.album mutagen_audio.save() else: raise Exception("Format {0} not recognized for item {1} tags.".format(item.digital_ext, item.name)) 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=item.bitrate, tags={ "title": (item.album or item.artist), "artist": item.artist, "albumartist": item.artist, "album": (item.album or item.artist), }, id3v2_version="3", ) # 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(v2_version=3) 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() elif item.image: logging.warning("No cover found for item {0}".format(item.name)) if config.just_add_tags: os.rename(item.digital_file_path, item.digital_rename_path) # Deluxe / 45 else: split.split_item(item, config.digital_folder, config.dropbox_move)