Exemple #1
0
def metadata(
    file_name, artist, title
):  # easyID3 and ID3 are used to write metadata tags and apply album art found using sacad
    audio = EasyID3(file_name)
    audio['artist'] = artist
    audio['title'] = title
    audio.save()

    audio = ID3(file_name)
    with open(artist + " - " + title + ".jpg", 'rb') as albumart:
        audio['APIC'] = APIC(encoding=3,
                             mime='image/jpeg',
                             type=3,
                             desc=u'Cover',
                             data=albumart.read())
    audio.save()
Exemple #2
0
    def write_id3_tags(self, filename, meta):
        print "Encoding . . . "

        audio = MP3(filename)
        audio["TIT2"] = TIT2(encoding=3, text=["title"])
        audio.save()

        audio = EasyID3(filename)
        audio["tracknumber"] = meta['track']
        audio["title"] = meta['title']
        audio["artist"] = meta['artist']
        audio["album"] = meta['album']
        audio["date"] = meta['date']
        audio.save()

        print "Done encoding . . . "
    def add_to_list(self):
        
        directory = askopenfilenames()
       
        for song_dir in directory:
            print(song_dir)
            self.playlist.append(song_dir)
            
        self.output.delete(0.0, END)

        for key, item in enumerate(self.playlist):
           
            song = EasyID3(item)
            song_data = (str(key + 1) + ' : ' + song['title'][0] + ' - '
                         + song['artist'][0])
            self.output.insert(END, song_data + '\n')
Exemple #4
0
def apply_tags(file_path, tag_list):
    """
    Using mutagen, apply the tags to the file.
    """

    if file_path.endswith(".mp3"):
        muta = EasyID3(file_path)
    elif file_path.endswith(".m4a"):
        muta = EasyMP4(file_path)
    else:
        muta = File(file_path)

    for key in tag_list:
        muta.update({key: tag_list[key]})

    muta.save()
Exemple #5
0
def get_file_tag(f):
    system_tag = None

    if f.endswith(types["mp3"]["ext"]):
        system_tag = EasyID3(f)
    elif f.endswith(types["flac"]["ext"]):
        system_tag = FLAC(f)
    elif f.endswith(types["ogg"]["ext"]):
        system_tag = OggVorbis(f)

    out_tag = MusicTag(title=system_tag["title"][0],
                       title_number=system_tag["tracknumber"][0],
                       album=system_tag["album"][0],
                       artist=system_tag["artist"][0],
                       album_artist=system_tag["albumartist"][0])
    return out_tag
def compare(music_file, metadata):
    """Check if the input music file title matches the expected title."""
    already_tagged = False
    try:
        if music_file.endswith('.mp3'):
            audiofile = EasyID3(music_file)
            # fetch track title metadata
            already_tagged = audiofile['title'][0] == metadata['name']
        elif music_file.endswith('.m4a'):
            tags = {'title': '\xa9nam'}
            audiofile = MP4(music_file)
            # fetch track title metadata
            already_tagged = audiofile[tags['title']] == metadata['name']
    except (KeyError, TypeError):
        pass
    return already_tagged
Exemple #7
0
def updateMP3Info(fileName, like):

	try:
		meta = EasyID3(fileName)
	except error:
		meta = mutagen.File(fileName, easy=True)
		meta.add_tags()

	meta['title'] = like.title
	meta['artist'] = like.user
	meta.save()

	if(like.artworkURL is not None):
		addArtwork(fileName, like)
	else:
		print("Artwork Skipped")
Exemple #8
0
def GetTags(sourcePath):
    global title
    global artist
    global date
    global album
    fileType = os.path.splitext(sourcePath)[1]
    metadata = None
    if (fileType == ".flac"):
        metadata = FLAC(sourcePath)
    elif (fileType == ".mp3"):
        metadata = EasyID3(sourcePath)
    title = metadata["title"][0]
    artist = metadata["artist"][0]
    date = metadata["date"][0]
    album = metadata["album"][0]
    print("Finished getting tags")
def get_pieces_from_sets(sets):
    """	takes a list of set filenames, reads the directories from those sets
        and then gets all the pieces which are in those directories """

    directories = []
    pieces = {}
    prefix = ''

    for path in sets:
        # utf-8 is important
        with open('../directories/' + path, encoding='utf-8') as input_file:
            lines = input_file.readlines()
        for line in lines:
            if line.startswith('prefix='):  # set prefix to non-empty string
                prefix = line[7:-1]
            # ignore commented or empty lines
            elif not ((line[0] == '#') or (line == '\n')):
                directories.append(prefix + line.replace('\n', ''))

    for directory in directories:
        # ID3-title (piece-specific, not per-movement) of last file
        # ('' if new directory, used to decide whether we found a new piece)
        id3 = ''
        for filename in sorted(os.listdir(directory)):
            if '.mp3' in filename:  # ignore non-mp3 files
                audio = EasyID3(os.path.join(directory, filename))
                try:
                    id3_text = audio['title'][0]
                except KeyError:
                    print(
                        os.path.join(directory, filename) +
                        ' does not have a TIT2 ID3 tag')
                    continue
                n_id3 = id3_text[:id3_text.find(' - ')] if (
                    ' - ' in id3_text) else id3_text
                # ID3-title of current file
                n_id3 = n_id3.strip()  # remove any spaces at beginning/end
                if n_id3 != id3:  # seems to be a new piece
                    id3 = n_id3  # set new ID3-title because new piece
                    # new piece so we need to create a new empty list that we
                    # can append files to
                    pieces[id3] = []
                pieces[id3].append(
                    '"' + os.path.join(directory, filename) +
                    '"')  # quotes needed for windows file name handling

    return pieces
def sendAudio(chat_id, audio, lang, music, image=None, youtube=False):
    sleep(0.8)
    bot.sendChatAction(chat_id, "upload_audio")
    try:
        url = "https://api.telegram.org/bot" + token + "/sendAudio"
        if os.path.isfile(audio):
            audio = open(audio, "rb")
            try:
                tag = EasyID3(audio.name)
                duration = MP3(audio.name).info.length
            except mutagen.id3._util.ID3NoHeaderError:
                tag = FLAC(audio.name)
                duration = tag.info.length
            data = {
                "chat_id": chat_id,
                "duration": duration,
                "performer": tag['artist'],
                "title": tag['title']
            }
            file = {"audio": audio, "thumb": requests.get(image).content}
            try:
                request = requests.post(url, params=data, files=file)
            except:
                request = requests.post(url, params=data, files=file)
            if request.status_code == 413:
                sendMessage(
                    chat_id,
                    translate(
                        lang, "The song " + tag['artist'] + " - " +
                        tag['title'] + " is too big to be sent"))
            else:
                if youtube == False:
                    audio = request.json()['result']['audio']['file_id']
                    write_db(
                        "INSERT INTO DWSONGS(id, query, quality) values('%s', '%s', '%s')"
                        % (music, audio, qualit[chat_id]))
        else:
            bot.sendAudio(chat_id, audio)
    except telepot.exception.TelegramError:
        sendMessage(
            chat_id,
            translate(lang,
                      "Sorry the track doesn't seem readable on Deezer :("))
    except:
        sendMessage(
            chat_id,
            translate(lang, "Sorry for some reason I can't send the track"))
def make_tags(podcast, attribs, path, filename, episode):
    # Tag the episode with ID3 metadata
    print(f"-- Tagging {filename}")
    try:
        try:
            tags = EasyID3(f"{path}/{filename}")
        except:
            tags = mutagen.File(f"{path}/{filename}", easy=True)
    except:
        print(
            f"############ Unable to open {path}/{filename} for tagging ############"
        )
        sys.exit()

    tags['title'] = episode.get('title', filename)
    tags['artist'] = attribs.get('artist', podcast)
    tags['album'] = attribs.get('album', podcast)
    tags['author'] = attribs.get('author', podcast)

    # tags['comments'] = episode.metadata['comments']
    # tags['creative_commons'] = episode.metadata['creative_commons']
    # tags['enclosure_url']  = episode.metadata['enclosure_url']
    # tags['enclosure_type'] = episode.metadata['enclosure_type']
    # tags['enclosure_length'] = episode.metadata['enclosure_length']
    # tags['enclosure_type']  = episode.metadata['enclosure_type']
    # tags['guid']  = episode.metadata['guid']
    # tags['itunes_author_name']  = episode.metadata['itunes_author_name']
    # tags['itunes_block']  = episode.metadata['itunes_block']
    # tags['itunes_closed_captioned'] = episode.metadata['itunes_closed_captioned']
    # tags['itunes_duration'] = episode.metadata['itunes_duration']
    # tags['itunes_explicit'] = episode.metadata['itunes_explicit']
    # tags['itune_image']  = episode.metadata['itune_image']
    # tags['itunes_order']  = episode.metadata['itunes_order']
    # tags['itunes_subtitle'] = episode.metadata['itunes_subtitle']
    # tags['itunes_summary']  = episode.metadata['itunes_summary']
    # tags['link']  = episode.metadata['link']
    # tags['published_date'] = episode.metadata['published_date']
    # tags['title']  = episode.metadata['title']

    genres = attribs.get('genres', [])
    genres.append('Podcast')
    tags['genre'] = ','.join(genres)
    if attribs.get('track_num'):
        tags['tracknumber'] = str(attribs.get('track_num'))
    tags.save()

    return
Exemple #12
0
 def download_music(url, index=None):
     url_hash = hashlib.md5(url.encode()).hexdigest()
     if index:
         url_hash = url_hash + "-" + str(index)
     path = var.config.get('bot', 'tmp_folder') + url_hash + ".%(ext)s"
     mp3 = path.replace(".%(ext)s", ".mp3")
     if os.path.isfile(mp3):
         audio = EasyID3(mp3)
         video_title = audio["title"][0]
     else:
         if index:
             ydl_opts = {
                 'format': 'bestaudio/best',
                 'outtmpl': path,
                 'writethumbnail': True,
                 'updatetime': False,
                 'playlist_items': str(index),
                 'postprocessors': [{
                     'key': 'FFmpegExtractAudio',
                     'preferredcodec': 'mp3',
                     'preferredquality': '192'},
                     {'key': 'FFmpegMetadata'}]
             }
         else:
             ydl_opts = {
                 'format': 'bestaudio/best',
                 'outtmpl': path,
                 'noplaylist': True,
                 'writethumbnail': True,
                 'updatetime': False,
                 'postprocessors': [{
                     'key': 'FFmpegExtractAudio',
                     'preferredcodec': 'mp3',
                     'preferredquality': '192'},
                     {'key': 'FFmpegMetadata'}]
             }
         video_title = ""
         with youtube_dl.YoutubeDL(ydl_opts) as ydl:
             for i in range(2):
                 try:
                     info_dict = ydl.extract_info(url)
                     video_title = info_dict['title']
                 except youtube_dl.utils.DownloadError:
                     pass
                 else:
                     break
     return mp3, video_title
Exemple #13
0
    def fix_names(self):
        API_key = "ebd06f4e0ef7f4affadd430237a839b1"
        art_url = "http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=" + API_key + "&artist=" + self.artistName + "&album=" + self.albumName + "&format=json"
        res = requests.get(art_url)
        res = json.loads(res.text)

        # Sanitize titles
        for title in self.songs:
            bad_chars = '<>:"/\|?*'
            for c in bad_chars:
                title = title.replace(c, ';')
            title = title.replace('.', '')

        # Rename files
        os.chdir('./' + self.artistName.replace('+', ' ') + '/' +
                 self.albumName.replace('+', ' ') + '/')
        for filename in sorted(os.listdir('./')):
            self.files.append(filename)

        print("\n\nAdding Album art and renaming songs....  ")

        http = urllib3.PoolManager()
        albumart = http.request('GET', res['album']['image'][-2]['#text']).data

        for i in range(0, len(self.songs)):
            data = EasyID3(self.files[i])
            data['title'] = self.songs[i]
            data['album'] = self.albumName
            data['tracknumber'] = str(i + 1)
            data['albumartist'] = self.artistName
            data['artist'] = self.artistName
            data.save()

            data = ID3(self.files[i])

            data['APIC'] = APIC(
                encoding=3,  # 3 is for utf-8
                mime='image/png',  # image/jpeg or image/png
                type=3,  # 3 is for the cover image
                desc=u'Cover',
                data=albumart)
            data.save()

            os.rename(self.files[i], self.songs[i] + '.mp3')

        print("\nSuccessfully downloaded album \"" + self.albumName +
              "\" by " + self.artistName)
    def _score_songs_and_titles_in_sentence(self, sentence):
        file_set_to_search = os.listdir(self._music_folderpath)
        splitted_sentence = sentence.split(" ")

        scores_for_songs = {}
        scores_for_assumed_titles = {}
        for file_name in file_set_to_search:
            try:
                file_name = self._music_folderpath + "/" + file_name
                audio_file = EasyID3(file_name)
                audio_file_title = audio_file[
                    LocalStorageForMusic.METADATA_KEY_TITLE][0]
                audio_file_artist = audio_file[
                    LocalStorageForMusic.METADATA_KEY_ARTIST][0]

                # At this point, it is safe to assume the file is an audio format.
                # Therefore we can assign it a place in scores_for_song_titles dictionary.
                score_for_song = {}
                for assumed_title_begin_index in range(len(splitted_sentence)):
                    for assumed_title_end_index in range(
                            assumed_title_begin_index, len(splitted_sentence)):
                        assumed_title = " ".join(splitted_sentence[
                            assumed_title_begin_index:assumed_title_end_index +
                            1])
                        assumed_title_score = self._score_title_same_as_heard_title(
                            audio_file_title, assumed_title)

                        score_for_song[assumed_title] = assumed_title_score
                        scores_for_assumed_titles[assumed_title] = (
                            scores_for_assumed_titles[assumed_title]
                            if assumed_title in scores_for_assumed_titles else
                            0.0) + assumed_title_score

                score_data_for_song = {
                    self.KEY_SONG_TITLE: audio_file_title,
                    self.KEY_SONG_ARTIST: audio_file_artist,
                    self.KEY_SONG_SCORE: score_for_song
                }
                scores_for_songs[audio_file] = score_data_for_song

            except:
                continue

        # We have to adjust the scores according to the assumed title being a real title by passing it through a certain
        # model. This model should reduce the score for including words which would not preferably exist in song titles.

        return scores_for_songs, scores_for_assumed_titles
Exemple #15
0
def read_artists(path):
    artist_set = set()

    total_count = 0
    unreadable_count = 0
    for root, dirs, files in os.walk(path, topdown=False):
        file_count = 0
        for file_count, filename in enumerate(files, start=1):
            path = root + "/" + filename
            ext = os.path.splitext(path)[1]

            # skip some common file extensions that may be found in music folders
            if filename.startswith(
                    ".") or ext == ".jpg" or ext == ".m3u" or ext == ".txt":
                continue
            try:
                # guess the file type by extension. this is faster than looking at file contents
                if ext == ".m4v" or ext == ".mp4" or ext == ".m4a":
                    audio = EasyMP4(path)
                elif ext == ".ogg":
                    audio = OggVorbis(path)
                elif ext == ".flac":
                    audio = FLAC(path)
                else:
                    audio = EasyID3(path)

            except Exception as e:
                Logger.debug(e)
                # try slower magic number/tag lookup if filename based guess doesn't work.
                audio = mutagen.File(path, easy=True)

            if audio is not None and 'artist' in audio:
                for artist in audio['artist']:
                    if len(artist) != 0 and not artist.lower().startswith(
                            "various") and not artist.lower().startswith(
                                "unknown"):
                        artist_set.add(artist)
            else:
                unreadable_count += 1

        total_count += file_count
    Logger.info("Total files %i, Total unreadable %i", total_count,
                unreadable_count)
    Logger.info("Total artist count %i", len(artist_set))
    Logger.debug(artist_set)

    return artist_set
Exemple #16
0
def sendAudio(
	chat_id, audio,
	link = None,
	image = None,
	youtube = False
):
	sleep(default_time)

	try:
		if os.path.isfile(audio):
			bot.sendChatAction(chat_id, "upload_audio")

			try:
				tag = EasyID3(audio)
				duration = int(MP3(audio).info.length)
			except ID3NoHeaderError:
				tag = FLAC(audio)
				duration = int(tag.info.length)

			if os.path.getsize(audio) < telegram_audio_api_limit:
				file_id = bot.sendAudio(
					chat_id, open(audio, "rb"),
					thumb = open(image.url, "rb"),
					duration = duration,
					performer = tag['artist'][0],
					title = tag['title'][0],
					caption = "@Music_Geeks"
				)['audio']['file_id']

				if not youtube:
					quality = fast_split(audio)
					link = "track/%s" % link.split("/")[-1]

					write_db(
						insert_query
						% (
							link,
							file_id,
							quality
						)
					)
			else:
				sendMessage(chat_id, "Song too big :(")
		else:
			bot.sendAudio(chat_id, audio, caption = "@Music_Geeks")
	except error.BadRequest:
		sendMessage(chat_id, "Sorry the track %s doesn't seem readable on Deezer :(" % link)
Exemple #17
0
def create_link_song(source, base_folder):
    """Make song Filename fitting to the database structure

	this ensures that duplicate songs don't clutter mp3 players'
	album views"""
    dest = ""

    try:
        song = source.decode(sys.getfilesystemencoding())
    except:
        song = make_compat_str(source)

    song = song.encode('ascii', 'ignore')

    song_file = {}
    try:
        song_file = EasyID3(song)
    except:
        song_file['artist'] = "Unknown"
        song_file['album'] = "Unknown"

    try:
        src = song
        target = base_folder

        try:
            artist = ''.join(song_file['artist'])
            if (artist == ""):
                artist = ''.join(song_file['author'])
            if (artist == ""):
                artist = ''.join(song_file['performer'])
            if (artist == ""):
                artist = ''.join(song_file['composer'])
        except KeyError, exception_reason:
            artist = u"Unknown Artist"

        artist = (binascii.crc32(artist.encode('utf-8')) & 0xffffffff)
        artist = "%x" % (artist)

        target = os.path.join(target, artist)
        if not os.path.isdir(target):
            os.makedirs(target)

        try:
            album = ''.join(song_file['album'])
        except KeyError, exception_reason:
            album = u"Unknown Album"
    def _score_songs_and_artists_in_sentence(self, sentence):
        file_set_to_search = os.listdir(self._music_folderpath)
        splitted_sentence = sentence.split(" ")

        scores_for_songs = {}
        scores_for_assumed_artists = {}
        for file_name in file_set_to_search:
            try:
                file_name = self._music_folderpath + "/" + file_name
                audio_file = EasyID3(file_name)
                audio_file_title = audio_file[
                    LocalStorageForMusic.METADATA_KEY_TITLE][0]
                audio_file_artist = audio_file[
                    LocalStorageForMusic.METADATA_KEY_ARTIST][0]

                # At this point, it is safe to assume the file is an audio format.
                # Therefore we can assign it a place in scores_for_song_titles dictionary.
                score_for_song = {}
                for assumed_artist_begin_index in range(
                        len(splitted_sentence)):
                    for assumed_artist_end_index in range(
                            assumed_artist_begin_index,
                            len(splitted_sentence)):
                        assumed_artist = " ".join(
                            splitted_sentence[assumed_artist_begin_index:
                                              assumed_artist_end_index + 1])
                        assumed_artist_score = self._score_artist_same_as_heard_artist(
                            audio_file_artist, assumed_artist)

                        score_for_song[assumed_artist] = assumed_artist_score
                        scores_for_assumed_artists[assumed_artist] = (
                            scores_for_assumed_artists[assumed_artist]
                            if assumed_artist in scores_for_assumed_artists
                            else 0.0) + assumed_artist_score

                score_data_for_song = {
                    self.KEY_SONG_TITLE: audio_file_title,
                    self.KEY_SONG_ARTIST: audio_file_artist,
                    self.KEY_SONG_SCORE: score_for_song
                }
                scores_for_songs[audio_file] = score_data_for_song

            except:
                continue

        return scores_for_songs, scores_for_assumed_artists
Exemple #19
0
 def __init__(self,
              filename,
              newtracklength,
              albumname='',
              trackname='',
              performer='',
              genre='',
              albumyear=''):
     assert_str(filename)
     if IO.file_exists(filename):
         self.fileName = filename
         if filename.endswith('.mp3'):
             self.EasyID3 = EasyID3(filename)
             self.mp3 = MP3(filename)
             assert_int_or_float(newtracklength)
             self.newTrackLength = newtracklength
             assert_str(trackname)
             if trackname != '':
                 self.trackName = trackname
             else:
                 self.trackName = str(tryGet(self.EasyID3, 'title')[0])
             assert_str(performer)
             if performer != '':
                 self.performer = performer
             else:
                 self.performer = str(tryGet(self.EasyID3, 'artist')[0])
             assert_str(albumname)
             if albumname != '':
                 self.albumName = albumname
             else:
                 self.albumName = str(tryGet(self.EasyID3, 'album')[0])
             assert_str(genre)
             if genre != '':
                 self.albumGenre = genre
             else:
                 self.albumGenre = str(tryGet(self.EasyID3, 'genre')[0])
             assert_str(albumyear)
             if albumyear != '':
                 self.albumYear = albumyear
             else:
                 self.albumYear = str(tryGet(self.EasyID3, 'date')[0])
             self.trackLength = self.mp3.info.length
         else:
             raise ValueError('File should be an mp3, bitch!')
     else:
         raise ValueError('Enter a valid file name, bitch!')
    def set_id3_data(self, convertedFilePath, songObj):
        # embed song details
        # ! we save tags as both ID3 v2.3 and v2.4
        # ! The simple ID3 tags
        audioFile = EasyID3(convertedFilePath)
        # ! Get rid of all existing ID3 tags (if any exist)
        audioFile.delete()
        # ! song name
        audioFile['title'] = songObj.get_song_name()
        audioFile['titlesort'] = songObj.get_song_name()
        # ! track number
        audioFile['tracknumber'] = str(songObj.get_track_number())
        # ! disc number
        audioFile['discnumber'] = str(songObj.get_disc_number())
        # ! genres (pretty pointless if you ask me)
        # ! we only apply the first available genre as ID3 v2.3 doesn't support multiple
        # ! genres and ~80% of the world PC's run Windows - an OS with no ID3 v2.4 support
        genres = songObj.get_genres()
        if len(genres) > 0:
            audioFile['genre'] = genres[0]
        # ! all involved artists
        audioFile['artist'] = songObj.get_contributing_artists()
        # ! album name
        audioFile['album'] = songObj.get_album_name()
        # ! album artist (all of 'em)
        audioFile['albumartist'] = songObj.get_album_artists()
        # ! album release date (to what ever precision available)
        audioFile['date'] = songObj.get_album_release()
        audioFile['originaldate'] = songObj.get_album_release()
        # ! save as both ID3 v2.3 & v2.4 as v2.3 isn't fully features and
        # ! windows doesn't support v2.4 until later versions of Win10
        audioFile.save(v2_version=3)
        # ! setting the album art
        audioFile = ID3(convertedFilePath)
        rawAlbumArt = urlopen(songObj.get_album_cover_url()).read()
        audioFile['APIC'] = AlbumCover(encoding=3,
                                       mime='image/jpeg',
                                       type=3,
                                       desc='Cover',
                                       data=rawAlbumArt)
        # ! setting the lyrics
        lyrics = songObj.get_lyrics()
        USLTOutput = USLT(encoding=3, lang=u'eng', desc=u'desc', text=lyrics)
        audioFile["USLT::'eng'"] = USLTOutput

        audioFile.save(v2_version=3)
Exemple #21
0
def showMusic():

    globPath = argv[-1]

    directory, glob = path.split(globPath)

    for (top, dirs, files) in walk(directory):
        for file in files:
            if fnmatch(file, glob):

                # "Normalizing the path just for safety"
                # This makes sure all of the path separators are correct for the OS etc..
                mp3FilePath = path.normpath(path.join(top, file))

                try:
                    media = EasyID3(mp3FilePath)
                    data = {  tagName:tagValue[0] for tagName,tagValue in media.items()}

                    args = [f.lstrip("-").split("=") for f in argv if f.startswith("--")]

                    tag, value = [(x,y) for x,y in args][0]

                    for tag,val in args:

                        # match expression with arguments
                        if re.match("^(The)*\s*\w.+", val):


                            if data["artist"] == val:

                                tmplt = "Found: {artist} {album} {title}"
                                print(tmplt.format(**data))

                            if data["title"] == val:

                                tmplt = "Found: {artist} {album} {title}"
                                print(tmplt.format(**data))

                            if data["album"] == val:

                                tmplt = "Found: {artist} {album} {title}"
                                print(tmplt.format(**data))
                            
                except Exception as e:
                    print("Could not read: " + file + " " + str(e))
                    print("Usage: LAB5.py [--artist=\"artistname\"] [--song=\"songname\"] [--album=\"albumname\"] fileGlob")
Exemple #22
0
    def tag_and_copy(self, audio_data, tmpdirname):
        dest_path = path.join(self.playlist_path_location, audio_data.filename)
        filepath = path.join(tmpdirname, audio_data.filename)

        # if artist and audio -> use id3 tags
        if self.audio_transform and audio_data.artist is not None:
            try:
                meta = EasyID3(filepath)
            except mutagen.id3.ID3NoHeaderError:
                meta = mutagen.File(filepath, easy=True)
                meta["title"] = audio_data.tagtitle
                meta["artist"] = audio_data.artist
                meta.save()
        # copy audio file (no need to remove files in tmpdir)
        if not path.exists(dest_path):
            log.debug(f'Moving {filepath} -> {dest_path}')
            shutil.copyfile(filepath, dest_path)
Exemple #23
0
def main(delete, title_artist, title_only, min_bitrate, directory):
    songs = getMP3s(directory)
    for song in songs:
        try:
            loaded = EasyID3(song)
            if ("title" in loaded and "artist" in loaded):
                bitrate = MP3(song).info.bitrate / 1000
                if (min_bitrate >=
                        bitrate):  ## Ensure minimum bitrate is reached
                    deleteSong(song, "Bitrate below: " + str(min_bitrate))
                    continue

                title = sanitizeString(str(loaded["title"][0]))
                renamed = [
                    '', '', '', '.mp3'
                ]  ## Since we're only dealing with mp3s at the moment.

                if (not title_only
                    ):  ## Thus, we'll have the title and the artist somewhere.
                    renamed[1] = ' - '

                if (not title_artist):  ## Thus, the artist string comes first
                    renamed[0] = sanitizeString(str(
                        loaded["artist"][0])) * (not title_only)
                    renamed[2] = title
                else:  ## Thus, the title string comes first
                    renamed[0] = title
                    renamed[2] = sanitizeString(str(
                        loaded["artist"][0])) * (not title_only)

                renamed = os.path.join(directory, ''.join(renamed))

                os.rename(song, renamed)
                print(getPathEnd(song) + " ==> " + getPathEnd(renamed))

        except ID3NoHeaderError:
            if (delete):
                deleteSong(song, "ID3NoHeaderError exception")
            continue
        except error:
            if (delete):
                deleteSong(song, "MutagenError exception")
            continue
        except:
            exception = sys.exc_info()[0].__name__
            print(exception + " exception for song: " + song)
Exemple #24
0
def addID3Tags(filename, config, title, desc):
    """Add ID3 tags."""
    logger.info("Adding ID3 tags...")

    # Get reference to tags, add them if not found
    try:
        metaData = EasyID3(filename)
    except mutagen.id3.ID3NoHeaderError:
        metaData = MP3(filename, ID3=EasyID3)
        metaData.add_tags()

    # Set tags
    metaData['title'] = title
    metaData['artist'] = unicode(config['episodeAuthor'])
    metaData['date'] = unicode(str(datetime.datetime.now().year))
    metaData['album'] = unicode(config['rssTitle'])
    metaData.save()
Exemple #25
0
    def initialize_meta(self):
        try:
            self.meta = EasyID3(self.filePath)
        except MutagenError:

            class meta:
                def __init__(self):
                    pass

                def get(self, prop, default):
                    return default

                def pprint(self):
                    return {}

            self.meta = meta()
            pass
Exemple #26
0
def split_song(album, tracksStarts, index, track, FOLDER):
    print("\t{}) {}".format(str(index+1), track))
    start = tracksStarts[index]
    end = tracksStarts[index+1]
    duration = end-start
    track_path = '{}/{:02d} - {}.mp3'.format(FOLDER, index+1, track)
    album[start:][:duration].export(track_path, format="mp3")

    print("\t\tTagging")
    song = EasyID3(track_path)
    if ARTIST:
            song['artist'] = ARTIST
    if ALBUM:
            song['album'] = ALBUM
    song['title'] = track
    song['tracknumber'] = str(index+1)
    song.save()
Exemple #27
0
def download_track(title, link, artist, album, tracknum, year, path):
    print("Downloading " + title)
    filename = "./downloads/" + path + "/" + title + ".mp3"
    file = open(filename, "wb")
    file.write(requests.get(link).content)
    file.close()
    mp3 = MP3(filename)
    if mp3.tags is None:
        mp3.add_tags()
    mp3.save()
    audio = EasyID3(filename)
    audio["artist"] = u"" + artist
    audio["title"] = u"" + title
    audio["album"] = u"" + album
    audio["tracknumber"] = u"" + str(tracknum)
    audio["date"] = u"" + year
    audio.save()
Exemple #28
0
    def test_save_meta(self):
        # Given
        audio_src = os.path.join(TEST_DATA_DIR, 'file_example_MP3_700KB.mp3')
        audio_dst = os.path.join(self.out_dir, 'test.mp3')
        art_srt = os.path.join(TEST_DATA_DIR, 'SampleJPGImage_50kbmb.jpg')
        shutil.copy(audio_src, audio_dst)

        # When
        save_meta(audio_dst, self.info_obj, art_srt)

        # Then
        meta = EasyID3(audio_dst)
        for meta_key, meta_val in self.info_obj.id3_meta.items():
            self.assertEqual(meta[meta_key][0], meta_val)

        meta = ID3(audio_dst)
        self.assertTrue(meta['APIC:Cover'])
Exemple #29
0
def addMetadata(fileName,thumbnail,title,artist,album):
    """ Add metadata and thumbnail to mp3 and mp4 files (TODO for mp4).
    
    Parameters:
    ----------
    fileName : str
        Source file with complete path.
    thumbnail : str
        Name of the thumbnail image file with full path.
    title : str
    artist : str
    album : str
    
    Usage:
    -----
    utils.convertFileFormat(source,target,deleteSource=True)
    
    Returns:
    -------
    title : str
    artist : str
    album : str
    """
    
    if ('.mp3' in fileName):
        audio = MP3(fileName,ID3=ID3)
        audio.tags.add(APIC(mime='image/jpeg',type=3,desc=u'Cover',data=open(thumbnail,'rb').read()))
        audio.save()
        os.remove(thumbnail)
        
        # ADD TITLE AND ALBUM NAME
        audio = EasyID3(fileName)
        audio['title'] = title
        audio['artist'] = artist
        audio['album'] = album
        audio.save()
    elif ('.mp4' in fileName):
        video = MP4(fileName)
        tags = video.tags
        tags['\xa9nam'] = title
        tags['\xa9ART'] = artist
        tags['\xa9alb'] = album
        with open(thumbnail,'rb') as f:
            tags["covr"] = [MP4Cover(f.read(), imageformat=MP4Cover.FORMAT_JPEG)]
        tags.save(fileName)
        os.remove(thumbnail)
 def processFile(self, path):
     try:
         mp3info = EasyID3(path)
     except Exception as e:
         return
     print(path)
     info = mp3info.pprint()
     name = self.getId3Info(mp3info, "title", info)
     trackNum = self.getId3Info(mp3info, "tracknumber", info)
     artist = self.getId3Info(mp3info, "performer", info)
     album = self.getId3Info(mp3info, "album", info)
     gender = self.getId3Info(mp3info, "genre", info)
     year = self.getId3Info(mp3info, "date", info)
     artist = dh.artistId(artist)
     gender = dh.genderId(gender)
     album = dh.albumId(album, year, artist, gender)
     album = dh.songId(name, trackNum, artist, album)