Пример #1
0
    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())
Пример #2
0
    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)
Пример #3
0
    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())
Пример #4
0
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
Пример #5
0
    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)
Пример #6
0
 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()
Пример #7
0
    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
Пример #8
0
    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
Пример #9
0
 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_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')))
Пример #11
0
 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)
Пример #12
0
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)
Пример #13
0
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)))
Пример #14
0
    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()
Пример #15
0
    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)
Пример #16
0
    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)
Пример #17
0
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')
Пример #18
0
    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)
Пример #19
0
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')
Пример #20
0
def write_tags(pre_abs, meta, fmt, cov_abs):
	if fmt == "FLAC":
		audio = FLAC(pre_abs)
		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)
Пример #21
0
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()
Пример #22
0
    def buttonAddPictureClicked(self):
        self.logger("buttonAddPictureClicked")
        filename = QtGui.QFileDialog.getOpenFileName(self, "Image File")
        reader = QtGui.QImageReader(filename)
        rformat = reader.format()
        image = reader.read()
        self.coverArtPixmap = QtGui.QPixmap.fromImage(image)
        self.logger(
            'width = %d, height = %d' %
            (self.coverArtPixmap.width(), self.coverArtPixmap.height()))
        self.labelPicture.setPixmap(
            self.coverArtPixmap.scaled(self.labelPicture.width(),
                                       self.labelPicture.height(),
                                       QtCore.Qt.KeepAspectRatio))

        pic = Picture()

        data = Qt.QByteArray()
        buf = Qt.QBuffer(data)

        pic.type = 3  # APICType.COVER_FRONT
        self.logger('format: %s' % rformat)
        if rformat == 'png':
            pic.mime = 'image/png'
            image.save(buf, 'PNG')
        elif rformat == 'jpg' or rformat == 'jpeg':
            pic.mime = 'image/jpeg'
            image.save(buf, 'JPG')
        else:
            pic.mime = 'image/unknown'
        self.logger("format: %s" % pic.mime)
        pic.data = data.data()
        pic.width = self.coverArtPixmap.width()
        pic.height = self.coverArtPixmap.height()
        pic.depth = self.coverArtPixmap.depth()
        pic.colors = image.colorCount()
        if len(self.audio.pictures) > 0:
            ret = QtGui.QMessageBox.warning(
                self, "FLAC Tagger",
                "This FLAC file already contains one or more pictures.\n"
                "Do you want to replace them?",
                QtGui.QMessageBox.Yes | QtGui.QMessageBox.Cancel,
                QtGui.QMessageBox.Cancel)
            if ret == QtGui.QMessageBox.Yes:
                self.audio.clear_pictures()
                self.audio.addPicture(pic)
            else:
                # make sure the old picture is displayed again
                self.displayPictures()
        else:
            self.audio.addPicture(pic)
Пример #23
0
    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()
Пример #24
0
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)
        except:
            return

    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
Пример #25
0
    def set_image(self, image):
        pic = Picture()
        pic.data = image.read()
        pic.type = COVER_FRONT
        pic.mime = image.mime_type
        pic.width = image.width
        pic.height = image.height
        # pic.depth = image.color_depth

        self.audio.add_picture(pic)
        with translate_errors():
            self.audio.save()
        # clear vcomment tags
        super().clear_images()
Пример #26
0
    def test_clear_images(self):
        data = b"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())
Пример #27
0
    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())
Пример #28
0
    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)
Пример #29
0
    def set_image(self, image):
        """Replaces all embedded images by the passed image"""

        with image:
            pic = Picture()
            pic.data = image.read()
            pic.type = COVER_FRONT
            pic.mime = image.mime_type
            pic.width = image.width
            pic.height = image.height

            self.audio.pop("coverart", None)
            self.audio.pop("coverartmime", None)
            self.audio["metadata_block_picture"] = base64.b64encode(
                pic.write()).decode("ascii")
Пример #30
0
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()
Пример #31
0
    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)
Пример #32
0
    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
Пример #33
0
 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)
Пример #34
0
 def test_clear_tags_preserve_legacy_coverart(self):
     # FLAC does not use the cover art tags but has its separate image implementation
     pic = Picture()
     pic.data = load_coverart_file('mb.png')
     save_raw(
         self.filename, {
             'coverart':
             PNG_BASE64,
             'metadata_block_picture':
             base64.b64encode(pic.write()).decode('ascii')
         })
     config.setting['clear_existing_tags'] = True
     config.setting['preserve_images'] = True
     metadata = save_and_load_metadata(self.filename, Metadata())
     self.assertEqual(0, len(metadata.images))
Пример #35
0
    def get_cover_picture(self, cover):
        """ Returns mutagen 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
Пример #36
0
 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)
Пример #37
0
def tag_put_picture(album_id):
    pic = Picture()
    album = get_album(album_id)
    with open(album['Path'] + "/folder.jpg", "rb") as f:
        pic.data = f.read()
    if not pic.data:
        return 'No folder.jpg found'
    pic.type = id3.PictureType.COVER_FRONT
    pic.mime = u"image/jpeg"
    pic.width = 500
    pic.height = 500
    pic.depth = 16
    for p in tag_get_piece_paths(album_id):
        set_pic(p, pic)
    return 'success'
Пример #38
0
def write_tags(pre_path, meta, cov_path):
	del meta['track_padded']
	audio = FLAC(pre_path)
	audio.delete()
	for k, v in meta.items():
		if v:
			audio[k] = str(v)
	if cov_path:
		image = Picture()
		with open(cov_path, 'rb') as f:
			image.data = f.read()
		image.type = 3
		image.mime = "image/jpeg"
		audio.add_picture(image)
	audio.save(pre_path)
Пример #39
0
 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)
Пример #40
0
 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)
Пример #41
0
    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_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
Пример #43
0
def addInfoToFlac(filename, songInfo):
    filePath = os.path.join(songInfo["audioBasePath"], filename)
    audio = FLAC(filePath)

    pic = Picture()
    with open(songInfo["imgPath"], "rb") as f:
        pic.data = f.read()
    pic.type = PictureType.COVER_FRONT
    pic.mime = u"image/jpeg"

    audio.add_picture(pic)
    audio["title"] = songInfo["name"]
    audio["artist"] = songInfo["artist"]
    audio["album"] = songInfo["album"]

    audio.save()
Пример #44
0
 def _image_flac(self):
     if self.image and cfg.embed_cover:
         audio = FLAC(self.path)
         img = Picture()
         img.type = 3
         img.data = requests.get(self.image).content
         if cfg.overwrite_cover:
             audio.clear_pictures()
             audio.add_picture(img)
             self.cover_updated = True
         else:
             if self.cover_embedded is False:
                 audio.clear_pictures()
                 audio.add_picture(img)
                 self.cover_updated = True
         audio.save()
Пример #45
0
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()
Пример #46
0
 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)
Пример #47
0
def writeAlbumCov(file):
	if file.endswith('c'):
		audio = File(file)
		image = Picture()
		image.type = 3
		mime = "image/jpeg"
		with open("cover.jpg", 'rb') as f:
			image.data = f.read()
			audio.clear_pictures()
			audio.add_picture(image)
			audio.save()
	else:
		audio = MP4(file)
		with open("cover.jpg", 'rb') as f:
			audio['covr'] = [MP4Cover(f.read(), imageformat = MP4Cover.FORMAT_JPEG)]
			audio.save(file)
Пример #48
0
 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)
Пример #49
0
    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()
Пример #50
0
    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()
Пример #51
0
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.")
Пример #52
0
    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 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()
Пример #54
0
    def tag_flac(self, file_path, track_info, album_info, album_art_path=None):
        tagger = FLAC(file_path)

        self._meta_tag(tagger, track_info, album_info)
        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()
    	    
    	    pic.type = PictureType.COVER_FRONT
    	    pic.mime = u"image/jpeg"
            # TODO: detect this automatically?
    	    pic.width = 1280
    	    pic.height = 1280
    	    pic.depth = 24
    	    tagger.add_picture(pic)
        tagger.save(file_path)
Пример #55
0
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
Пример #56
0
    def to_flac(self, flac_meta: FLAC, builtin_cuesheet=False) -> None:
        '''
        :param builtin_cuesheet: Whether to use the cuesheet field builtin FLAC specs
        '''
        def add_if_exist(obj, tag_key):
            if obj:
                flac_meta.tags[tag_key] = obj

        add_if_exist(self.title, 'ALBUM')
        add_if_exist(self.genre, 'GENRE')
        add_if_exist(self.date, 'DATE')
        if self.artists:
            flac_meta.tags['ALBUM ARTIST'] = list(self.artists)
        if self.discnumber is not None:
            flac_meta.tags['DISCNUMBER'] = str(self.discnumber)

        if self.cover:
            image = Image.open(BytesIO(self.cover))
            pic = Picture()
            pic.type = PictureType.COVER_FRONT
            pic.data = self.cover
            pic.mime = Image.MIME[image.format]
            pic.width = image.width
            pic.height = image.height
            flac_meta.add_picture(pic)

        if self.cuesheet:
            if builtin_cuesheet:
                flac_meta.cuesheet = self.cuesheet.to_flac(
                    flac_meta.info.sample_rate)
                flac_meta.cuesheet.tracks.append(
                    CueSheetTrack(170,
                                  flac_meta.info.total_samples))  # lead-out

                # save track-wise tags in foobar2000 style
                tracks = next(iter(self.cuesheet.files.values()))
                for i, track in tracks.items():
                    add_if_exist(track.title, f'CUE_TRACK{i:02}_TITLE')
                    add_if_exist(track.performer, f'CUE_TRACK{i:02}_PERFORMER')
            else:
                flac_meta.tags['CUESHEET'] = str(self.cuesheet)
            add_if_exist(self.cuesheet.catalog, 'Catalog')
            add_if_exist(self.cuesheet.rems.get('COMMENT', None), 'Comment')

        flac_meta.save()
Пример #57
0
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
Пример #58
0
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()
Пример #59
0
    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
Пример #60
0
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