def _tag_flac(self, trackno):
        """ Calls the mutagen library to perform metadata changes for FLAC files """

        logging.debug("Tagging '%s'" % os.path.join(self.dest_dir_name,
                    self.file_tag_map[trackno][1]))

        audio = FLAC(os.path.join(self.dest_dir_name,
                    self.file_tag_map[trackno][1]))
        try:
            encoding = audio["ENCODING"]
        except:
            encoding = ""
            audio.delete()

        # add FLAC tag data
        audio["TITLE"] = self.tracks[trackno][1]
        audio["ARTIST"] = self.tracks[trackno][0]
        audio["ALBUM"] = self.title
        audio["COMPOSER"] = self.artist
        audio["ORGANIZATION"] = self.label
        audio["CATALOGNUM"] = self.catno
        audio["GENRE"] = self.genre
        audio["YEAR"] = self.year
        audio["TRACKNUMBER"] = str(trackno)
        audio["TRACKTOTAL"] = str(len(self.tracks))
        audio["DESCRIPTION"] = '::> Don\'t believe the hype! <::'
        if(len(encoding) != 0):
            audio["ENCODING"] = encoding
        audio.pprint()
        try:
            audio.save()
        except:
            logging.error("Unable to tag '%s'" % self.file_tag_map[trackno][1])
            raise DiscogsTaggerError, "Unable to write tag '%s'" % \
                            self.file_tag_map[trackno][1]
Beispiel #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
def main():
    print("start")
    tracks = []
    root = tkinter.Tk()
    root.withdraw()
    root.update()
    folder = askdirectory(title = "choose the dir u want to delete on tags in",initialdir = r"C:\Users\User\Desktop", mustexist=True )
    root.destroy()


    for root, dirs, files, in os.walk(folder):
        for name in files:
            if name.endswith((".mp3", ".flac")):
                print("the name= "+os.path.splitext(name)[0])
                print("the type= "+os.path.splitext(name)[1])
                if(name.endswith(".flac")):
                    print("its .flac")
                    audio=FLAC(root + "\\" + name)
                    audio.delete()
                    audio.clear_pictures()
                    audio.save()
                if(name.endswith(".mp3")):
                    print("its .mp3")
                    audio=MP3(root + "\\" + name)
                    audio.delete()
                    audio.clear()
                    audio.save()
Beispiel #4
0
 def test_delete_multiple(self):
     # on delete we delete both
     f = FLAC(self.filename)
     f.delete()
     assert len(f.tags) == 0
     f = FLAC(self.filename)
     assert f.tags is None
Beispiel #5
0
 def test_delete_multiple(self):
     # on delete we delete both
     f = FLAC(self.filename)
     f.delete()
     assert len(f.tags) == 0
     f = FLAC(self.filename)
     assert f.tags is None
Beispiel #6
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
 def cleanTags(filepath):
     if Path(filepath).suffix == ".flac":
         audiof = FLAC(filepath)
         audiof.clear_pictures()
         audiof.delete()
     elif Path(filepath).suffix == ".mp3":
         audiof = EasyID3(filepath)
         audiof.delete()
     audiof.save()
Beispiel #8
0
def retag(filename):
    audio = FLAC(filename)
    audio.delete()
    artist, title = os.path.splitext(filename)[0].split(' - ', 1)
    audio['artist'] = artist
    audio['title'] = title
    audio.save(deleteid3=True)
    print('  Cleared metadata.\n  Tagged flac with:')
    print('    artist: %r' % artist)
    print('    title: %r' % title)
Beispiel #9
0
    def test_delete_multiple_fail(self):
        f = FLAC(self.filename)
        with pytest.raises(MutagenError):
            f.delete(os.devnull)
        f.save()

        # if delete failed we shouldn't see a difference
        f = FLAC(self.filename)
        assert f.metadata_blocks[2] is f.tags
        assert f.metadata_blocks[3].code == f.tags.code
Beispiel #10
0
    def test_delete_multiple_fail(self):
        f = FLAC(self.filename)
        with pytest.raises(MutagenError):
            f.delete(os.devnull)
        f.save()

        # if delete failed we shouldn't see a difference
        f = FLAC(self.filename)
        assert f.metadata_blocks[2] is f.tags
        assert f.metadata_blocks[3].code == f.tags.code
Beispiel #11
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
Beispiel #12
0
    def remove_all(self):
        '''
            Remove the "metadata" block from the file
        '''
        if self.backup is True:
            shutil.copy2(self.filename, self.output)
            self.filename = self.output

        mfile = FLAC(self.filename)
        mfile.delete()
        mfile.clear_pictures()
        mfile.save()
    def remove_all(self):
        '''
            Remove the "metadata" block from the file
        '''
        if self.backup is True:
            shutil.copy2(self.filename, self.output)
            self.filename = self.output

        mfile = FLAC(self.filename)
        mfile.delete()
        mfile.clear_pictures()
        mfile.save()
Beispiel #14
0
def main(flac_file_path):
    audio = FLAC(flac_file_path)
    audio.delete()
    audio.save()

    audio = FLAC(flac_file_path)
    audio["title"] = "Unknown Title"
    audio["artist"] = "Unknown Artist"
    audio["album"] = "Unknown Album"
    audio["date"] = "2017"
    audio["genre"] = "Unknown Genre"
    audio["tracknumber"] = "1"
    audio.save()
Beispiel #15
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)
Beispiel #16
0
def set_tag_info_flac(f_path, tag_info, cover_data=None):
    if tag_info.get('date'):
        tag_info['date'] = tag_info['date'] + 'Z'
    if tag_info.get('tracknumber'):
        tag_info['tracknumber'], tag_info['tracktotal'] = tag_info['tracknumber'].split('/')
    if tag_info.get('discnumber'):
        tag_info['discnumber'], tag_info['disctotal'] = tag_info['discnumber'].split('/')

    audio = FLAC(f_path)
    audio.delete()
    for key in tag_info.keys():
        audio[key] = tag_info[key]
    if cover_data:
        pic = mutagen.flac.Picture()
        pic.mime = 'image/jpeg'
        pic.type = 3
        pic.data = cover_data
        audio.clear_pictures()
        audio.add_picture(pic)
    audio.save()
Beispiel #17
0
    def _tag_flac(self, file):
        """
        Tag Flac file only called from `track.tag()`
        """
        tagger = Tagger(self, '.flac')
        tag = FLAC(file)
        tag.delete()

        for tag_obj in tagger.tag_map:
            tag[tag_obj.key] = str(tag_obj.value)

        # image
        if cc.tag_cover and self.album.picture_url is not None:
            cover_data = self.get_cover_data()
            if cover_data:
                img = Picture()
                img.type = 3
                img.data = cover_data
                tag.clear_pictures()
                tag.add_picture(img)
            else:
                log.warning(f'No Cover for {self}')
        tag.save()
Beispiel #18
0
def reset_flac_tags(full_path):

    f = FLAC(full_path)

    t = f.tags

    # we need to save the 'vendor' string because calling mutagen's delete() removes it too
    for block in list(f.metadata_blocks):
        if isinstance(block, VCFLACDict):
            vendor = block.vendor

    f.clear_pictures()

    f.delete()

    for item in 'artist', 'album', 'tracknumber', 'tracktotal', 'title', 'date':
        if item in t:
            f[item] = t[item]

    for block in list(f.metadata_blocks):
        if isinstance(block, VCFLACDict):
            block.vendor = vendor

    f.save(deleteid3=True)
Beispiel #19
0
def write_tags(song, data):
    try:
       tag = FLAC(song)
       tag.delete()
       images = Picture()
       images.type = 3
       images.data = data['image']
       tag.add_picture(images)
       tag['lyrics'] = data['lyric']
    except mutagen.flac.FLACNoHeaderError:
       tag = mutagen.File(song, easy=True)
    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['APIC'] = APIC(encoding=3, mime="image/jpeg", type=3, desc=u"Cover", data=data['image']) 
       audio['USLT'] = USLT(encoding=3, lang=u'eng', desc=u'desc', text=data['lyric'])
       audio.save()
    except mutagen.id3._util.ID3NoHeaderError:
       pass
Beispiel #20
0
 def download_albumdee(self,
                       URL,
                       output=localdir + "/Songs/",
                       check=True,
                       quality="MP3_320",
                       recursive=True):
     if output == localdir + "/Songs":
         if not os.path.isdir("Songs"):
             os.makedirs("Songs")
     if quality == "FLAC":
         extension = ".flac"
     else:
         extension = ".mp3"
     array = []
     music = []
     artist = []
     album = []
     tracknum = []
     discnum = []
     year = []
     genre = []
     ar_album = []
     urls = []
     names = []
     if "?utm" in URL:
         URL, a = URL.split("?utm")
     URL = "http://www.deezer.com/album/" + URL.split("/")[-1]
     try:
         url = json.loads(
             requests.get("http://api.deezer.com/album/" +
                          URL.split("/")[-1],
                          headers=header).text)
     except:
         url = json.loads(
             requests.get("http://api.deezer.com/album/" +
                          URL.split("/")[-1],
                          headers=header).text)
     try:
         if url['error']['message'] == "Quota limit exceeded":
             raise QuotaExceeded("Too much requests limit yourself")
     except KeyError:
         None
     try:
         if url['error']:
             raise InvalidLink("Invalid link ;)")
     except KeyError:
         None
     try:
         image = url['cover_xl'].replace("1000", "1200")
     except AttributeError:
         try:
             image = requests.get(URL).text
         except:
             image = requests.get(URL).text
         image = BeautifulSoup(image, "html.parser").find(
             "img", class_="img_main").get("src").replace("200", "1200")
     try:
         image = requests.get(image).content
     except:
         image = requests.get(image).content
     for a in url['tracks']['data']:
         del array[:]
         music.append(a['title'])
         urls.append(a['link'])
         try:
             ur = json.loads(
                 requests.get("https://api.deezer.com/track/" +
                              str(a['id'])).text)
         except:
             ur = json.loads(
                 requests.get("https://api.deezer.com/track/" +
                              str(a['id'])).text)
         try:
             if ur['error']['message'] == "Quota limit exceeded":
                 raise QuotaExceeded("Too much requests limit yourself")
         except KeyError:
             None
         tracknum.append(ur['track_position'])
         discnum.append(ur['disk_number'])
         for a in ur['contributors']:
             array.append(a['name'])
         if len(array) > 1:
             for a in array:
                 for b in array:
                     if a in b and a != b:
                         array.remove(b)
         artist.append(", ".join(OrderedDict.fromkeys(array)))
     album.append(url['title'])
     year.append(url['release_date'])
     try:
         for a in url['genres']['data']:
             genre.append(a['name'])
     except KeyError:
         None
     ar_album.append(url['artist']['name'])
     dir = str(output) + "/" + album[0].replace("/", "").replace("$",
                                                                 "S") + "/"
     try:
         os.makedirs(dir)
     except FileExistsError:
         None
     for a in tqdm(range(len(urls))):
         name = artist[a].replace("/", "").replace(
             "$", "S") + " " + music[a].replace("/", "").replace(
                 "$", "S") + extension
         names.append(dir + name)
         if os.path.isfile(dir + name):
             if check == False:
                 continue
             print(dir + name)
             ans = input(
                 "Song already exist do you want to redownload it?(y or n):"
             )
             if not ans == "y":
                 return
         try:
             self.download(urls[a], dir, quality, recursive, extension)
         except TrackNotFound:
             try:
                 url = json.loads(
                     requests.get(
                         "https://api.deezer.com/search/track/?q=" +
                         music[a].replace("#", "") + " + " +
                         artist[a].replace("#", "")).text)
             except:
                 url = json.loads(
                     requests.get(
                         "https://api.deezer.com/search/track/?q=" +
                         music[a].replace("#", "") + " + " +
                         artist[a].replace("#", "")).text)
             try:
                 if url['error']['message'] == "Quota limit exceeded":
                     raise QuotaExceeded("Too much requests limit yourself")
             except KeyError:
                 None
             try:
                 for b in range(url['total'] + 1):
                     if url['data'][b]['title'] == music[a] or url['data'][
                             b]['title_short'] in music[a]:
                         URL = url['data'][b]['link']
                         break
             except IndexError:
                 try:
                     try:
                         url = json.loads(
                             requests.get(
                                 "https://api.deezer.com/search/track/?q=" +
                                 music[a].replace("#", "").split(" ")[0] +
                                 " + " + artist[a].replace("#", "")).text)
                     except:
                         url = json.loads(
                             requests.get(
                                 "https://api.deezer.com/search/track/?q=" +
                                 music[a].replace("#", "").split(" ")[0] +
                                 " + " + artist[a].replace("#", "")).text)
                     try:
                         if url['error'][
                                 'message'] == "Quota limit exceeded":
                             raise QuotaExceeded(
                                 "Too much requests limit yourself")
                     except KeyError:
                         None
                     for b in range(url['total'] + 1):
                         if music[a].split(
                                 " ")[0] in url['data'][b]['title']:
                             URL = url['data'][b]['link']
                             break
                 except IndexError:
                     print("\nTrack not found: " + music[a] + " - " +
                           artist[a])
                     continue
             self.download(URL, dir, quality, recursive, extension)
             urls[a] = URL
         try:
             os.rename(dir + urls[a].split("/")[-1] + extension, dir + name)
         except FileNotFoundError:
             None
         try:
             tag = EasyID3(dir + name)
             tag.delete()
         except mutagen.id3.ID3NoHeaderError:
             try:
                 tag = mutagen.File(dir + name, easy=True)
                 tag.add_tags()
             except mutagen.flac.FLACVorbisError:
                 tag = FLAC(dir + name)
                 tag.delete()
                 images = Picture()
                 images.type = 3
                 images.data = image
                 tag.add_picture(images)
         except:
             return dir + name
         tag['artist'] = artist[a]
         tag['title'] = music[a]
         tag['date'] = year[0]
         tag['album'] = album[0]
         tag['tracknumber'] = str(tracknum[a])
         tag['discnumber'] = str(discnum[a])
         tag['genre'] = " & ".join(genre)
         tag['albumartist'] = ", ".join(ar_album)
         tag.save()
         try:
             audio = ID3(dir + name)
             audio['APIC'] = APIC(encoding=3,
                                  mime='image/jpeg',
                                  type=3,
                                  desc=u'Cover',
                                  data=image)
             audio.save()
         except:
             None
     return names
Beispiel #21
0
class TFLAC(TestCase):
    SAMPLE = os.path.join(DATA_DIR, "silence-44-s.flac")

    def setUp(self):
        self.NEW = get_temp_copy(self.SAMPLE)
        self.flac = FLAC(self.NEW)

    def tearDown(self):
        os.unlink(self.NEW)

    def test_zero_samples(self):
        # write back zero sample count and load again
        self.flac.info.total_samples = 0
        self.flac.save()
        new = FLAC(self.flac.filename)
        assert new.info.total_samples == 0
        assert new.info.bitrate == 0
        assert new.info.length == 0.0

    def test_bitrate(self):
        assert self.flac.info.bitrate == 101430
        old_file_size = os.path.getsize(self.flac.filename)
        self.flac.save(padding=lambda x: 9999)
        new_flac = FLAC(self.flac.filename)
        assert os.path.getsize(new_flac.filename) > old_file_size
        assert new_flac.info.bitrate == 101430

    def test_padding(self):
        for pad in [0, 42, 2**24 - 1, 2 ** 24]:
            self.flac.save(padding=lambda x: pad)
            new = FLAC(self.flac.filename)
            expected = min(2**24 - 1, pad)
            self.assertEqual(new.metadata_blocks[-1].length, expected)

    def test_save_multiple_padding(self):
        # we don't touch existing padding blocks on save, but will
        # replace them in the file with one at the end

        def num_padding(f):
            blocks = f.metadata_blocks
            return len([b for b in blocks if isinstance(b, Padding)])

        num_blocks = num_padding(self.flac)
        self.assertEqual(num_blocks, 1)
        block = Padding()
        block.length = 42
        self.flac.metadata_blocks.append(block)
        block = Padding()
        block.length = 24
        self.flac.metadata_blocks.append(block)
        self.flac.save()
        self.assertEqual(num_padding(self.flac), num_blocks + 2)

        new = FLAC(self.flac.filename)
        self.assertEqual(num_padding(new), 1)
        self.assertTrue(isinstance(new.metadata_blocks[-1], Padding))

    def test_increase_size_new_padding(self):
        self.assertEqual(self.flac.metadata_blocks[-1].length, 3060)
        value = u"foo" * 100
        self.flac[u"foo"] = [value]
        self.flac.save()
        new = FLAC(self.NEW)
        self.assertEqual(new.metadata_blocks[-1].length, 2752)
        self.assertEqual(new[u"foo"], [value])

    def test_delete(self):
        self.failUnless(self.flac.tags)
        self.flac.delete()
        self.assertTrue(self.flac.tags is not None)
        self.assertFalse(self.flac.tags)
        flac = FLAC(self.NEW)
        self.assertTrue(flac.tags is None)

    def test_delete_change_reload(self):
        self.flac.delete()
        self.flac.tags["FOO"] = ["BAR"]
        self.flac.save()
        assert FLAC(self.flac.filename)["FOO"] == ["BAR"]

        # same with delete failing due to IO etc.
        with pytest.raises(MutagenError):
            self.flac.delete(os.devnull)
        self.flac.tags["FOO"] = ["QUUX"]
        self.flac.save()
        assert FLAC(self.flac.filename)["FOO"] == ["QUUX"]

    def test_module_delete(self):
        delete(self.NEW)
        flac = FLAC(self.NEW)
        self.failIf(flac.tags)

    def test_info(self):
        self.failUnlessAlmostEqual(FLAC(self.NEW).info.length, 3.7, 1)

    def test_keys(self):
        self.failUnlessEqual(
            list(self.flac.keys()), list(self.flac.tags.keys()))

    def test_values(self):
        self.failUnlessEqual(
            list(self.flac.values()), list(self.flac.tags.values()))

    def test_items(self):
        self.failUnlessEqual(
            list(self.flac.items()), list(self.flac.tags.items()))

    def test_vc(self):
        self.failUnlessEqual(self.flac['title'][0], 'Silence')

    def test_write_nochange(self):
        f = FLAC(self.NEW)
        f.save()
        with open(self.SAMPLE, "rb") as a:
            with open(self.NEW, "rb") as b:
                self.failUnlessEqual(a.read(), b.read())

    def test_write_changetitle(self):
        f = FLAC(self.NEW)
        if PY3:
            self.assertRaises(
                TypeError, f.__setitem__, b'title', b"A New Title")
        else:
            f[b"title"] = b"A New Title"
            f.save()
            f = FLAC(self.NEW)
            self.failUnlessEqual(f[b"title"][0], b"A New Title")

    def test_write_changetitle_unicode_value(self):
        f = FLAC(self.NEW)
        if PY3:
            self.assertRaises(
                TypeError, f.__setitem__, b'title', u"A Unicode Title \u2022")
        else:
            f[b"title"] = u"A Unicode Title \u2022"
            f.save()
            f = FLAC(self.NEW)
            self.failUnlessEqual(f[b"title"][0], u"A Unicode Title \u2022")

    def test_write_changetitle_unicode_key(self):
        f = FLAC(self.NEW)
        f[u"title"] = b"A New Title"
        if PY3:
            self.assertRaises(ValueError, f.save)
        else:
            f.save()
            f = FLAC(self.NEW)
            self.failUnlessEqual(f[u"title"][0], b"A New Title")

    def test_write_changetitle_unicode_key_and_value(self):
        f = FLAC(self.NEW)
        f[u"title"] = u"A Unicode Title \u2022"
        f.save()
        f = FLAC(self.NEW)
        self.failUnlessEqual(f[u"title"][0], u"A Unicode Title \u2022")

    def test_force_grow(self):
        f = FLAC(self.NEW)
        f["faketag"] = ["a" * 1000] * 1000
        f.save()
        f = FLAC(self.NEW)
        self.failUnlessEqual(f["faketag"], ["a" * 1000] * 1000)

    def test_force_shrink(self):
        self.test_force_grow()
        f = FLAC(self.NEW)
        f["faketag"] = "foo"
        f.save()
        f = FLAC(self.NEW)
        self.failUnlessEqual(f["faketag"], ["foo"])

    def test_add_vc(self):
        f = FLAC(os.path.join(DATA_DIR, "no-tags.flac"))
        self.failIf(f.tags)
        f.add_tags()
        self.failUnless(f.tags == [])
        self.failUnlessRaises(ValueError, f.add_tags)

    def test_add_vc_implicit(self):
        f = FLAC(os.path.join(DATA_DIR, "no-tags.flac"))
        self.failIf(f.tags)
        f["foo"] = "bar"
        self.failUnless(f.tags == [("foo", "bar")])
        self.failUnlessRaises(ValueError, f.add_tags)

    def test_ooming_vc_header(self):
        # issue 112: Malformed FLAC Vorbis header causes out of memory error
        # https://github.com/quodlibet/mutagen/issues/112
        self.assertRaises(error, FLAC, os.path.join(DATA_DIR,
                                                    'ooming-header.flac'))

    def test_with_real_flac(self):
        if not have_flac:
            return
        self.flac["faketag"] = "foobar" * 1000
        self.flac.save()
        self.failIf(call_flac("-t", self.flac.filename) != 0)

    def test_save_unknown_block(self):
        block = MetadataBlock(b"test block data")
        block.code = 99
        self.flac.metadata_blocks.append(block)
        self.flac.save()

    def test_load_unknown_block(self):
        self.test_save_unknown_block()
        flac = FLAC(self.NEW)
        self.failUnlessEqual(len(flac.metadata_blocks), 7)
        self.failUnlessEqual(flac.metadata_blocks[5].code, 99)
        self.failUnlessEqual(flac.metadata_blocks[5].data, b"test block data")

    def test_two_vorbis_blocks(self):
        self.flac.metadata_blocks.append(self.flac.metadata_blocks[1])
        self.flac.save()
        self.failUnlessRaises(error, FLAC, self.NEW)

    def test_missing_streaminfo(self):
        self.flac.metadata_blocks.pop(0)
        self.flac.save()
        self.failUnlessRaises(error, FLAC, self.NEW)

    def test_load_invalid_flac(self):
        self.failUnlessRaises(
            error, FLAC, os.path.join(DATA_DIR, "xing.mp3"))

    def test_save_invalid_flac(self):
        self.failUnlessRaises(
            error, self.flac.save, os.path.join(DATA_DIR, "xing.mp3"))

    def test_pprint(self):
        self.failUnless(self.flac.pprint())

    def test_double_load(self):
        blocks = list(self.flac.metadata_blocks)
        self.flac.load(self.flac.filename)
        self.failUnlessEqual(blocks, self.flac.metadata_blocks)

    def test_seektable(self):
        self.failUnless(self.flac.seektable)

    def test_cuesheet(self):
        self.failUnless(self.flac.cuesheet)

    def test_pictures(self):
        self.failUnless(self.flac.pictures)

    def test_add_picture(self):
        f = FLAC(self.NEW)
        c = len(f.pictures)
        f.add_picture(Picture())
        f.save()
        f = FLAC(self.NEW)
        self.failUnlessEqual(len(f.pictures), c + 1)

    def test_clear_pictures(self):
        f = FLAC(self.NEW)
        c1 = len(f.pictures)
        c2 = len(f.metadata_blocks)
        f.clear_pictures()
        f.save()
        f = FLAC(self.NEW)
        self.failUnlessEqual(len(f.metadata_blocks), c2 - c1)

    def test_ignore_id3(self):
        id3 = ID3()
        id3.add(TIT2(encoding=0, text='id3 title'))
        id3.save(self.NEW)
        f = FLAC(self.NEW)
        f['title'] = 'vc title'
        f.save()
        id3 = ID3(self.NEW)
        self.failUnlessEqual(id3['TIT2'].text, ['id3 title'])
        f = FLAC(self.NEW)
        self.failUnlessEqual(f['title'], ['vc title'])

    def test_delete_id3(self):
        id3 = ID3()
        id3.add(TIT2(encoding=0, text='id3 title'))
        id3.save(self.NEW, v1=2)
        f = FLAC(self.NEW)
        f['title'] = 'vc title'
        f.save(deleteid3=True)
        self.failUnlessRaises(ID3NoHeaderError, ID3, self.NEW)
        f = FLAC(self.NEW)
        self.failUnlessEqual(f['title'], ['vc title'])

    def test_save_on_mp3(self):
        path = os.path.join(DATA_DIR, "silence-44-s.mp3")
        self.assertRaises(error, self.flac.save, path)

    def test_mime(self):
        self.failUnless("audio/x-flac" in self.flac.mime)

    def test_variable_block_size(self):
        FLAC(os.path.join(DATA_DIR, "variable-block.flac"))

    def test_load_flac_with_application_block(self):
        FLAC(os.path.join(DATA_DIR, "flac_application.flac"))
Beispiel #22
0
        mp3['TRCK'] = TRCK(encoding=3, text=t['track_num'])
        mp3['TIT2'] = TIT2(encoding=3, text=t['track_title'])
        mp3.save()

    elif t['track_format'] == 'ogg':
        ogg = OggVorbis(t['track_fname'])
        ogg.delete()

        ogg['artist'] = t['track_artist']
        ogg['album'] = t['album']
        ogg['date'] = t['date']
        ogg['year'] = t['year']
        ogg['tracknumber'] = t['track_num']
        ogg['title'] = t['track_title']
        ogg.save()

    elif t['track_format'] == 'flac':
        flac = FLAC(t['track_fname'])
        flac.delete()

        flac['artist'] = t['track_artist']
        flac['album'] = t['album']
        flac['date'] = t['date']
        flac['year'] = t['year']
        flac['tracknumber'] = t['track_num']
        flac['title'] = t['track_title']
        flac.save()

# change back to original working directory
os.chdir(ori_cwd)
Beispiel #23
0
class TFLAC(TestCase):
    SAMPLE = os.path.join(DATA_DIR, "silence-44-s.flac")

    def setUp(self):
        self.NEW = get_temp_copy(self.SAMPLE)
        self.flac = FLAC(self.NEW)

    def tearDown(self):
        os.unlink(self.NEW)

    def test_zero_samples(self):
        # write back zero sample count and load again
        self.flac.info.total_samples = 0
        self.flac.save()
        new = FLAC(self.flac.filename)
        assert new.info.total_samples == 0
        assert new.info.bitrate == 0
        assert new.info.length == 0.0

    def test_bitrate(self):
        assert self.flac.info.bitrate == 101430
        old_file_size = os.path.getsize(self.flac.filename)
        self.flac.save(padding=lambda x: 9999)
        new_flac = FLAC(self.flac.filename)
        assert os.path.getsize(new_flac.filename) > old_file_size
        assert new_flac.info.bitrate == 101430

    def test_padding(self):
        for pad in [0, 42, 2**24 - 1, 2**24]:
            self.flac.save(padding=lambda x: pad)
            new = FLAC(self.flac.filename)
            expected = min(2**24 - 1, pad)
            self.assertEqual(new.metadata_blocks[-1].length, expected)

    def test_save_multiple_padding(self):
        # we don't touch existing padding blocks on save, but will
        # replace them in the file with one at the end

        def num_padding(f):
            blocks = f.metadata_blocks
            return len([b for b in blocks if isinstance(b, Padding)])

        num_blocks = num_padding(self.flac)
        self.assertEqual(num_blocks, 1)
        block = Padding()
        block.length = 42
        self.flac.metadata_blocks.append(block)
        block = Padding()
        block.length = 24
        self.flac.metadata_blocks.append(block)
        self.flac.save()
        self.assertEqual(num_padding(self.flac), num_blocks + 2)

        new = FLAC(self.flac.filename)
        self.assertEqual(num_padding(new), 1)
        self.assertTrue(isinstance(new.metadata_blocks[-1], Padding))

    def test_increase_size_new_padding(self):
        self.assertEqual(self.flac.metadata_blocks[-1].length, 3060)
        value = u"foo" * 100
        self.flac[u"foo"] = [value]
        self.flac.save()
        new = FLAC(self.NEW)
        self.assertEqual(new.metadata_blocks[-1].length, 2752)
        self.assertEqual(new[u"foo"], [value])

    def test_delete(self):
        self.failUnless(self.flac.tags)
        self.flac.delete()
        self.assertTrue(self.flac.tags is not None)
        self.assertFalse(self.flac.tags)
        flac = FLAC(self.NEW)
        self.assertTrue(flac.tags is None)

    def test_module_delete(self):
        delete(self.NEW)
        flac = FLAC(self.NEW)
        self.failIf(flac.tags)

    def test_info(self):
        self.failUnlessAlmostEqual(FLAC(self.NEW).info.length, 3.7, 1)

    def test_keys(self):
        self.failUnlessEqual(list(self.flac.keys()),
                             list(self.flac.tags.keys()))

    def test_values(self):
        self.failUnlessEqual(list(self.flac.values()),
                             list(self.flac.tags.values()))

    def test_items(self):
        self.failUnlessEqual(list(self.flac.items()),
                             list(self.flac.tags.items()))

    def test_vc(self):
        self.failUnlessEqual(self.flac['title'][0], 'Silence')

    def test_write_nochange(self):
        f = FLAC(self.NEW)
        f.save()
        with open(self.SAMPLE, "rb") as a:
            with open(self.NEW, "rb") as b:
                self.failUnlessEqual(a.read(), b.read())

    def test_write_changetitle(self):
        f = FLAC(self.NEW)
        if PY3:
            self.assertRaises(TypeError, f.__setitem__, b'title',
                              b"A New Title")
        else:
            f[b"title"] = b"A New Title"
            f.save()
            f = FLAC(self.NEW)
            self.failUnlessEqual(f[b"title"][0], b"A New Title")

    def test_write_changetitle_unicode_value(self):
        f = FLAC(self.NEW)
        if PY3:
            self.assertRaises(TypeError, f.__setitem__, b'title',
                              u"A Unicode Title \u2022")
        else:
            f[b"title"] = u"A Unicode Title \u2022"
            f.save()
            f = FLAC(self.NEW)
            self.failUnlessEqual(f[b"title"][0], u"A Unicode Title \u2022")

    def test_write_changetitle_unicode_key(self):
        f = FLAC(self.NEW)
        f[u"title"] = b"A New Title"
        if PY3:
            self.assertRaises(ValueError, f.save)
        else:
            f.save()
            f = FLAC(self.NEW)
            self.failUnlessEqual(f[u"title"][0], b"A New Title")

    def test_write_changetitle_unicode_key_and_value(self):
        f = FLAC(self.NEW)
        f[u"title"] = u"A Unicode Title \u2022"
        f.save()
        f = FLAC(self.NEW)
        self.failUnlessEqual(f[u"title"][0], u"A Unicode Title \u2022")

    def test_force_grow(self):
        f = FLAC(self.NEW)
        f["faketag"] = ["a" * 1000] * 1000
        f.save()
        f = FLAC(self.NEW)
        self.failUnlessEqual(f["faketag"], ["a" * 1000] * 1000)

    def test_force_shrink(self):
        self.test_force_grow()
        f = FLAC(self.NEW)
        f["faketag"] = "foo"
        f.save()
        f = FLAC(self.NEW)
        self.failUnlessEqual(f["faketag"], ["foo"])

    def test_add_vc(self):
        f = FLAC(os.path.join(DATA_DIR, "no-tags.flac"))
        self.failIf(f.tags)
        f.add_tags()
        self.failUnless(f.tags == [])
        self.failUnlessRaises(ValueError, f.add_tags)

    def test_add_vc_implicit(self):
        f = FLAC(os.path.join(DATA_DIR, "no-tags.flac"))
        self.failIf(f.tags)
        f["foo"] = "bar"
        self.failUnless(f.tags == [("foo", "bar")])
        self.failUnlessRaises(ValueError, f.add_tags)

    def test_ooming_vc_header(self):
        # issue 112: Malformed FLAC Vorbis header causes out of memory error
        # https://github.com/quodlibet/mutagen/issues/112
        self.assertRaises(error, FLAC,
                          os.path.join(DATA_DIR, 'ooming-header.flac'))

    def test_with_real_flac(self):
        if not have_flac:
            return
        self.flac["faketag"] = "foobar" * 1000
        self.flac.save()
        self.failIf(call_flac("-t", self.flac.filename) != 0)

    def test_save_unknown_block(self):
        block = MetadataBlock(b"test block data")
        block.code = 99
        self.flac.metadata_blocks.append(block)
        self.flac.save()

    def test_load_unknown_block(self):
        self.test_save_unknown_block()
        flac = FLAC(self.NEW)
        self.failUnlessEqual(len(flac.metadata_blocks), 7)
        self.failUnlessEqual(flac.metadata_blocks[5].code, 99)
        self.failUnlessEqual(flac.metadata_blocks[5].data, b"test block data")

    def test_two_vorbis_blocks(self):
        self.flac.metadata_blocks.append(self.flac.metadata_blocks[1])
        self.flac.save()
        self.failUnlessRaises(error, FLAC, self.NEW)

    def test_missing_streaminfo(self):
        self.flac.metadata_blocks.pop(0)
        self.flac.save()
        self.failUnlessRaises(error, FLAC, self.NEW)

    def test_load_invalid_flac(self):
        self.failUnlessRaises(error, FLAC, os.path.join(DATA_DIR, "xing.mp3"))

    def test_save_invalid_flac(self):
        self.failUnlessRaises(error, self.flac.save,
                              os.path.join(DATA_DIR, "xing.mp3"))

    def test_pprint(self):
        self.failUnless(self.flac.pprint())

    def test_double_load(self):
        blocks = list(self.flac.metadata_blocks)
        self.flac.load(self.flac.filename)
        self.failUnlessEqual(blocks, self.flac.metadata_blocks)

    def test_seektable(self):
        self.failUnless(self.flac.seektable)

    def test_cuesheet(self):
        self.failUnless(self.flac.cuesheet)

    def test_pictures(self):
        self.failUnless(self.flac.pictures)

    def test_add_picture(self):
        f = FLAC(self.NEW)
        c = len(f.pictures)
        f.add_picture(Picture())
        f.save()
        f = FLAC(self.NEW)
        self.failUnlessEqual(len(f.pictures), c + 1)

    def test_clear_pictures(self):
        f = FLAC(self.NEW)
        c1 = len(f.pictures)
        c2 = len(f.metadata_blocks)
        f.clear_pictures()
        f.save()
        f = FLAC(self.NEW)
        self.failUnlessEqual(len(f.metadata_blocks), c2 - c1)

    def test_ignore_id3(self):
        id3 = ID3()
        id3.add(TIT2(encoding=0, text='id3 title'))
        id3.save(self.NEW)
        f = FLAC(self.NEW)
        f['title'] = 'vc title'
        f.save()
        id3 = ID3(self.NEW)
        self.failUnlessEqual(id3['TIT2'].text, ['id3 title'])
        f = FLAC(self.NEW)
        self.failUnlessEqual(f['title'], ['vc title'])

    def test_delete_id3(self):
        id3 = ID3()
        id3.add(TIT2(encoding=0, text='id3 title'))
        id3.save(self.NEW, v1=2)
        f = FLAC(self.NEW)
        f['title'] = 'vc title'
        f.save(deleteid3=True)
        self.failUnlessRaises(ID3NoHeaderError, ID3, self.NEW)
        f = FLAC(self.NEW)
        self.failUnlessEqual(f['title'], ['vc title'])

    def test_save_on_mp3(self):
        path = os.path.join(DATA_DIR, "silence-44-s.mp3")
        self.assertRaises(error, self.flac.save, path)

    def test_mime(self):
        self.failUnless("audio/x-flac" in self.flac.mime)

    def test_variable_block_size(self):
        FLAC(os.path.join(DATA_DIR, "variable-block.flac"))

    def test_load_flac_with_application_block(self):
        FLAC(os.path.join(DATA_DIR, "flac_application.flac"))
Beispiel #24
0
# 1) Get the current directory the file was opened from.
# 2) Choose a directory to function from.
# 3) Change the current directory to the one chossen in step 2.
# 4) Make a list of the song files and store them in a variable.
currDir = os.getcwd()
getDir = tkinter.filedialog.askdirectory(parent=root,
                                         initialdir=currDir,
                                         title="Pick song library...")

os.chdir(getDir)

songs = os.listdir(getDir)

# Change the name of every .flac in the list of songs
# based on "genre - artist - album - tracknumber - title"
for s in songs:
    if s.endswith('.flac'):
        songObject = mutagen.File(s)

        newname = songObject['genre'].pop() + ' - '
        newname += songObject['artist'].pop() + ' - '
        newname += songObject['album'].pop() + ' - '
        newname += songObject['tracknumber'].pop() + ' - '
        newname += songObject['title'].pop() + '.flac'

        song = FLAC(s)

        song.delete()
        song.save()
        os.rename(s, newname)
Beispiel #25
0
class TFLAC(TestCase):
    SAMPLE = os.path.join("tests", "data", "silence-44-s.flac")
    NEW = SAMPLE + ".new"

    def setUp(self):
        shutil.copy(self.SAMPLE, self.NEW)
        self.failUnlessEqual(open(self.SAMPLE, "rb").read(),
                             open(self.NEW, "rb").read())
        self.flac = FLAC(self.NEW)

    def test_delete(self):
        self.failUnless(self.flac.tags)
        self.flac.delete()
        self.failIf(self.flac.tags)
        flac = FLAC(self.NEW)
        self.failIf(flac.tags)

    def test_module_delete(self):
        delete(self.NEW)
        flac = FLAC(self.NEW)
        self.failIf(flac.tags)

    def test_info(self):
        self.failUnlessAlmostEqual(FLAC(self.NEW).info.length, 3.7, 1)

    def test_keys(self):
        self.failUnlessEqual(
            list(self.flac.keys()), list(self.flac.tags.keys()))

    def test_values(self):
        self.failUnlessEqual(
            list(self.flac.values()), list(self.flac.tags.values()))

    def test_items(self):
        self.failUnlessEqual(
            list(self.flac.items()), list(self.flac.tags.items()))

    def test_vc(self):
        self.failUnlessEqual(self.flac['title'][0], 'Silence')

    def test_write_nochange(self):
        f = FLAC(self.NEW)
        f.save()
        self.failUnlessEqual(open(self.SAMPLE, "rb").read(),
                             open(self.NEW, "rb").read())

    def test_write_changetitle(self):
        f = FLAC(self.NEW)
        if PY3:
            self.assertRaises(
                TypeError, f.__setitem__, b'title', b"A New Title")
        else:
            f[b"title"] = b"A New Title"
            f.save()
            f = FLAC(self.NEW)
            self.failUnlessEqual(f[b"title"][0], b"A New Title")

    def test_write_changetitle_unicode_value(self):
        f = FLAC(self.NEW)
        if PY3:
            self.assertRaises(
                TypeError, f.__setitem__, b'title', u"A Unicode Title \u2022")
        else:
            f[b"title"] = u"A Unicode Title \u2022"
            f.save()
            f = FLAC(self.NEW)
            self.failUnlessEqual(f[b"title"][0], u"A Unicode Title \u2022")

    def test_write_changetitle_unicode_key(self):
        f = FLAC(self.NEW)
        f[u"title"] = b"A New Title"
        if PY3:
            self.assertRaises(ValueError, f.save)
        else:
            f.save()
            f = FLAC(self.NEW)
            self.failUnlessEqual(f[u"title"][0], b"A New Title")

    def test_write_changetitle_unicode_key_and_value(self):
        f = FLAC(self.NEW)
        f[u"title"] = u"A Unicode Title \u2022"
        f.save()
        f = FLAC(self.NEW)
        self.failUnlessEqual(f[u"title"][0], u"A Unicode Title \u2022")

    def test_force_grow(self):
        f = FLAC(self.NEW)
        f["faketag"] = ["a" * 1000] * 1000
        f.save()
        f = FLAC(self.NEW)
        self.failUnlessEqual(f["faketag"], ["a" * 1000] * 1000)

    def test_force_shrink(self):
        self.test_force_grow()
        f = FLAC(self.NEW)
        f["faketag"] = "foo"
        f.save()
        f = FLAC(self.NEW)
        self.failUnlessEqual(f["faketag"], ["foo"])

    def test_add_vc(self):
        f = FLAC(os.path.join("tests", "data", "no-tags.flac"))
        self.failIf(f.tags)
        f.add_tags()
        self.failUnless(f.tags == [])
        self.failUnlessRaises(ValueError, f.add_tags)

    def test_add_vc_implicit(self):
        f = FLAC(os.path.join("tests", "data", "no-tags.flac"))
        self.failIf(f.tags)
        f["foo"] = "bar"
        self.failUnless(f.tags == [("foo", "bar")])
        self.failUnlessRaises(ValueError, f.add_tags)

    def test_ooming_vc_header(self):
        # issue 112: Malformed FLAC Vorbis header causes out of memory error
        # http://code.google.com/p/mutagen/issues/detail?id=112
        self.assertRaises(IOError, FLAC, os.path.join('tests', 'data',
                                                      'ooming-header.flac'))

    def test_with_real_flac(self):
        if not have_flac:
            return
        self.flac["faketag"] = "foobar" * 1000
        self.flac.save()
        badval = os.system("tools/notarealprogram 2> %s" % devnull)
        value = os.system("flac -t %s 2> %s" % (self.flac.filename, devnull))
        self.failIf(value and value != badval)

    def test_save_unknown_block(self):
        block = MetadataBlock(b"test block data")
        block.code = 99
        self.flac.metadata_blocks.append(block)
        self.flac.save()

    def test_load_unknown_block(self):
        self.test_save_unknown_block()
        flac = FLAC(self.NEW)
        self.failUnlessEqual(len(flac.metadata_blocks), 7)
        self.failUnlessEqual(flac.metadata_blocks[5].code, 99)
        self.failUnlessEqual(flac.metadata_blocks[5].data, b"test block data")

    def test_two_vorbis_blocks(self):
        self.flac.metadata_blocks.append(self.flac.metadata_blocks[1])
        self.flac.save()
        self.failUnlessRaises(IOError, FLAC, self.NEW)

    def test_missing_streaminfo(self):
        self.flac.metadata_blocks.pop(0)
        self.flac.save()
        self.failUnlessRaises(IOError, FLAC, self.NEW)

    def test_load_invalid_flac(self):
        self.failUnlessRaises(
            IOError, FLAC, os.path.join("tests", "data", "xing.mp3"))

    def test_save_invalid_flac(self):
        self.failUnlessRaises(
            IOError, self.flac.save, os.path.join("tests", "data", "xing.mp3"))

    def test_pprint(self):
        self.failUnless(self.flac.pprint())

    def test_double_load(self):
        blocks = list(self.flac.metadata_blocks)
        self.flac.load(self.flac.filename)
        self.failUnlessEqual(blocks, self.flac.metadata_blocks)

    def test_seektable(self):
        self.failUnless(self.flac.seektable)

    def test_cuesheet(self):
        self.failUnless(self.flac.cuesheet)

    def test_pictures(self):
        self.failUnless(self.flac.pictures)

    def test_add_picture(self):
        f = FLAC(self.NEW)
        c = len(f.pictures)
        f.add_picture(Picture())
        f.save()
        f = FLAC(self.NEW)
        self.failUnlessEqual(len(f.pictures), c + 1)

    def test_clear_pictures(self):
        f = FLAC(self.NEW)
        c1 = len(f.pictures)
        c2 = len(f.metadata_blocks)
        f.clear_pictures()
        f.save()
        f = FLAC(self.NEW)
        self.failUnlessEqual(len(f.metadata_blocks), c2 - c1)

    def test_ignore_id3(self):
        id3 = ID3()
        id3.add(TIT2(encoding=0, text='id3 title'))
        id3.save(self.NEW)
        f = FLAC(self.NEW)
        f['title'] = 'vc title'
        f.save()
        id3 = ID3(self.NEW)
        self.failUnlessEqual(id3['TIT2'].text, ['id3 title'])
        f = FLAC(self.NEW)
        self.failUnlessEqual(f['title'], ['vc title'])

    def test_delete_id3(self):
        id3 = ID3()
        id3.add(TIT2(encoding=0, text='id3 title'))
        id3.save(self.NEW, v1=2)
        f = FLAC(self.NEW)
        f['title'] = 'vc title'
        f.save(deleteid3=True)
        self.failUnlessRaises(ID3NoHeaderError, ID3, self.NEW)
        f = FLAC(self.NEW)
        self.failUnlessEqual(f['title'], ['vc title'])

    def test_mime(self):
        self.failUnless("audio/x-flac" in self.flac.mime)

    def test_variable_block_size(self):
        FLAC(os.path.join("tests", "data", "variable-block.flac"))

    def test_load_flac_with_application_block(self):
        FLAC(os.path.join("tests", "data", "flac_application.flac"))

    def tearDown(self):
        os.unlink(self.NEW)
Beispiel #26
0
def set_release_metadata(artist_name, album_name, record_id):
    translation = {'/': '-'}
    table = str.maketrans(translation)
    record = get_local_record_list(artist_name, album_name.translate(table))
    record_dir = record['record_dir']

    try:
        release = musicbrainzngs.get_release_by_id(record_id,
                                                   includes=[
                                                       'recordings',
                                                   ])
        release = release['release']
    except:
        release = musicbrainzngs.get_release_by_id(record_id)
    try:
        album = release['title']
    except KeyError:
        album = 'not defined'
    try:
        date = release['date']
    except KeyError:
        date = 'not defined'
    try:
        country = release['country']
    except KeyError:
        country = 'not defined'
    try:
        mediumtotal = release['medium-count']
    except KeyError:
        mediumtotal = 0

    tracknumber = 1
    for i in range(1, mediumtotal + 1):

        if mediumtotal > 1:
            base_dir = record_dir + f'/CD{i}/'
            base_dir_art = record_dir + '/'
        else:
            base_dir = record_dir + '/'
            base_dir_art = record_dir + '/'

        try:
            pic = Picture()
            with open(f'{base_dir_art}fanart.jpg', "rb") as f:
                pic.data = f.read()
            pic.mime = u"image/jpeg"
            pic.width = 1000
            pic.height = 1000
            pic.depth = 16
        except:
            logger.warning('No Fan Art Available!')

        songs = os.listdir(base_dir)
        for song in songs:
            fullpath = base_dir + song
            extension = pathlib.Path(fullpath).suffix

            if extension == '.flac':
                metadata = FLAC(fullpath)

                for item in metadata.items():
                    if item[0] == 'tracknumber':
                        tracknumber = int(item[1].pop())

                records = filter(lambda x: int(x['position']) == i,
                                 release['medium-list'])
                for recording in records:
                    tracktotal = recording['track-count']
                    for track in recording['track-list']:
                        if int(track['number']) == tracknumber:
                            tracktitle = track['recording']['title'].translate(
                                table)
                            trackid = track['recording']['id']
                            track_musicbrainz = musicbrainzngs.get_recording_by_id(
                                trackid, includes=[
                                    'artists',
                                ])
                            artist = track_musicbrainz['recording'][
                                'artist-credit-phrase']

                metadata.delete()
                metadata.clear_pictures()
                if pic:
                    metadata.add_picture(pic)
                metadata["Album"] = album
                metadata["Albumartist"] = artist_name
                metadata["Artist"] = artist_name
                metadata["Country"] = country
                metadata["Date"] = date
                metadata["Discnumber"] = str(i)
                metadata["Title"] = tracktitle
                metadata["Tracktotal"] = str(tracktotal)
                metadata["Tracknumber"] = str(tracknumber)
                metadata.save()

                logger.info(f'old name: {song}')
                if mediumtotal != 1:
                    logger.info(
                        f'new name: {artist} - {album.translate(table)} - CD{i} - {tracknumber:02} - {tracktitle}.flac'
                    )
                    os.rename(
                        fullpath,
                        f'{base_dir}{artist} - {album.translate(table)} - CD{i} - {tracknumber:02} - {tracktitle}.flac'
                    )
                else:
                    logger.info(
                        f'new name: {artist} - {album.translate(table)} - {tracknumber:02} - {tracktitle}.flac'
                    )
                    os.rename(
                        fullpath,
                        f'{base_dir}{artist} - {album.translate(table)} - {tracknumber:02} - {tracktitle}.flac'
                    )
Beispiel #27
0
    if ft == u'mp3':
      # remove tags in audio files
      try:
        audio = ID3(f)
        audio.delete()
      except mutagen.id3.ID3NoHeaderError:
        pass
    elif ft == u'flac':
      audio = FLAC(f)
      # remember the encoding settings before deleting all tags:
      try:
        encoding = audio["ENCODING"]
      except:
        encoding = ""
        audio.delete()
    if ft == u'mp3':
      # add new ID3 tags
      try:
        id3 = mutagen.id3.ID3(f)
      except mutagen.id3.ID3NoHeaderError:
        id3 = mutagen.id3.ID3()

    if ft == u'mp3':
      # adding new id3 frames
      id3.add(TIT2(encoding=3, text=disc.track_list[c].title))
      id3.add(TPE1(encoding=3, text=disc.track_list[c].artist))
      id3.add(TALB(encoding=3, text=disc.title))
      id3.add(TCOM(encoding=3, text=disc.artist))
      id3.add(TPUB(encoding=3, text=disc.label))
      id3.add(TDRC(encoding=3, text=disc.year))
Beispiel #28
0
class TFLAC(TestCase):
    SAMPLE = os.path.join("tests", "data", "silence-44-s.flac")
    NEW = SAMPLE + ".new"
    def setUp(self):
        shutil.copy(self.SAMPLE, self.NEW)
        self.failUnlessEqual(open(self.SAMPLE).read(), open(self.NEW).read())
        self.flac = FLAC(self.NEW)

    def test_delete(self):
        self.failUnless(self.flac.tags)
        self.flac.delete()
        self.failIf(self.flac.tags)
        flac = FLAC(self.NEW)
        self.failIf(flac.tags)

    def test_module_delete(self):
        delete(self.NEW)
        flac = FLAC(self.NEW)
        self.failIf(flac.tags)

    def test_info(self):
        self.failUnlessAlmostEqual(FLAC(self.NEW).info.length, 3.7, 1)

    def test_keys(self):
        self.failUnlessEqual(self.flac.keys(), self.flac.tags.keys())

    def test_values(self):
        self.failUnlessEqual(self.flac.values(), self.flac.tags.values())

    def test_items(self):
        self.failUnlessEqual(self.flac.items(), self.flac.tags.items())

    def test_vc(self):
        self.failUnlessEqual(self.flac['title'][0], 'Silence')

    def test_write_nochange(self):
        f = FLAC(self.NEW)
        f.save()
        self.failUnlessEqual(open(self.SAMPLE).read(), open(self.NEW).read())

    def test_write_changetitle(self):
        f = FLAC(self.NEW)
        f["title"] = "A New Title"
        f.save()
        f = FLAC(self.NEW)
        self.failUnlessEqual(f["title"][0], "A New Title")

    def test_write_changetitle_unicode_value(self):
        f = FLAC(self.NEW)
        f["title"] = u"A Unicode Title \u2022"
        f.save()
        f = FLAC(self.NEW)
        self.failUnlessEqual(f["title"][0], u"A Unicode Title \u2022")

    def test_write_changetitle_unicode_key(self):
        f = FLAC(self.NEW)
        f[u"title"] = "A New Title"
        f.save()
        f = FLAC(self.NEW)
        self.failUnlessEqual(f[u"title"][0], "A New Title")

    def test_write_changetitle_unicode_key_and_value(self):
        f = FLAC(self.NEW)
        f[u"title"] = u"A Unicode Title \u2022"
        f.save()
        f = FLAC(self.NEW)
        self.failUnlessEqual(f[u"title"][0], u"A Unicode Title \u2022")

    def test_force_grow(self):
        f = FLAC(self.NEW)
        f["faketag"] = ["a" * 1000] * 1000
        f.save()
        f = FLAC(self.NEW)
        self.failUnlessEqual(f["faketag"], ["a" * 1000] * 1000)

    def test_force_shrink(self):
        self.test_force_grow()
        f = FLAC(self.NEW)
        f["faketag"] = "foo"
        f.save()
        f = FLAC(self.NEW)
        self.failUnlessEqual(f["faketag"], ["foo"])

    def test_add_vc(self):
        f = FLAC(os.path.join("tests", "data", "no-tags.flac"))
        self.failIf(f.tags)
        f.add_tags()
        self.failUnless(f.tags == [])
        self.failUnlessRaises(ValueError, f.add_tags)

    def test_add_vc_implicit(self):
        f = FLAC(os.path.join("tests", "data", "no-tags.flac"))
        self.failIf(f.tags)
        f["foo"] = "bar"
        self.failUnless(f.tags == [("foo", "bar")])
        self.failUnlessRaises(ValueError, f.add_tags)

    def test_ooming_vc_header(self):
        # issue 112: Malformed FLAC Vorbis header causes out of memory error
        # http://code.google.com/p/mutagen/issues/detail?id=112
        self.assertRaises(IOError, FLAC, os.path.join('tests', 'data',
                                                      'ooming-header.flac'))

    def test_with_real_flac(self):
        if not have_flac: return
        self.flac["faketag"] = "foobar" * 1000
        self.flac.save()
        badval = os.system("tools/notarealprogram 2> %s" % devnull)
        value = os.system("flac -t %s 2> %s" % (self.flac.filename, devnull))
        self.failIf(value and value != badval)

    def test_save_unknown_block(self):
        block = MetadataBlock("test block data")
        block.code = 99
        self.flac.metadata_blocks.append(block)
        self.flac.save()

    def test_load_unknown_block(self):
        self.test_save_unknown_block()
        flac = FLAC(self.NEW)
        self.failUnlessEqual(len(flac.metadata_blocks), 7)
        self.failUnlessEqual(flac.metadata_blocks[5].code, 99)
        self.failUnlessEqual(flac.metadata_blocks[5].data, "test block data")

    def test_two_vorbis_blocks(self):
        self.flac.metadata_blocks.append(self.flac.metadata_blocks[1])
        self.flac.save()
        self.failUnlessRaises(IOError, FLAC, self.NEW)

    def test_missing_streaminfo(self):
        self.flac.metadata_blocks.pop(0)
        self.flac.save()
        self.failUnlessRaises(IOError, FLAC, self.NEW)

    def test_load_invalid_flac(self):
        self.failUnlessRaises(
            IOError, FLAC, os.path.join("tests", "data", "xing.mp3"))

    def test_save_invalid_flac(self):
        self.failUnlessRaises(
            IOError, self.flac.save, os.path.join("tests", "data", "xing.mp3"))

    def test_pprint(self):
        self.failUnless(self.flac.pprint())

    def test_double_load(self):
        blocks = list(self.flac.metadata_blocks)
        self.flac.load(self.flac.filename)
        self.failUnlessEqual(blocks, self.flac.metadata_blocks)

    def test_seektable(self):
        self.failUnless(self.flac.seektable)

    def test_cuesheet(self):
        self.failUnless(self.flac.cuesheet)

    def test_pictures(self):
        self.failUnless(self.flac.pictures)

    def test_add_picture(self):
        f = FLAC(self.NEW)
        c = len(f.pictures)
        f.add_picture(Picture())
        f.save()
        f = FLAC(self.NEW)
        self.failUnlessEqual(len(f.pictures), c + 1)

    def test_clear_pictures(self):
        f = FLAC(self.NEW)
        c1 = len(f.pictures)
        c2 = len(f.metadata_blocks)
        f.clear_pictures()
        f.save()
        f = FLAC(self.NEW)
        self.failUnlessEqual(len(f.metadata_blocks), c2 - c1)

    def test_ignore_id3(self):
        id3 = ID3()
        id3.add(TIT2(encoding=0, text='id3 title'))
        id3.save(self.NEW)
        f = FLAC(self.NEW)
        f['title'] = 'vc title'
        f.save()
        id3 = ID3(self.NEW)
        self.failUnlessEqual(id3['TIT2'].text, ['id3 title'])
        f = FLAC(self.NEW)
        self.failUnlessEqual(f['title'], ['vc title'])

    def test_delete_id3(self):
        id3 = ID3()
        id3.add(TIT2(encoding=0, text='id3 title'))
        id3.save(self.NEW, v1=2)
        f = FLAC(self.NEW)
        f['title'] = 'vc title'
        f.save(deleteid3=True)
        self.failUnlessRaises(ID3NoHeaderError, ID3, self.NEW)
        f = FLAC(self.NEW)
        self.failUnlessEqual(f['title'], ['vc title'])

    def test_mime(self):
        self.failUnless("audio/x-flac" in self.flac.mime)

    def test_variable_block_size(self):
        FLAC(os.path.join("tests", "data", "variable-block.flac"))

    def test_load_flac_with_application_block(self):
        FLAC(os.path.join("tests", "data", "flac_application.flac"))

    def tearDown(self):
        os.unlink(self.NEW)
Beispiel #29
0
def flac_tag(flac_dirname, flac_filename, artist, album, track, tracks, title, year, genre, bpms, compilation):
	# Delete existing tags
	id3 = FLAC(flac_filename)
	id3.clear_pictures()
	id3.delete()
	
	# Artist, Composer
	id3["ARTIST"] = artist
	id3["ALBUM_ARTIST"] = artist
	id3["ALBUMARTIST"] = artist
	id3["COMPOSER"] = artist
	
	# Artistsort
	id3["SORT_ARTIST"] = artist
	id3["SORT_COMPOSER"] = artist
	id3["SORT_ALBUM_ARTIST"] = artist
	id3["ARTISTSORT"] = artist
	id3["ALBUMARTISTSORT"] = artist
	id3["COMPOSERSORT"] = artist
	id3["soar"] = artist
	id3["soaa"] = artist
	id3["soco"] = artist
	
	# Album
	id3["ALBUM"] = album
	
	# Albumsort
	id3["SORT_ALBUM"] = album
	id3["ALBUMSORT"] = album
	
	# Track
	id3["TRACKNUMBER"] = tracks
	id3["TRACK"] = tracks
	id3["DISCNUMBER"] = '1/1'
	
	# Title
	id3["TITLE"] = title
	
	# Year
	id3["YEAR_OF_RELEASE"] = year
	id3["DATE"] = year
	
	# Genre
	id3["GENRE"] = genre
	
	# BPMs
	id3["BPM"] = bpms
	id3["tmpo"] = bpms

	# Compilation
	if (compilation):
		id3["COMPILATION"] = '1'
	else:
		id3["COMPILATION"] = '0'
	
	# Cover
	id3.clear_pictures()
	try:
		image = Picture()
		image.data = open(str(flac_dirname + '/Cover.jpg'), 'rb').read()
		image.type = PictureType.COVER_FRONT
		image.mime = "image/jpeg"
		id3.add_picture(image)
	except:
		print("Warning. No Cover.jpg in directory " + flac_dirname + ".")
	
	# Save tags to file
	id3.save(filename=flac_filename, deleteid3=True)