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')))
Exemplo n.º 2
0
 def write_tags(self, song, data):
     try:
         tag = mutagen.File(song, easy=True)
         tag.add_tags()
     except mutagen.flac.FLACVorbisError:
         tag = FLAC(song)
         tag.delete()
         images = Picture()
         images.type = 3
         images.data = data['image']
         tag.add_picture(images)
     except mutagen.id3._util.error:
         pass
     tag['artist'] = data['artist']
     tag['title'] = data['music']
     tag['date'] = data['year']
     tag['album'] = data['album']
     tag['tracknumber'] = data['tracknum']
     tag['discnumber'] = data['discnum']
     tag['genre'] = " & ".join(data['genre'])
     tag['albumartist'] = data['ar_album']
     tag.save()
     try:
         audio = ID3(song)
         audio['APIC'] = APIC(encoding=3,
                              mime="image/jpeg",
                              type=3,
                              desc=u"Cover",
                              data=data['image'])
         audio.save()
     except mutagen.id3._util.ID3NoHeaderError:
         pass
Exemplo n.º 3
0
def write_tags(f, meta, cov, com, fmt):
    if fmt == "FLAC":
        audio = FLAC(f)
        for tag, value in meta.items():
            if value:
                audio[tag] = str(value)
        if com:
            audio['COMMENT'] = com
    else:
        audio = MP4(f)
        audio['\xa9nam'] = meta['TITLE']
        audio['\xa9alb'] = meta['ALBUM']
        audio['aART'] = meta['ALBUMARTIST']
        audio['\xa9ART'] = meta['ARTIST']
        audio['trkn'] = [(meta['TRACK'], meta['TRACKTOTAL'])]
        audio['\xa9day'] = meta['YEAR']
        if meta['COPYRIGHT']:
            audio['cprt'] = meta['COPYRIGHT']
        if com:
            audio['\xa9cmt'] = com
    with open(cov, 'rb') as cov_obj:
        if fmt == "FLAC":
            image = Picture()
            image.type = 3
            image.mime = "image/jpeg"
            image.data = cov_obj.read()
            audio.add_picture(image)
        else:
            audio['covr'] = [
                MP4Cover(cov_obj.read(), imageformat=MP4Cover.FORMAT_JPEG)
            ]
    audio.save()
Exemplo n.º 4
0
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)
Exemplo n.º 5
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()
Exemplo n.º 6
0
    def test_get_images(self):
        pic = Picture()
        pic.data = _get_jpeg()
        pic.type = APICType.COVER_FRONT
        b64pic_cover = base64.b64encode(pic.write()).decode("ascii")

        # metadata_block_picture
        song = FLAC(self.filename)
        song["metadata_block_picture"] = [b64pic_cover]
        song.save()

        song = FLACFile(self.filename)
        self.assertEqual(len(song.get_images()), 1)
        self.assertEqual(song.get_images()[0].type, APICType.COVER_FRONT)

        # flac Picture
        song = FLAC(self.filename)
        pic = Picture()
        pic.data = _get_jpeg()
        pic.type = APICType.COVER_BACK
        song.add_picture(pic)
        song.save()

        song = FLACFile(self.filename)
        self.assertEqual(len(song.get_images()), 2)
        self.assertEqual(song.get_images()[-1].type, APICType.COVER_BACK)
Exemplo n.º 7
0
def write_tags(f, meta, cov):
    if f.endswith('.mp3'):
        try:
            audio = id3.ID3(f)
        except ID3NoHeaderError:
            audio = id3.ID3()
        audio['TRCK'] = id3.TRCK(encoding=3,
                                 text=str(meta['TRACK']) + "/" +
                                 str(meta['TRACKTOTAL']))
        legend = {
            "ALBUM": id3.TALB,
            "ALBUMARTIST": id3.TPE2,
            "ARTIST": id3.TPE1,
            "COPYRIGHT": id3.TCOP,
            "TITLE": id3.TIT2,
            "YEAR": id3.TYER
        }
        for tag, value in meta.items():
            if not tag in ['UPC', 'TRACK', 'TRACKTOTAL']:
                id3tag = legend[tag]
                audio[id3tag.__name__] = id3tag(encoding=3, text=value)
        with open(cov, 'rb') as cov_obj:
            audio.add(id3.APIC(3, 'image/jpeg', 3, '', cov_obj.read()))
        audio.save(f, 'v2_version=3')
    else:
        audio = FLAC(f)
        for tag, value in meta.items():
            audio[tag] = str(value)
            image = Picture()
        image.type = 3
        image.mime = "image/jpeg"
        with open(cov, 'rb') as cov_obj:
            image.data = cov_obj.read()
            audio.add_picture(image)
        audio.save()
Exemplo n.º 8
0
 def test_add_picture(self):
     f = FLAC(self.NEW)
     c = len(f.pictures)
     f.add_picture(Picture())
     f.save()
     f = FLAC(self.NEW)
     self.failUnlessEqual(len(f.pictures), c + 1)
Exemplo n.º 9
0
    def tag_flac(self,
                 file_path,
                 track_info,
                 album_info,
                 lyrics,
                 album_art_path=None):
        tagger = FLAC(file_path)

        self._meta_tag(tagger, track_info, album_info, 'flac')
        if self.fmtopts['embed_album_art'] and album_art_path is not None:
            pic = Picture()
            with open(album_art_path, 'rb') as f:
                pic.data = f.read()

            # Check if cover is smaller than 16MB
            if len(pic.data) < pic._MAX_SIZE:
                pic.type = PictureType.COVER_FRONT
                pic.mime = u"image/jpeg"
                tagger.add_picture(pic)
            else:
                print(
                    '\tCover file size is too large, only {0:.2f}MB are allowed.'
                    .format(pic._MAX_SIZE / 1024**2))
                print(
                    '\tSet "artwork_size" to a lower value in config/settings.py'
                )

        # Set lyrics from Deezer
        if lyrics:
            tagger['lyrics'] = lyrics

        tagger.save(file_path)
Exemplo n.º 10
0
    def on_save(self):
        audio = FLAC(self.song.get("~filename", ""))
        ## if file has no images -> leave
        if (audio.pictures is None) or (len(audio.pictures) <= 0):
            return
        ## first,clear all pictures, then add the images in order
        try:
            audio.clear_pictures()
        except:
            self.printError()
            return False
        for row in self.liststore:
            img = row[1]
            try:
                audio.add_picture(img)
            except:
                self.printError()
                return False
        audio.save()
        count = 0
        if (audio.pictures is None) or (len(audio.pictures) <= 0):
            pass
        else:
            count = str(len(audio.pictures))

        self.song["pictures"] = count
        app.window.emit("artwork-changed", [self.song])
        del self.coverlist[:]
        self.liststore.clear()
        self.start_search()
        return True
Exemplo n.º 11
0
 def test_add_picture(self):
     f = FLAC(self.NEW)
     c = len(f.pictures)
     f.add_picture(Picture())
     f.save()
     f = FLAC(self.NEW)
     self.failUnlessEqual(len(f.pictures), c + 1)
Exemplo n.º 12
0
class MetaFLAC(MetaAudio):
    def __init__(self, path):
        self.audio_path = path
        self.audio = FLAC(path)
        try:
            if 'albumartist' in self.audio:
                # use Album Artist first
                self.artist = self.audio['albumartist'][0]
            else:
                self.artist = self.audio['artist'][0]
            self.album = self.audio['album'][0]
            self.title = self.audio['title'][0]
        except Exception:
            raise Exception("missing FLAC tags")

    def has_embedded_art(self):
        return self.audio.pictures != []

    def detach_art(self):
        self.audio.clear_pictures()

    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 save(self):
        self.audio.save()
Exemplo n.º 13
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
Exemplo n.º 14
0
	def setImage(self, song):
		audio = FLAC(song.get("~filename", ""))
		if len(self.imgFiles) <= 0:
			return

		for p in self.imgFiles:
			try:
				audio.add_picture(p)
			except:
				printError()
				return False
		audio.save()
		## and now count the images
		count = "0"
		## if file has no images -> set to 0
		if (audio.pictures is None) or (len(audio.pictures) <= 0):
			pass
		else:
			count = str(len(audio.pictures))

		if not "pictures" in song:
			song["pictures"] = count

		if song["pictures"] <> count:
			song["pictures"] = count
		app.window.emit("artwork-changed", [song])
		return
    def 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()
Exemplo n.º 16
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()
Exemplo n.º 17
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)
Exemplo n.º 18
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().clear_images()

        self.has_images = True
Exemplo n.º 19
0
	def on_save(self):
		audio = FLAC(self.song.get("~filename", ""))
		## if file has no images -> leave
		if (audio.pictures is None) or (len(audio.pictures) <= 0):
			return
		## first,clear all pictures, then add the images in order
		try:
			audio.clear_pictures()
		except:
			self.printError()
			return False
		for row in self.liststore:
			img = row[1]
			try:
				audio.add_picture(img)
			except:
				self.printError()
				return False
		audio.save()
		count = 0
		if (audio.pictures is None) or (len(audio.pictures) <= 0):
			pass
		else:
			count = str(len(audio.pictures))

		self.song["pictures"] = count
		app.window.emit("artwork-changed", [self.song])
		del self.coverlist[:]
		self.liststore.clear()
		self.start_search()
		return True
Exemplo n.º 20
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)
Exemplo n.º 21
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)
            tag.delete()
        except:
            if isfile(song):
                remove(song)

            raise exceptions.TrackNotFound("")
    except NOTVALIDSONG:
        raise exceptions.TrackNotFound("")

    tag["artist"] = data["artist"]
    tag["title"] = data["music"]
    tag["date"] = data["year"]
    tag["album"] = data["album"]
    tag["tracknumber"] = data["tracknum"]
    tag["discnumber"] = data["discnum"]
    tag["genre"] = data["genre"]
    tag["albumartist"] = data["ar_album"]
    tag["author"] = data["author"]
    tag["composer"] = data["composer"]
    tag["copyright"] = data["copyright"]
    tag["bpm"] = data["bpm"]
    tag["length"] = data["duration"]
    tag["organization"] = data["label"]
    tag["isrc"] = data["isrc"]
    tag["lyricist"] = data["lyricist"]
    tag.save()

    try:
        audio = ID3(song)

        audio.add(
            APIC(
                encoding=3,
                mime="image/jpeg",
                type=3,
                desc=u"Cover",
                data=data["image"],
            ))

        audio.add(
            USLT(encoding=3, lang=u"eng", desc=u"desc", text=data["lyric"]))

        audio.save()
    except ID3NoHeaderError:
        pass
Exemplo n.º 22
0
def download_flac(track: tidalapi.models.Track, file_path, album=None):
    if album is None:
        album = track.album
    url = session.get_media_url(track_id=track.id)

    r = requests.get(url, stream=True)
    r.raw.decode_content = True
    data = BytesIO()
    shutil.copyfileobj(r.raw, data)
    data.seek(0)
    audio = FLAC(data)

    # general metatags
    audio['artist'] = track.artist.name
    audio[
        'title'] = f'{track.name}{f" ({track.version})" if track.version else ""}'

    # album related metatags
    audio['albumartist'] = album.artist.name
    audio[
        'album'] = f'{album.name}{f" ({album.version})" if album.version else ""}'
    audio['date'] = str(album.year)

    # track/disc position metatags
    audio['discnumber'] = str(track.volumeNumber)
    audio['disctotal'] = str(album.numberOfVolumes)
    audio['tracknumber'] = str(track.trackNumber)
    audio['tracktotal'] = str(album.numberOfTracks)

    # Tidal sometimes returns null for track copyright
    if hasattr(track, 'copyright') and track.copyright:
        audio['copyright'] = track.copyright
    elif hasattr(album, 'copyright') and album.copyright:
        audio['copyright'] = album.copyright

    # identifiers for later use in own music libraries
    if hasattr(track, 'isrc') and track.isrc:
        audio['isrc'] = track.isrc
    if hasattr(album, 'upc') and album.upc:
        audio['upc'] = album.upc

    pic = Picture()
    pic.type = id3.PictureType.COVER_FRONT
    pic.width = 640
    pic.height = 640
    pic.mime = 'image/jpeg'
    r = requests.get(track.album.image, stream=True)
    r.raw.decode_content = True
    pic.data = r.raw.read()

    audio.add_picture(pic)

    data.seek(0)
    audio.save(data)
    with open(file_path, "wb") as f:
        data.seek(0)
        shutil.copyfileobj(data, f)
Exemplo n.º 23
0
 def flac():
     song = FLAC(file)
     write_keys(song)
     if exists(cover_img):
         pic = Picture()
         pic.data = open(cover_img, 'rb').read()
         pic.mime = 'image/jpeg'
         song.add_picture(pic)
         song.save()
Exemplo n.º 24
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)))
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')
Exemplo n.º 26
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()
Exemplo n.º 27
0
def write_tags(pre_abs, meta, fmt, cov_abs):
    if fmt == "FLAC":
        audio = FLAC(pre_abs)
        del meta['track_padded']
        for k, v in meta.items():
            if v:
                audio[k] = str(v)
        if cov_abs:
            with open(cov_abs, "rb") as f:
                image = Picture()
                image.type = 3
                image.mime = "image/jpeg"
                image.data = f.read()
                audio.add_picture(image)
    elif fmt == "MP3":
        try:
            audio = id3.ID3(pre_abs)
        except ID3NoHeaderError:
            audio = id3.ID3()
        audio['TRCK'] = id3.TRCK(encoding=3,
                                 text="{}/{}".format(meta['track'],
                                                     meta['tracktotal']))
        legend = {
            "album": id3.TALB,
            "albumartist": id3.TPE2,
            "artist": id3.TPE1,
            #"comment": id3.COMM,
            "copyright": id3.TCOP,
            "isrc": id3.TSRC,
            "label": id3.TPUB,
            "title": id3.TIT2,
            "year": id3.TYER
        }
        for k, v in meta.items():
            id3tag = legend.get(k)
            if v and id3tag:
                audio[id3tag.__name__] = id3tag(encoding=3, text=v)
        if cov_abs:
            with open(cov_abs, "rb") as cov_obj:
                audio.add(id3.APIC(3, "image/jpeg", 3, None, cov_obj.read()))
    else:
        audio = MP4(pre_abs)
        audio['\xa9nam'] = meta['title']
        audio['\xa9alb'] = meta['album']
        audio['aART'] = meta['albumartist']
        audio['\xa9ART'] = meta['artist']
        audio['trkn'] = [(meta['track'], meta['tracktotal'])]
        audio['\xa9day'] = meta['year']
        audio['cprt'] = meta['copyright']
        if cov_abs:
            with open(cov_abs, "rb") as f:
                audio['covr'] = [
                    MP4Cover(f.read(), imageformat=MP4Cover.FORMAT_JPEG)
                ]
    audio.save(pre_abs)
Exemplo n.º 28
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)
            tag.delete()
        except:
            raise exceptions.TrackNotFound("")
    except error:
        raise exceptions.TrackNotFound("")

    tag['artist'] = data['artist']
    tag['title'] = data['music']
    tag['date'] = data['year']
    tag['album'] = data['album']
    tag['tracknumber'] = data['tracknum']
    tag['discnumber'] = data['discnum']
    tag['genre'] = data['genre']
    tag['albumartist'] = data['ar_album']
    tag['author'] = data['author']
    tag['composer'] = data['composer']
    tag['copyright'] = data['copyright']
    tag['bpm'] = data['bpm']
    tag['length'] = data['duration']
    tag['organization'] = data['label']
    tag['isrc'] = data['isrc']
    tag['replaygain_*_gain'] = data['gain']
    tag['lyricist'] = data['lyricist']
    tag.save()

    try:
        audio = ID3(song)

        audio.add(
            APIC(encoding=3,
                 mime="image/jpeg",
                 type=3,
                 desc=u"Cover",
                 data=data['image']))

        audio.add(
            USLT(encoding=3, lang=u"eng", desc=u"desc", text=data['lyric']))

        audio.save()
    except _util.ID3NoHeaderError:
        pass
Exemplo n.º 29
0
    def _embed_picture(self):
        """
        Get flac picture generated from mutagen.flac.Picture then embed
        it to given track if the flac picture exists.
        """
        flac_pic = self._make_flac_picture(self.cover_art_path)
        if flac_pic:
            w = FLAC(self.track_path)
            w.add_picture(flac_pic)

        self.stop()
Exemplo n.º 30
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')
Exemplo n.º 31
0
def write_tags(f, meta, cov):
    audio = FLAC(f)
    for tag, value in meta.items():
        if value:
            audio[tag] = str(value)
    if cov:
        image = Picture()
        image.type = 3
        image.mime = "image/jpeg"
        image.data = cov
        audio.add_picture(image)
    audio.save()
Exemplo n.º 32
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)
Exemplo n.º 33
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)
Exemplo n.º 34
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)
Exemplo n.º 35
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()
Exemplo n.º 36
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()
Exemplo n.º 37
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())
Exemplo n.º 38
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())
Exemplo n.º 39
0
class _FLACWrapper(_AbstractWrapper):
    VALID_TAG_KEYS = (
        'artwork',
        'artist',
        'album',
        'title',
        'genre',
    )

    def __init__(self, filename):
        _AbstractWrapper.__init__(self)
        self.audio = FLAC(filename)

    def __getattr__(self, attr):
        if attr in self.VALID_TAG_KEYS:
            if attr == 'artwork':
                if self.audio.pictures:
                    picture = self.audio.pictures[0]
                    return Artwork(picture.mime, picture.data)
                else:
                    return None
            else:
                try:
                    return self.audio[attr][0]
                except KeyError:
                    return None
        raise TagError(self, attr)

    def __setattr__(self, attr, value):
        if attr in self.VALID_TAG_KEYS:
            if isinstance(value, Artwork):
                picture = Picture()
                picture.type = 3
                picture.mime = value.mime
                picture.data = value.data
                self.audio.clear_pictures()
                self.audio.add_picture(picture)
            elif isinstance(value, str):
                self.audio[attr] = [value]
            else:
                raise TagValueError(value)
        else:
            object.__setattr__(self, attr, value)

    def __repr__(self):
        return repr(self.audio)

    def save(self):
        self.audio.save()
Exemplo n.º 40
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)
Exemplo n.º 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()
Exemplo n.º 42
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()
Exemplo n.º 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()
Exemplo n.º 44
0
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
Exemplo n.º 45
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()
Exemplo n.º 46
0
	def removeImage(self, song):
		audio = FLAC(song.get("~filename", ""))
		store = False
		## if file has no images -> leave
		if (audio.pictures is None) or (len(audio.pictures) <= 0):
			return
		images = list()
		for img in audio.pictures:
			if img.type == self.type \
			and img.desc == self.desc:
				store = True
			else:
				images.append(img)

		if store:
			## first,clear all pictures, then add the frontcover
			try:
				audio.clear_pictures()
			except:
				self.printError()
				return False
			## now add all other images
			for img in images:
				try:
					audio.add_picture(img)
				except:
					self.printError()
					return False
			audio.save()
			## and now count the images
			count = "0"
			## if file has no images -> set to 0
			if (audio.pictures is None) or (len(audio.pictures) <= 0):
				pass
			else:
				count = str(len(audio.pictures))

			if not "pictures" in song:
				song["pictures"] = count

			if song["pictures"] <> count:
				song["pictures"] = count
			app.window.emit("artwork-changed", [song])
		return
Exemplo n.º 47
0
class _FLACWrapper(_AbstractWrapper):
    VALID_TAG_KEYS = ('artwork', 'artist', 'album', 'title', 'genre', )

    def __init__(self, filename):
        _AbstractWrapper.__init__(self)
        self.audio = FLAC(filename)

    def __getattr__(self, attr):
        if attr in self.VALID_TAG_KEYS:
            if attr == 'artwork':
                if self.audio.pictures:
                    picture = self.audio.pictures[0]
                    return Artwork(picture.mime, picture.data)
                else:
                    return None
            else:
                try:
                    return self.audio[attr][0]
                except KeyError:
                    return None
        raise TagError(self, attr)

    def __setattr__(self, attr, value):
        if attr in self.VALID_TAG_KEYS:
            if isinstance(value, Artwork):
                picture = Picture()
                picture.type = 3
                picture.mime = value.mime
                picture.data = value.data
                self.audio.clear_pictures()
                self.audio.add_picture(picture)
            elif isinstance(value, str):
                self.audio[attr] = [value]
            else:
                raise TagValueError(value)
        else:
            object.__setattr__(self, attr, value)

    def __repr__(self):
        return repr(self.audio)

    def save(self):
        self.audio.save()
Exemplo n.º 48
0
	def setImage(self, song):
		audio = FLAC(song.get("~filename", ""))
		## if file has no images -> leave
		if (audio.pictures is None) or (len(audio.pictures) <= 0):
			return

		## if first image is frontcover -> leave
		img = audio.pictures[0]
		if img.type == 3:
			return

		## ok, we have to lookup the data...
		images = list()
		frontcover = None
		for img in audio.pictures:
			if img.type == 3:
				frontcover = img
			else:
				images.append(img)

		## if file has no frontcover -> leave
		if (frontcover is None):
			print(_("No frontcover found in {!s}.").format(song.get("~filename", "")))
			return

		## first,clear all pictures, then add the frontcover
		try:
			audio.clear_pictures()
			audio.add_picture(frontcover)
		except:
			self.printError()
			return False
		## now add all other images
		for img in images:
			try:
				audio.add_picture(img)
			except:
				self.printError()
				return False
		audio.save()
		app.window.emit("artwork-changed", [song])
		return
Exemplo n.º 49
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
Exemplo n.º 50
0
    print ["Sorry, i need piece of covert art labeled: ", picpath]

p_data = open(picpath).read()
# pic =   Picture(
#        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=p_data
#    )
# apic =   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=p_data
#    )
pic = Picture()
pic.load(open(picpath))
flaccount = 0
flext = re.compile(".*\.flac")
for f in files:
    if re.search(flext, f) != None:
        flaccount = flaccount + 1
        ftag = FLAC(f)
        ftag.clear_pictures()
        ftag.add_picture(pic)
        ftag.save

exit(0)
Exemplo n.º 51
0
 def test_smallest_invalid(self):
     f = FLAC(self.filename)
     pic = Picture()
     pic.data = b"\x00" * (2 ** 24 - 32)
     f.add_picture(pic)
     self.assertRaises(error, f.save)
Exemplo n.º 52
0
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
Exemplo n.º 54
0
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)