Exemplo n.º 1
0
def organise(source_file, dest_root):
    ''' Take the source file and organise by artist/album '''
    source_mp3 = MP3File(source_file)

    artist_dir = source_mp3.artist
    album_dir = source_mp3.album

    print(artist_dir)
    print(album_dir)

    ' check if sub folder 1 exists and create as necessary '

    artist_album_dir = dest_root + SEP + artist_dir + SEP + album_dir

    if (os.path.isdir(artist_album_dir) == False):
        os.mkdir(artist_album_dir)

    ' check if sub folder 2 exists and create as necessary '

    fileName = _path_leaf(source_file)

    dest_mp3 = MP3File(artist_album_dir + SEP + filename)

    ' write file to dest_root/artist_dir/album_dir'
    dest_mp3.save()
def setRjBuffer(filePath):
    rj = getRandomRj()

    if len(filePath) < 1:
        speech = 'You are listening to '+streamName + \
            '. '+streamDescription + '. I am RJ '+rj[1]+'.'
        prepareRjBufferMp3(speech, rj)

    else:
        mp3 = MP3File(filePath)
        mp3.set_version(VERSION_2)
        if filePath.find('music/') > -1:
            speech = 'You are listening to '+streamName+'. I am RJ ' + \
                rj[1]+'. Now, You will listen to ' + \
                mp3.song+' by ' + mp3.artist+'.'
            #print(speech)
            prepareRjBufferMp3(speech, rj)
        elif filePath.find('news/news.mp3') > -1:
            speech = "Hello listeners, Its RJ "+rj[1]+". You are listening to "+streamName+". Now you will listen to the latest bulletin from BBC World Service."
            prepareRjBufferMp3(speech, rj)
		
        elif filePath.find('request/') > -1:
            speech = 'Hello listeners, Its RJ '+rj[1]+ \
                 '. You are listening to '+streamName+'. We just recieved a song request from ' + \
                 filePath.replace(requestPath,'').replace('.mp3','') + ' with love. Now you will listen to ' + \
                 mp3.song+' by ' + mp3.artist+'.'
            prepareRjBufferMp3(speech, rj)
Exemplo n.º 3
0
    def getlist(self):
        self.musiclist = []
        for file in os.listdir("music/"):
            if file.endswith(".mp3"):
                musicdata = {}
                filename = 'music/' + file

                if os.path.isfile(filename):

                    # Get tags
                    mp3 = MP3File(filename)
                    musicdata['filename'] = filename
                    musicdata['data'] = mp3.get_tags()

                    # Get coverdata
                    file = File(filename)
                    if 'APIC:' in file.tags:
                        coverdata = file.tags['APIC:'].data
                        musicdata['cover'] = pil2cairo(
                            Image.open(io.BytesIO(coverdata)), 128, 128)

                    self.musiclist.append(musicdata)

        self.shufflelist()

        return self.musiclist
Exemplo n.º 4
0
async def download_track(session, track, progress_queue):
    output_file = os.path.join(
        output_directory,
        track['user']['username'],
        f"{track['title']}.mp3",
    )
    chunk_size = 2**10
    async with session.get(track['stream_url'],
                           params={'client_id': client_id}) as response:
        target = f"{track['user']['username']} - {track['title']}"
        size = int(response.headers.get('content-length', 0)) or None
        position = await progress_queue.get()
        progress_bar = tqdm.tqdm(
            desc=target,
            total=size,
            position=position,
            leave=False,
            unit='iB',
            ascii=True,
            unit_scale=True,
        )
        with open(output_file, 'wb+') as f:
            async for chunk in response.content.iter_chunked(chunk_size):
                f.write(chunk)
                progress_bar.update(len(chunk))

    mp3 = MP3File(output_file)
    mp3.set_version(VERSION_BOTH)
    mp3.song = track['title']
    mp3.artist = track['user']['username']
    mp3.track = f"{track['track_num']}"
    mp3.album = 'Soundcloud'
    mp3.save()

    await progress_queue.put(position)
Exemplo n.º 5
0
def getMeta(fileName):
    audio = MP3(fileName)
    print(fileName)
    fileDets = {}
    if os.path.exists(fileName):
        mp3 = MP3File(fileName)
        try:
            tags = mp3.get_tags()["ID3TagV2"]

            for value in attrKeys.values():
                fileDets[value] = tags[value.lower()]
                print(tags[value.lower()])

            fileDets["Title"] = tags["song"]
            fileDets["Summary"] = tags["song"]
            fileDets["Summary"] = tags["song"]
            fileDets["Authors"] = tags["artist"]
            fileDets["Duration"] = audio.info.length
            fileDets["Size"] = audio.info.length
            fileDets["PubDate"] = None
        except:
            fileDets["Album"] = "The Dragon Reborn"
            fileDets["Title"] = ""
            fileDets["Summary"] = ""
            fileDets["Summary"] = ""
            fileDets["Authors"] = "Wheel of Time"
            fileDets["Duration"] = audio.info.length
            fileDets["Size"] = None
            fileDets["PubDate"] = None

    return fileDets
Exemplo n.º 6
0
def get_ID3v2_tags(mp3_file):
    """
    Extract ID3v2 tags (artist, album, song) from *.mp3. If ID3v2 tags missing or not file permissions equate
    (artist=None, album=None, song=None).
    :param mp3_file: some *.mp3
    :return: namedtuple(artist, album, song)
    """
    try:
        audio = MP3File(mp3_file).get_tags().get('ID3TagV2')
    except AttributeError:
        audio = None
    except PermissionError:
        audio = None
    tags_mp3 = namedtuple('Tags', 'artist album song')
    tags = None
    if not audio:
        tags = tags_mp3(None, None, None)
    else:
        try:
            artist = del_system_char(audio.get('artist').strip())
        except AttributeError:
            artist = None
        try:
            album = del_system_char(audio.get('album').strip())
        except AttributeError:
            album = None
        try:
            song = del_system_char(audio.get('song').strip())
        except AttributeError:
            song = None
        if artist and album and song:
            tags = tags_mp3(artist, album, song)
    return tags
Exemplo n.º 7
0
def dict_fill_from_bulk_mp3s(dict_input, mp3_location):

    for song in os.listdir(mp3_location):

        print('Currently processing dictionary fill for: ' + song)

        if song.endswith(".mp3"):
            # Defining starting file location of MP3
            song_location = mp3_location + '\\' + song
            song_start = MP3File(song_location)
            song_start.set_version(VERSION_2)

            # Getting artist name and album name from MP3 tags
            artist_name = song_start.artist
            album_name = song_start.album

        else:
            print('This file is not an MP3! Moving on...')
            continue

        if artist_name == [] or album_name == []:
            print('This MP3 is missing necessary tags! Moving on...')
            continue

        # Otherwise goes on to add dictionary entries if artist or album is unique
        else:
            artist_check = False    # Resets variable that keeps track of whether artist entry already exists

            # Checks to see if this artist already exists in the dictionary
            for entry in dict_input:

                if similar(entry, artist_name) > 0.85:
                    print('There is already a dictionary entry for this artist.')
                    artist_check = True    # Variable is updated to represent artist being redundant for this song
                    artist_name = entry
                    break

            # If the artist entry already exists then...
            if artist_check:

                # Checks to see if the album for this artist already exists in the dictionary as well
                for entry in dict_input[artist_name]:

                    if similar(entry, album_name) > 0.85:
                        print("There is already a dictionary entry for this artist's album. Moving on...")
                        break

                # If none of the album names are redundant, a new album name entry is created
                album_name = sanitize(album_name)
                dict_input[artist_name].append(album_name)
                print('A new album entry has been created for this artist in the dictionary. Moving on...')

            # If neither artist entry or album entry exists, this creates both of them
            else:
                artist_name = sanitize(artist_name)
                album_name = sanitize(album_name)
                dict_input[artist_name] = [album_name]
                print('A new artist entry with a corresponding album has been created in the dictionary. Moving on...')

    return dict_input
Exemplo n.º 8
0
def myFun(fileName):
    audFetch = r"C:\Users\Dharmik\Desktop\New\songs\\" + fileName
    mp3 = MP3File(audFetch)
    mp3.set_version(VERSION_2)

    s = mp3.song
    y = mp3.year
    a = mp3.artist
    g = mp3.genre

    for i in s:
        if (i == "("):
            ind = s.index(i)
            s = s[0:ind]
            break
        elif (i == "["):
            ind = s.index(i)
            s = s[0:ind]

    re.sub('[^A-Za-z0-9]+', '', s)
    print("Song", s)

    os.rename(audFetch, r"C:\Users\Dharmik\Desktop\New\songs\\" + s + ".mp3")

    show_info(s, a, g, y)
Exemplo n.º 9
0
    def import_song(self, path):
        ext = os.path.splitext(path)[-1].lower()
        if ext == ".mp3":
            try:
                mp3 = MP3File(path)
                try:
                    tags = mp3.get_tags()
                except Exception:
                    pass
                else:
                    song_dict = dict(path=path)
                    try:
                        Song.objects.get(**song_dict)
                    except Song.DoesNotExist:

                        for tag_key, tag_dict in tags.items():
                            for song_key in ID3_FIELDS:
                                if not song_dict.get(song_key):
                                    song_dict.update({song_key: tag_dict.get(song_key)})
                        try:
                            Song.objects.create(**song_dict)

                        except Exception:
                            pass

            except Exception:
                pass
Exemplo n.º 10
0
def get_track_features(token):
    '''
    Function that retrieves track features for songs in database.

    :param token: Oath token of spotify

    :return: Dict of dicts that contains the features for all songs.
    '''

    # Hardcoded names of directories that contain the songs.
    folders = ["classical", "rock", "pop", "electronic"]
    song_info = {folder: {} for folder in folders}

    # Retrieve song and artist from mp3 file. Loop over all 100 songs per dir.
    for folder in folders:
        for index in range(1, 101):
            mp3 = MP3File("./../../../songs/" + folder + "/" + str(index) +
                          ".mp3")
            mp3.set_version(VERSION_2)

            # Retrieve song information from spotify
            id, song_name = get_track_id(mp3.song, mp3.artist, token)
            if (id != None):
                # put audio features in dict.
                audio_features = add_audio_features(id, token)
                audio_features["name"] = song_name
                song_info[folder][str(index)] = audio_features
            # this sleep prevents the api from being queried too often.
            sleep(0.10)

    return song_info
Exemplo n.º 11
0
def filter_duplicates(extension, types, path, fileList, size):
    if extension in types:
        mp3 = MP3File(path)
        tags = "empty"
        try:
            tags = mp3.get_tags()
        except UnicodeDecodeError as err:
            click.echo("\nError retreiving tags, file: {} - error: {}".format(
                path, err.reason))
        except:
            click.echo("\nBad MP3 tags , file: {}".format(path))
        for i in range(9):
            suffix = "({})".format(i)
            suffix2 = "_{}.".format(i)
            if suffix in path or suffix2 in path:
                track = "empty"
                name = "empty"
                if tags['ID3TagV2'] and tags['ID3TagV2']['track']:
                    track = tags['ID3TagV2']['track']
                if tags['ID3TagV2'] and tags['ID3TagV2']['song']:
                    name = tags['ID3TagV2']['song']
                DUPLICATES.onemore()
                fileList.append({
                    "path": path,
                    "size": size,
                    "track": track,
                    "name": name
                })
Exemplo n.º 12
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('directory',
                        help='System path to directory containing files.')
    parser.add_argument('--rename_files',
                        help='Use this if you want to rename files.  \
    Useful only if the files haven\'t already been manually renamed.',
                        action='store_true')
    parser.add_argument('--correct_key_comment',
                        help='Use this if you want to remove the `/` between \
    keys added by MixedInKey, and add `N/A` if no key was added (i.e. file was too long).',
                        action='store_true')
    args = parser.parse_args()
    correct_key_comment = args.correct_key_comment
    directory = args.directory
    rename_files = args.rename_files
    # First, rename the files themselves to get rid of Album and Track number) if that option was passed:
    if rename_files:
        file_list = get_file_list(directory)
        for file in file_list:
            rename_file(file, directory)
    # Next, re-read the files with their new names and update the ID3 tags:
    file_list = get_file_list(directory)
    for file in file_list:
        print(f"Scrubbing ID3 tags for `{file}`.")
        artist, song = get_info_from_filename(file)
        file = MP3File(directory + file)
        delete_unnecessary_tags(file, correct_key_comment)
        set_necessary_tags(file, artist, song)
        # Correct the key written to the comment tag if MixedInKey has already been run.
        if correct_key_comment:
            correct_comment_tag(file)
    exit()
Exemplo n.º 13
0
def main():
    args = def_params()
    bas_dir = os.path.dirname(os.path.realpath(__file__))
    logging.debug("parametry:" + str(args))
    mp3 = MP3File(args.file)
    mp3.set_version(VERSION_1)
    logging.debug("parametry:" + str(args))
    if args.album is not None:
        mp3.album = args.album
    if args.artist is not None:
        mp3.artist = args.artist
    if args.song is not None:
        mp3.song = args.song
    if args.track is not None:  # track powinno być number nie literal !
        mp3.track = args.track
    if args.comment is not None:
        mp3.comment = args.comment
    else:
        mp3.comment = ""
    if args.genre is not None:
        mp3.genre = args.genre  #to jest enum de facto - przyjmijmy że wpisujemy 0
    if args.year is not None:
        mp3.year = args.year
    mp3.save()

    pprint(mp3.get_tags())
Exemplo n.º 14
0
    def get_song_info(self):
        audio_path = self.fileName
        try:
            msg = QMessageBox()
            fullText = '<table class="tftable" border="0">'
            try:
                mp3 = MP3File(audio_path())
                tags = mp3.get_tags()
                self.tags = tags

                for k, v in tags.items():
                    for i, t in v.items():
                        fullText = fullText + '<tr><td>' + str(i) + '</td><td>' + str(t) + '</td></tr>'
                fullText = fullText + '</table>'
                msg = QMessageBox()
                msg.setText(fullText)
            except TypeError:
                fullText = fullText + '<tr><td>' + "Lütfen bir şarkı seçiniz!" + '</td><td>' + "" + '</td></tr>'
                fullText = fullText + '</table>'
                msg.setText(fullText)
            msg.about(self, "Title", fullText)
        except MP3OpenFileError:
            msg.setIcon(QMessageBox.Information)
            msg = "Audio file cannot be read"
            msg.setText("Audio file cannot be read")
            msg.about(self, "Title", msg)
            print("Audio file cannot be read")
Exemplo n.º 15
0
def write_mp3_tags(fout,targetdir):
    
    total_number_of_mp3 = do_initial_scan_for_mp3s(targetdir)
    current_time = time.time()
    count = 0
    
    print("Writing out mp3 tags now")

    f = open(fout,"w+")
    f_errors = open(fout+".err","w+")
    f.write('|'.join(tags)+"\n")

    for root,dirs, files in os.walk(targetdir,topdown=False):
        for name in files:
            try:
                mp3 = MP3File(os.path.join(root,name))
            except:
                continue
            data = []
            for tag in tags:
                if tag != "filePath":
                    try:
                        data.append(str(mp3.get_tags()['ID3TagV1'][tag]))
                    except:
                        data.append('Not Assigned')
            data.append(os.path.join(root,name))
            #try:
            f.write('|'.join(data)+"\n")
            except:
               f_errors.write(os.path.join(root,name) + "\n")
Exemplo n.º 16
0
def searchMusicFile(songName, artistName):
    global numGenre
    global path_genre

    artistName = artistName.lower()
    songName = songName.lower()

    g = 0

    while g < numGenre:

        mus_list = os.listdir(path_genre[g])

        l = len(mus_list)

        i = 0

        while i < l:
            mp3 = MP3File(path_genre[g]+mus_list[i])
            mp3.set_version(VERSION_2)

            art = mp3.artist.lower()
            son = mp3.song.lower()

            if art == artistName and son == songName:

                return (path_genre[g] + mus_list[i])

            i = i + 1

        g = g + 1

    return ""
Exemplo n.º 17
0
def download(mode, url, num):
    print(f"Downloading for {mode}")

    #Options
    ydl_opts = {
        'format':
        'bestaudio/best',
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'mp3',
            'preferredquality': '320',
        }],
        'logger':
        MyLogger(),
        'progress_hooks': [my_hook],
        'outtmpl':
        folders[num][mode][0] + '/%(title)s.%(ext)s'
    }

    #Download the video and extract all the metadata
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        info_dict = ydl.extract_info(url, download=True)
        video_title = info_dict.get('title', None)
        video_filename = '.'.join(
            ydl.prepare_filename(info_dict).split('.')[:-1]) + '.mp3'
    print(video_filename)

    #Edit mp3 tag.
    try:
        print(f"Editing artist tag to {mode.capitalize()}...")
        mp3 = MP3File(video_filename)
        mp3.artist = mode.title()
        mp3.save()
        insert_album_art(video_filename, info_dict['id'])
        print("Done!\n")
    except Exception as e:
        print("Error at editing mp3 tag.\n")
        print(e)

    #Backup
    if num != 3:
        try:
            print(f"Making a backup of {video_title}...")
            copy(video_filename, folders[num][mode][1])
            print("Done!\n")
        except:
            print("Error at doing backup.\n")

    #Upload to google
    if num != 3:
        try:
            print(f"Uploading {video_title} to Google Music\n")
            print(f'With url {url}')
            mm = Musicmanager()
            mm.login(uploader_id='D0:50:99:83:B0:0C')
            mm.upload(video_filename)
            print("Done!\n")
        except Exception as e:
            print("Error at uploading the song to google:\n" + e)
Exemplo n.º 18
0
def get_mp3_tags(file):
    from mp3_tagger import MP3File
    if util.get_file_extension(file).lower() != 'mp3':
        raise FileTypeError('File %s is not an mp3 file')
    # Create MP3File instance.
    mp3 = MP3File(file)
    return {'artist' : mp3.artist, 'author' : mp3.artist, 'song' : mp3.song, 'title' : mp3.song, \
        'album' : mp3.album, 'year' : mp3.year, 'track' : mp3.track, 'genre' : mp3.genre, 'comment' : mp3.comment}
Exemplo n.º 19
0
def main():
    print("Welcome to AutoTag")
    time.sleep(1)
    print("\nBefore using, please back up your music folder")
    time.sleep(4)
    print("PLEASE NOTE: ANY NON-AUDIO FILES WILL BE DELETED\n")
    time.sleep(2)
    print("MP3 files will be automatically tagged")
    print("Directories that cannot be tagged will be listed in 'Untagged.txt'")
    rootPath = os.path.dirname(os.path.realpath(__file__))
    flacList = []
    dirList = listDirectories()
    for folder in dirList:
        trackList, flacList = getFiles(folder, rootPath, flacList)
        if folder in flacList:
            continue
        trackList.sort()
        mp3 = MP3File(os.path.join(rootPath, folder, trackList[0]))
        mp3.set_version(VERSION_2)
        tags = mp3.get_tags()
        genre = getGenre(folder, tags)
        year = getYear(folder, tags)
        for track in trackList:
            mp3 = MP3File(os.path.join(rootPath, folder, track))
            mp3.set_version(VERSION_2)
            tags = mp3.get_tags()
            skipFolder = trackTagger(tags, genre, year, folder, mp3, track)
            if skipFolder:
                successRate['Fail'] += 1
                break
        trackList, flacList = getFiles(folder, rootPath, flacList)
        mp3 = MP3File(os.path.join(rootPath, folder, trackList[0]))
        mp3.set_version(VERSION_2)
        tags = mp3.get_tags()
        os.chdir("..")
        try:
            os.rename(folder, tags['artist'] + ' - ' + tags['album'])
        except ValueError as e:
            if folder not in untagged:
                untagged.append("   " + folder)
                successRate['Fail'] += 1
                continue
        if folder not in untagged:
            successRate['Pass'] += 1
    printUntagged()
Exemplo n.º 20
0
 def _fill_tags(self):
     mp3 = MP3File(os.path.join(self.download_path, f"{self}.mp3"))
     mp3.set_version(VERSION_BOTH)
     mp3.artist = self.author
     mp3.album = self.album
     mp3.song = self.name
     if self.track is not None:
         mp3.track = str(self.track)
     mp3.save()
Exemplo n.º 21
0
def tag(file, artist="", track="", album=""):
    mp3 = MP3File(file)
    if artist:
        mp3.artist = artist
    if track:
        mp3.track = track
    if album:
        mp3.album = album
    mp3.save()
def process(file):
    print(file)
    mp3 = MP3File(file)
    parts = file.split('/')
    mp3.set_version(VERSION_2)
    mp3.genre = parts[0]
    mp3.artist = parts[1]
    mp3.album = parts[2]
    mp3.song = parts[3]
Exemplo n.º 23
0
def changeMetaTags(newPath, songPath, artist, album):
    try:
        mp3 = MP3File(newPath)
        mp3.artist = artist
        mp3.album = album
        mp3.save()
        os.remove(songPath)
    except Exception as e:
        print(e)
        pass
Exemplo n.º 24
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('path', help='System path to file.')
    args = parser.parse_args()
    path = args.path
    # Create MP3File instance.
    mp3 = MP3File(path)
    tags = mp3.get_tags()
    print(json.dumps(tags, indent=2, default=str))
    exit()
Exemplo n.º 25
0
def fix_specific(filepath):
    print("Fixing genre for specific song...")
    mp3 = MP3File(filepath.replace("\\", ""))
    mp3.set_version(VERSION_2)
    old_genre = str(mp3.genre)
    print("Genre to fix: " + old_genre)
    new_genre = input("Enter new genre: ")
    mp3.genre = new_genre
    mp3.save()
    print("Fixed!")
Exemplo n.º 26
0
    def __init__(self, path):
        super(Mp3Info, self).__init__(path)

        mp3 = MP3File(self.path)
        tags = mp3.get_tags()

        for tag_version, tag_dict in tags.items():
            for attr_name in self.attrib_list:
                if not getattr(self, attr_name):
                    setattr(self, attr_name, tag_dict.get(attr_name, None))
Exemplo n.º 27
0
    def writeTags(self, path):
        mp3 = MP3File(path)
        mp3.song = self.data['title']
        mp3.track = self.data['number']

        if self.album:
            mp3.artist = self.album.data['artist']
            mp3.album = self.album.data['title']
            mp3.year = self.album.data['year']

        mp3.save()
Exemplo n.º 28
0
 def salvaID3(self, artista, album, titulo, musicaatual):
     try:
         mp3 = MP3File(musicaatual)
         mp3.artist = artista
         mp3.song = titulo
         mp3.album = album
         print(artista + ' - ' + album + ' ' + ' ' + titulo)
         mp3.save()
         
     except Exception as inst:
         print(type(inst))            
         print(artista + ' - ' + album + ' ' + ' ' + titulo)
Exemplo n.º 29
0
 def on_done(filename):
     self.adapter.bot.sendChatAction(chat_id=chat_id,
                                     action=ChatAction.UPLOAD_AUDIO)
     mp3 = MP3File(filename)
     mp3.song = track_name
     mp3.artist = artists
     mp3.set_version(VERSION_BOTH)
     mp3.save()
     with open(filename, 'rb') as fp:
         self.adapter.bot.sendAudio(chat_id=chat_id,
                                    audio=fp,
                                    timeout=60)
Exemplo n.º 30
0
    def pegaTagsID3(self, musicaatual):

        try:
            print("entrando na pegatagsid3 " + musicaatual)
            mp3 = MP3File(musicaatual)
            tags = mp3.get_tags()            
            return tags

        except:
            print("erro")
            # tag = mutagen.File(listofsongs[index], easy=True)
            # tag.add_tags()