from mutagen.flac import FLAC from shutil import copyfile import subprocess import sys import glob import pathlib # Some files don't have album artist so we fallback on just the artist. def get_album_artist(song): if song.tags.get("ALBUMARTIST"): return song.tags["ALBUMARTIST"][0] else: return song.tags["ARTIST"][0] music_directory = sys.argv[1] for song_filename in glob.glob("%s/**/*.flac" % music_directory, recursive=True): song = FLAC(song_filename) print(song.pprint() + "\n") album_artist = get_album_artist(song) album = song.tags["ALBUM"][0] # Some song numbers are "3/8" or something like that, so we split on "/" to # grab the first part as "3/9" is not a valid filename. Then we fill single # digit numbers with a leading zero to keep filesnames consistent. number = song.tags["TRACKNUMBER"][0].split("/")[0].zfill(2) # Replace "/" to keep the string path safe. title = song.tags["TITLE"][0].replace("/", "_") directory = "%s/%s/%s - %s/" % (sys.argv[2], album_artist, album_artist, album) filename = "%s - %s.flac" % (number, title) # Make all the required directories. pathlib.Path(directory).mkdir(parents=True, exist_ok=True) # Copy the file after the directories are ready. copyfile(song_filename, directory + filename) # If the song has an embedded photo, we should save it as a separate file. if song.pictures: with open(directory + "cover.jpg", "wb") as cover_file: cover_file.write(song.pictures[0].data)