summaryrefslogtreecommitdiff
path: root/main.py
blob: f0f0bd458335e9502237131bed598e281842e202 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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)